orderBy('account_code') ->get(); $selectedAccountId = $request->input('account_id'); $startDate = $request->input('start_date', now()->startOfYear()->format('Y-m-d')); $endDate = $request->input('end_date', now()->format('Y-m-d')); $entries = null; $selectedAccount = null; $openingBalance = 0; $debitTotal = 0; $creditTotal = 0; $closingBalance = 0; if ($selectedAccountId) { $selectedAccount = ChartOfAccount::findOrFail($selectedAccountId); // Get opening balance (all entries before start date) $openingDebit = AccountingEntry::where('chart_of_account_id', $selectedAccountId) ->where('entry_date', '<', $startDate) ->where('entry_type', AccountingEntry::ENTRY_TYPE_DEBIT) ->sum('amount'); $openingCredit = AccountingEntry::where('chart_of_account_id', $selectedAccountId) ->where('entry_date', '<', $startDate) ->where('entry_type', AccountingEntry::ENTRY_TYPE_CREDIT) ->sum('amount'); // Calculate opening balance based on account type if (in_array($selectedAccount->account_type, ['asset', 'expense'])) { // Assets and Expenses: Debit increases, Credit decreases $openingBalance = $openingDebit - $openingCredit; } else { // Liabilities, Equity, Income: Credit increases, Debit decreases $openingBalance = $openingCredit - $openingDebit; } // Get entries for the period $entries = AccountingEntry::with(['financeDocument', 'chartOfAccount']) ->where('chart_of_account_id', $selectedAccountId) ->whereBetween('entry_date', [$startDate, $endDate]) ->orderBy('entry_date') ->orderBy('id') ->get(); // Calculate totals for the period $debitTotal = $entries->where('entry_type', AccountingEntry::ENTRY_TYPE_DEBIT)->sum('amount'); $creditTotal = $entries->where('entry_type', AccountingEntry::ENTRY_TYPE_CREDIT)->sum('amount'); // Calculate closing balance if (in_array($selectedAccount->account_type, ['asset', 'expense'])) { $closingBalance = $openingBalance + $debitTotal - $creditTotal; } else { $closingBalance = $openingBalance + $creditTotal - $debitTotal; } } return view('admin.general-ledger.index', compact( 'accounts', 'selectedAccount', 'entries', 'startDate', 'endDate', 'openingBalance', 'debitTotal', 'creditTotal', 'closingBalance' )); } }