<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/init.php';
app_require_login();

$requestedCompanyId = (int) ($_GET['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, true);
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}

$companies = app_current_user_company_options();
$company = $companyId ? app_company_by_id((int) $companyId) : null;

$fromDate = app_sanitize_date((string) ($_GET['from_date'] ?? date('Y-01-01')), date('Y-01-01'));
$toDate = app_sanitize_date((string) ($_GET['to_date'] ?? date('Y-m-d')), date('Y-m-d'));
if ($fromDate > $toDate) {
    [$fromDate, $toDate] = [$toDate, $fromDate];
}
$accountCode = app_normalize_whitespace((string) ($_GET['account_code'] ?? ''));
$contactCode = app_normalize_whitespace((string) ($_GET['contact_code'] ?? ''));
$costCenterCode = app_normalize_whitespace((string) ($_GET['cost_center_code'] ?? ''));
$eclCountryOptions = app_module_lookup_options('ecl_country_code', $companyId);
$defaultEclCountryCode = app_ecl_default_country_code((int) $companyId);
$eclCountryCode = app_normalize_whitespace((string) ($_GET['ecl_country_code'] ?? $defaultEclCountryCode));
if ($eclCountryCode === '' || ($eclCountryOptions && !array_key_exists($eclCountryCode, $eclCountryOptions))) {
    $eclCountryCode = $defaultEclCountryCode;
}
$includeZero = !empty($_GET['include_zero']);
$reportCatalog = app_accounting_reports_catalog();
$requestedReport = app_normalize_whitespace((string) ($_GET['report'] ?? 'ledger'));
if ($requestedReport === '' || !array_key_exists($requestedReport, $reportCatalog)) {
    $requestedReport = 'ledger';
}
$activeReport = $requestedReport;
$activeReportLabel = (string) ($reportCatalog[$activeReport]['label'] ?? 'Accounting Report');
$comparisonAllowed = in_array($activeReport, ['income_statement', 'balance_sheet'], true);
$comparisonEnabled = $comparisonAllowed && !empty($_GET['enable_comparison']);
$defaultCompareFromDate = date('Y-m-d', strtotime($fromDate . ' -1 year'));
$defaultCompareToDate = date('Y-m-d', strtotime($toDate . ' -1 year'));
$compareFromDate = app_sanitize_date((string) ($_GET['compare_from_date'] ?? $defaultCompareFromDate), $defaultCompareFromDate);
$compareToDate = app_sanitize_date((string) ($_GET['compare_to_date'] ?? $defaultCompareToDate), $defaultCompareToDate);
if ($compareFromDate > $compareToDate) {
    [$compareFromDate, $compareToDate] = [$compareToDate, $compareFromDate];
}
$currentColumnLabel = $activeReport === 'balance_sheet'
    ? ('As of ' . $toDate)
    : ($fromDate . ' to ' . $toDate);
$compareColumnLabel = $activeReport === 'balance_sheet'
    ? ('As of ' . $compareToDate)
    : ($compareFromDate . ' to ' . $compareToDate);

$ledger = $accountCode !== ''
    ? app_accounting_ledger((int) $companyId, $accountCode, $fromDate, $toDate)
    : [
        'account' => null,
        'rows' => [],
        'opening_signed' => 0.0,
        'closing_signed' => 0.0,
        'totals' => ['debit' => 0.0, 'credit' => 0.0],
    ];
$contactStatement = $contactCode !== ''
    ? app_accounting_contact_statement((int) $companyId, $contactCode, $fromDate, $toDate)
    : [
        'contact' => null,
        'rows' => [],
        'opening_signed' => 0.0,
        'closing_signed' => 0.0,
        'totals' => ['debit' => 0.0, 'credit' => 0.0],
    ];
$trial = app_accounting_trial_balance((int) $companyId, $fromDate, $toDate, $includeZero);
$income = app_accounting_income_statement((int) $companyId, $fromDate, $toDate);
$balance = app_accounting_balance_sheet((int) $companyId, $toDate);
$compareIncome = $comparisonEnabled ? app_accounting_income_statement((int) $companyId, $compareFromDate, $compareToDate) : null;
$compareBalance = $comparisonEnabled ? app_accounting_balance_sheet((int) $companyId, $compareToDate) : null;
$cashFlow = app_accounting_cash_flow_summary((int) $companyId, $fromDate, $toDate);
$journalBook = app_accounting_journal_book((int) $companyId, $fromDate, $toDate);
$costCenterReport = app_accounting_cost_center_report((int) $companyId, $fromDate, $toDate, $costCenterCode);
$vatSummary = app_accounting_vat_summary((int) $companyId, $fromDate, $toDate);
$eclReport = app_accounting_ecl_report((int) $companyId, $toDate, $eclCountryCode);
$accountOptions = app_module_lookup_options('chart_account_code', $companyId);
$contactOptions = app_module_lookup_options('all_contact_code', $companyId);
$costCenterOptions = app_module_lookup_options('cost_center_code', $companyId);

$exportQuery = $_GET;
$exportQuery['report'] = $activeReport;
$exportQuery['from_date'] = $fromDate;
$exportQuery['to_date'] = $toDate;
$exportQuery['ecl_country_code'] = $eclCountryCode;
if ($comparisonEnabled) {
    $exportQuery['enable_comparison'] = '1';
    $exportQuery['compare_from_date'] = $compareFromDate;
    $exportQuery['compare_to_date'] = $compareToDate;
} else {
    unset($exportQuery['enable_comparison'], $exportQuery['compare_from_date'], $exportQuery['compare_to_date']);
}
if ($companyId !== null && $companyId > 0) {
    $exportQuery['company_id'] = $companyId;
}
$exportQuery['export'] = 'xlsx';
$exportUrl = 'accounting_reports.php?' . http_build_query($exportQuery);

if (app_normalize_whitespace((string) ($_GET['export'] ?? '')) === 'xlsx') {
    $companyName = (string) ($company['name'] ?? 'N/A');
    $companyVatNumber = (string) ($company['vat_number'] ?? '');
    $preparedBy = (string) (app_current_user()['full_name'] ?? app_current_username());
    $infoRows = static function (string $title) use ($companyName, $companyVatNumber, $preparedBy, $fromDate, $toDate): array {
        return [
            app_xlsx_row([$title], 'title'),
            ['Company', $companyName],
            ['VAT Number', $companyVatNumber !== '' ? $companyVatNumber : 'N/A'],
            ['From Date', $fromDate],
            ['To Date', $toDate],
            ['Prepared By', $preparedBy],
            ['Generated At', date('Y-m-d H:i')],
            [],
        ];
    };

    $sheets = [];
    if ($activeReport === 'ledger') {
        $accountLabel = $ledger['account']
            ? ((string) ($ledger['account']['account_code'] ?? '') . ' - ' . (string) ($ledger['account']['account_name'] ?? ''))
            : 'No account selected';
        $rows = array_merge($infoRows('Account Statement'), [
            ['Account', $accountLabel],
            ['Opening Balance', app_signed_balance_label(app_number($ledger['opening_signed'] ?? 0))],
            ['Total Debit', app_number($ledger['totals']['debit'] ?? 0)],
            ['Total Credit', app_number($ledger['totals']['credit'] ?? 0)],
            ['Closing Balance', app_signed_balance_label(app_number($ledger['closing_signed'] ?? 0))],
            [],
            app_xlsx_row(['Date', 'Entry No.', 'Reference', 'Description', 'Debit', 'Credit', 'Running Balance'], 'header'),
        ]);
        foreach ((array) ($ledger['rows'] ?? []) as $row) {
            $rows[] = [
                (string) ($row['entry_date'] ?? ''),
                (string) ($row['entry_number'] ?? ''),
                (string) ($row['reference'] ?? ''),
                (string) ($row['description'] ?? ''),
                app_number($row['debit'] ?? 0),
                app_number($row['credit'] ?? 0),
                app_number($row['running_signed'] ?? 0),
            ];
        }
        $sheets[] = ['title' => 'Account Statement', 'rows' => $rows];
    } elseif ($activeReport === 'contact_statement') {
        $contactLabel = $contactStatement['contact']
            ? ((string) ($contactStatement['contact']['contact_code'] ?? '') . ' - ' . (string) ($contactStatement['contact']['contact_name'] ?? ''))
            : 'No contact selected';
        $rows = array_merge($infoRows('Contact Statement'), [
            ['Contact', $contactLabel],
            ['Opening Balance', app_signed_balance_label(app_number($contactStatement['opening_signed'] ?? 0))],
            ['Total Debit', app_number($contactStatement['totals']['debit'] ?? 0)],
            ['Total Credit', app_number($contactStatement['totals']['credit'] ?? 0)],
            ['Closing Balance', app_signed_balance_label(app_number($contactStatement['closing_signed'] ?? 0))],
            [],
            app_xlsx_row(['Date', 'Type', 'Reference', 'Description', 'Debit', 'Credit', 'Running Balance'], 'header'),
        ]);
        foreach ((array) ($contactStatement['rows'] ?? []) as $row) {
            $rows[] = [
                (string) ($row['date'] ?? ''),
                (string) ($row['type'] ?? ''),
                (string) ($row['reference'] ?? ''),
                (string) ($row['description'] ?? ''),
                app_number($row['debit'] ?? 0),
                app_number($row['credit'] ?? 0),
                app_number($row['running_signed'] ?? 0),
            ];
        }
        $sheets[] = ['title' => 'Contact Statement', 'rows' => $rows];
    } elseif ($activeReport === 'journal_book') {
        $rows = array_merge($infoRows('Journal Book'), [
            app_xlsx_row(['Date', 'Entry No.', 'Line', 'Account Code', 'Account Name', 'Cost Center', 'Description', 'Debit', 'Credit', 'Source'], 'header'),
        ]);
        foreach ((array) ($journalBook['rows'] ?? []) as $row) {
            $center = app_normalize_whitespace((string) ($row['cost_center_code'] ?? ''));
            $centerName = app_normalize_whitespace((string) ($row['cost_center_name'] ?? ''));
            if ($centerName !== '' && $centerName !== $center) {
                $center .= ' - ' . $centerName;
            }
            $rows[] = [
                (string) ($row['entry_date'] ?? ''),
                (string) ($row['entry_number'] ?? ''),
                (int) ($row['line_no'] ?? 0),
                (string) ($row['account_code'] ?? ''),
                (string) ($row['account_name'] ?? ''),
                $center,
                (string) ($row['description'] ?? ''),
                app_number($row['debit'] ?? 0),
                app_number($row['credit'] ?? 0),
                (string) ($row['source_label'] ?? ''),
            ];
        }
        $rows[] = app_xlsx_row(['Totals', '', '', '', '', '', '', app_number($journalBook['totals']['debit'] ?? 0), app_number($journalBook['totals']['credit'] ?? 0), ''], 'total');
        $sheets[] = ['title' => 'Journal Book', 'rows' => $rows];
    } elseif ($activeReport === 'cost_center') {
        $summaryRows = array_merge($infoRows('Cost Center Summary'), [
            app_xlsx_row(['Cost Center', 'Total Debit', 'Total Credit', 'Net', 'Lines'], 'header'),
        ]);
        foreach ((array) ($costCenterReport['summary'] ?? []) as $row) {
            $center = app_normalize_whitespace((string) ($row['cost_center_code'] ?? ''));
            $centerName = app_normalize_whitespace((string) ($row['cost_center_name'] ?? ''));
            if ($centerName !== '' && $centerName !== $center) {
                $center .= ' - ' . $centerName;
            }
            $summaryRows[] = [$center, app_number($row['total_debit'] ?? 0), app_number($row['total_credit'] ?? 0), app_number($row['net'] ?? 0), (int) ($row['lines_count'] ?? 0)];
        }
        $detailRows = array_merge($infoRows('Cost Center Detailed Lines'), [
            app_xlsx_row(['Date', 'Entry No.', 'Line', 'Cost Center', 'Account', 'Description', 'Debit', 'Credit', 'Source'], 'header'),
        ]);
        foreach ((array) ($costCenterReport['lines'] ?? []) as $row) {
            $center = app_normalize_whitespace((string) ($row['cost_center_code'] ?? ''));
            $centerName = app_normalize_whitespace((string) ($row['cost_center_name'] ?? ''));
            if ($centerName !== '' && $centerName !== $center) {
                $center .= ' - ' . $centerName;
            }
            $account = app_normalize_whitespace((string) ($row['account_code'] ?? ''));
            $accountName = app_normalize_whitespace((string) ($row['account_name'] ?? ''));
            if ($accountName !== '' && $accountName !== $account) {
                $account .= ' - ' . $accountName;
            }
            $detailRows[] = [
                (string) ($row['entry_date'] ?? ''),
                (string) ($row['entry_number'] ?? ''),
                (int) ($row['line_no'] ?? 0),
                $center,
                $account,
                (string) ($row['description'] ?? ''),
                app_number($row['debit'] ?? 0),
                app_number($row['credit'] ?? 0),
                (string) ($row['source_label'] ?? ''),
            ];
        }
        $sheets[] = ['title' => 'Cost Center Summary', 'rows' => $summaryRows];
        $sheets[] = ['title' => 'Cost Center Lines', 'rows' => $detailRows];
    } elseif ($activeReport === 'trial_balance') {
        $rows = array_merge($infoRows('Trial Balance'), [
            app_xlsx_row(['Account Code', 'Account Name', 'Type', 'Opening Dr', 'Opening Cr', 'Period Dr', 'Period Cr', 'Closing Dr', 'Closing Cr'], 'header'),
        ]);
        foreach ((array) ($trial['rows'] ?? []) as $row) {
            $rows[] = [
                (string) ($row['account_code'] ?? ''),
                (string) ($row['account_name'] ?? ''),
                (string) ($row['account_type'] ?? ''),
                app_number($row['opening_dr'] ?? 0),
                app_number($row['opening_cr'] ?? 0),
                app_number($row['period_debit'] ?? 0),
                app_number($row['period_credit'] ?? 0),
                app_number($row['closing_dr'] ?? 0),
                app_number($row['closing_cr'] ?? 0),
            ];
        }
        $rows[] = app_xlsx_row(['Totals', '', '', app_number($trial['totals']['opening_dr'] ?? 0), app_number($trial['totals']['opening_cr'] ?? 0), app_number($trial['totals']['period_debit'] ?? 0), app_number($trial['totals']['period_credit'] ?? 0), app_number($trial['totals']['closing_dr'] ?? 0), app_number($trial['totals']['closing_cr'] ?? 0)], 'total');
        $sheets[] = ['title' => 'Trial Balance', 'rows' => $rows];
    } elseif ($activeReport === 'vat_summary') {
        $rows = array_merge($infoRows('VAT Summary'), [
            app_xlsx_row(['Section', 'Amount Before Tax', 'Return Before Tax', 'Tax'], 'header'),
            ['Sales taxable at standard rate (15%)', app_number($vatSummary['sales_taxable']['base'] ?? 0), app_number($vatSummary['sales_taxable']['return_base'] ?? 0), app_number($vatSummary['sales_taxable']['tax'] ?? 0)],
            ['Sales borne by state / zero tax', app_number($vatSummary['sales_exempt']['base'] ?? 0), app_number($vatSummary['sales_exempt']['return_base'] ?? 0), app_number($vatSummary['sales_exempt']['tax'] ?? 0)],
            app_xlsx_row(['Sales Total', app_number($vatSummary['sales_total']['base'] ?? 0), app_number($vatSummary['sales_total']['return_base'] ?? 0), app_number($vatSummary['sales_total']['tax'] ?? 0)], 'total'),
            [],
            ['Purchases taxable at standard rate (15%)', app_number($vatSummary['purchase_taxable']['base'] ?? 0), app_number($vatSummary['purchase_taxable']['return_base'] ?? 0), app_number($vatSummary['purchase_taxable']['tax'] ?? 0)],
            app_xlsx_row(['Purchase Total', app_number($vatSummary['purchase_total']['base'] ?? 0), app_number($vatSummary['purchase_total']['return_base'] ?? 0), app_number($vatSummary['purchase_total']['tax'] ?? 0)], 'total'),
            [],
            app_xlsx_row(['Summary', '', '', ''], 'header'),
            ['Total VAT due for current period', '', '', app_number($vatSummary['summary']['current_period_vat'] ?? 0)],
            ['VAT carried forward from previous periods', '', '', app_number($vatSummary['summary']['carried_forward_vat'] ?? 0)],
            app_xlsx_row(['Net VAT due or recoverable', '', '', app_number($vatSummary['summary']['net_due_or_recoverable'] ?? 0)], 'total'),
        ]);
        $sheets[] = ['title' => 'VAT Summary', 'rows' => $rows];
    } elseif ($activeReport === 'income_statement') {
        $rows = $infoRows('Income Statement');
        if (!empty($income['grouped_enabled'])) {
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Financial Statement Group', $currentColumnLabel, $compareColumnLabel], 'header')
                : app_xlsx_row(['Financial Statement Group', 'Amount'], 'header');
            foreach ((array) ($income['sections'] ?? []) as $sectionCode => $section) {
                $rows[] = $comparisonEnabled
                    ? app_xlsx_row([(string) ($section['label'] ?? ''), '', ''], 'header')
                    : app_xlsx_row([(string) ($section['label'] ?? ''), ''], 'header');
                foreach ((array) ($section['groups'] ?? []) as $groupCode => $group) {
                    $rows[] = $comparisonEnabled
                        ? [(string) ($group['name'] ?? ''), app_number($group['display_amount'] ?? 0), $statementSectionCompareAmount($compareIncome, (string) $sectionCode, (string) $groupCode)]
                        : [(string) ($group['name'] ?? ''), app_number($group['display_amount'] ?? 0)];
                }
                $rows[] = $comparisonEnabled
                    ? app_xlsx_row([(string) ($section['total_label'] ?? 'Total'), app_number($section['display_total'] ?? 0), $statementSectionCompareAmount($compareIncome, (string) $sectionCode)], 'total')
                    : app_xlsx_row([(string) ($section['total_label'] ?? 'Total'), app_number($section['display_total'] ?? 0)], 'total');
                $rows[] = [];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Net Income', app_number($income['net_income'] ?? 0), app_number($compareIncome['net_income'] ?? 0)], 'total')
                : app_xlsx_row(['Net Income', app_number($income['net_income'] ?? 0)], 'total');
        } else {
            $compareRevenueMap = $comparisonEnabled && $compareIncome ? $statementRowsByCode((array) ($compareIncome['revenues'] ?? [])) : [];
            $compareExpenseMap = $comparisonEnabled && $compareIncome ? $statementRowsByCode((array) ($compareIncome['expenses'] ?? [])) : [];
            $rows = array_merge($rows, [
                app_xlsx_row(['Revenue'], 'header'),
                $comparisonEnabled ? app_xlsx_row(['Code', 'Account', $currentColumnLabel, $compareColumnLabel], 'header') : app_xlsx_row(['Code', 'Account', 'Amount'], 'header'),
            ]);
            foreach ((array) ($income['revenues'] ?? []) as $row) {
                $code = (string) ($row['account_code'] ?? '');
                $rows[] = $comparisonEnabled
                    ? [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0), app_number($compareRevenueMap[$code] ?? 0)]
                    : [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0)];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Revenue', '', app_number($income['total_revenue'] ?? 0), app_number($compareIncome['total_revenue'] ?? 0)], 'total')
                : app_xlsx_row(['Total Revenue', '', app_number($income['total_revenue'] ?? 0)], 'total');
            $rows[] = [];
            $rows[] = app_xlsx_row(['Expenses'], 'header');
            $rows[] = $comparisonEnabled ? app_xlsx_row(['Code', 'Account', $currentColumnLabel, $compareColumnLabel], 'header') : app_xlsx_row(['Code', 'Account', 'Amount'], 'header');
            foreach ((array) ($income['expenses'] ?? []) as $row) {
                $code = (string) ($row['account_code'] ?? '');
                $rows[] = $comparisonEnabled
                    ? [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0), app_number($compareExpenseMap[$code] ?? 0)]
                    : [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0)];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Expense', '', app_number($income['total_expense'] ?? 0), app_number($compareIncome['total_expense'] ?? 0)], 'total')
                : app_xlsx_row(['Total Expense', '', app_number($income['total_expense'] ?? 0)], 'total');
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Net Income', '', app_number($income['net_income'] ?? 0), app_number($compareIncome['net_income'] ?? 0)], 'total')
                : app_xlsx_row(['Net Income', '', app_number($income['net_income'] ?? 0)], 'total');
        }
        $sheets[] = ['title' => 'Income Statement', 'rows' => $rows];
    } elseif ($activeReport === 'balance_sheet') {
        $rows = array_merge($infoRows('Statement of Financial Position'), [
            ['As Of', (string) ($balance['as_of_date'] ?? $toDate)],
        ]);
        if (!empty($balance['grouped_enabled'])) {
            $rows[] = [];
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Financial Statement Group', $currentColumnLabel, $compareColumnLabel], 'header')
                : app_xlsx_row(['Financial Statement Group', 'Amount'], 'header');
            foreach ((array) ($balance['sections'] ?? []) as $sectionCode => $section) {
                $rows[] = $comparisonEnabled
                    ? app_xlsx_row([(string) ($section['label'] ?? ''), '', ''], 'header')
                    : app_xlsx_row([(string) ($section['label'] ?? ''), ''], 'header');
                foreach ((array) ($section['groups'] ?? []) as $groupCode => $group) {
                    $rows[] = $comparisonEnabled
                        ? [(string) ($group['name'] ?? ''), app_number($group['display_amount'] ?? 0), $statementSectionCompareAmount($compareBalance, (string) $sectionCode, (string) $groupCode)]
                        : [(string) ($group['name'] ?? ''), app_number($group['display_amount'] ?? 0)];
                }
                $rows[] = $comparisonEnabled
                    ? app_xlsx_row([(string) ($section['total_label'] ?? 'Total'), app_number($section['display_total'] ?? 0), $statementSectionCompareAmount($compareBalance, (string) $sectionCode)], 'total')
                    : app_xlsx_row([(string) ($section['total_label'] ?? 'Total'), app_number($section['display_total'] ?? 0)], 'total');
                $rows[] = [];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Assets', app_number($balance['total_assets'] ?? 0), app_number($compareBalance['total_assets'] ?? 0)], 'total')
                : app_xlsx_row(['Total Assets', app_number($balance['total_assets'] ?? 0)], 'total');
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Equity and Liabilities', app_number($balance['equity_and_liabilities'] ?? 0), app_number($compareBalance['equity_and_liabilities'] ?? 0)], 'total')
                : app_xlsx_row(['Total Equity and Liabilities', app_number($balance['equity_and_liabilities'] ?? 0)], 'total');
        } else {
            $compareAssetMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['assets'] ?? [])) : [];
            $compareLiabilityMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['liabilities'] ?? [])) : [];
            $compareEquityMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['equity'] ?? [])) : [];
            $rows = array_merge($rows, [
                [],
                app_xlsx_row(['Assets'], 'header'),
                $comparisonEnabled ? app_xlsx_row(['Code', 'Account', $currentColumnLabel, $compareColumnLabel], 'header') : app_xlsx_row(['Code', 'Account', 'Amount'], 'header'),
            ]);
            foreach ((array) ($balance['assets'] ?? []) as $row) {
                $code = (string) ($row['account_code'] ?? '');
                $rows[] = $comparisonEnabled
                    ? [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0), app_number($compareAssetMap[$code] ?? 0)]
                    : [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0)];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Assets', '', app_number($balance['total_assets'] ?? 0), app_number($compareBalance['total_assets'] ?? 0)], 'total')
                : app_xlsx_row(['Total Assets', '', app_number($balance['total_assets'] ?? 0)], 'total');
            $rows[] = [];
            $rows[] = app_xlsx_row(['Liabilities'], 'header');
            foreach ((array) ($balance['liabilities'] ?? []) as $row) {
                $code = (string) ($row['account_code'] ?? '');
                $rows[] = $comparisonEnabled
                    ? [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0), app_number($compareLiabilityMap[$code] ?? 0)]
                    : [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0)];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Liabilities', '', app_number($balance['total_liabilities'] ?? 0), app_number($compareBalance['total_liabilities'] ?? 0)], 'total')
                : app_xlsx_row(['Total Liabilities', '', app_number($balance['total_liabilities'] ?? 0)], 'total');
            $rows[] = [];
            $rows[] = app_xlsx_row(['Equity'], 'header');
            foreach ((array) ($balance['equity'] ?? []) as $row) {
                $code = (string) ($row['account_code'] ?? '');
                $rows[] = $comparisonEnabled
                    ? [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0), app_number($compareEquityMap[$code] ?? 0)]
                    : [$code, (string) ($row['account_name'] ?? ''), app_number($row['amount'] ?? 0)];
            }
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Total Equity', '', app_number($balance['total_equity'] ?? 0), app_number($compareBalance['total_equity'] ?? 0)], 'total')
                : app_xlsx_row(['Total Equity', '', app_number($balance['total_equity'] ?? 0)], 'total');
            $rows[] = $comparisonEnabled
                ? app_xlsx_row(['Liabilities + Equity', '', app_number($balance['equity_and_liabilities'] ?? 0), app_number($compareBalance['equity_and_liabilities'] ?? 0)], 'total')
                : app_xlsx_row(['Liabilities + Equity', '', app_number($balance['equity_and_liabilities'] ?? 0)], 'total');
        }
        $sheets[] = ['title' => 'Financial Position', 'rows' => $rows];
    } elseif ($activeReport === 'expected_credit_loss') {
        $country = (array) ($eclReport['country'] ?? []);
        $rows = array_merge($infoRows('Expected Credit Loss'), [
            ['As Of', $toDate],
            ['Country', (string) ($country['country_name'] ?? $eclCountryCode)],
            ['S&P Rating', (string) ($country['sp_rating'] ?? '')],
            ["Moody's Rating", (string) ($country['moodys_rating'] ?? '')],
            ['Fitch Rating', (string) ($country['fitch_rating'] ?? '')],
            [],
            app_xlsx_row(['Category', 'Expected loss rate %', 'Gross carrying amount ' . $toDate, 'Forward Looking ECL Allowance ' . $toDate], 'header'),
        ]);
        foreach ((array) ($eclReport['rows'] ?? []) as $row) {
            $rows[] = [
                (string) ($row['category_name'] ?? ''),
                app_number($row['loss_rate'] ?? 0) * 100,
                app_number($row['gross'] ?? 0),
                app_number($row['allowance'] ?? 0),
            ];
        }
        $totals = (array) ($eclReport['totals'] ?? []);
        $rows[] = app_xlsx_row([
            'Total',
            app_number($totals['loss_rate'] ?? 0) * 100,
            app_number($totals['gross'] ?? 0),
            app_number($totals['allowance'] ?? 0),
        ], 'total');

        $bucketRows = [];
        foreach ((array) ($eclReport['rows'] ?? []) as $row) {
            foreach ((array) (($row['details'] ?? [])['receivable_buckets'] ?? []) as $bucket) {
                $bucketRows[] = $bucket;
            }
        }
        if ($bucketRows) {
            $rows[] = [];
            $rows[] = app_xlsx_row(['Receivable Aging Detail'], 'header');
            $rows[] = app_xlsx_row(['Bucket', 'Loss Rate %', 'Gross', 'Allowance', 'Invoices'], 'header');
            foreach ($bucketRows as $bucket) {
                $rows[] = [
                    (string) ($bucket['bucket_name'] ?? ''),
                    app_number($bucket['loss_rate'] ?? 0) * 100,
                    app_number($bucket['gross'] ?? 0),
                    app_number($bucket['allowance'] ?? 0),
                    (int) ($bucket['invoice_count'] ?? 0),
                ];
            }
        }
        $sheets[] = ['title' => 'ECL Report', 'rows' => $rows];
    } elseif ($activeReport === 'cash_flow') {
        $rows = array_merge($infoRows('Cash Flow'), [
            ['Total Inflow', app_number($cashFlow['inflow'] ?? 0)],
            ['Total Outflow', app_number($cashFlow['outflow'] ?? 0)],
            ['Net Cash', app_number($cashFlow['net_cash'] ?? 0)],
            [],
            app_xlsx_row(['Direction', 'Method', 'Amount'], 'header'),
        ]);
        foreach ((array) ($cashFlow['breakdown'] ?? []) as $row) {
            $rows[] = [(string) ($row['direction'] ?? ''), (string) ($row['payment_method'] ?? ''), app_number($row['amount'] ?? 0)];
        }
        $sheets[] = ['title' => 'Cash Flow', 'rows' => $rows];
    }

    app_export_xlsx('accounting-' . $activeReport . '-' . date('Ymd-His') . '.xlsx', $sheets);
}

