<?php
require_once __DIR__ . '/config.php';
session_start();
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    header('Content-Type: text/plain');
    exit('Login required');
}

$type = $_GET['type'] ?? 'pending';
$clientFilter = trim($_GET['client'] ?? '');
if (!in_array($type, ['received', 'pending', 'bad_debt'], true)) {
    http_response_code(400);
    exit('Invalid type');
}

try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (Exception $e) {
    http_response_code(500);
    exit('DB error');
}

$userId = (int)$_SESSION['user_id'];
$stmt = $pdo->prepare('SELECT * FROM payments WHERE user_id = ? ORDER BY due_on IS NULL, due_on ASC, id DESC');
$stmt->execute([$userId]);
$payments = $stmt->fetchAll();

function stmt_remaining($p) {
    return max(0, (float)$p['amount'] - (float)($p['received_amount'] ?? 0));
}
function stmt_overdue($p) {
    if (stmt_remaining($p) <= 0) return false;
    if (strtolower($p['status'] ?? '') === 'overdue') return true;
    $due = $p['due_on'] ?? null;
    if (!$due) return false;
    return strtotime(substr($due, 0, 10)) < strtotime(date('Y-m-d'));
}

$rows = [];
foreach ($payments as $p) {
    if ($clientFilter !== '' && trim($p['client_name'] ?? '') !== $clientFilter) continue;
    $rem = stmt_remaining($p);
    $rec = (float)($p['received_amount'] ?? 0);
    if ($type === 'received' && $rec <= 0) continue;
    if ($type === 'pending' && $rem <= 0) continue;
    if ($type === 'bad_debt' && !($rem > 0 && stmt_overdue($p))) continue;
    $rows[] = $p;
}

$titles = [
    'received' => 'Payments Received Statement',
    'pending' => 'Payments Pending Statement',
    'bad_debt' => 'Bad Debts Statement',
];
$title = $titles[$type];
$clientLabel = $clientFilter !== '' ? $clientFilter : 'All Clients';
$singleClient = ($clientFilter !== '');
$dateStr = date('M j, Y, g:i A');

class SimplePDF {
    private $pages = [];
    private $page = '';
    public $pageW = 595.28;
    public $pageH = 841.89;
    private $fontSize = 10;
    private $images = []; // name => [data, w, h]

