<?php
/**
 * PacificP9Pdf — annual employee PAYE certificate (TRA form P.9A shape).
 *
 * One landscape A4 page per employee. Layout:
 *   Header      — Pacific brand mark + "P9 CERTIFICATE FOR THE YEAR YYYY"
 *   Employer    — company name, TIN, VRN
 *   Employee    — full name, employee #, NIDA, position, hire date
 *   Grid        — Jan..Dec × [Basic, Allowances, Gross, NSSF, Taxable, PAYE]
 *   Totals      — annual totals in a bold footer row
 *   Attestation — printed line for signatures + issue date
 *
 * Uses the same Open Sans self-hosted fonts as the invoice + payslip PDFs
 * so the P9 sits inside the Pacific brand family.
 */
class PacificP9Pdf extends FPDF
{
    private const C_BRAND    = [ 38,  38, 245];
    private const C_BRAND_D  = [ 20,  20, 214];
    private const C_INK      = [ 15,  18,  32];
    private const C_MUTED    = [107, 116, 132];
    private const C_RULE     = [226, 231, 239];
    private const C_TINT     = [235, 239, 250];
    private const C_GROUND   = [245, 247, 251];

    private const M_L = 12;
    private const M_R = 12;
    private const M_T = 12;

    public function __construct()
    {
        if (!defined('FPDF_FONTPATH')) define('FPDF_FONTPATH', ROOT . '/fonts/fpdf/');
        parent::__construct('L', 'mm', 'A4');
        $this->AddFont('OpenSans-Regular', '', 'OpenSans-Regular.php');
        $this->AddFont('OpenSans-Bold',    '', 'opensans-bold.php');
        $this->SetMargins(self::M_L, self::M_T, self::M_R);
        $this->SetAutoPageBreak(false);
    }

    public function Header(): void {}
    public function Footer(): void {}

    public function renderOne(array $c): void
    {
        $this->SetTitle($this->safe('P9 · ' . ($c['driver']['full_name'] ?? '') . ' · ' . $c['year']));
        $this->SetAuthor($this->safe(defined('COMPANY_NAME') ? COMPANY_NAME : 'Pacific Group'));
        $this->AddPage();
        $this->drawCert($c);
    }

    public function renderMany(array $certs): void
    {
        $this->SetTitle($this->safe('P9 certificates · batch'));
        foreach ($certs as $c) {
            $this->AddPage();
            $this->drawCert($c);
        }
    }

