/**
 * FEL Integration - Sistema Sufarma
 * Versión Modificada: Conserva todo el código original + Selección de Fecha + Recarga Admin
 */

class FEL {
    constructor() {
        this.ventaId = null;
        this.itemsToInvoice = [];
        this.logoUrl = 'assets/images/logo.png';
    }

    openModal(ventaId, items) {
        this.ventaId = ventaId;
        this.itemsToInvoice = items;
        this.renderModal();
    }

    renderModal() {
        const modal = document.getElementById('felModal');
        if (!modal) return;

        // --- LÓGICA FECHA RETROACTIVA (NUEVO) ---
        const hoy = new Date();
        const hace5dias = new Date();
        hace5dias.setDate(hoy.getDate() - 5);
        const maxDate = hoy.toISOString().split('T')[0];
        const minDate = hace5dias.toISOString().split('T')[0];
        // -----------------------------------------

        const modalBody = modal.querySelector('.modal-body');

        modalBody.innerHTML = `
            <div style="padding:25px;">
                <div style="text-align:center; margin-bottom:20px;">
                    <img src="${this.logoUrl}" style="max-height:50px; display:block; margin:0 auto; filter:brightness(0) invert(1);" onerror="this.style.display='none'">
                    <h3 style="margin:10px 0 0; color:var(--neon-cyan); font-weight:800; text-shadow:var(--shadow-glow-cyan);">Facturación Electrónica</h3>
                    <p style="font-size:0.9em; color:var(--text-secondary);">Venta #${this.ventaId}</p>
                </div>
                
                <div id="felStatus" style="display:none; padding:12px; border-radius:8px; margin-bottom:20px; font-size:0.9rem; text-align:center;"></div>

                <div style="margin-bottom:15px;">
                    <label style="font-size:0.75rem; color:var(--text-primary); font-weight:bold; letter-spacing:0.5px; text-transform:uppercase;">Fecha de Emisión</label>
                    <input type="date" id="felDate" value="${maxDate}" max="${maxDate}" min="${minDate}" 
                        style="width:100%; padding:10px; border:2px solid var(--border-color); border-radius:12px; font-family:inherit; background:var(--background); color:var(--text-primary); outline:none;">
                    <small style="font-size:0.7rem; color:var(--warning-color); display:block; margin-top:3px;">ℹ️ Permitido hasta 5 días atrás por la SAT.</small>
                </div>

                <div style="display:flex; gap:10px; margin-bottom:15px;">
                    <select id="felType" style="padding:12px; border:2px solid var(--border-color); border-radius:12px; background-color:var(--background); color:var(--text-primary); font-weight:500; outline:none;">
                        <option value="NIT">NIT</option>
                        <option value="CUI">DPI</option>
                        <option value="CF">CF</option>
                    </select>
                    <div style="position:relative; flex:1;">
                        <input type="text" id="felNit" placeholder="Ingrese número..." style="width:100%; padding:12px; padding-right: 45px; border:2px solid var(--border-color); background:var(--background); color:var(--text-primary); border-radius:12px; outline:none;">
                        <button id="btnSearch" style="position:absolute; right:8px; top:8px; padding:4px 8px; border:none; background:transparent; cursor:pointer; font-size:1.2rem;">🔍</button>
                    </div>
                </div>

                <div style="background:var(--card-bg); padding:15px; border-radius:12px; border:1px solid var(--border-color); margin-bottom:20px;">
                    <label style="font-size:0.75rem; color:var(--text-primary); font-weight:bold; letter-spacing:0.5px; text-transform:uppercase;">Nombre del Cliente</label>
                    <input type="text" id="felName" style="width:100%; padding:8px 0; background:transparent; border:none; border-bottom:1px solid var(--border-color); font-size:1rem; color:var(--neon-cyan); outline:none;">
                    
                    <label style="font-size:0.75rem; color:var(--text-primary); font-weight:bold; letter-spacing:0.5px; text-transform:uppercase; display:block; margin-top:10px;">Dirección</label>
                    <input type="text" id="felAddr" style="width:100%; padding:8px 0; background:transparent; border:none; border-bottom:1px solid var(--border-color); font-size:1rem; color:var(--neon-cyan); outline:none;">
                </div>

                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px; margin-top:25px;">
                    <button class="close-modal" style="padding:12px; background:transparent; border:1px solid var(--border-color); border-radius:12px; color:var(--text-primary); font-weight:600; cursor:pointer; transition:0.2s;" onmouseover="this.style.color='var(--neon-red)'; this.style.borderColor='var(--neon-red)';" onmouseout="this.style.color='var(--text-primary)'; this.style.borderColor='var(--border-color)';">Cancelar</button>
                    <button id="btnCertify" disabled style="padding:12px; background:var(--secondary-light); color:white; border:none; border-radius:12px; font-weight:600; cursor:not-allowed; transition:0.3s;">Certificar Venta</button>
                </div>
            </div>
        `;

        Object.assign(modal.style, { display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(0, 0, 0, 0.75)', backdropFilter: 'blur(4px)' });
        const content = modal.querySelector('.modal-content');
        if (content) Object.assign(content.style, { width: '90%', maxWidth: '420px', background: 'var(--surface-elevated)', borderRadius: '16px', boxShadow: '0 10px 40px rgba(0, 233, 255, 0.15), 0 0 0 1px var(--border-color)', border: 'none' });

        this.attachEvents(modal);
    }

    showMessage(msg, type = 'info') {
        const el = document.getElementById('felStatus');
        el.style.display = 'block';
        el.textContent = msg;
        el.style.background = type === 'error' ? '#fef2f2' : (type === 'success' ? '#f0fdf4' : '#eff6ff');
        el.style.color = type === 'error' ? '#991b1b' : (type === 'success' ? '#166534' : '#1e40af');
        el.style.border = `1px solid ${type === 'error' ? '#fecaca' : (type === 'success' ? '#bbf7d0' : '#bfdbfe')}`;
    }

    attachEvents(modal) {
        modal.querySelectorAll('.close-modal').forEach(b => b.onclick = () => modal.style.display = 'none');

        const inputType = document.getElementById('felType');
        const inputNit = document.getElementById('felNit');
        const inputName = document.getElementById('felName');
        const inputAddr = document.getElementById('felAddr');
        const btnSearch = document.getElementById('btnSearch');
        const btnCertify = document.getElementById('btnCertify');
        // Nuevo input fecha
        const inputDate = document.getElementById('felDate');

        inputType.onchange = () => {
            if (inputType.value === 'CF') {
                inputNit.value = 'CF'; inputNit.disabled = true;
                inputName.value = 'CONSUMIDOR FINAL'; inputName.readOnly = true;
                inputAddr.value = 'CIUDAD';
            } else {
                inputNit.value = ''; inputNit.disabled = false;
                inputName.value = ''; inputName.readOnly = false;
                inputAddr.value = '';
            }
            this.checkReady();
        };

        btnSearch.onclick = async () => {
            if (!inputNit.value) return;
            btnSearch.textContent = '⏳';
            try {
                const res = await fetch('api/fel/lookup_nit.php', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ identifier: inputNit.value, type: inputType.value })
                });
                const data = await res.json();
                if (data.success) {
                    inputName.value = data.data.name || '';
                    inputAddr.value = data.data.address || 'CIUDAD';
                    this.showMessage("✅ Datos encontrados", "success");
                } else {
                    this.showMessage("⚠️ No encontrado, ingrese manualmente", "info");
                }
            } catch (e) { console.error(e); }
            btnSearch.textContent = '🔍';
            this.checkReady();
        };