$statementMoney = static function (mixed $value): string {
    $amount = round(app_number($value), 2);
    if ($amount < -0.005) {
        return '(' . app_money_format(abs($amount)) . ')';
    }
    return app_money_format($amount);
};
$statementSectionCompareAmount = static function (?array $comparison, string $sectionCode, ?string $groupCode = null): float {
    if (!$comparison) {
        return 0.0;
    }
    $section = (array) (($comparison['sections'] ?? [])[$sectionCode] ?? []);
    if ($groupCode === null) {
        return app_number($section['display_total'] ?? 0);
    }
    return app_number(((array) (($section['groups'] ?? [])[$groupCode] ?? []))['display_amount'] ?? 0);
};
$statementRowsByCode = static function (array $rows): array {
    $map = [];
    foreach ($rows as $row) {
        $code = app_normalize_whitespace((string) ($row['account_code'] ?? ''));
        if ($code !== '') {
            $map[$code] = app_number($row['amount'] ?? 0);
        }
    }
    return $map;
};
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape(app_t((string) app_config('app_name'))) ?> - <?= app_escape(app_t('Accounting Reports')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<div class="app-shell has-sidebar">
  <?= app_sidebar_nav_html('accounting_reports', null, $companyId, $activeReport) ?>

  <header class="header">
    <div class="header-side right">
      <div class="header-title"><?= app_escape(app_t('Accounting Reports')) ?></div>
      <div class="header-subtitle"><?= app_escape($activeReportLabel) ?> &bull; <?= app_escape(app_t('Ledger, Journal Book, Cost Center, Trial Balance, Income Statement, Financial Position, ECL, and Cash Flow')) ?></div>
    </div>
    <div class="header-center">
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Logo" class="school-logo">
    </div>
    <div class="header-side left">
      <div class="header-title"><?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
      <div class="header-subtitle"><a href="index.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape(app_t('Dashboard')) ?></a> &bull; <a href="logout.php"><?= app_escape(app_t('Logout')) ?></a></div>
    </div>
  </header>

  <div class="date-bar">
    <div class="date-item"><?= app_escape(app_t('Date :')) ?> <span><?= app_escape(date('Y-m-d')) ?></span></div>
    <div class="date-item"><?= app_escape(app_t('Company :')) ?> <span><?= app_escape((string) ($company['name'] ?? 'N/A')) ?></span></div>
    <div class="date-author"><?= app_escape(app_t('Prepared by :')) ?> <?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
  </div>

  <?= app_back_button_html('Back') ?>

  <div class="container">
    <section class="panel screen-only context-switch-panel">
      <div class="section-heading">
        <h3>Report Filters</h3>
        <span>Select company, period, and account</span>
      </div>
      <form method="get" class="form-grid four">
        <input type="hidden" name="report" value="<?= app_escape($activeReport) ?>">
        <?php if (app_is_admin()): ?>
          <div class="field">
            <label for="company_id">Company</label>
            <select id="company_id" name="company_id" data-auto-submit>
              <?php foreach ($companies as $companyRow): ?>
                <option value="<?= (int) $companyRow['id'] ?>" <?= (int) $companyRow['id'] === (int) $companyId ? 'selected' : '' ?>>
                  <?= app_escape((string) $companyRow['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php else: ?>
          <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
        <?php endif; ?>

        <div class="field">
          <label for="from_date">From Date</label>
          <input id="from_date" name="from_date" type="date" value="<?= app_escape($fromDate) ?>">
        </div>

        <div class="field">
          <label for="to_date">To Date</label>
          <input id="to_date" name="to_date" type="date" value="<?= app_escape($toDate) ?>">
        </div>

        <?php if ($comparisonAllowed): ?>
          <div class="field">
            <label for="enable_comparison">Comparison Period</label>
            <select id="enable_comparison" name="enable_comparison">
              <option value="">No comparison</option>
              <option value="1" <?= $comparisonEnabled ? 'selected' : '' ?>>Show comparison</option>
            </select>
          </div>

          <div class="field">
            <label for="compare_from_date">Comparison From Date</label>
            <input id="compare_from_date" name="compare_from_date" type="date" value="<?= app_escape($compareFromDate) ?>">
          </div>

          <div class="field">
            <label for="compare_to_date">Comparison To Date</label>
            <input id="compare_to_date" name="compare_to_date" type="date" value="<?= app_escape($compareToDate) ?>">
          </div>
        <?php endif; ?>

        <?php if ($activeReport === 'expected_credit_loss'): ?>
          <div class="field">
            <label for="ecl_country_code">ECL Country</label>
            <select id="ecl_country_code" name="ecl_country_code">
              <?php foreach ($eclCountryOptions as $code => $label): ?>
                <option value="<?= app_escape((string) $code) ?>" <?= $eclCountryCode === (string) $code ? 'selected' : '' ?>>
                  <?= app_escape((string) $label) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="field-help">Used for country ratings, scenario weights, and forward-looking PD.</div>
          </div>
        <?php endif; ?>

        <div class="field">
          <label for="account_code">Ledger Account</label>
          <select id="account_code" name="account_code">
            <option value="">Choose account for statement</option>
            <?php foreach ($accountOptions as $code => $label): ?>
              <option value="<?= app_escape((string) $code) ?>" <?= $accountCode === (string) $code ? 'selected' : '' ?>>
                <?= app_escape((string) $label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label for="contact_code">Contact</label>
          <select id="contact_code" name="contact_code">
            <option value="">Choose contact for statement</option>
            <?php foreach ($contactOptions as $code => $label): ?>
              <option value="<?= app_escape((string) $code) ?>" <?= $contactCode === (string) $code ? 'selected' : '' ?>>
                <?= app_escape((string) $label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label for="cost_center_code">Cost Center</label>
          <select id="cost_center_code" name="cost_center_code">
            <option value="">All cost centers</option>
            <?php foreach ($costCenterOptions as $code => $label): ?>
              <option value="<?= app_escape((string) $code) ?>" <?= $costCenterCode === (string) $code ? 'selected' : '' ?>>
                <?= app_escape((string) $label) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="field-help">Used by Cost Center report when selected.</div>
        </div>

        <div class="field">
          <label style="display:flex;align-items:center;gap:8px;">
            <input type="checkbox" name="include_zero" value="1" <?= $includeZero ? 'checked' : '' ?>>
            Include zero-balance accounts
          </label>
        </div>

        <div class="form-actions">
          <button class="btn btn-primary" type="submit">Apply</button>
          <button class="btn btn-secondary" type="button" data-print-page>Print Report</button>
          <a class="btn btn-secondary" href="<?= app_escape($exportUrl) ?>">Export XLSX</a>
          <a class="btn btn-secondary" href="accounting_reports.php?report=<?= app_escape($activeReport) ?><?= $companyId ? '&company_id=' . (int) $companyId : '' ?>">Reset</a>
        </div>
      </form>
    </section>

    <main
      id="accountingReportPrintArea"
      class="print-scope"
      data-print-scope
      data-default-print-target
      data-report-print
      data-print-title="<?= app_escape($activeReportLabel) ?>"
      data-print-logo="<?= app_escape(app_logo_path_for_header($company)) ?>"
    >
    <?php if ($activeReport === 'ledger'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Account Statement (Ledger)</h3>
          <div class="hint"><?= $ledger['account'] ? app_escape((string) ($ledger['account']['account_code'] ?? '') . ' - ' . (string) ($ledger['account']['account_name'] ?? '')) : 'Choose an account from filters above' ?></div>
        </div>
      </div>
      <?php if (!$ledger['account']): ?>
        <div class="empty-state">Select a ledger account to display detailed account statement.</div>
      <?php elseif (!$ledger['rows']): ?>
        <div class="empty-state">No posted transactions for this account in the selected period.</div>
      <?php else: ?>
        <div class="panel" style="margin-bottom:12px;">
          <div class="form-grid four">
            <div class="field"><label>Opening Balance</label><input type="text" readonly value="<?= app_escape(app_signed_balance_label(app_number($ledger['opening_signed'] ?? 0))) ?>"></div>
            <div class="field"><label>Total Debit</label><input type="text" readonly value="<?= app_escape(app_money_format($ledger['totals']['debit'] ?? 0)) ?>"></div>
            <div class="field"><label>Total Credit</label><input type="text" readonly value="<?= app_escape(app_money_format($ledger['totals']['credit'] ?? 0)) ?>"></div>
            <div class="field"><label>Closing Balance</label><input type="text" readonly value="<?= app_escape(app_signed_balance_label(app_number($ledger['closing_signed'] ?? 0))) ?>"></div>
          </div>
        </div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 980px;">
            <thead>
              <tr>
                <th>Date</th>
                <th>Entry No.</th>
                <th>Reference</th>
                <th>Description</th>
                <th>Debit</th>
                <th>Credit</th>
                <th>Running Balance</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($ledger['rows'] ?? []) as $row): ?>
                <tr>
                  <td><?= app_escape(app_date_format((string) ($row['entry_date'] ?? ''))) ?></td>
                  <td><?= app_escape((string) ($row['entry_number'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['reference'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['description'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['credit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_signed_balance_label(app_number($row['running_signed'] ?? 0))) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'contact_statement'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Contact Statement</h3>
          <div class="hint"><?= $contactStatement['contact'] ? app_escape((string) ($contactStatement['contact']['contact_code'] ?? '') . ' - ' . (string) ($contactStatement['contact']['contact_name'] ?? '')) : 'Choose contact for statement' ?></div>
        </div>
      </div>
      <?php if (!$contactStatement['contact']): ?>
        <div class="empty-state">Select a contact to display detailed statement.</div>
      <?php elseif (!$contactStatement['rows']): ?>
        <div class="empty-state">No transactions for this contact in the selected period.</div>
      <?php else: ?>
        <div class="panel" style="margin-bottom:12px;">
          <div class="form-grid four">
            <div class="field"><label>Opening Balance</label><input type="text" readonly value="<?= app_escape(app_signed_balance_label(app_number($contactStatement['opening_signed'] ?? 0))) ?>"></div>
            <div class="field"><label>Total Debit</label><input type="text" readonly value="<?= app_escape(app_money_format($contactStatement['totals']['debit'] ?? 0)) ?>"></div>
            <div class="field"><label>Total Credit</label><input type="text" readonly value="<?= app_escape(app_money_format($contactStatement['totals']['credit'] ?? 0)) ?>"></div>
            <div class="field"><label>Closing Balance</label><input type="text" readonly value="<?= app_escape(app_signed_balance_label(app_number($contactStatement['closing_signed'] ?? 0))) ?>"></div>
          </div>
        </div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 1080px;">
            <thead>
              <tr>
                <th>Date</th>
                <th>Type</th>
                <th>Reference</th>
                <th>Description</th>
                <th>Debit</th>
                <th>Credit</th>
                <th>Running Balance</th>
                <th class="print-hide">Source</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($contactStatement['rows'] ?? []) as $row): ?>
                <tr>
                  <td><?= app_escape(app_date_format((string) ($row['date'] ?? ''))) ?></td>
                  <td><?= app_escape((string) ($row['type'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['reference'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['description'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['credit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_signed_balance_label(app_number($row['running_signed'] ?? 0))) ?></td>
                  <td class="print-hide">
                    <?php if (!empty($row['source_url'])): ?>
                      <a class="icon-btn" href="<?= app_escape((string) $row['source_url']) ?>">Open</a>
                    <?php else: ?>
                      <span class="muted">N/A</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'journal_book'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Journal Book</h3>
          <div class="hint">Detailed posted journal lines by account name, description, debit, and credit.</div>
        </div>
      </div>
      <?php if (!(array) ($journalBook['rows'] ?? [])): ?>
        <div class="empty-state">No posted journal lines for the selected period.</div>
      <?php else: ?>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 1220px;">
            <thead>
              <tr>
                <th>Date</th>
                <th>Entry No.</th>
                <th>Line</th>
                <th>Account Code</th>
                <th>Account Name</th>
                <th>Cost Center</th>
                <th>Description</th>
                <th>Debit</th>
                <th>Credit</th>
                <th class="print-hide">Source</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($journalBook['rows'] ?? []) as $row): ?>
                <tr>
                  <td><?= app_escape(app_date_format((string) ($row['entry_date'] ?? ''))) ?></td>
                  <td><?= app_escape((string) ($row['entry_number'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['line_no'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['account_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td>
                    <?php
                      $journalCenterCode = app_normalize_whitespace((string) ($row['cost_center_code'] ?? ''));
                      $journalCenterName = app_normalize_whitespace((string) ($row['cost_center_name'] ?? ''));
                      $journalCenterLabel = $journalCenterCode !== ''
                          ? ($journalCenterCode . ($journalCenterName !== '' && $journalCenterName !== $journalCenterCode ? (' - ' . $journalCenterName) : ''))
                          : 'N/A';
                    ?>
                    <?= app_escape($journalCenterLabel) ?>
                  </td>
                  <td><?= app_escape((string) ($row['description'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['credit'] ?? 0)) ?></td>
                  <td class="print-hide">
                    <?php if (!empty($row['source_url'])): ?>
                      <a class="icon-btn" href="<?= app_escape((string) $row['source_url']) ?>">Open <?= app_escape((string) ($row['source_label'] ?? 'Source')) ?></a>
                    <?php else: ?>
                      <span class="muted"><?= app_escape((string) ($row['source_label'] ?? 'Manual')) ?></span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="7">Totals</th>
                <th><?= app_escape(app_money_format($journalBook['totals']['debit'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($journalBook['totals']['credit'] ?? 0)) ?></th>
                <th class="print-hide"></th>
              </tr>
            </tfoot>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'cost_center'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Cost Center Report</h3>
          <div class="hint">
            Revenue and expense journal lines grouped by cost center for posted entries.
          </div>
        </div>
      </div>

      <div class="panel" style="margin-bottom:12px;">
        <div class="form-grid four">
          <div class="field"><label>From</label><input type="text" readonly value="<?= app_escape((string) ($costCenterReport['from_date'] ?? $fromDate)) ?>"></div>
          <div class="field"><label>To</label><input type="text" readonly value="<?= app_escape((string) ($costCenterReport['to_date'] ?? $toDate)) ?>"></div>
          <div class="field"><label>Total Debit</label><input type="text" readonly value="<?= app_escape(app_money_format($costCenterReport['totals']['debit'] ?? 0)) ?>"></div>
          <div class="field"><label>Total Credit</label><input type="text" readonly value="<?= app_escape(app_money_format($costCenterReport['totals']['credit'] ?? 0)) ?>"></div>
        </div>
      </div>

      <?php if (!(array) ($costCenterReport['summary'] ?? [])): ?>
        <div class="empty-state">No cost center activity for the selected period.</div>
      <?php else: ?>
        <div class="table-wrap" style="margin-bottom: 14px;">
          <table class="data-table" style="min-width: 980px;">
            <thead>
              <tr>
                <th>Cost Center</th>
                <th>Total Debit</th>
                <th>Total Credit</th>
                <th>Net</th>
                <th>Lines</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($costCenterReport['summary'] ?? []) as $summaryRow): ?>
                <?php
                  $summaryCenterCode = app_normalize_whitespace((string) ($summaryRow['cost_center_code'] ?? ''));
                  $summaryCenterName = app_normalize_whitespace((string) ($summaryRow['cost_center_name'] ?? ''));
                  $summaryCenterLabel = $summaryCenterCode !== ''
                      ? ($summaryCenterCode . ($summaryCenterName !== '' && $summaryCenterName !== $summaryCenterCode ? (' - ' . $summaryCenterName) : ''))
                      : 'N/A';
                ?>
                <tr>
                  <td><?= app_escape($summaryCenterLabel) ?></td>
                  <td><?= app_escape(app_money_format($summaryRow['total_debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($summaryRow['total_credit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($summaryRow['net'] ?? 0)) ?></td>
                  <td><?= app_escape(number_format((int) ($summaryRow['lines_count'] ?? 0))) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

      <div class="table-header" style="padding: 0 0 10px;">
        <div>
          <h3 style="font-size: 1rem; margin: 0;">Detailed Lines</h3>
        </div>
      </div>
      <?php if (!(array) ($costCenterReport['lines'] ?? [])): ?>
        <div class="empty-state">No detailed lines for the selected cost center filter.</div>
      <?php else: ?>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 1320px;">
            <thead>
              <tr>
                <th>Date</th>
                <th>Entry No.</th>
                <th>Line</th>
                <th>Cost Center</th>
                <th>Account</th>
                <th>Description</th>
                <th>Debit</th>
                <th>Credit</th>
                <th class="print-hide">Source</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($costCenterReport['lines'] ?? []) as $line): ?>
                <?php
                  $detailCenterCode = app_normalize_whitespace((string) ($line['cost_center_code'] ?? ''));
                  $detailCenterName = app_normalize_whitespace((string) ($line['cost_center_name'] ?? ''));
                  $detailCenterLabel = $detailCenterCode !== ''
                      ? ($detailCenterCode . ($detailCenterName !== '' && $detailCenterName !== $detailCenterCode ? (' - ' . $detailCenterName) : ''))
                      : 'N/A';
                  $accountLabel = app_normalize_whitespace((string) ($line['account_code'] ?? ''));
                  $accountName = app_normalize_whitespace((string) ($line['account_name'] ?? ''));
                  if ($accountName !== '' && $accountName !== $accountLabel) {
                      $accountLabel .= ' - ' . $accountName;
                  }
                ?>
                <tr>
                  <td><?= app_escape(app_date_format((string) ($line['entry_date'] ?? ''))) ?></td>
                  <td><?= app_escape((string) ($line['entry_number'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($line['line_no'] ?? '')) ?></td>
                  <td><?= app_escape($detailCenterLabel) ?></td>
                  <td><?= app_escape($accountLabel) ?></td>
                  <td><?= app_escape((string) ($line['description'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($line['debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($line['credit'] ?? 0)) ?></td>
                  <td class="print-hide">
                    <?php if (!empty($line['source_url'])): ?>
                      <a class="icon-btn" href="<?= app_escape((string) $line['source_url']) ?>">Open <?= app_escape((string) ($line['source_label'] ?? 'Source')) ?></a>
                    <?php else: ?>
                      <span class="muted"><?= app_escape((string) ($line['source_label'] ?? 'Manual')) ?></span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'vat_summary'): ?>
    <section class="table-card" style="padding:0; overflow:hidden;">
      <div class="table-wrap">
        <table class="data-table" dir="rtl" style="min-width:920px; width:100%; border-collapse:collapse; font-size:18px; color:#000; background:#fff;">
          <thead>
            <tr>
              <th colspan="4" style="background:#17677f; color:#fff; border:1px solid #111; text-align:center; font-size:18px; font-weight:800; padding:8px 10px;">
                ملخص ض.ق.م (<?= app_escape((string) ($company['legal_name'] ?? $company['name'] ?? 'N/A')) ?>) للفترة من <?= app_escape($fromDate) ?> إلى <?= app_escape($toDate) ?>
              </th>
            </tr>
            <tr>
              <th colspan="4" style="background:#fff; color:#000; border:1px solid #111; text-align:center; font-size:22px; font-weight:800; padding:8px 10px;">
                <?= app_escape(app_normalize_whitespace((string) ($company['vat_number'] ?? '')) !== '' ? (string) $company['vat_number'] : 'N/A') ?>
              </th>
            </tr>
            <tr>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">ضريبة القيمة المضافة على المبيعات</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">المبلغ</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">التعديل</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">مبلغ ضريبة القيمة المضافة</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style="border:1px solid #111; text-align:center; font-weight:700;">المبيعات الخاضعة للنسبة الأساسية (15%)</td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_taxable']['base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_taxable']['return_base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_taxable']['tax'] ?? 0)) ?></td>
            </tr>
            <tr>
              <td style="border:1px solid #111; text-align:center; font-weight:700;">المبيعات التي تتحمل الدولة ضريبتها</td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_exempt']['base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_exempt']['return_base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['sales_exempt']['tax'] ?? 0)) ?></td>
            </tr>
            <tr>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">الإجمالي</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['sales_total']['base'] ?? 0)) ?></th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['sales_total']['return_base'] ?? 0)) ?></th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['sales_total']['tax'] ?? 0)) ?></th>
            </tr>
            <tr>
              <td colspan="4" style="height:32px; border:1px solid #111; background:#fff;"></td>
            </tr>
            <tr>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">البيان</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">الإجمالي قبل الضريبة</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">التعديل</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">الضريبة</th>
            </tr>
            <tr>
              <td style="border:1px solid #111; text-align:center; font-weight:700;">المشتريات الخاضعة للنسبة الأساسية (15%)</td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['purchase_taxable']['base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['purchase_taxable']['return_base'] ?? 0)) ?></td>
              <td style="border:1px solid #111; text-align:center; font-weight:700;"><?= app_escape(app_money_format($vatSummary['purchase_taxable']['tax'] ?? 0)) ?></td>
            </tr>
            <tr>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">الإجمالي</th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['purchase_total']['base'] ?? 0)) ?></th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['purchase_total']['return_base'] ?? 0)) ?></th>
              <th style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['purchase_total']['tax'] ?? 0)) ?></th>
            </tr>
            <tr>
              <td colspan="4" style="height:32px; border:1px solid #111; background:#fff; text-align:right; font-weight:800;">الملخص:</td>
            </tr>
            <tr>
              <th colspan="2" style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">البيان</th>
              <th colspan="2" style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">الإجمالي قبل الضريبة</th>
            </tr>
            <tr>
              <td colspan="2" style="border:1px solid #111; text-align:center; font-weight:700;">إجمالي ضريبة القيمة المضافة المستحقة للفترة الحالية</td>
              <td colspan="2" style="border:1px solid #111; text-align:center; font-weight:800;"><?= app_escape(app_money_format($vatSummary['summary']['current_period_vat'] ?? 0)) ?></td>
            </tr>
            <tr>
              <td colspan="2" style="border:1px solid #111; text-align:center; font-weight:700;">ضريبة القيمة المضافة التي تم ترحيلها من فترات سابقة</td>
              <td colspan="2" style="border:1px solid #111; text-align:center; font-weight:800;"><?= app_escape(app_money_format($vatSummary['summary']['carried_forward_vat'] ?? 0)) ?></td>
            </tr>
            <tr>
              <th colspan="2" style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;">صافي الضريبة المستحقة أو المستعادة</th>
              <th colspan="2" style="background:#17677f; color:#fff; border:1px solid #111; text-align:center;"><?= app_escape(app_money_format($vatSummary['summary']['net_due_or_recoverable'] ?? 0)) ?></th>
            </tr>
          </tbody>
        </table>
      </div>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'trial_balance'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Trial Balance</h3>
          <div class="hint">Debit and credit totals must match for posted entries.</div>
        </div>
      </div>
      <?php if (!(array) ($trial['rows'] ?? [])): ?>
        <div class="empty-state">No trial balance data for the selected period.</div>
      <?php else: ?>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 1220px;">
            <thead>
              <tr>
                <th>Account Code</th>
                <th>Account Name</th>
                <th>Type</th>
                <th>Opening Dr</th>
                <th>Opening Cr</th>
                <th>Period Dr</th>
                <th>Period Cr</th>
                <th>Closing Dr</th>
                <th>Closing Cr</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($trial['rows'] ?? []) as $row): ?>
                <tr>
                  <td><?= app_escape((string) ($row['account_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(ucfirst((string) ($row['account_type'] ?? ''))) ?></td>
                  <td><?= app_escape(app_money_format($row['opening_dr'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['opening_cr'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['period_debit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['period_credit'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['closing_dr'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['closing_cr'] ?? 0)) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="3">Totals</th>
                <th><?= app_escape(app_money_format($trial['totals']['opening_dr'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($trial['totals']['opening_cr'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($trial['totals']['period_debit'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($trial['totals']['period_credit'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($trial['totals']['closing_dr'] ?? 0)) ?></th>
                <th><?= app_escape(app_money_format($trial['totals']['closing_cr'] ?? 0)) ?></th>
              </tr>
            </tfoot>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'income_statement'): ?>
    <section class="panel">
      <div class="section-heading">
        <h3>Income Statement</h3>
        <span>
          <?= app_escape(app_t('Period:')) ?> <?= app_escape($fromDate) ?> <?= app_escape(app_t('to')) ?> <?= app_escape($toDate) ?>
          <?php if ($comparisonEnabled): ?>
            | <?= app_escape(app_t('Comparison:')) ?> <?= app_escape($compareFromDate) ?> <?= app_escape(app_t('to')) ?> <?= app_escape($compareToDate) ?>
          <?php endif; ?>
        </span>
      </div>
      <?php if (!empty($income['grouped_enabled'])): ?>
        <div class="table-wrap">
          <table class="data-table financial-statement-table" style="min-width: 720px;">
            <thead>
              <tr>
                <th>Financial Statement Group</th>
                <th class="amount-col"><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th class="amount-col"><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($income['sections'] ?? []) as $sectionCode => $section): ?>
                <tr class="statement-section-row">
                  <td colspan="<?= $comparisonEnabled ? 3 : 2 ?>"><?= app_escape((string) ($section['label'] ?? '')) ?></td>
                </tr>
                <?php foreach ((array) ($section['groups'] ?? []) as $groupCode => $group): ?>
                  <tr>
                    <td><?= app_escape((string) ($group['name'] ?? '')) ?></td>
                    <td class="amount-col"><?= app_escape($statementMoney($group['display_amount'] ?? 0)) ?></td>
                    <?php if ($comparisonEnabled): ?>
                      <td class="amount-col"><?= app_escape($statementMoney($statementSectionCompareAmount($compareIncome, (string) $sectionCode, (string) $groupCode))) ?></td>
                    <?php endif; ?>
                  </tr>
                <?php endforeach; ?>
                <tr class="statement-total-row">
                  <td><?= app_escape((string) ($section['total_label'] ?? 'Total')) ?></td>
                  <td class="amount-col"><?= app_escape($statementMoney($section['display_total'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td class="amount-col"><?= app_escape($statementMoney($statementSectionCompareAmount($compareIncome, (string) $sectionCode))) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th>Net Income</th>
                <th class="amount-col"><?= app_escape($statementMoney($income['net_income'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th class="amount-col"><?= app_escape($statementMoney($compareIncome['net_income'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
        <?php if (!empty($income['has_unmapped'])): ?>
          <div class="empty-state" style="margin-top:12px;">Some accounts are not mapped to a financial statement group yet and are shown under Unmapped Accounts.</div>
        <?php endif; ?>
      <?php else: ?>
      <?php
        $compareRevenueMap = $comparisonEnabled && $compareIncome ? $statementRowsByCode((array) ($compareIncome['revenues'] ?? [])) : [];
        $compareExpenseMap = $comparisonEnabled && $compareIncome ? $statementRowsByCode((array) ($compareIncome['expenses'] ?? [])) : [];
      ?>
      <div class="form-grid two">
        <div class="table-wrap">
          <table class="data-table" style="min-width: 520px;">
            <thead>
              <tr>
                <th colspan="<?= $comparisonEnabled ? 4 : 3 ?>">Revenue</th>
              </tr>
              <tr>
                <th>Code</th>
                <th>Account</th>
                <th><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($income['revenues'] ?? []) as $row): ?>
                <?php $code = (string) ($row['account_code'] ?? ''); ?>
                <tr>
                  <td><?= app_escape($code) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td><?= app_escape(app_money_format($compareRevenueMap[$code] ?? 0)) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="2">Total Revenue</th>
                <th><?= app_escape(app_money_format($income['total_revenue'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape(app_money_format($compareIncome['total_revenue'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 520px;">
            <thead>
              <tr>
                <th colspan="<?= $comparisonEnabled ? 4 : 3 ?>">Expenses</th>
              </tr>
              <tr>
                <th>Code</th>
                <th>Account</th>
                <th><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($income['expenses'] ?? []) as $row): ?>
                <?php $code = (string) ($row['account_code'] ?? ''); ?>
                <tr>
                  <td><?= app_escape($code) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td><?= app_escape(app_money_format($compareExpenseMap[$code] ?? 0)) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="2">Total Expense</th>
                <th><?= app_escape(app_money_format($income['total_expense'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape(app_money_format($compareIncome['total_expense'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
      <div class="panel" style="margin-top: 12px;">
        <div class="form-grid four">
          <div class="field"><label>Total Revenue</label><input type="text" readonly value="<?= app_escape(app_money_format($income['total_revenue'] ?? 0)) ?>"></div>
          <div class="field"><label>Total Expense</label><input type="text" readonly value="<?= app_escape(app_money_format($income['total_expense'] ?? 0)) ?>"></div>
          <div class="field"><label>Net Income</label><input type="text" readonly value="<?= app_escape(app_money_format($income['net_income'] ?? 0)) ?>"></div>
          <div class="field"><label>Cash Net Change</label><input type="text" readonly value="<?= app_escape(app_money_format($cashFlow['net_cash'] ?? 0)) ?>"></div>
        </div>
      </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'balance_sheet'): ?>
    <section class="panel">
      <div class="section-heading">
        <h3>Statement of Financial Position</h3>
        <span>
          <?= app_escape(app_t('As of')) ?> <?= app_escape((string) ($balance['as_of_date'] ?? $toDate)) ?>
          <?php if ($comparisonEnabled): ?>
            | <?= app_escape(app_t('Comparison as of')) ?> <?= app_escape($compareToDate) ?>
          <?php endif; ?>
        </span>
      </div>
      <?php if (!empty($balance['grouped_enabled'])): ?>
        <div class="table-wrap">
          <table class="data-table financial-statement-table" style="min-width: 760px;">
            <thead>
              <tr>
                <th>Financial Statement Group</th>
                <th class="amount-col"><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th class="amount-col"><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($balance['sections'] ?? []) as $sectionCode => $section): ?>
                <tr class="statement-section-row">
                  <td colspan="<?= $comparisonEnabled ? 3 : 2 ?>"><?= app_escape((string) ($section['label'] ?? '')) ?></td>
                </tr>
                <?php foreach ((array) ($section['groups'] ?? []) as $groupCode => $group): ?>
                  <tr>
                    <td><?= app_escape((string) ($group['name'] ?? '')) ?></td>
                    <td class="amount-col"><?= app_escape($statementMoney($group['display_amount'] ?? 0)) ?></td>
                    <?php if ($comparisonEnabled): ?>
                      <td class="amount-col"><?= app_escape($statementMoney($statementSectionCompareAmount($compareBalance, (string) $sectionCode, (string) $groupCode))) ?></td>
                    <?php endif; ?>
                  </tr>
                <?php endforeach; ?>
                <tr class="statement-total-row">
                  <td><?= app_escape((string) ($section['total_label'] ?? 'Total')) ?></td>
                  <td class="amount-col"><?= app_escape($statementMoney($section['display_total'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td class="amount-col"><?= app_escape($statementMoney($statementSectionCompareAmount($compareBalance, (string) $sectionCode))) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th>Total Assets</th>
                <th class="amount-col"><?= app_escape($statementMoney($balance['total_assets'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th class="amount-col"><?= app_escape($statementMoney($compareBalance['total_assets'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
              <tr>
                <th>Total Equity and Liabilities</th>
                <th class="amount-col"><?= app_escape($statementMoney($balance['equity_and_liabilities'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th class="amount-col"><?= app_escape($statementMoney($compareBalance['equity_and_liabilities'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
        <?php if (!empty($balance['has_unmapped'])): ?>
          <div class="empty-state" style="margin-top:12px;">Some accounts are not mapped to a financial statement group yet and are shown under Unmapped Accounts.</div>
        <?php endif; ?>
      <?php else: ?>
      <?php
        $compareAssetMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['assets'] ?? [])) : [];
        $compareLiabilityMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['liabilities'] ?? [])) : [];
        $compareEquityMap = $comparisonEnabled && $compareBalance ? $statementRowsByCode((array) ($compareBalance['equity'] ?? [])) : [];
      ?>
      <div class="form-grid two">
        <div class="table-wrap">
          <table class="data-table" style="min-width: 520px;">
            <thead>
              <tr>
                <th colspan="<?= $comparisonEnabled ? 4 : 3 ?>">Assets</th>
              </tr>
              <tr>
                <th>Code</th>
                <th>Account</th>
                <th><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($balance['assets'] ?? []) as $row): ?>
                <?php $code = (string) ($row['account_code'] ?? ''); ?>
                <tr>
                  <td><?= app_escape($code) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td><?= app_escape(app_money_format($compareAssetMap[$code] ?? 0)) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="2">Total Assets</th>
                <th><?= app_escape(app_money_format($balance['total_assets'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape(app_money_format($compareBalance['total_assets'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 520px;">
            <thead>
              <tr>
                <th colspan="<?= $comparisonEnabled ? 4 : 3 ?>">Liabilities and Equity</th>
              </tr>
              <tr>
                <th>Code</th>
                <th>Account</th>
                <th><?= app_escape($comparisonEnabled ? $currentColumnLabel : 'Amount') ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape($compareColumnLabel) ?></th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($balance['liabilities'] ?? []) as $row): ?>
                <?php $code = (string) ($row['account_code'] ?? ''); ?>
                <tr>
                  <td><?= app_escape($code) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td><?= app_escape(app_money_format($compareLiabilityMap[$code] ?? 0)) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
              <tr>
                <td colspan="2"><strong>Total Liabilities</strong></td>
                <td><strong><?= app_escape(app_money_format($balance['total_liabilities'] ?? 0)) ?></strong></td>
                <?php if ($comparisonEnabled): ?>
                  <td><strong><?= app_escape(app_money_format($compareBalance['total_liabilities'] ?? 0)) ?></strong></td>
                <?php endif; ?>
              </tr>
              <?php foreach ((array) ($balance['equity'] ?? []) as $row): ?>
                <?php $code = (string) ($row['account_code'] ?? ''); ?>
                <tr>
                  <td><?= app_escape($code) ?></td>
                  <td><?= app_escape((string) ($row['account_name'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <?php if ($comparisonEnabled): ?>
                    <td><?= app_escape(app_money_format($compareEquityMap[$code] ?? 0)) ?></td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th colspan="2">Total Equity</th>
                <th><?= app_escape(app_money_format($balance['total_equity'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape(app_money_format($compareBalance['total_equity'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
              <tr>
                <th colspan="2">Liabilities + Equity</th>
                <th><?= app_escape(app_money_format($balance['equity_and_liabilities'] ?? 0)) ?></th>
                <?php if ($comparisonEnabled): ?>
                  <th><?= app_escape(app_money_format($compareBalance['equity_and_liabilities'] ?? 0)) ?></th>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'expected_credit_loss'): ?>
    <?php
      $eclTotals = (array) ($eclReport['totals'] ?? []);
      $eclCountry = (array) ($eclReport['country'] ?? []);
      $eclPeriodLabel = 'Q' . (int) ceil(((int) date('n', strtotime($toDate))) / 3) . ' ' . date('Y', strtotime($toDate));
    ?>
    <section class="panel">
      <div class="section-heading">
        <h3>Expected Credit Loss</h3>
        <span>
          <?= app_escape(app_t('As of')) ?> <?= app_escape($toDate) ?> &bull;
          <?= app_escape((string) ($eclCountry['country_name'] ?? $eclCountryCode)) ?>
          <?php if (!empty($eclCountry)): ?>
            &bull; S&amp;P <?= app_escape((string) ($eclCountry['sp_rating'] ?? '')) ?>,
            Moody's <?= app_escape((string) ($eclCountry['moodys_rating'] ?? '')) ?>,
            Fitch <?= app_escape((string) ($eclCountry['fitch_rating'] ?? '')) ?>
          <?php endif; ?>
        </span>
      </div>
      <?php if (!(array) ($eclReport['rows'] ?? [])): ?>
        <div class="empty-state">No ECL report categories are configured yet.</div>
      <?php else: ?>
        <div class="table-wrap">
          <table class="data-table ecl-report-table" style="min-width: 840px;">
            <thead>
              <tr>
                <th>Category</th>
                <th class="amount-col">Expected loss rate</th>
                <th class="amount-col">Gross carrying amount <?= app_escape($eclPeriodLabel) ?></th>
                <th class="amount-col"><?= app_escape(app_t('Forward Looking ECL Allowance')) ?> <?= app_escape($eclPeriodLabel) ?></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($eclReport['rows'] ?? []) as $row): ?>
                <tr>
                  <td>
                    <?= app_escape((string) ($row['category_name'] ?? '')) ?>
                    <?php $message = app_normalize_whitespace((string) (($row['rate_meta'] ?? [])['message'] ?? '')); ?>
                    <?php if ($message !== '' && app_number($row['gross'] ?? 0) > 0): ?>
                      <div class="field-help"><?= app_escape($message) ?></div>
                    <?php endif; ?>
                  </td>
                  <td class="amount-col"><?= app_escape(number_format(app_number($row['loss_rate'] ?? 0) * 100, 2)) ?>%</td>
                  <td class="amount-col"><?= app_escape($statementMoney($row['gross'] ?? 0)) ?></td>
                  <td class="amount-col"><?= app_escape($statementMoney($row['allowance'] ?? 0)) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <th>Total</th>
                <th class="amount-col"><?= app_escape(number_format(app_number($eclTotals['loss_rate'] ?? 0) * 100, 2)) ?>%</th>
                <th class="amount-col"><?= app_escape($statementMoney($eclTotals['gross'] ?? 0)) ?></th>
                <th class="amount-col"><?= app_escape($statementMoney($eclTotals['allowance'] ?? 0)) ?></th>
              </tr>
            </tfoot>
          </table>
        </div>

        <?php
          $eclBucketRows = [];
          foreach ((array) ($eclReport['rows'] ?? []) as $row) {
              foreach ((array) (($row['details'] ?? [])['receivable_buckets'] ?? []) as $bucket) {
                  $eclBucketRows[] = $bucket;
              }
          }
        ?>
        <?php if ($eclBucketRows): ?>
          <div class="table-wrap" style="margin-top:14px;">
            <table class="data-table" style="min-width: 760px;">
              <thead>
                <tr>
                  <th>Receivable Aging Bucket</th>
                  <th class="amount-col">Loss Rate</th>
                  <th class="amount-col">Gross</th>
                  <th class="amount-col">Allowance</th>
                  <th class="amount-col">Invoices</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($eclBucketRows as $bucket): ?>
                  <tr>
                    <td><?= app_escape((string) ($bucket['bucket_name'] ?? '')) ?></td>
                    <td class="amount-col"><?= app_escape(number_format(app_number($bucket['loss_rate'] ?? 0) * 100, 2)) ?>%</td>
                    <td class="amount-col"><?= app_escape($statementMoney($bucket['gross'] ?? 0)) ?></td>
                    <td class="amount-col"><?= app_escape($statementMoney($bucket['allowance'] ?? 0)) ?></td>
                    <td class="amount-col"><?= app_escape(number_format((int) ($bucket['invoice_count'] ?? 0))) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    <?php if ($activeReport === 'cash_flow'): ?>
    <section class="table-card">
      <div class="table-header">
        <div>
          <h3>Cash Flow Snapshot (From Payments)</h3>
          <div class="hint"><?= app_escape(app_t('Period:')) ?> <?= app_escape($fromDate) ?> <?= app_escape(app_t('to')) ?> <?= app_escape($toDate) ?></div>
        </div>
      </div>
      <div class="panel" style="margin-bottom:12px;">
        <div class="form-grid four">
          <div class="field"><label>Total Inflow</label><input type="text" readonly value="<?= app_escape(app_money_format($cashFlow['inflow'] ?? 0)) ?>"></div>
          <div class="field"><label>Total Outflow</label><input type="text" readonly value="<?= app_escape(app_money_format($cashFlow['outflow'] ?? 0)) ?>"></div>
          <div class="field"><label>Net Cash</label><input type="text" readonly value="<?= app_escape(app_money_format($cashFlow['net_cash'] ?? 0)) ?>"></div>
          <div class="field"><label>Entries</label><input type="text" readonly value="<?= app_escape(number_format(count((array) ($cashFlow['breakdown'] ?? [])))) ?>"></div>
        </div>
      </div>
      <?php if (!(array) ($cashFlow['breakdown'] ?? [])): ?>
        <div class="empty-state">No payment activity for selected period.</div>
      <?php else: ?>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 760px;">
            <thead>
              <tr>
                <th>Direction</th>
                <th>Method</th>
                <th>Amount</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ((array) ($cashFlow['breakdown'] ?? []) as $row): ?>
                <tr>
                  <td><?= app_escape(strtoupper((string) ($row['direction'] ?? ''))) ?></td>
                  <td><?= app_escape((string) ($row['payment_method'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </section>
    <?php endif; ?>

    </main>

    <div class="footer">
      <?= app_escape((string) app_config('app_name')) ?> &bull; <?= app_escape(app_t('Accounting Reports')) ?>
    </div>
  </div>

  <button id="floatingPrintBtn" class="floating-print-btn screen-only" type="button">Print</button>
</div>
<script src="assets/app.js"></script>
</body>
</html>