    /* ── Certificate body ─────────────────────────────────────────── */
    private function drawCert(array $c): void
    {
        $x = self::M_L; $y = self::M_T;
        $w = 297 - self::M_L - self::M_R;
        $d = $c['driver']; $t = $c['totals']; $months = $c['months'];

        // ── Header strip ──
        $logoPath = ROOT . '/images/logo.png';
        if (is_file($logoPath)) {
            @$this->Image($logoPath, $x, $y, 40);
            $headerY = $y + 13;
        } else {
            $this->SetFont('OpenSans-Bold', '', 12);
            $this->SetTextColor(...self::C_BRAND);
            $this->Text($x, $y + 7, $this->safe('PACIFIC GROUP'));
            $headerY = $y + 9;
        }

        $this->SetFont('OpenSans-Bold', '', 14);
        $this->SetTextColor(...self::C_INK);
        $title = 'P9 CERTIFICATE · ' . $c['year'];
        $tw = $this->GetStringWidth($title);
        $this->Text($x + $w - $tw, $y + 8, $this->safe($title));

        $this->SetFont('OpenSans-Regular', '', 7);
        $this->SetTextColor(...self::C_MUTED);
        $sub = 'Annual PAYE Deduction Certificate';
        $sw = $this->GetStringWidth($sub);
        $this->Text($x + $w - $sw, $y + 12, $this->safe($sub));

        // Brand rule under header
        $this->SetDrawColor(...self::C_BRAND);
        $this->SetLineWidth(0.7);
        $this->Line($x, $headerY + 4, $x + $w, $headerY + 4);

        // ── Employer / Employee blocks ──
        $yBlock = $headerY + 8;
        $blockH = 24;
        $blockW = ($w - 3) / 2;

        // Employer
        $this->SetFillColor(...self::C_GROUND);
        $this->Rect($x, $yBlock, $blockW, $blockH, 'F');
        $this->SetFont('OpenSans-Regular', '', 6.5);
        $this->SetTextColor(...self::C_MUTED);
        $this->Text($x + 3, $yBlock + 4, $this->safe('EMPLOYER'));

        $this->SetFont('OpenSans-Bold', '', 11);
        $this->SetTextColor(...self::C_INK);
        $this->Text($x + 3, $yBlock + 10, $this->safe(defined('COMPANY_NAME') ? COMPANY_NAME : 'Pacific Group Company Limited'));

        $this->SetFont('OpenSans-Regular', '', 7);
        $this->SetTextColor(...self::C_BRAND_D);
        $tin = defined('COMPANY_TIN') ? COMPANY_TIN : '—';
        $vrn = defined('COMPANY_VRN') ? COMPANY_VRN : '—';
        $this->Text($x + 3, $yBlock + 15, $this->safe('TIN  ' . $tin));
        $this->Text($x + 3, $yBlock + 20, $this->safe('VRN  ' . $vrn));

        // Employee
        $xE = $x + $blockW + 3;
        $this->SetFillColor(...self::C_TINT);
        $this->Rect($xE, $yBlock, $blockW, $blockH, 'F');
        $this->SetFont('OpenSans-Regular', '', 6.5);
        $this->SetTextColor(...self::C_MUTED);
        $this->Text($xE + 3, $yBlock + 4, $this->safe('EMPLOYEE'));

        $this->SetFont('OpenSans-Bold', '', 11);
        $this->SetTextColor(...self::C_INK);
        $this->Text($xE + 3, $yBlock + 10, $this->safe($d['full_name'] ?? '—'));

        $this->SetFont('OpenSans-Regular', '', 7);
        $this->SetTextColor(...self::C_BRAND_D);
        $this->Text($xE + 3, $yBlock + 15,
            $this->safe(($d['employee_no'] ?: '—') . '   ·   NIDA ' . ($d['id_no'] ?: '—')));
        if (!empty($d['hire_date'])) {
            $this->Text($xE + 3, $yBlock + 20, $this->safe('Hired ' . $this->fmtDate($d['hire_date'])));
        }

        // ── Grid ──
        $yGrid = $yBlock + $blockH + 6;
        $cols  = [
            ['Month',       28, 'L'],
            ['Basic',       28, 'R'],
            ['Allowances',  28, 'R'],
            ['Commission',  28, 'R'],
            ['Other',       28, 'R'],
            ['Gross Pay',   34, 'R'],
            ['NSSF Ee',     30, 'R'],
            ['Taxable',     34, 'R'],
            ['PAYE',        34, 'R'],
        ];
        $rowH = 6;

        // Header row
        $this->SetFillColor(...self::C_BRAND);
        $this->Rect($x, $yGrid, $w, $rowH, 'F');
        $this->SetFont('OpenSans-Bold', '', 7);
        $this->SetTextColor(255, 255, 255);
        $cx = $x;
        foreach ($cols as [$label, $cw, $align]) {
            $this->drawCell($cx, $yGrid, $cw, $rowH, $label, $align, 1.5);
            $cx += $cw;
        }

        // Month rows
        $yr = $yGrid + $rowH;
        $this->SetTextColor(...self::C_INK);
        foreach ($months as $mIdx => $m) {
            // Alternating tint for legibility on a dense grid
            if ($mIdx % 2 === 0) {
                $this->SetFillColor(...self::C_GROUND);
                $this->Rect($x, $yr, $w, $rowH, 'F');
            }
            $this->SetFont('OpenSans-Bold', '', 7.5);
            $this->drawCell($x, $yr, $cols[0][1], $rowH, $m['name'], 'L', 3);

            $this->SetFont('OpenSans-Regular', '', 7);
            $this->SetTextColor(...($m['has_data'] ? self::C_INK : self::C_MUTED));
            $cx = $x + $cols[0][1];
            $vals = [
                $m['base']       > 0 ? number_format($m['base'], 2)       : '—',
                $m['allowances'] > 0 ? number_format($m['allowances'], 2) : '—',
                $m['commission'] > 0 ? number_format($m['commission'], 2) : '—',
                $m['other_e']    > 0 ? number_format($m['other_e'], 2)    : '—',
                $m['gross']      > 0 ? number_format($m['gross'], 2)      : '—',
                $m['nssf_ee']    > 0 ? number_format($m['nssf_ee'], 2)    : '—',
                $m['taxable']    > 0 ? number_format($m['taxable'], 2)    : '—',
                $m['paye']       > 0 ? number_format($m['paye'], 2)       : '—',
            ];
            for ($i = 0; $i < 8; $i++) {
                $cw = $cols[$i + 1][1];
                $this->drawCell($cx, $yr, $cw, $rowH, $vals[$i], 'R', 2);
                $cx += $cw;
            }
            $this->SetTextColor(...self::C_INK);
            $yr += $rowH;
        }

        // Totals row (brand-blue accent)
        $this->SetFillColor(...self::C_BRAND);
        $this->Rect($x, $yr, $w, $rowH + 1, 'F');
        $this->SetFont('OpenSans-Bold', '', 8);
        $this->SetTextColor(255, 255, 255);
        $this->drawCell($x, $yr, $cols[0][1], $rowH + 1, 'TOTAL', 'L', 3);
        $vals = [
            number_format($t['base'], 2),
            number_format($t['allowances'], 2),
            number_format($t['commission'], 2),
            number_format($t['other_e'], 2),
            number_format($t['gross'], 2),
            number_format($t['nssf_ee'], 2),
            number_format($t['taxable'], 2),
            number_format($t['paye'], 2),
        ];
        $cx = $x + $cols[0][1];
        for ($i = 0; $i < 8; $i++) {
            $cw = $cols[$i + 1][1];
            $this->drawCell($cx, $yr, $cw, $rowH + 1, $vals[$i], 'R', 2);
            $cx += $cw;
        }

        // ── Signature block ──
        $ySig = $yr + $rowH + 10;
        $this->SetFont('OpenSans-Regular', '', 8);
        $this->SetTextColor(...self::C_INK);
        $sigColW = ($w - 6) / 3;
        $labels  = ['Employer signature', 'Employee signature', 'Date issued'];
        for ($i = 0; $i < 3; $i++) {
            $sx = $x + $i * ($sigColW + 3);
            $this->SetDrawColor(...self::C_INK);
            $this->SetLineWidth(0.2);
            $this->Line($sx, $ySig, $sx + $sigColW, $ySig);
            $this->SetFont('OpenSans-Regular', '', 6.5);
            $this->SetTextColor(...self::C_MUTED);
            $this->Text($sx, $ySig + 4, $this->safe(strtoupper($labels[$i])));
            if ($i === 2) {
                $this->SetFont('OpenSans-Bold', '', 9);
                $this->SetTextColor(...self::C_INK);
                $this->Text($sx, $ySig - 2, $this->safe(date('d M Y')));
            }
        }

        // Attestation
        $yAtt = $ySig + 12;
        $this->SetFont('OpenSans-Regular', '', 6.5);
        $this->SetTextColor(...self::C_MUTED);
        $att = 'Certified that the amounts shown above are the actual amounts deducted from the employee\'s pay '
             . 'during the year ' . $c['year'] . ' and have been remitted to the Tanzania Revenue Authority in accordance '
             . 'with the Income Tax Act, Cap. 332.';
        $this->SetXY($x, $yAtt);
        $this->MultiCell($w, 3.6, $this->safe($att), 0, 'L');

        // Footer strip
        $yFoot = 210 - self::M_T - 6;
        $this->SetFillColor(...self::C_GROUND);
        $this->Rect($x, $yFoot, $w, 5, 'F');
        $this->SetFont('OpenSans-Regular', '', 6);
        $this->SetTextColor(...self::C_MUTED);
        $this->Text($x + 2, $yFoot + 3.5, $this->safe('Generated ' . date('d M Y H:i') . ' · System-generated document · Retain for your records.'));
        $rightFoot = 'Form P.9A (Pacific)';
        $rfw = $this->GetStringWidth($rightFoot);
        $this->Text($x + $w - $rfw - 2, $yFoot + 3.5, $rightFoot);
    }

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

    private function drawCell(float $x, float $y, float $w, float $h, string $text, string $align, float $pad): void
    {
        $text = $this->safe($text);
        if ($align === 'R') {
            $tw = $this->GetStringWidth($text);
            $this->Text($x + $w - $tw - $pad, $y + $h * 0.7, $text);
        } else {
            $this->Text($x + $pad, $y + $h * 0.7, $text);
        }
    }

    private function fmtDate(?string $ymd): string
    {
        if (!$ymd) return '—';
        $t = strtotime($ymd);
        return $t ? date('d M Y', $t) : $ymd;
    }

    private function safe($s): string
    {
        $s = (string)$s;
        $s = strtr($s, [
            "\u{2013}" => '-',   "\u{2014}" => '-',
            "\u{2018}" => "'",   "\u{2019}" => "'",
            "\u{201C}" => '"',   "\u{201D}" => '"',
            "\u{2026}" => '...', "\u{2192}" => '->',
            "\u{00A0}" => ' ',   "\u{00B7}" => '.',
        ]);
        return @iconv('UTF-8', 'CP1252//TRANSLIT//IGNORE', $s) ?: $s;
    }
}
