<?php

namespace App\Http\Controllers\ChartOfAccounts;

use App\Http\Controllers\Controller;
use App\Models\AccountTypes;
use App\Models\GeneralLedger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class GeneralLedgerController extends Controller
{
    public function index(Request $request)
    {
        $relations = ['subAccounts'];

        if (Schema::hasTable('sub_accounts_2')) {
            $relations[] = 'subAccounts2';
        }
        if (Schema::hasTable('sub_accounts_3')) {
            $relations[] = 'subAccounts3';
        }
        if (Schema::hasTable('sub_accounts_4')) {
            $relations[] = 'subAccounts4';
        }
        if (Schema::hasTable('sub_accounts_5')) {
            $relations[] = 'subAccounts5';
        }

        $query = GeneralLedger::query()->with('accountType')->withCount($relations);

        if ($request->filled('account_type')) {
            $query->where('account_type', $request->string('account_type')->toString());
        }

        if ($request->filled('financial_category')) {
            $query->where('financial_category', $request->string('financial_category')->toString());
        }

        $accounts = $query->orderBy('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.general-ledger.index', compact(
            'accounts',
            'accountTypes',
            'financialCategories'
        ));
    }

    public function destroy(GeneralLedger $generalLedger)
    {
        $generalLedger->delete();

        return redirect()
            ->route('chart-of-accounts.general-ledger.index')
            ->with('success', 'General ledger account deleted successfully.');
    }
}
