<?php
/**
 * Financial reports controller — three canonical reports for month-end
 * (and, importantly, for the accountant/auditor conversation).
 *
 * Every action accepts an optional date range via query string. Default
 * window is the current month (P&L / TB) or "as of today" (BS).
 */
class FinancialReportsController extends Controller
{
    public function indexAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/index', [
            'page_title' => 'Financial Reports',
        ]);
    }

    public function trialBalanceAction()
    {
        [$from, $to] = $this->range();
        $m = new FinancialReports();
        $r = $m->trialBalance($from, $to);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/trialBalance', [
            'page_title' => 'Trial Balance',
            'r'          => $r,
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    public function pnlAction()
    {
        [$from, $to] = $this->range();
        $m = new FinancialReports();
        $r = $m->pnl($from, $to);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/pnl', [
            'page_title' => 'Profit &amp; Loss',
            'r'          => $r,
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    public function cashFlowAction()
    {
        [$from, $to] = $this->range();
        $m = new FinancialReports();
        $r = $m->cashFlow($from, $to);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/cashFlow', [
            'page_title' => 'Cash Flow',
            'r'          => $r,
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    public function balanceSheetAction()
    {
        $asOf = trim((string)($_GET['as_of'] ?? date('Y-m-d')));
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $asOf)) $asOf = date('Y-m-d');

        $m = new FinancialReports();
        $r = $m->balanceSheet($asOf);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/balanceSheet', [
            'page_title' => 'Balance Sheet',
            'r'          => $r,
            'as_of'      => $asOf,
        ]);
    }

    /**
     * GET-style ledger drill-down. Renders a plain table of postings so the
     * reader can trace a report figure back to its source journals.
     *   /FinancialReports/ledger/{account_id}?from=YYYY-MM-DD&to=YYYY-MM-DD
     */
    public function ledgerAction($accountId = 0)
    {
        [$from, $to] = $this->range();
        $m  = new FinancialReports();
        $rs = $m->ledger((int)$accountId, $from, $to);

        // Fetch the account row too so the header shows what we're inspecting.
        $db  = new DB();
        $acc = $db->mySelect(
            'SELECT c0d, account_code, account_name, account_type FROM chart_of_accounts WHERE c0d = :id',
            [':id' => (int)$accountId]
        );
        $acc = $acc[0] ?? null;
        if (!$acc) { $this->notFound('Account'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('FinancialReports/ledger', [
            'page_title' => 'Ledger · ' . $acc['account_code'] . ' ' . $acc['account_name'],
            'acc'        => $acc,
            'rows'       => $rs,
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    /* ── helpers ───────────────────────────────────────────────────── */

    private function range(): array
    {
        $from = trim((string)($_GET['from'] ?? ''));
        $to   = trim((string)($_GET['to']   ?? ''));
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = date('Y-m-01');
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = date('Y-m-t');
        return [$from, $to];
    }

    private function notFound(string $what): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Not found',
            'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($what) . ' not found.</div>',
        ]);
    }
}
