<?php
/**
 * Supplier statements — Pacific's ledger view per supplier, brand PDF.
 *
 *   /SupplierStatements                          — landing (pick supplier + range)
 *   /SupplierStatements/pdf/{vendorId}?from=&to=[&dl=1]
 */
class SupplierStatementsController extends Controller
{
    public function indexAction()
    {
        [$from, $to] = $this->range();
        $m = new SupplierStatements();

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

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

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

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

    /* ── 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-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>',
        ]);
    }
}
