<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Tax;
use App\Models\Currency;
use App\Models\SubAccount;
use App\Models\SubAccount2;
use App\Models\SubAccount3;
use App\Models\SubAccount4;
use App\Models\SubAccount5;
use App\Models\MainAccount;
use App\Models\Departments;
use App\Models\HomeCurrency;
use App\Models\AccountTypes;
use Illuminate\Http\Request;
use App\Models\GeneralLedger;
use App\Models\TransactionType;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class MaintananceCOAController extends Controller
{
    //create accountTypes
   // Show form and list of account types
    public function create_account_type()
    {
        $account_types = AccountTypes::all();
        return view('maintanance.chart_of_accounts.create', compact('account_types'));
    }

    // Store new account type
    public function store_account_type(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255|unique:account_types,name',
            ], [
                'name.unique' => 'The account type already exists. Please choose a different name.',
            ]);

            $type = new AccountTypes();
            $type->name = $request->name;
            $type->save();

            return redirect()->route('account_types.create')->with('success', 'Account type created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit existing account type
    public function edit_account_type(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:account_types,id',
                'name' => 'required|string|max:255',
            ]);

            $type = AccountTypes::findOrFail($request->id);
            $type->name = $request->name;
            $type->save();

            return redirect()->route('account_types.create')->with('success', 'Account type updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete account type
    public function delete_account_type($id)
    {
        try {
            $type = AccountTypes::findOrFail($id);
            $type->delete();

            return redirect()->route('account_types.create')->with('success', 'Account type deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('account_types.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
    public function addSubAccount($id)
    {
        $mainAccount = MainAccount::findOrFail($id);
        $subAccounts = $mainAccount->allSubAccounts();
        $mainAccounts = MainAccount::orderBy('account_code')->get();

        return view('maintanance.chart_of_accounts.createsubAcc', [
            'records'  => $mainAccount,
            'recordss' => $subAccounts,
            'mainAccounts' => $mainAccounts,
        ]);
    }
    

    //create department
    public function create_dept()
    {
        $records = Departments::all();
        return view('maintanance.chart_of_accounts.create_dept',compact('records'));
    }

    //store department
    public function store_dept(Request $request)
    {
        try {
        $validator = Validator::make($request->all(), [
            'code' => 'required',
            'desc' => 'required',
        ]);

        if ($validator->fails()) {
            throw new Exception('Validation failed.');
        }

        $record = new Departments();
        $record->code = $request->code;
        $record->desc = $request->desc;
        $record->save();
        return redirect()->route('departments.create');
    } catch (Exception $e) {
        return $e;
        return redirect()->back();
    }

    }

public function edit_dept(Request $request)
{
    // 1. Validate incoming data
    $request->validate([
        'id'   => 'required|integer',
        'code' => 'required|string|max:50',
        'desc' => 'required|string|max:255',
    ]);

    $id   = $request->input('id');
    $code = $request->input('code');
    $desc = $request->input('desc');

    try {
        // 2. Check if this department exists
        $exists = DB::table('departments')->where('id', $id)->exists();

        if ($exists) {
            // 3. Perform the update on columns code and desc
            $result = DB::table('departments')
                ->where('id', $id)
                ->update([
                    'code' => $code,
                    'desc' => $desc,
                ]);

            if ($result) {
                return redirect()
                    ->route('departments.create')
                    ->with('success', 'Department updated successfully.');
            } else {
                return redirect()
                    ->route('departments.create')
                    ->with('success', 'Nothing to update.');
            }
        } else {
            return redirect()
                ->route('departments.create')
                ->withErrors(['error' => 'Department not found.']);
        }
    } catch (\Exception $e) {
        return redirect()
            ->route('departments.create')
            ->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
    }
}

/**
 * Delete an existing Department.
 *
 * Expects GET to /delete/departments/{id}.
 */
public function delete_dept($id)
{
    try {
        // 1. Check if this department exists
        $exists = DB::table('departments')->where('id', $id)->exists();

        if ($exists) {
            // 2. Perform the delete
            $result = DB::table('departments')->where('id', $id)->delete();

            if ($result) {
                return redirect()
                    ->route('departments.create')
                    ->with('success', 'Department removed successfully.');
            } else {
                return redirect()
                    ->route('departments.create')
                    ->withErrors(['error' => 'Failed to remove department.']);
            }
        } else {
            return redirect()
                ->route('departments.create')
                ->withErrors(['error' => 'Department not found.']);
        }
    } catch (\Exception $e) {
        return redirect()
            ->route('departments.create')
            ->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
    }
}

    
   // GeneralLedgerController.php

public function createGL()
{
    $accounts = AccountTypes::all();
    $records = GeneralLedger::with('accountType')
                ->orderBy('code') // Add this to sort by code
                ->get();
                
    return view('maintanance.chart_of_accounts.createGL', compact('records', 'accounts'));
}

public function storeGL(Request $request)
{
    try {
        $request->validate([
            'account_type' => 'required|string',
            'code' => 'required|string|unique:main_accounts,code',
            'financial_category' => 'required|string',
            'account_name' => 'required|string'
        ]);

        $record = new GeneralLedger();
        $record->code = $request->code;
        $record->financial_category = $request->financial_category;
        $record->account_name = $request->account_name;
        $record->account_type = $request->account_type;
        $record->save();
        
        return redirect()->route('ledger.create')->with('success', 'Account created successfully!');

    } catch (\Illuminate\Validation\ValidationException $e) {
        return redirect()->back()
            ->withErrors($e->validator)
            ->withInput();
    } catch (\Exception $e) {
        return redirect()->back()
            ->with('error', 'An error occurred: ' . $e->getMessage())
            ->withInput();
    }
}

public function editMainAccount(Request $request)
{
    $id = $request->input('id');
    
    try {
        $request->validate([
            'account_type' => 'required|string',
            'code' => 'required|string|unique:main_accounts,code,'.$id,
            'financial_category' => 'required|string',
            'account_name' => 'required|string'
        ]);

        $result = GeneralLedger::editMainAccount(
            $id,
            $request->account_type,
            $request->code,
            $request->financial_category,
            $request->account_name
        );

        if ($result) {
            return redirect()->route('ledger.create')->with('success', 'Account updated successfully!');
        } else {
            return redirect()->route('ledger.create')->with('info', 'No changes made.');
        }

    } catch (\Illuminate\Validation\ValidationException $e) {
        return redirect()->back()
            ->withErrors($e->validator)
            ->withInput();
    } catch (\Exception $e) {
        return redirect()->route('ledger.create')
            ->with('error', 'An error occurred: ' . $e->getMessage())
            ->withInput();
    }
}

public function deleteMainAccount($id)
{
    try {
        $result = GeneralLedger::deleteMainAccount($id);
        
        if ($result) {
            return redirect()->route('ledger.create')->with('success', 'Account deleted successfully!');
        } else {
            return redirect()->route('ledger.create')->with('error', 'Account not found!');
        }
    } catch (\Exception $e) {
        return redirect()->route('ledger.create')
            ->with('error', 'An error occurred: ' . $e->getMessage());
    }
}
               

    

    //storeSubAccount
    public function storeSubAccount(Request $request)
    {
    try {
        // Validate the input fields
        $validatedData = $request->validate([
            'parent_id' => 'required|exists:main_accounts,id',
            'sub_table' => 'required|in:sub_accounts,sub_accounts_2,sub_accounts_3,sub_accounts_4,sub_accounts_5',
            'account_code' => 'required|string|max:255',
            'sub_name' => 'required|string|max:255',
            'code' => 'nullable|string|max:255',
            'sub_code' => 'nullable|string|max:255',
        ]);

        $modelMap = [
            'sub_accounts' => SubAccount::class,
            'sub_accounts_2' => SubAccount2::class,
            'sub_accounts_3' => SubAccount3::class,
            'sub_accounts_4' => SubAccount4::class,
            'sub_accounts_5' => SubAccount5::class,
        ];

        $modelClass = $modelMap[$validatedData['sub_table']];
        $payload = [
            'parent_id' => $validatedData['parent_id'],
            'account_code' => $validatedData['account_code'],
            'sub_name' => $validatedData['sub_name'],
        ];

        if ($validatedData['sub_table'] === 'sub_accounts') {
            $payload['code'] = $validatedData['code'] ?? null;
            $payload['sub_code'] = $validatedData['sub_code'] ?? null;
        }

        $modelClass::create($payload);


        return redirect()->route('subaccount.add', ['id' => $validatedData['parent_id']])
                         ->with('success', 'Sub Account created successfully!');
    } catch (Exception $e) {

        return redirect()->back()->withErrors(['error' => 'There was an error creating the sub-account.']);
    }
}


// EDIT SUB ACCOUNT
public function editSubAccount(Request $request)
{
    $request->validate([
        'id' => 'required|integer',
        'sub_table' => 'required|in:sub_accounts,sub_accounts_2,sub_accounts_3,sub_accounts_4,sub_accounts_5',
        'parent_id' => 'required|exists:main_accounts,id',
        'account_code' => 'required|string',
        'sub_name' => 'required|string',
    ]);

    $modelMap = [
        'sub_accounts' => SubAccount::class,
        'sub_accounts_2' => SubAccount2::class,
        'sub_accounts_3' => SubAccount3::class,
        'sub_accounts_4' => SubAccount4::class,
        'sub_accounts_5' => SubAccount5::class,
    ];

    $subAccount = $modelMap[$request->sub_table]::findOrFail($request->id);

    $subAccount->account_code = $request->account_code;
    $subAccount->sub_name = $request->sub_name;
    $subAccount->parent_id = $request->parent_id;
    if ($request->sub_table === 'sub_accounts') {
        $subAccount->code = $request->code;
        $subAccount->sub_code = $request->sub_code;
    }

    $subAccount->save();

    return redirect()->back()->with('success', 'Sub Account updated successfully.');
}



// Delete Sub Accounts
public function deleteSubAccount($table, $id)
{
    try {
        $modelMap = [
            'sub_accounts' => SubAccount::class,
            'sub_accounts_2' => SubAccount2::class,
            'sub_accounts_3' => SubAccount3::class,
            'sub_accounts_4' => SubAccount4::class,
            'sub_accounts_5' => SubAccount5::class,
        ];

        abort_unless(array_key_exists($table, $modelMap), 404);
        $modelClass = $modelMap[$table];
        $record = $modelClass::findOrFail($id);
        $record->delete();

        return redirect()->back()->with('success', 'Sub Account Deleted Successfully.');
    } catch (\Exception $e) {
        return redirect()->back()->withErrors(['error' => 'An error occurred!! ' . $e->getMessage()]);
    }
}


 // Show form and list of currencies
    public function createCurrency()
    {
        $records = Currency::all();
        return view('maintanance.chart_of_accounts.create_currency', compact('records'));
    }

    // Store new currency
    public function storeCurrency(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'symbol' => 'required|string|max:10',
            ]);

            $record = new Currency();
            $record->name = $request->name;
            $record->symbol = $request->symbol;
            $record->code = $request->symbol;  // Assuming code same as symbol
            $record->save();

            return redirect()->route('currency.create')->with('success', 'Currency created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit existing currency
    public function editCurrency(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:currencies,id',
                'name' => 'required|string|max:255',
                'symbol' => 'required|string|max:10',
            ]);

            $record = Currency::findOrFail($request->id);
            $record->name = $request->name;
            $record->symbol = $request->symbol;
            $record->code = $request->symbol;
            $record->save();

            return redirect()->route('currency.create')->with('success', 'Currency updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete currency
    public function deleteCurrency($id)
    {
        try {
            $record = Currency::findOrFail($id);
            $record->delete();

            return redirect()->route('currency.create')->with('success', 'Currency deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('currency.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

 
}
