<?php

namespace App\Http\Controllers\ChartOfAccounts;

use App\Http\Controllers\Controller;
use App\Models\AccountTypes;
use App\Models\GeneralLedger;
use App\Models\MainSubAccount;
use Illuminate\Http\Request;

class MainSubAccountController extends Controller
{
    public function index(Request $request, GeneralLedger $generalLedger)
    {
        $query = MainSubAccount::query()->where('parent_id', $generalLedger->id);

        $mainSubAccounts = $query->orderBy('account_code')->paginate(25)->withQueryString();

        $accountTypes = AccountTypes::orderBy('code')->get();
        $financialCategories = GeneralLedger::query()
            ->select('financial_category')
            ->whereNotNull('financial_category')
            ->distinct()
            ->orderBy('financial_category')
            ->pluck('financial_category');

        return view('chart-of-accounts.main-sub-accounts.index', [
            'generalLedger' => $generalLedger,
            'mainSubAccounts' => $mainSubAccounts,
            'accountTypes' => $accountTypes,
            'financialCategories' => $financialCategories,
        ]);
    }

    public function destroy(GeneralLedger $generalLedger, MainSubAccount $mainSubAccount)
    {
        if ((int) $mainSubAccount->parent_id !== (int) $generalLedger->id) {
            abort(404);
        }

        $mainSubAccount->delete();

        return redirect()
            ->route('chart-of-accounts.general-ledger.main-sub-accounts.index', $generalLedger)
            ->with('success', 'Main sub-account deleted successfully.');
    }
}