    public function __construct() { $this->addPage(); }
    public function addPage() {
        if ($this->page !== '') $this->pages[] = $this->page;
        $this->page = "0 0 0 rg\n0 0 0 RG\n1 w\n";
    }
    private function esc($s) {
        return str_replace([chr(92), '(', ')'], [chr(92).chr(92), chr(92).'(', chr(92).')'], $s);
    }
    public function setFontSize($s) { $this->fontSize = $s; }
    public function text($x, $y, $str) {
        $this->page .= sprintf("BT /F1 %.2f Tf %.2f %.2f Td (%s) Tj ET\n", $this->fontSize, $x, $this->pageH - $y, $this->esc($str));
    }
    public function textRight($xRight, $y, $str) {
        $w = strlen($str) * $this->fontSize * 0.52;
        $this->text($xRight - $w, $y, $str);
    }
    public function line($x1, $y1, $x2, $y2) {
        $this->page .= sprintf("%.2f %.2f m %.2f %.2f l S\n", $x1, $this->pageH - $y1, $x2, $this->pageH - $y2);
    }
    public function rect($x, $y, $w, $h, $fill = false) {
        $this->page .= sprintf("%.2f %.2f %.2f %.2f re %s\n", $x, $this->pageH - $y - $h, $w, $h, $fill ? 'f' : 'S');
    }
    public function filledRect($x, $y, $w, $h, $r, $g, $b) {
        $this->page .= sprintf("%.3f %.3f %.3f rg\n", $r/255, $g/255, $b/255);
        $this->rect($x, $y, $w, $h, true);
        $this->page .= "0 0 0 rg\n";
    }
    public function setColor($r, $g, $b) {
        $this->page .= sprintf("%.3f %.3f %.3f rg\n", $r/255, $g/255, $b/255);
    }
    public function setStroke($r, $g, $b) {
        $this->page .= sprintf("%.3f %.3f %.3f RG\n", $r/255, $g/255, $b/255);
    }
    public function setLineWidth($w) {
        $this->page .= sprintf("%.2f w\n", $w);
    }
    /** Word-wrap text to fit maxWidth (approx Helvetica). Returns array of lines. */
    public function wrapText($text, $maxWidth, $fontSize = 9) {
        $text = trim(preg_replace('/\s+/', ' ', (string)$text));
        if ($text === '') return ['-'];
        $charW = $fontSize * 0.50;
        $maxChars = max(4, (int)floor($maxWidth / $charW));
        $words = explode(' ', $text);
        $lines = [];
        $cur = '';
        foreach ($words as $w) {
            $trial = ($cur === '') ? $w : ($cur . ' ' . $w);
            if (strlen($trial) <= $maxChars) {
                $cur = $trial;
            } else {
                if ($cur !== '') $lines[] = $cur;
                if (strlen($w) > $maxChars) {
                    while (strlen($w) > $maxChars) {
                        $lines[] = substr($w, 0, $maxChars);
                        $w = substr($w, $maxChars);
                    }
                    $cur = $w;
                } else {
                    $cur = $w;
                }
            }
        }
        if ($cur !== '') $lines[] = $cur;
        return $lines ?: ['-'];
    }
    public function addJpeg($name, $path) {
        if (!is_file($path)) return false;
        $data = file_get_contents($path);
        $w = 0; $h = 0;
        $i = 2;
        $len = strlen($data);
        while ($i < $len - 8) {
            if (ord($data[$i]) !== 0xFF) { $i++; continue; }
            $marker = ord($data[$i + 1]);
            if ($marker === 0xC0 || $marker === 0xC1 || $marker === 0xC2) {
                $h = (ord($data[$i + 5]) << 8) + ord($data[$i + 6]);
                $w = (ord($data[$i + 7]) << 8) + ord($data[$i + 8]);
                break;
            }
            if ($marker === 0xD9 || $marker === 0xDA) break;
            $seg = (ord($data[$i + 2]) << 8) + ord($data[$i + 3]);
            $i += 2 + $seg;
        }
        if ($w < 1 || $h < 1) return false;
        $this->images[$name] = ['data' => $data, 'w' => $w, 'h' => $h];
        return true;
    }
    /** Draw image: x,y top-left in our coordinate system, display width/height in points */
    public function image($name, $x, $y, $dw, $dh = 0) {
        if (!isset($this->images[$name])) return;
        $img = $this->images[$name];
        if ($dh <= 0) $dh = $dw * $img['h'] / $img['w'];
        // PDF y is bottom-left of image
        $pdfY = $this->pageH - $y - $dh;
        $this->page .= sprintf("q %.2f 0 0 %.2f %.2f %.2f cm /%s Do Q\n", $dw, $dh, $x, $pdfY, $name);
    }
    public function output($filename) {
        if ($this->page !== '') $this->pages[] = $this->page;
        $out = "%PDF-1.4\n";
        $offsets = [];
        $obj = 1;

        // collect image objects first after pages structure
        $n = count($this->pages);
        $pageObjStart = 3;
        $fontObj = $pageObjStart + $n * 2;
        $imgStart = $fontObj + 1;
        $imgNames = array_keys($this->images);
        $imgObjs = [];
        foreach ($imgNames as $idx => $name) {
            $imgObjs[$name] = $imgStart + $idx;
        }

        // 1 catalog
        $offsets[1] = strlen($out);
        $out .= "1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n";
        // 2 pages
        $kids = [];
        for ($i = 0; $i < $n; $i++) $kids[] = ($pageObjStart + $i * 2) . ' 0 R';
        $offsets[2] = strlen($out);
        $out .= "2 0 obj<< /Type /Pages /Kids [" . implode(' ', $kids) . "] /Count $n >>endobj\n";

        // Build XObject resource dict fragment
        $xobj = '';
        foreach ($imgObjs as $name => $oid) {
            $xobj .= "/$name $oid 0 R ";
        }

        for ($i = 0; $i < $n; $i++) {
            $pageObj = $pageObjStart + $i * 2;
            $contentObj = $pageObj + 1;
            $stream = $this->pages[$i];
            $offsets[$pageObj] = strlen($out);
            $res = "/Font << /F1 $fontObj 0 R >>";
            if ($xobj !== '') $res .= " /XObject << $xobj >>";
            $out .= "$pageObj 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {$this->pageW} {$this->pageH}] /Contents $contentObj 0 R /Resources << $res >> >>endobj\n";
            $offsets[$contentObj] = strlen($out);
            $out .= "$contentObj 0 obj<< /Length " . strlen($stream) . " >>stream\n{$stream}endstream\nendobj\n";
        }
        $offsets[$fontObj] = strlen($out);
        $out .= "$fontObj 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n";

        foreach ($imgObjs as $name => $oid) {
            $img = $this->images[$name];
            $data = $img['data'];
            $offsets[$oid] = strlen($out);
            $out .= "$oid 0 obj<< /Type /XObject /Subtype /Image /Width {$img['w']} /Height {$img['h']} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length " . strlen($data) . " >>stream\n";
            $out .= $data;
            $out .= "\nendstream\nendobj\n";
        }

        $maxObj = $fontObj;
        if ($imgObjs) $maxObj = max($imgObjs);
        $count = $maxObj + 1;
        $xref = strlen($out);
        $out .= "xref\n0 $count\n0000000000 65535 f \n";
        for ($i = 1; $i < $count; $i++) $out .= sprintf("%010d 00000 n \n", $offsets[$i] ?? 0);
        $out .= "trailer<< /Size $count /Root 1 0 R >>\nstartxref\n$xref\n%%EOF";
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: private, max-age=0, must-revalidate');
        echo $out;
        exit;
    }
}

