<?php
require_once '../db.php';
require_once '../includes/company.php';
require_once '../includes/number_to_words.php';

$id       = (int)($_GET['id'] ?? 0);
$template = preg_replace('/[^a-z]/', '', $_GET['template'] ?? 'simple');

if ($id <= 0) die("Invalid Invoice ID");

$inv = $conn->query("SELECT * FROM sales_invoices WHERE id = $id")->fetch_assoc();
if (!$inv) die("Invoice not found");

$company = getCompany($conn, $inv['company_id']);
$client  = $conn->query("SELECT * FROM clients WHERE id = {$inv['client_id']}")->fetch_assoc();
$items   = $conn->query("
    SELECT si.*, p.name AS product_name, p.hsn_code, p.unit,
           pi.mrp, pi.batch_no, pi.purchase_price
    FROM sales_items si
    JOIN products p ON p.id = si.product_id
    LEFT JOIN purchase_items pi ON pi.id = si.purchase_item_id
    WHERE si.sales_invoice_id = $id
");

$templatePath = __DIR__ . "/templates/$template/layout.php";
$stylePath    = __DIR__ . "/templates/$template/style.css";
if (!file_exists($templatePath)) die("Template not found: $template");

$css = file_exists($stylePath) ? file_get_contents($stylePath) : '';

// dompdf does not support flexbox — these overrides replace flex layouts
// with block/float/table equivalents for correct PDF rendering
$pdfCssOverrides = '
@page { margin: 10mm 8mm; }
body { font-family: DejaVu Sans, sans-serif; }
.simple-invoice, .modern-invoice, .tally-invoice { display: block !important; min-height: 0 !important; }
.si-bottom, .ti-bottom { display: block !important; margin-top: 0 !important; }
.si-totals-wrap { display: block !important; overflow: hidden !important; }
.si-totals { float: right !important; }
.mi-totals-wrap { display: block !important; overflow: hidden !important; }
.ti-head-left { padding: 5px 8px !important; }
.ti-company-name { font-size: 13px !important; margin-bottom: 1px !important; }
.ti-company-sub { font-size: 9px !important; line-height: 1.35 !important; }
.ti-meta-table { height: auto !important; }
.ti-meta-table td { padding: 3px 6px !important; }
.ti-meta-k { font-size: 8px !important; }
.ti-meta-v { font-size: 10px !important; }
';

// Outer border per template — wrapping in a table is the only reliable way
// to get all-4-sides border in dompdf (div borders overflow on the right)
$_pdfBorders = [
    'simple' => '1.5px solid #2563eb',
    'modern' => '1.5px solid #444',
    'tally'  => '1.5px solid #000',
];
$_pdfBorder = $_pdfBorders[$template] ?? '1.5px solid #333';

$isPdf = true;

$qrLibPath = __DIR__ . '/../vendors/phpqrcode/phpqrcode.php';
$hasPHPQR  = file_exists($qrLibPath);
if ($hasPHPQR) require_once $qrLibPath;

ob_start();
require $templatePath;
$invoiceHtml = ob_get_clean();

$html = '<!DOCTYPE html><html><head><meta charset="utf-8">'
    . '<style>' . $css . $pdfCssOverrides . '</style>'
    . '</head><body>'
    . '<table style="width:100%;border-collapse:collapse;border:' . $_pdfBorder . ';"><tr><td style="padding:0;margin:0;">'
    . $invoiceHtml
    . '</td></tr></table>'
    . '</body></html>';

require_once '../vendors/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', false);
$options->set('defaultFont', 'DejaVu Sans');
$options->set('chroot', realpath(__DIR__ . '/../'));

$dompdf = new Dompdf($options);
$dompdf->setBasePath(realpath(__DIR__));
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$filename = 'Invoice_' . preg_replace('/[^A-Za-z0-9\-_]/', '_', $inv['invoice_no']) . '.pdf';
$dompdf->stream($filename, ['Attachment' => true]);