        [inputName, inputNit].forEach(el => el.addEventListener('input', () => this.checkReady()));

        btnCertify.onclick = async () => {
            if (!inputName.value || !inputNit.value) return;

            btnCertify.disabled = true;
            btnCertify.innerHTML = `Procesando...`;

            // Deshabilitar botón de cerrar durante el proceso
            modal.querySelectorAll('.close-modal').forEach(b => b.disabled = true);

            try {
                // Preparar datos del comprador
                const buyerData = {
                    taxID: inputNit.value,
                    name: inputName.value,
                    address: inputAddr.value || 'CIUDAD',
                    type: inputType.value
                };

                // Detectar si hay productos mixtos (exentos + gravados)
                const itemsExentos = this.itemsToInvoice.filter(i => i.exento_iva == 1);
                const itemsGravados = this.itemsToInvoice.filter(i => i.exento_iva != 1);
                const hasMixed = itemsExentos.length > 0 && itemsGravados.length > 0;

                if (hasMixed) {
                    // CASO: Productos Mixtos - Generar 2 facturas, imprimir 2 tickets separados en una ventana
                    this.showMessage("🚀 Generando factura 1 de 2 (Productos Exentos)...", "info");

                    const result1 = await this.certifyInvoice(itemsExentos, buyerData, inputDate.value, "1 de 2");
                    if (!result1.success) {
                        throw new Error(result1.error || "Error en factura 1");
                    }

                    // Pequeña pausa entre facturas
                    await new Promise(resolve => setTimeout(resolve, 1000));

                    this.showMessage("🚀 Generando factura 2 de 2 (Productos Gravados)...", "info");

                    const result2 = await this.certifyInvoice(itemsGravados, buyerData, inputDate.value, "2 de 2");
                    if (!result2.success) {
                        throw new Error(result2.error || "Error en factura 2");
                    }

                    // ✨ IMPRIMIR DOS FACTURAS SEPARADAS EN UNA SOLA VENTANA
                    this.showMessage("✅ ¡2 Facturas generadas! Imprimiendo...", "success");
                    this.printMultipleTickets([result1.data, result2.data]);

                } else {
                    // CASO: Un solo tipo de producto - Factura única
                    this.showMessage("🚀 Conectando con SAT...", "info");

                    const result = await this.certifyInvoice(this.itemsToInvoice, buyerData, inputDate.value);
                    if (result.success) {
                        this.printTicket(result.data);
                        this.showMessage("✅ ¡Factura Exitosa!", "success");
                    } else {
                        throw new Error(result.error || "Error desconocido");
                    }
                }

                // --- RECARGA DE PÁGINAS ---
                setTimeout(() => {
                    modal.style.display = 'none';
                    // Recargar lista lateral del POS si existe
                    if (typeof recentSales !== 'undefined') recentSales.loadRecentSales();

                    // Recargar lista de Admin si existe la función global
                    if (typeof window.reloadAdminVentas === 'function') {
                        window.reloadAdminVentas();
                    }

                    // Recargar Ventas del Día si está abierto
                    if (typeof window.reloadVentasDia === 'function') {
                        window.reloadVentasDia();
                    }
                }, 1500);
                // --------------------------

            } catch (error) {
                this.showMessage("❌ Error: " + error.message, "error");
                btnCertify.disabled = false;
                btnCertify.textContent = "Certificar Venta";
                // Rehabilitar botón de cerrar
                modal.querySelectorAll('.close-modal').forEach(b => b.disabled = false);
            }
        };
    }

    /**
     * Método para certificar una factura
     * @param {Array} items - Items a facturar
     * @param {Object} buyerData - Datos del comprador
     * @param {String} fechaEmision - Fecha de emisión
     * @param {String} sequence - Secuencia de factura (opcional, ej: "1 de 2")
     * @returns {Promise<Object>} - Resultado de la certificación
     */
    async certifyInvoice(items, buyerData, fechaEmision, sequence = null) {
        const payload = {
            venta_id: this.ventaId,
            items: items,
            fecha_emision: fechaEmision,
            buyer: buyerData,
            invoice_sequence: sequence
        };

        const res = await fetch('api/fel/certificar.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        return await res.json();
    }

    checkReady() {
        const btn = document.getElementById('btnCertify');
        if (document.getElementById('felName').value && document.getElementById('felNit').value) {
            btn.disabled = false;
            btn.style.background = 'var(--neon-cyan)';
            btn.style.color = 'var(--background)';
            btn.style.boxShadow = 'var(--shadow-glow-cyan)';
            btn.style.cursor = 'pointer';
            
            // Add hover effects dynamically
            btn.onmouseover = () => {
                btn.style.transform = 'translateY(-2px)';
                btn.style.boxShadow = '0 0 20px rgba(0, 233, 255, 0.6)';
            };
            btn.onmouseout = () => {
                btn.style.transform = 'translateY(0)';
                btn.style.boxShadow = 'var(--shadow-glow-cyan)';
            };
        } else {
            btn.disabled = true;
            btn.style.background = 'var(--secondary-light)';
            btn.style.color = 'white';
            btn.style.boxShadow = 'none';
            btn.style.cursor = 'not-allowed';
            btn.onmouseover = null;
            btn.onmouseout = null;
        }
    }

    /**
     * Imprimir múltiples tickets en una sola ventana (facturas separadas en tira continua)
     * @param {Array} invoicesData - Array de datos de facturas
     */
    printMultipleTickets(invoicesData) {
        const fmt = (num) => "Q" + parseFloat(num).toFixed(2);

        // Generar HTML para cada factura
        let allInvoicesHtml = '';

        invoicesData.forEach((data, index) => {
            // Ajuste visual de fecha para el ticket
            const dateObj = new Date(data.fecha);
            const dia = String(dateObj.getDate()).padStart(2, '0');
            const mes = String(dateObj.getMonth() + 1).padStart(2, '0');
            const anio = dateObj.getFullYear();
            const horaStr = dateObj.toLocaleTimeString('es-GT', { hour: '2-digit', minute: '2-digit', hour12: false });
            const fechaCompleta = `${dia}-${mes}-${anio} ${horaStr}`;

            let itemsHtml = '';
            data.items.forEach(item => {
                itemsHtml += `
                    <tr>
                        <td class="qty">${item.Qty}</td>
                        <td class="desc">${item.Description}</td>
                        <td class="qty" style="width:15%; text-align:right; padding-right:5px;">${fmt(item.Totals.TotalItem / item.Qty)}</td>
                        <td class="total">${fmt(item.Totals.TotalItem)}</td>
                    </tr>`;
            });

            // Agregar separador entre facturas (excepto después de la última)
            const separator = index < invoicesData.length - 1 ? `
                <div class="invoice-separator">
                    <div style="border-top: 2px dashed #000; margin: 20px 0;"></div>
                    <div style="text-align: center; font-size: 10px; margin: 10px 0;">✂ ---------------------- CORTAR AQUÍ ---------------------- ✂</div>
                    <div style="border-top: 2px dashed #000; margin: 20px 0;"></div>
                </div>
            ` : '';

            allInvoicesHtml += `
                <div class="invoice-section">
                    <div class="header-logo">
                        <img src="${this.logoUrl}" alt="LOGO" onerror="this.style.display='none'">
                    </div>
                    
                    <div class="text-center bold" style="font-size: 13px;">${data.emisor.nombre}</div>
                    <div class="text-center">${data.emisor.direccion}</div>
                    <div class="text-center bold">NIT: ${data.emisor.nit}</div>
                    
                    <div class="separator"></div>
                    
                    <div style="font-size: 12px;">Documento Tributario Electrónico</div>
                    <div class="text-center bold" style="font-size: 14px; margin-bottom: 5px;">FACTURA</div>
                    
                    <div>
                        <span class="data-label">Numero de Autorización:</span><br>
                        ${data.uuid}
                    </div>
                    
                    <div class="data-row" style="margin-top:5px;">
                        <div><span class="data-label">Serie:</span>   ${data.serie}</div>
                        <div><span class="data-label">No:</span>   ${data.numero}</div>
                    </div>

                    <div class="data-row">
                        <div><span class="data-label">Fecha De Emisión:</span> ${fechaCompleta}</div>
                    </div>
                    <div class="separator"></div>
                    
                    <div style="margin-bottom: 2px;">
                        <span class="bold">CLIENTE:</span> ${data.receptor.Name}
                    </div>
                    <div>
                        <span class="bold">NIT/CUI:</span> ${data.receptor.TaxID}
                    </div>
                    <div>
                        <span class="bold">DIR:</span> ${data.receptor.AddressInfo.Address}
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th class="text-center">CANT</th>
                                <th style="padding-left:5px;">DESCRIPCION</th>
                                <th class="text-right" style="width:15%;">P.UNIT</th>
                                <th class="text-right">TOTAL</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${itemsHtml}
                        </tbody>
                    </table>

                    <div class="grand-total">
                        <span>TOTAL:</span>
                        <span>${fmt(data.total)}</span>
                    </div>

                    <div class="footer">
                        Sujeto a pagos trimestrales ISR<br>
                        Certificador: DIGIFACT<br>
                        <br>
                        *** GRACIAS POR SU COMPRA ***
                    </div>
                </div>
                ${separator}
            `;
        });

        // Abrir ventana de impresión
        const uniqueWindowName = 'PrintTicket_' + Date.now();
        const win = window.open('', uniqueWindowName, 'width=400,height=800');

        if (!win) {
            console.error('No se pudo abrir la ventana de impresión.');
            return;
        }

        win.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Facturas</title>
                <style>
                    @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;500;700&display=swap');
                    
                    body {
                        font-family: 'Roboto Mono', 'Courier New', monospace;
                        font-size: 11px;
                        line-height: 1.2;
                        margin: 0;
                        padding: 5px;
                        width: 72mm;
                        color: #000;
                    }
                    .text-center { text-align: center; }
                    .text-right { text-align: right; }
                    .bold { font-weight: 700; }
                    
                    .header-logo { margin-bottom: 5px; }
                    .header-logo img { max-width: 60%; height: auto; display: block; margin: 0 auto; -webkit-filter: grayscale(100%); filter: grayscale(100%); }
                    
                    .separator {
                        border-bottom: 1px dashed #000;
                        margin: 5px 0;
                        display: block;
                    }
                    
                    .data-row {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 2px;
                    }
                    .data-label {
                        font-weight: bold;
                    }
                    
                    table { width: 100%; border-collapse: collapse; margin-top: 5px; }
                    th { border-bottom: 1px solid #000; text-align: left; padding-bottom: 2px; font-size: 10px; }
                    td { vertical-align: top; padding: 2px 0; }
                    
                    .qty { width: 10%; text-align: center; }
                    .desc { width: 65%; padding-left: 5px; white-space: pre-wrap; }
                    .total { width: 25%; text-align: right; }
                    
                    .grand-total { font-size: 16px; font-weight: 700; border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 5px 0; margin-top: 5px; display:flex; justify-content:space-between; }
                    
                    .footer { margin-top: 15px; font-size: 9px; text-align: center; color: #444; }
                    
                    .invoice-section { margin-bottom: 10px; }
                    .invoice-separator { margin: 20px 0; }
                    
                    @media print {
                        .invoice-separator {
                            page-break-after: avoid;
                        }
                    }
                </style>
            </head>
            <body>
                ${allInvoicesHtml}

                <script>
                    window.onload = function() {
                        setTimeout(function() {
                            window.print();
                            // Cerrar ventana después de imprimir o cancelar
                            window.onafterprint = function() {
                                window.close();
                            };
                            // Fallback: cerrar después de un breve delay
                            setTimeout(function() {
                                window.close();
                            }, 100);
                        }, 500);
                    }
                </script>
            </body>
            </html>
        `);

        win.document.close();
    }

    // --- CÓDIGO ORIGINAL DE IMPRESIÓN (SIN CAMBIOS ESTRUCTURALES) ---
    printTicket(data) {
        const fmt = (num) => "Q" + parseFloat(num).toFixed(2);

        // Ajuste visual de fecha para el ticket
        const dateObj = new Date(data.fecha);
        const dia = String(dateObj.getDate()).padStart(2, '0');
        const mes = String(dateObj.getMonth() + 1).padStart(2, '0');
        const anio = dateObj.getFullYear();
        // Usamos formato 24h para evitar confusión
        const horaStr = dateObj.toLocaleTimeString('es-GT', { hour: '2-digit', minute: '2-digit', hour12: false });
        const fechaCompleta = `${dia}-${mes}-${anio} ${horaStr}`;

        let itemsHtml = '';
        data.items.forEach(item => {
            itemsHtml += `
                <tr>
                    <td class="qty">${item.Qty}</td>
                    <td class="desc">${item.Description}</td>
                    <td class="qty" style="width:15%; text-align:right; padding-right:5px;">${fmt(item.Totals.TotalItem / item.Qty)}</td>
                    <td class="total">${fmt(item.Totals.TotalItem)}</td>
                </tr>`;
        });

        // Usar nombre único para cada ventana de impresión (evita conflictos)
        const uniqueWindowName = 'PrintTicket_' + Date.now();
        const win = window.open('', uniqueWindowName, 'width=400,height=600');

        // Verificar que la ventana se abrió correctamente
        if (!win) {
            console.error('No se pudo abrir la ventana de impresión. Verifique el bloqueador de ventanas emergentes.');
            return;
        }

        win.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Factura ${data.serie}-${data.numero}</title>
                <style>
                    @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;500;700&display=swap');
                    
                    body {
                        font-family: 'Roboto Mono', 'Courier New', monospace;
                        font-size: 11px;
                        line-height: 1.2;
                        margin: 0;
                        padding: 5px;
                        width: 72mm;
                        color: #000;
                    }
                    .text-center { text-align: center; }
                    .text-right { text-align: right; }
                    .bold { font-weight: 700; }
                    
                    .header-logo { margin-bottom: 5px; }
                    .header-logo img { max-width: 60%; height: auto; display: block; margin: 0 auto; -webkit-filter: grayscale(100%); filter: grayscale(100%); }
                    
                    .separator {
                        border-bottom: 1px dashed #000;
                        margin: 5px 0;
                        display: block;
                    }
                    
                    .data-row {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 2px;
                    }
                    .data-label {
                        font-weight: bold;
                    }
                    
                    /* Tabla de Items */
                    table { width: 100%; border-collapse: collapse; margin-top: 5px; }
                    th { border-bottom: 1px solid #000; text-align: left; padding-bottom: 2px; font-size: 10px; }
                    td { vertical-align: top; padding: 2px 0; }
                    
                    .qty { width: 10%; text-align: center; }
                    .desc { width: 65%; padding-left: 5px; white-space: pre-wrap; }
                    .total { width: 25%; text-align: right; }
                    
                    .grand-total { font-size: 16px; font-weight: 700; border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 5px 0; margin-top: 5px; display:flex; justify-content:space-between; }
                    
                    .footer { margin-top: 15px; font-size: 9px; text-align: center; color: #444; }
                </style>
            </head>
            <body>
                <div class="header-logo">
                    <img src="${this.logoUrl}" alt="LOGO" onerror="this.style.display='none'">
                </div>
                
                <div class="text-center bold" style="font-size: 13px;">${data.emisor.nombre}</div>
                <div class="text-center">${data.emisor.direccion}</div>
                <div class="text-center bold">NIT: ${data.emisor.nit}</div>
                
                <div class="separator"></div>
                
                <div style="font-size: 12px;">Documento Tributario Electrónico</div>
                <div class="text-center bold" style="font-size: 14px; margin-bottom: 5px;">FACTURA</div>
                
                <div>
                    <span class="data-label">Numero de Autorización:</span><br>
                    ${data.uuid}
                </div>
                
                <div class="data-row" style="margin-top:5px;">
                    <div><span class="data-label">Serie:</span>   ${data.serie}</div>
                    <div><span class="data-label">No:</span>   ${data.numero}</div>
                </div>

                <div class="data-row">
                    <div><span class="data-label">Fecha De Emisión:</span> ${fechaCompleta}</div>
                </div>
                <div class="separator"></div>
                
                <div style="margin-bottom: 2px;">
                    <span class="bold">CLIENTE:</span> ${data.receptor.Name}
                </div>
                <div>
                    <span class="bold">NIT/CUI:</span> ${data.receptor.TaxID}
                </div>
                <div>
                    <span class="bold">DIR:</span> ${data.receptor.AddressInfo.Address}
                </div>

                <table>
                    <thead>
                        <tr>
                            <th class="text-center">CANT</th>
                            <th style="padding-left:5px;">DESCRIPCION</th>
                            <th class="text-right">SUBT.</th>
                            <th class="text-right">TOTAL</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${itemsHtml}
                    </tbody>
                </table>

                <div class="grand-total">
                    <span>TOTAL:</span>
                    <span>${fmt(data.total)}</span>
                </div>

                <div class="footer">
                    Sujeto a pagos trimestrales ISR<br>
                    Certificador: DIGIFACT<br>
                    <br>
                    *** GRACIAS POR SU COMPRA ***
                </div>

                <script>
                    window.onload = function() {
                        setTimeout(function() {
                            window.print();
                            // Cerrar ventana después de imprimir o cancelar
                            window.onafterprint = function() {
                                window.close();
                            };
                            // Fallback: cerrar después de un breve delay
                            setTimeout(function() {
                                window.close();
                            }, 100);
                        }, 500);
                    }
                </script>
            </body>
            </html>
        `);

        win.document.close();
    }
}

const fel = new FEL();