$pdf = new SimplePDF();
$logoPath = __DIR__ . '/assets/logo-icon.jpg';
$hasLogo = $pdf->addJpeg('Logo', $logoPath);

$L = 36;
$R = 36;
$pageW = $pdf->pageW;
$contentW = $pageW - $L - $R;

// Brand colors
$navy = [15, 23, 42];
$teal = [20, 184, 166];
$tealDark = [13, 148, 136];
$slate = [100, 116, 139];
$light = [240, 253, 250];
$lightGray = [248, 250, 252];

// === TOP ACCENT BAR ===
$pdf->filledRect(0, 0, $pageW, 6, $teal[0], $teal[1], $teal[2]);

// === HEADER BAND ===
$pdf->filledRect(0, 6, $pageW, 58, $navy[0], $navy[1], $navy[2]);
if ($hasLogo) {
    $pdf->image('Logo', $L, 14, 36, 36);
    $pdf->setFontSize(18);
    $pdf->setColor(255, 255, 255);
    $pdf->text($L + 44, 32, 'Flowtica');
    $pdf->setFontSize(9);
    $pdf->setColor(153, 246, 228);
    $pdf->text($L + 44, 46, 'Task & Payment Manager');
} else {
    $pdf->setFontSize(18);
    $pdf->setColor(255, 255, 255);
    $pdf->text($L, 32, 'Flowtica');
    $pdf->setFontSize(9);
    $pdf->setColor(153, 246, 228);
    $pdf->text($L, 46, 'Task & Payment Manager');
}

$pdf->setFontSize(12);
$pdf->setColor(255, 255, 255);
$pdf->textRight($pageW - $R, 30, $title);
$pdf->setFontSize(8);
$pdf->setColor(148, 163, 184);
$pdf->textRight($pageW - $R, 44, 'Generated: ' . $dateStr);

// Teal underline under header
$pdf->filledRect(0, 64, $pageW, 3, $teal[0], $teal[1], $teal[2]);

// === INFO CARDS ===
$boxY = 78;
$boxH = 40;
$boxW = ($contentW - 12) / 2;
$pdf->filledRect($L, $boxY, $boxW, $boxH, $light[0], $light[1], $light[2]);
$pdf->setStroke($teal[0], $teal[1], $teal[2]);
$pdf->setLineWidth(1.2);
$pdf->line($L, $boxY, $L + 4, $boxY);
$pdf->line($L, $boxY, $L, $boxY + $boxH);
$pdf->line($L, $boxY + $boxH, $L + 4, $boxY + $boxH);
$pdf->setLineWidth(0.5);
$pdf->setStroke(204, 251, 241);
$pdf->rect($L, $boxY, $boxW, $boxH, false);

