let pmModule = '';
let pmId = 0;
let pmPaper = 'thermal';

function openPrintModal(module, id, type = 'invoice', paper = 'thermal') {
    pmModule = module;
    pmId = id;
    pmPaper = paper;
	document.body.classList.add('print-modal-active'); // ✅ ADD
    document.getElementById('printModal').style.display = 'flex';

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

    setModalWidth();
    loadPrintLayout(type);
}

function closePrintModal() {
	document.body.classList.remove('print-modal-active'); // ✅ REMOVE
    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) {
    fetch(`../${pmModule}/layout_loader.php?id=${pmId}&paper=${pmPaper}&type=${type}`)
        .then(r => r.text())
        .then(html => {
            const body = document.getElementById('printModalBody');
            body.innerHTML = html;
            renderBarcodeAndQR(body);
        });
}

function printModalNow() {

    // 🔥 Force modal print mode ON
    document.body.classList.add('print-modal-active');

    // Ensure CSS is applied before print
    setTimeout(() => {
        window.print();
    }, 50);
}

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

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

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