<?php
require($_SERVER['DOCUMENT_ROOT'] . "/fpdf.php");
include "../../root.class.php";

$db        = new db_safeguard();
$record_id = (int) ($_GET['record_id'] ?? 0);

$inv_res = $db->query("invoices", "SELECT * FROM invoices WHERE record_id = $record_id");
$invoice = $inv_res->fetch_assoc();

if (!$invoice) { die("Invoice not found."); }

$items_res = $db->query("invoice_items",
    "SELECT * FROM invoice_items WHERE invoice_no = '{$invoice['invoice_no']}'"
);
$items = [];
while ($item = $items_res->fetch_assoc()) {
    $items[] = $item;
}

/* ── PDF class ── */
class PDF extends FPDF
{
    function Footer()
    {
        $this->SetY(-12);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(120, 120, 120);
        $this->Cell(0, 10, 'Generated: ' . date('Y-m-d H:i'), 0, 0, 'L');
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'R');
    }
}

$pdf = new PDF();
$pdf->SetAutoPageBreak(true, 25);
$pdf->SetMargins(15, 15, 15);
$pdf->AddPage();

/* Brand colours */
$blue   = [30, 58, 138];
$orange = [249, 115, 22];
$gray   = [245, 247, 250];

/* ── Logo ── */
$logo = $_SERVER['DOCUMENT_ROOT'] . '/icons/Savuki_Logo.png';
if (file_exists($logo)) {
    $pdf->Image($logo, 150, 12, 45);
}

/* ── Title ── */
$pdf->SetFont('Arial', 'B', 24);
$pdf->SetTextColor($blue[0], $blue[1], $blue[2]);
$pdf->Cell(0, 12, 'INVOICE', 0, 1, 'L');

/* Orange accent line */
$pdf->SetDrawColor($orange[0], $orange[1], $orange[2]);
$pdf->SetLineWidth(0.8);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());
$pdf->Ln(4);

/* ── Invoice Meta + Client (two columns) ── */
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(40, 40, 40);
$y_start = $pdf->GetY();

// Left col — invoice details
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(95, 6, 'INVOICE DETAILS', 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);

$meta = [
    'Invoice No'   => $invoice['invoice_no'],
    'Invoice Date' => $invoice['invoice_date'],
    'Due Date'     => $invoice['due_date'],
    'Status'       => $invoice['status'],
];

foreach ($meta as $label => $value) {
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(40, 6, $label . ':', 0, 0, 'L');
    $pdf->SetFont('Arial', '', 10);
    $pdf->Cell(55, 6, $value, 0, 1, 'L');
}

// Right col — client details
$y_right = $y_start;
$pdf->SetXY(115, $y_right);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(80, 6, 'BILL TO', 0, 1, 'L');

$pdf->SetXY(115, $pdf->GetY());
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(80, 6, $invoice['client_name'], 0, 1, 'L');

$pdf->SetFont('Arial', '', 10);
foreach (['client_address', 'client_email', 'client_phone'] as $field) {
    if (!empty($invoice[$field])) {
        $pdf->SetX(115);
        $pdf->Cell(80, 5, $invoice[$field], 0, 1, 'L');
    }
}

$pdf->Ln(8);

/* ── Line Items Table ── */
$pdf->SetFillColor($blue[0], $blue[1], $blue[2]);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('Arial', 'B', 10);

$pdf->Cell(90,  8, 'Description',    1, 0, 'L', true);
$pdf->Cell(25,  8, 'Qty',            1, 0, 'C', true);
$pdf->Cell(35,  8, 'Unit Price (R)', 1, 0, 'C', true);
$pdf->Cell(30,  8, 'Total (R)',      1, 1, 'C', true);

$pdf->SetTextColor(40, 40, 40);
$pdf->SetFont('Arial', '', 10);

$grand_total = 0;
$fill = false;

foreach ($items as $item) {
    $row_total = (float) $item['total'];
    $grand_total += $row_total;

    $pdf->SetFillColor($fill ? $gray[0] : 255, $fill ? $gray[1] : 255, $fill ? $gray[2] : 255);

    $pdf->Cell(90,  7, $item['description'],              1, 0, 'L', $fill);
    $pdf->Cell(25,  7, number_format($item['quantity'], 2), 1, 0, 'C', $fill);
    $pdf->Cell(35,  7, 'R ' . number_format($item['unit_price'], 2), 1, 0, 'R', $fill);
    $pdf->Cell(30,  7, 'R ' . number_format($row_total,  2), 1, 1, 'R', $fill);

    $fill = !$fill;
}

/* ── Totals ── */
$pdf->Ln(2);

$pdf->SetFont('Arial', 'B', 11);
$pdf->SetFillColor($blue[0], $blue[1], $blue[2]);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(150, 8, 'TOTAL',                              1, 0, 'R', true);
$pdf->Cell(30,  8, 'R ' . number_format($grand_total, 2), 1, 1, 'R', true);

/* ── Notes ── */
if (!empty($invoice['notes'])) {
    $pdf->Ln(8);
    $pdf->SetTextColor(40, 40, 40);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(0, 6, 'NOTES:', 0, 1, 'L');
    $pdf->SetFont('Arial', '', 10);
    $pdf->SetFillColor($gray[0], $gray[1], $gray[2]);
    $pdf->MultiCell(0, 6, $invoice['notes'], 1, 'L', true);
}

/* ── Status stamp ── */
$pdf->Ln(6);
if ($invoice['status'] === 'PAID') {
    $pdf->SetFont('Arial', 'B', 28);
    $pdf->SetTextColor(22, 163, 74);
    $pdf->Cell(0, 12, 'PAID', 0, 1, 'R');
} else {
    $pdf->SetFont('Arial', 'B', 28);
    $pdf->SetTextColor(220, 38, 38);
    $pdf->Cell(0, 12, 'UNPAID', 0, 1, 'R');
}

$pdf->Output('I', 'Invoice_' . $invoice['invoice_no'] . '.pdf');
exit;