<?php
/**
 * TaxReturns controller — monthly statutory return reports.
 *
 *   /TaxReturns                              → landing page
 *   /TaxReturns/paye?year=2026&month=8       → PAYE return with employee schedule
 *   /TaxReturns/payeCsv/2026/8               → CSV export (accountant uploads to TRA)
 *   /TaxReturns/vat?year=2026&month=8        → VAT return: output vs input, net
 *   /TaxReturns/statutory?year=2026&month=8  → NSSF + SDL + WCF summary
 */
class TaxReturnsController extends Controller
{
    public function indexAction()
    {
        [$year, $month] = $this->currentPeriod();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('TaxReturns/index', [
            'page_title' => 'Tax Returns',
            'year'       => $year,
            'month'      => $month,
        ]);
    }

    public function payeAction()
    {
        [$year, $month] = $this->periodFromRequest();
        $m = new TaxReturns();
        $r = $m->paye($year, $month);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('TaxReturns/paye', [
            'page_title' => 'PAYE Return · ' . $this->periodLabel($year, $month),
            'r'          => $r,
            'year'       => $year,
            'month'      => $month,
        ]);
    }

    public function vatAction()
    {
        [$year, $month] = $this->periodFromRequest();
        $m = new TaxReturns();
        $r = $m->vat($year, $month);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('TaxReturns/vat', [
            'page_title' => 'VAT Return · ' . $this->periodLabel($year, $month),
            'r'          => $r,
            'year'       => $year,
            'month'      => $month,
        ]);
    }

    public function statutoryAction()
    {
        [$year, $month] = $this->periodFromRequest();
        $m = new TaxReturns();
        $r = $m->statutory($year, $month);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('TaxReturns/statutory', [
            'page_title' => 'Statutory Summary · ' . $this->periodLabel($year, $month),
            'r'          => $r,
            'year'       => $year,
            'month'      => $month,
        ]);
    }

    /**
     * Streams the PAYE schedule as CSV. Accountant filename is
     * PAYE-YYYY-MM.csv and matches TRA's upload template column order.
     * URL: /TaxReturns/payeCsv/{year}/{month}
     */
    public function payeCsvAction($year = 0, $month = 0)
    {
        $year  = (int)$year  ?: (int)date('Y');
        $month = (int)$month ?: (int)date('n');

        $m   = new TaxReturns();
        $csv = $m->payeCsv($year, $month);

        if (ob_get_length()) ob_clean();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="PAYE-' . sprintf('%04d-%02d', $year, $month) . '.csv"');
        header('Content-Length: ' . strlen($csv));
        echo $csv;
        exit();
    }

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

    private function currentPeriod(): array
    {
        // Default to the previous month — most returns are prepared after
        // month-end but before the 7th / 20th filing deadline.
        $t = strtotime('first day of last month');
        return [(int)date('Y', $t), (int)date('n', $t)];
    }

    private function periodFromRequest(): array
    {
        [$defY, $defM] = $this->currentPeriod();
        $year  = (int)($_GET['year']  ?? $defY);
        $month = (int)($_GET['month'] ?? $defM);
        if ($year < 2000 || $year > 2100) $year = $defY;
        if ($month < 1 || $month > 12)    $month = $defM;
        return [$year, $month];
    }

    private function periodLabel(int $year, int $month): string
    {
        return date('F Y', strtotime(sprintf('%04d-%02d-01', $year, $month)));
    }
}
