<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid Invoice");

$type  = $_GET['type']  ?? 'invoice';   // invoice | transport
$paper = $_GET['paper'] ?? 'thermal';   // thermal | a4
?>

<!-- Screen CSS -->
<link rel="stylesheet" href="../assets/css/screen_invoice.css">

<!-- Dynamic Print CSS -->
<link rel="stylesheet" id="printStyle"
      href="../assets/css/<?= ($paper=='thermal'?'print_thermal.css':'print_a4_tally.css') ?>"
      media="print">

<!-- Barcode & QR -->
<script src="../assets/js/JsBarcode.all.min.js"></script>
<script src="../assets/js/qrcode.min.js"></script>

<div class="content-wrapper">
<div class="main-content">


    <!-- TOOLBAR -->
    <div class="invoice-toolbar no-print">
        <form id="printForm" method="get">
            <input type="hidden" name="id" value="<?= $id ?>">

            <label>
                <input type="radio" name="type" value="invoice" <?= $type=='invoice'?'checked':'' ?>>
                Invoice Copy
            </label>

            <label>
                <input type="radio" name="type" value="transport" <?= $type=='transport'?'checked':'' ?>>
                Transport Copy
            </label>

            &nbsp;&nbsp;|&nbsp;&nbsp;

            <label>
                <input type="radio" name="paper" value="thermal" <?= $paper=='thermal'?'checked':'' ?>>
                Thermal 80mm
            </label>

            <label>
                <input type="radio" name="paper" value="a4" <?= $paper=='a4'?'':'' ?>>
                A4
            </label>

            &nbsp;&nbsp;|&nbsp;&nbsp;

            <button type="submit">Preview</button>
            <button type="button" onclick="window.print()">Print</button>
        </form>
    </div>

    <!-- PREVIEW -->
    <div class="invoice-wrapper" id="invoicePreview">
        Loading...
    </div>
<div class="no-print">
    <button><a href="index.php">Back to List</a></button>
</div>
</div>
</div>

<script>
function loadLayout() {
    const type  = document.querySelector('input[name="type"]:checked').value;
    const paper = document.querySelector('input[name="paper"]:checked').value;

    // Switch print CSS
    document.getElementById('printStyle').href =
        (paper === 'thermal')
            ? '../assets/css/print_thermal.css'
            : '../assets/css/print_a4_tally.css';

    fetch(`layout_loader.php?id=<?= $id ?>&type=${type}&paper=${paper}`)
        .then(r => r.text())
        .then(html => {
            document.getElementById('invoicePreview').innerHTML = html;
            renderCodes();
        });
}

// Barcode + QR
function renderCodes() {

    const barcodeEl = document.getElementById("barcode");
    if (barcodeEl) {
        JsBarcode(barcodeEl, barcodeEl.dataset.invoice, {
            format: "CODE128",
            width: 1.4,
            height: 45,
            displayValue: false,
            margin: 0
        });
    }

    const qrEl = document.getElementById("upiQR");
    if (qrEl) {
        qrEl.innerHTML = "";

        const upi    = qrEl.dataset.upi;
        const name   = qrEl.dataset.name;
        const amount = qrEl.dataset.amount;

        const upiString = `upi://pay?pa=${upi}&pn=${encodeURIComponent(name)}&am=${amount}`;

        new QRCode(qrEl, {
            text: upiString,
            width: (document.querySelector('input[name="paper"]:checked').value === 'thermal') ? 90 : 120,
            height: (document.querySelector('input[name="paper"]:checked').value === 'thermal') ? 90 : 120
        });
    }
}



function renderBarcodeAndQR() {

    const container = document.getElementById('thermalPreview');
    if (!container) return;

    // BARCODE
    const barcodeEl = container.querySelector("#barcode");
    if (barcodeEl) {
        const invNo = barcodeEl.dataset.invoice;
        JsBarcode(barcodeEl, invNo, {
            format: "CODE128",
            width: 1.4,
            height: 40,
            displayValue: false,
            margin: 0
        });
    }

    // UPI QR
    const qrEl = container.querySelector("#upiQR");
    if (qrEl) {
        qrEl.innerHTML = "";

        const upi = qrEl.dataset.upi;
        const name = qrEl.dataset.name;
        const amount = qrEl.dataset.amount;

        const upiString = `upi://pay?pa=${upi}&pn=${encodeURIComponent(name)}&am=${amount}`;

        new QRCode(qrEl, {
            text: upiString,
            width: 90,
            height: 90
        });
    }
}

function printInvoice() {
    window.print();
}

// Bind
document.querySelectorAll('input[name="type"], input[name="paper"]').forEach(el => {
    el.addEventListener('change', loadLayout);
});

// Initial
loadLayout();
</script>
<?php require_once '../includes/footer.php'; ?>
