<?php
class FinancialStatementsController extends Controller
{
    public function indexAction()
    {
        // Landing page: link into all three statements.
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialStatements/index', [
            'page_title' => 'Financial Statements',
        ]);
    }

    public function trialBalanceAction()
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new FinancialStatements();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialStatements/trial_balance', [
            'page_title' => 'Trial Balance',
            'as_at'      => $asAt,
            'rows'       => $m->trialBalance($asAt),
        ]);
    }

    public function balanceSheetAction()
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new FinancialStatements();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialStatements/balance_sheet', [
            'page_title' => 'Balance Sheet',
            'as_at'      => $asAt,
            'bs'         => $m->balanceSheet($asAt),
        ]);
    }

    public function profitAndLossAction()
    {
        $from = (string)($_GET['from'] ?? date('Y-01-01'));
        $to   = (string)($_GET['to']   ?? date('Y-m-d'));
        $m    = new FinancialStatements();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialStatements/profit_and_loss', [
            'page_title' => 'Profit &amp; Loss',
            'from'       => $from,
            'to'         => $to,
            'pnl'        => $m->profitAndLoss($from, $to),
        ]);
    }

    /* ── Trial Balance exports ─────────────────────────────────────────── */

    public function trialBalanceXlsxAction()   { $this->exportTrialBalance('xlsx'); }
    public function trialBalancePdfAction()    { $this->exportTrialBalance('pdf'); }

    private function exportTrialBalance(string $format): void
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $rows = (new FinancialStatements())->trialBalance($asAt);
        $data = []; $sumD = 0; $sumC = 0;
        foreach ($rows as $r) {
            $data[] = [$r['account_code'], $r['account_name'], strtolower($r['account_type']),
                       (float)$r['total_debit'], (float)$r['total_credit'], (float)$r['balance']];
            $sumD += (float)$r['total_debit']; $sumC += (float)$r['total_credit'];
        }
        $columns = [
            ['label' => 'Code',    'width' => 12, 'align' => 'L'],
            ['label' => 'Account', 'width' => 40, 'align' => 'L'],
            ['label' => 'Type',    'width' => 14, 'align' => 'L'],
            ['label' => 'Debit',   'width' => 20, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Credit',  'width' => 20, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Balance', 'width' => 20, 'align' => 'R', 'type' => 'money'],
        ];
        $totals = [['label' => 'Totals', 'values' => [null, null, null, $sumD, $sumC, $sumD - $sumC]]];
        $title = 'Trial Balance';
        $sub   = 'As at ' . $asAt;
        $fname = 'trial_balance_' . $asAt;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'Trial Balance', $columns, $data, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $data, $totals, 'P');
        }
    }

    /* ── Balance Sheet exports ─────────────────────────────────────────── */

    public function balanceSheetXlsxAction()   { $this->exportBalanceSheet('xlsx'); }
    public function balanceSheetPdfAction()    { $this->exportBalanceSheet('pdf'); }

    private function exportBalanceSheet(string $format): void
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $bs   = (new FinancialStatements())->balanceSheet($asAt);
        $rows = [];
        $rows[] = ['', '— ASSETS —', ''];
        foreach ($bs['assets'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['balance']];
        $rows[] = ['', 'Total Assets', (float)$bs['total_assets']];
        $rows[] = ['', '', ''];
        $rows[] = ['', '— LIABILITIES —', ''];
        foreach ($bs['liabilities'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['balance']];
        $rows[] = ['', 'Sub-total Liabilities', (float)$bs['total_liabilities']];
        $rows[] = ['', '— EQUITY —', ''];
        foreach ($bs['equity'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['balance']];
        $rows[] = ['3900', 'Retained earnings (YTD)', (float)$bs['retained_earnings']];
        $rows[] = ['', 'Sub-total Equity',     (float)$bs['total_equity_all']];
        $columns = [
            ['label' => 'Code',    'width' => 14, 'align' => 'L'],
            ['label' => 'Account', 'width' => 50, 'align' => 'L'],
            ['label' => 'Amount',  'width' => 24, 'align' => 'R', 'type' => 'money'],
        ];
        $totals = [['label' => 'Total Liab. + Equity', 'values' => [null, null, (float)$bs['total_liab_and_eq']]]];
        $title = 'Balance Sheet';
        $sub   = 'As at ' . $asAt . ($bs['balances'] ? '  ·  Balanced' : '  ·  Out of balance');
        $fname = 'balance_sheet_' . $asAt;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'Balance Sheet', $columns, $rows, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $rows, $totals, 'P');
        }
    }

    /* ── P&L exports ───────────────────────────────────────────────────── */

    public function profitAndLossXlsxAction() { $this->exportPnl('xlsx'); }
    public function profitAndLossPdfAction()  { $this->exportPnl('pdf'); }

    private function exportPnl(string $format): void
    {
        $from = (string)($_GET['from'] ?? date('Y-01-01'));
        $to   = (string)($_GET['to']   ?? date('Y-m-d'));
        $p    = (new FinancialStatements())->profitAndLoss($from, $to);
        $rows = [];
        $rows[] = ['', '— REVENUE —', ''];
        foreach ($p['revenue'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['amount']];
        $rows[] = ['', 'Total revenue', (float)$p['total_revenue']];
        $rows[] = ['', '', ''];
        $rows[] = ['', '— COST OF SALES —', ''];
        foreach ($p['cogs'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['amount']];
        $rows[] = ['', 'Total cost of sales', (float)$p['total_cogs']];
        $rows[] = ['', 'Gross profit', (float)$p['gross_profit']];
        $rows[] = ['', '', ''];
        $rows[] = ['', '— OPERATING EXPENSES —', ''];
        foreach ($p['opex'] as $r) $rows[] = [$r['account_code'], $r['account_name'], (float)$r['amount']];
        $rows[] = ['', 'Total operating expenses', (float)$p['total_opex']];
        $columns = [
            ['label' => 'Code',    'width' => 14, 'align' => 'L'],
            ['label' => 'Account', 'width' => 50, 'align' => 'L'],
            ['label' => 'Amount',  'width' => 24, 'align' => 'R', 'type' => 'money'],
        ];
        $totals = [['label' => 'Net profit', 'values' => [null, null, (float)$p['net_profit']]]];
        $title = 'Profit & Loss';
        $sub   = $from . ' to ' . $to . '  ·  Net margin ' . number_format($p['net_margin'], 1) . '%';
        $fname = 'profit_and_loss_' . $from . '_' . $to;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'Profit and Loss', $columns, $rows, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $rows, $totals, 'P');
        }
    }
}
