<?php
/**
 * Customer Statements — send-to-customer AR statement, brand-consistent PDF.
 *
 *   /CustomerStatements                          — landing (pick customer + range)
 *   /CustomerStatements/pdf/{customerId}?from=&to=[&dl=1]
 */
class CustomerStatementsController extends Controller
{
    public function indexAction()
    {
        [$from, $to] = $this->range();
        $m = new CustomerStatements();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('CustomerStatements/index', [
            'page_title' => 'Customer Statements',
            'customers'  => $m->allActive(),
            'from'       => $from,
            'to'         => $to,
        ]);
    }

    public function pdfAction($customerId = 0)
    {
        [$from, $to] = $this->range();
        $m = new CustomerStatements();
        $s = $m->statement((int)$customerId, $from, $to);
        if (!$s) { $this->notFound('Customer'); return; }

        if (!class_exists('FPDF')) require_once ROOT . '/core/FPDF.php';
        $pdf = new PacificCustomerStatementPdf();
        $pdf->render($s);

        if (ob_get_length()) ob_clean();
        $filename = 'Statement-' . preg_replace('/[^A-Za-z0-9_-]/', '_',
            ($s['customer']['customer_no'] ?: $s['customer']['customer_name'])) . '-' . $from . '_' . $to . '.pdf';
        $mode = !empty($_GET['dl']) ? 'D' : 'I';
        $pdf->Output($mode, $filename);
        exit();
    }

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

    private function range(): array
    {
        // Default to year-to-date so the statement covers everything the
        // customer's likely to be asking about.
        $from = trim((string)($_GET['from'] ?? ''));
        $to   = trim((string)($_GET['to']   ?? ''));
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = date('Y-01-01');
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = date('Y-m-d');
        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>',
        ]);
    }
}
