class CouponPrinter {
    static async generate(employees, config) {
        const ensureQRCode = async () => {
            if (window.QRCode) return window.QRCode;
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js';
                script.onload = () => {
                    if (window.QRCode) resolve(window.QRCode);
                    else reject(new Error("QRCode library loaded but object not found"));
                };
                script.onerror = () => reject(new Error("Gagal mengunduh library QRCode"));
                document.body.appendChild(script);
            });
        };

        try {
            const { jsPDF } = window.jspdf;
            
            let QRCode = window.QRCode;
            if (!QRCode) {
                try {
                    QRCode = await ensureQRCode();
                } catch (loadErr) {
                    throw new Error("Library QR Code gagal dimuat.");
                }
            }

            const logoUrl = window.AppAssets?.logo;
            let logoDataUrl = null;
            if (logoUrl) {
                try {
                    const getImage = (url) => new Promise((resolve, reject) => {
                        const img = new Image();
                        img.crossOrigin = 'Anonymous';
                        img.onload = () => {
                            const canvas = document.createElement('canvas');
                            canvas.width = img.width;
                            canvas.height = img.height;
                            const ctx = canvas.getContext('2d');
                            ctx.drawImage(img, 0, 0);
                            resolve(canvas.toDataURL('image/png'));
                        };
                        img.onerror = reject;
                        img.src = url;
                    });
                    logoDataUrl = await getImage(logoUrl);
                } catch (e) {
                    console.warn("Gagal memuat logo untuk kupon", e);
                }
            }
            
            const doc = new jsPDF({
                orientation: 'p',
                unit: 'mm',
                format: [215.9, 330.2] // F4
            });

            const pageWidth = 215.9;
            const pageHeight = 330.2;
            const margin = 10;
            const cols = 2;
            const rows = 5; 
            const cellWidth = (pageWidth - (margin * 2)) / cols; 
            const cellHeight = (pageHeight - (margin * 2)) / rows; 
            
            // Format Date String
            const formattedDate = new Date(config.date).toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

            doc.setFont("helvetica");

            for (let i = 0; i < employees.length; i++) {
                const emp = employees[i];
                if (i > 0 && i % (cols * rows) === 0) doc.addPage();

                const indexOnPage = i % (cols * rows);
                const col = indexOnPage % cols;
                const row = Math.floor(indexOnPage / cols);
                const x = margin + (col * cellWidth);
                const y = margin + (row * cellHeight);

                // Border
                doc.setDrawColor(0);
                doc.setLineWidth(0.3);
                doc.rect(x, y, cellWidth, cellHeight);

                // --- Coupon Content ---
                
                // QR Code (Left Vertical Center)
                const qrValue = emp.nik || `ID-${emp.id}`;
                const qrDataUrl = await QRCode.toDataURL(qrValue, { width: 100, margin: 0 });
                const qrSize = 22;
                const qrX = x + 2;
                const qrY = y + (cellHeight - qrSize) / 2;
                doc.addImage(qrDataUrl, 'PNG', qrX, qrY, qrSize, qrSize);

                // NIK (Below QR Code)
                doc.setFontSize(7);
                doc.setTextColor(100);
                const nikText = `NIK: ${emp.nik || '-'}`;
                const nikTextWidth = doc.getTextWidth(nikText);
                const nikX = qrX + Math.max(0, (qrSize - nikTextWidth) / 2);
                const nikY = qrY + qrSize + 4;
                doc.text(nikText, nikX, nikY);
                doc.setTextColor(0);

                // Start Content after QR
                let contentStartX = qrX + qrSize + 3;
                const contentWidth = cellWidth - (contentStartX - x) - 2;

                // --- Header Block (Logo + Title) ---
                const logoSize = 10;
                let textX = contentStartX;
                let topY = y + 4;
                
                if (logoDataUrl) {
                    doc.addImage(logoDataUrl, 'PNG', contentStartX, topY, logoSize, logoSize);
                    textX += logoSize + 3;
                }

                doc.setFont("helvetica", "bold");
                doc.setFontSize(9);
                doc.text("KUPON PENGAMBILAN PARCEL", textX, topY + 3);
                doc.setFontSize(8);
                doc.text("PONPES KARANGASEM PACIRAN", textX, topY + 7);
                doc.text(`TAHUN ${config.year}`, textX, topY + 11);

                // Line Separator
                const headerLineY = topY + 13;
                doc.setDrawColor(0);
                doc.setLineWidth(0.2);
                doc.line(contentStartX, headerLineY, x + cellWidth - 3, headerLineY);

                // --- Employee Info ---
                let infoY = headerLineY + 5;
                
                doc.setFont("helvetica", "bold");
                doc.setFontSize(10);
                const splitName = doc.splitTextToSize(emp.nama || '-', contentWidth);
                
                doc.setTextColor(220, 38, 38); // Red Color
                doc.text(splitName, contentStartX, infoY);
                doc.setTextColor(0, 0, 0); // Reset

                let nextY = infoY + (splitName.length * 4.5);

                doc.setFontSize(9);
                doc.setFont("helvetica", "normal");
                
                const jabatan = emp.jabatan || 'Anggota';
                const splitJabatan = doc.splitTextToSize(jabatan, contentWidth);
                doc.text(splitJabatan, contentStartX, nextY);
                
                let unitY = nextY + (splitJabatan.length * 4);

                // Unit Name
                const unitName = emp.satminkal || emp.lembaga || '-';
                doc.setFont("helvetica", "bold");
                doc.setTextColor(0, 51, 204); // Blue
                const splitUnit = doc.splitTextToSize(unitName, contentWidth);
                doc.text(splitUnit, contentStartX, unitY);
                
                doc.setTextColor(0, 0, 0);
                doc.setFont("helvetica", "normal");

                let eventY = unitY + (splitUnit.length * 4) + 3;

                // --- Event Details ---
                doc.setFontSize(8);
                const labelWidth = 18;
                
                // Hari/Tanggal
                doc.setFont("helvetica", "bold");
                doc.text("Hari/Tanggal", contentStartX, eventY);
                doc.setFont("helvetica", "normal");
                doc.text(":", contentStartX + labelWidth, eventY);
                doc.text(formattedDate, contentStartX + labelWidth + 2, eventY);
                
                // Pukul
                eventY += 3.5;
                doc.setFont("helvetica", "bold");
                doc.text("Pukul", contentStartX, eventY);
                doc.setFont("helvetica", "normal");
                doc.text(":", contentStartX + labelWidth, eventY);
                doc.text(`${config.startTime} - ${config.endTime} WIB`, contentStartX + labelWidth + 2, eventY);

                // Tempat
                eventY += 3.5;
                doc.setFont("helvetica", "bold");
                doc.text("Tempat", contentStartX, eventY);
                doc.setFont("helvetica", "normal");
                doc.text(":", contentStartX + labelWidth, eventY);
                const maxLocWidth = contentWidth - labelWidth - 2;
                const splitLoc = doc.splitTextToSize(config.location, maxLocWidth);
                doc.text(splitLoc, contentStartX + labelWidth + 2, eventY);
                
                // Keterangan
                if (config.note) {
                    eventY += (splitLoc.length * 3.5) + 1;
                    doc.setFont("helvetica", "bold");
                    doc.text("Keterangan", contentStartX, eventY);
                    doc.setFont("helvetica", "normal");
                    doc.text(":", contentStartX + labelWidth, eventY);
                    const splitNote = doc.splitTextToSize(config.note, maxLocWidth);
                    doc.text(splitNote, contentStartX + labelWidth + 2, eventY);
                }

            }

            const fileName = `Kupon_Parsel_${config.year}_${new Date().getTime()}.pdf`;
            doc.save(fileName);
            return true;

        } catch (err) {
            console.error("Print Coupon Error:", err);
            throw err;
        }
    }
}

// Attach to window for global access
window.CouponPrinter = CouponPrinter;
