let pmModule = '';
let pmId = 0;
let pmPaper = 'thermal';
let pmTemplate = 'simple';   // default
let pmType = 'invoice';

function openPrintModal(module, id, type = 'invoice', paper = 'thermal', template = 'simple') {

    pmModule = module;
    pmId = id;
    pmPaper = paper;
    pmTemplate = template;
    pmType = type;

    document.body.classList.add('print-modal-active');
    document.getElementById('printModal').style.display = 'flex';

    // set correct radio checked
    document.querySelectorAll('input[name="pmType"]').forEach(r => {
        r.checked = (r.value === type);
    });

    setModalWidth();
    loadPrintLayout(type);
}

function closePrintModal() {
    document.body.classList.remove('print-modal-active');
    document.getElementById('printModal').style.display = 'none';
}

function setModalWidth() {
    const box = document.getElementById('printModalBox');
    box.classList.remove('paper-thermal', 'paper-a4');
    box.classList.add(pmPaper === 'thermal' ? 'paper-thermal' : 'paper-a4');
}

function loadPrintLayout(type) {

    pmType = type;

    document.getElementById('printModalBody').innerHTML = "Loading...";

    fetch(`../${pmModule}/layout_loader_thermal.php?id=${pmId}&type=${type}`)
        .then(r => r.text())
        .then(html => {

            document.getElementById('printModalBody').innerHTML = html;

            setTimeout(() => {
                renderBarcodeAndQR(document.getElementById('printModalBody'));
            }, 100);

        })
        .catch(err => {
            document.getElementById('printModalBody').innerHTML =
                "<div style='color:red;padding:10px;'>Invoice not loaded</div>";
            console.error(err);
        });
}

// ========================
// PRINT MODAL ONLY
// ========================
function printThermalPopup() {
    document.body.classList.add("print-modal-active");

    setTimeout(() => {
        window.print();
    }, 100);
}

window.addEventListener("afterprint", function () {
    document.body.classList.remove("print-modal-active");
});

// ========================
// TOGGLE LISTENER FIX
// ========================
document.addEventListener('change', function (e) {
    if (e.target.name === "pmType") {
        loadPrintLayout(e.target.value);
    }
});

// ========================
// BARCODE + QR
// ========================
function renderBarcodeAndQR(container) {

    const barcodeEl = container.querySelector("#barcode");
    if (barcodeEl) {
        const val = barcodeEl.dataset.invoice;
        JsBarcode(barcodeEl, val, {
            format: "CODE128",
            width: pmPaper === 'thermal' ? 1.4 : 1.2,
            height: pmPaper === 'thermal' ? 40 : 45,
            displayValue: false,
            margin: 0
        });
    }

    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: pmPaper === 'thermal' ? 90 : 120,
            height: pmPaper === 'thermal' ? 90 : 120
        });
    }
}