$pdf->filledRect($L + $boxW + 12, $boxY, $boxW, $boxH, $light[0], $light[1], $light[2]);
$pdf->setStroke($teal[0], $teal[1], $teal[2]);
$pdf->setLineWidth(1.2);
$rx = $L + $boxW + 12;
$pdf->line($rx, $boxY, $rx + 4, $boxY);
$pdf->line($rx, $boxY, $rx, $boxY + $boxH);
$pdf->line($rx, $boxY + $boxH, $rx + 4, $boxY + $boxH);
$pdf->setLineWidth(0.5);
$pdf->rect($rx, $boxY, $boxW, $boxH, false);

$pdf->setFontSize(8);
$pdf->setColor($tealDark[0], $tealDark[1], $tealDark[2]);
$pdf->text($L + 12, $boxY + 15, 'CLIENT FILTER');
$pdf->text($rx + 12, $boxY + 15, 'STATEMENT TYPE');
$pdf->setFontSize(11);
$pdf->setColor($navy[0], $navy[1], $navy[2]);
$pdf->text($L + 12, $boxY + 30, substr($clientLabel, 0, 30));
$pdf->text($rx + 12, $boxY + 30, substr($title, 0, 26));

// === TABLE ===
$nameColLabel = $singleClient ? 'Project' : 'Client';
$cols = [
    ['#', 28],
    [$nameColLabel, 160],
    ['Due Date', 72],
    ['Amount', 88],
    ['Received', 88],
    ['Balance', 88],
];
$tableW = 0;
foreach ($cols as $c) $tableW += $c[1];
$startX = $L;
$y = 134;
$rowH = 22;

$pdf->filledRect($startX, $y, $tableW, $rowH, $navy[0], $navy[1], $navy[2]);
// teal accent on left of header
$pdf->filledRect($startX, $y, 3, $rowH, $teal[0], $teal[1], $teal[2]);
$pdf->setColor(255, 255, 255);
$pdf->setFontSize(9);
$x = $startX + 8;
foreach ($cols as $c) {
    $pdf->text($x, $y + 15, $c[0]);
    $x += $c[1];
}
$y += $rowH;

$totalAmt = 0; $totalRec = 0; $totalBal = 0;
$pdf->setFontSize(9);

foreach ($rows as $i => $p) {
    $amt = (float)$p['amount'];
    $rec = (float)($p['received_amount'] ?? 0);
    $bal = max(0, $amt - $rec);
    $totalAmt += $amt; $totalRec += $rec; $totalBal += $bal;

    $due = substr((string)($p['due_on'] ?? '-'), 0, 10);
    $nameVal = $singleClient ? ((string)($p['project_name'] ?? '-')) : ((string)($p['client_name'] ?? '-'));
    $clientLines = $pdf->wrapText($nameVal, $cols[1][1] - 12, 9);
    $lineCount = max(1, count($clientLines));
    $thisRowH = max($rowH, 10 + $lineCount * 12);

    if ($y + $thisRowH > 700) {
        $pdf->addPage();
        $pdf->filledRect(0, 0, $pageW, 6, $teal[0], $teal[1], $teal[2]);
        $y = 24;
        $pdf->filledRect($startX, $y, $tableW, $rowH, $navy[0], $navy[1], $navy[2]);
        $pdf->filledRect($startX, $y, 3, $rowH, $teal[0], $teal[1], $teal[2]);
        $pdf->setColor(255, 255, 255);
        $pdf->setFontSize(9);
        $x = $startX + 8;
        foreach ($cols as $c) { $pdf->text($x, $y + 15, $c[0]); $x += $c[1]; }
        $y += $rowH;
    }

    if ($i % 2 === 1) {
        $pdf->filledRect($startX, $y, $tableW, $thisRowH, $lightGray[0], $lightGray[1], $lightGray[2]);
    }
    $pdf->setStroke(226, 232, 240);
    $pdf->line($startX, $y + $thisRowH, $startX + $tableW, $y + $thisRowH);

    $pdf->setColor($navy[0], $navy[1], $navy[2]);
    $pdf->setFontSize(9);

    // #
    $pdf->text($startX + 8, $y + 15, (string)($i + 1));

    // Client (wrapped)
    $cx = $startX + $cols[0][1] + 8;
    foreach ($clientLines as $li => $cline) {
        $pdf->text($cx, $y + 15 + ($li * 12), $cline);
    }

    // Due Date + amounts (vertically centered-ish on first line)
    $vals = [$due, number_format($amt, 2), number_format($rec, 2), number_format($bal, 2)];
    $x = $startX + $cols[0][1] + $cols[1][1] + 8;
    foreach ($vals as $vi => $val) {
        $colIdx = $vi + 2;
        $approx = strlen($val) * 4.8;
        if ($vi === 0) {
            $pdf->text($x, $y + 15, $val);
        } else {
            $pdf->text($x + $cols[$colIdx][1] - $approx - 20, $y + 15, $val);
        }
        $x += $cols[$colIdx][1];
    }
    $y += $thisRowH;
}

