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

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

if ($id <= 0) die("Invalid 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";
if (!file_exists($templatePath)) die("Template not found: $template");

ob_start();
require $templatePath;
$invoiceHtml = ob_get_clean();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice <?= htmlspecialchars($inv['invoice_no']) ?></title>
<link rel="stylesheet" href="templates/<?= $template ?>/style.css">
<script src="../assets/js/JsBarcode.all.min.js"></script>
<script src="../assets/js/qrcode.min.js"></script>
<style>
/* ── Screen view ── */
html, body { margin: 0; padding: 20px; background: #e5e7eb; }
#invoicePreview {
    max-width: 210mm;
    min-height: 297mm;      /* full A4 height on screen preview */
    margin: 0 auto;
    background: #fff;
    box-shadow: 0 2px 16px rgba(0,0,0,.18);
    display: flex;
    flex-direction: column;
}
/* ── Print ── */
@media print {
    @page { size: A4 portrait; margin: 10mm; }
    html, body { margin: 0 !important; padding: 0 !important; background: #fff !important; }
    #invoicePreview {
        max-width: none !important;
        min-height: 0 !important;   /* template handles its own min-height */
        margin: 0 !important;
        box-shadow: none !important;
    }
}
</style>
</head>
<body>
<div id="invoicePreview">
<?= $invoiceHtml ?>
</div>
<script>
window.onload = function() {
    var barcodeEl = document.getElementById('barcode');
    if (barcodeEl && typeof JsBarcode !== 'undefined') {
        JsBarcode(barcodeEl, barcodeEl.dataset.invoice, {
            format: 'CODE128', width: 1.4, height: 45, displayValue: false, margin: 0
        });
        // Remove fixed width/height so CSS max-width/height can scale via viewBox
        barcodeEl.removeAttribute('width');
        barcodeEl.removeAttribute('height');
    }
    var qrEl = document.getElementById('upiQR');
    if (qrEl && typeof QRCode !== 'undefined') {
        new QRCode(qrEl, {
            text: 'upi://pay?pa=' + qrEl.dataset.upi + '&pn=' + encodeURIComponent(qrEl.dataset.name) + '&am=' + qrEl.dataset.amount,
            width: 90, height: 90
        });
    }
    setTimeout(function() { window.print(); }, 500);
};
</script>
</body>
</html>