if (!$rows) {
    $pdf->setColor($slate[0], $slate[1], $slate[2]);
    $pdf->setFontSize(10);
    $pdf->text($startX + 8, $y + 18, 'No records found for this statement.');
    $y += 36;
}

// === TOTALS BOX ===
$y += 22;
$boxW = 230;
$boxX = $pageW - $R - $boxW;
$lineH = 26;

if ($type === 'received') {
    $items = [
        ['Total Received', 'SAR ' . number_format($totalRec, 2), true],
        ['Records', (string)count($rows), false],
    ];
} elseif ($type === 'pending') {
    $items = [
        ['Total Invoiced', 'SAR ' . number_format($totalAmt, 2), false],
        ['Total Received', 'SAR ' . number_format($totalRec, 2), false],
        ['Total Pending', 'SAR ' . number_format($totalBal, 2), true],
    ];
} else {
    $items = [
        ['Total Bad Debt', 'SAR ' . number_format($totalBal, 2), true],
        ['Records', (string)count($rows), false],
    ];
}

$boxH = count($items) * $lineH;
// teal top strip on totals
$pdf->filledRect($boxX, $y - 4, $boxW, 4, $teal[0], $teal[1], $teal[2]);
$pdf->setStroke(203, 213, 225);
$pdf->rect($boxX, $y, $boxW, $boxH, false);

foreach ($items as $ii => $item) {
    $ly = $y + $ii * $lineH;
    if ($item[2]) {
        $pdf->filledRect($boxX, $ly, $boxW, $lineH, $tealDark[0], $tealDark[1], $tealDark[2]);
        $pdf->setColor(255, 255, 255);
        $pdf->setFontSize(11);
    } else {
        if ($ii % 2 === 1) $pdf->filledRect($boxX, $ly, $boxW, $lineH, $light[0], $light[1], $light[2]);
        $pdf->setColor($navy[0], $navy[1], $navy[2]);
        $pdf->setFontSize(10);
        $pdf->setStroke(226, 232, 240);
        $pdf->line($boxX, $ly + $lineH, $boxX + $boxW, $ly + $lineH);
    }
    $pdf->text($boxX + 12, $ly + 17, $item[0]);
    $approx = strlen($item[1]) * ($item[2] ? 5.5 : 5.0);
    $pdf->text($boxX + $boxW - $approx - 12, $ly + 17, $item[1]);
}

// Footer
$y = $y + $boxH + 30;
$pdf->setStroke(204, 251, 241);
$pdf->line($L, $y - 12, $pageW - $R, $y - 12);
$pdf->setFontSize(8);
$pdf->setColor($slate[0], $slate[1], $slate[2]);
$pdf->text($L, $y, 'Flowtica  |  System-generated statement  |  ' . $dateStr);
$pdf->filledRect(0, $pdf->pageH - 6, $pageW, 6, $navy[0], $navy[1], $navy[2]);

$safeClient = preg_replace('/[^a-zA-Z0-9_-]/', '_', $clientFilter ?: 'all');
$pdf->output('Flowtica_' . $type . '_' . $safeClient . '_' . date('Y-m-d') . '.pdf');
