/**
 * FELL Integration - Sistema Sufarma (RENOVADO2026)
 * Rediseñado con Bootstrap 5 para máxima consistencia visual
 */

class FEL {
    constructor() {
        this.ventaId = null;
        this.itemsToInvoice = [];
        this.logoUrl = 'logo/Logo Positivo - Horizonal.png'; // Ruta del logo en SISTEMATIZADO
        this.modalInstance = null;
    }

    async startInvoicing(ventaId) {
        try {
            // Deshabilitar temporalmente los botones del POS para evitar doble clic
            const btn = document.querySelector(`.facturar-cliente-btn[data-id="${ventaId}"]`);
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`;
            }

            const response = await fetch(`api/fel/get_sale_details.php?id=${ventaId}`);
            const data = await response.json();

            if (btn) {
                btn.disabled = false;
                btn.innerHTML = `<i class="fas fa-file-invoice"></i> Factura Cliente`;
            }

            if (data.success) {
                this.openModal(ventaId, data.detalles);
            } else {
                this.showGlobalToast(data.error || 'Error al obtener detalles de la venta', 'danger');
            }
        } catch (error) {
            console.error('Error starting invoicing:', error);
            this.showGlobalToast('Error de comunicación con el servidor', 'danger');
        }
    }

    openModal(ventaId, items) {
        this.ventaId = ventaId;
        this.itemsToInvoice = items;
        this.renderModal();
        
        const modalEl = document.getElementById('felModal');
        this.modalInstance = new bootstrap.Modal(modalEl);
        this.modalInstance.show();
    }

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

        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];

        modal.innerHTML = `
            <div class="modal-dialog modal-dialog-centered" style="max-width: 450px;">
                <div class="modal-content border-0 shadow-lg">
                    <div class="modal-header bg-primary text-white py-3">
                        <h5 class="modal-title fw-bold">
                            <i class="fas fa-file-invoice-dollar me-2"></i>Facturación Electrónica
                        </h5>
                        <button type="button" class="btn-close btn-close-white close-modal" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4">
                        <div class="text-center mb-3">
                            <span class="badge bg-secondary">Venta #${this.ventaId}</span>
                        </div>
                        
                        <div id="felStatus" class="alert d-none text-center p-2 mb-3" style="font-size: 0.9rem;"></div>

                        <div class="mb-3">
                            <label for="felDate" class="form-label fw-semibold text-secondary small text-uppercase mb-1">Fecha de Emisión</label>
                            <input type="date" id="felDate" class="form-control" value="${maxDate}" max="${maxDate}" min="${minDate}">
                            <small class="text-muted d-block mt-1" style="font-size: 0.75rem;">
                                <i class="fas fa-info-circle text-info me-1"></i>Permitido hasta 5 días atrás por la SAT.
                            </small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold text-secondary small text-uppercase mb-1">Datos del Receptor</label>
                            <div class="d-flex gap-2">
                                <select id="felType" class="form-select border-primary" style="max-width: 90px;">
                                    <option value="NIT">NIT</option>
                                    <option value="CUI">DPI</option>
                                    <option value="CF">CF</option>
                                </select>
                                <input type="text" id="felNit" class="form-control border-primary" placeholder="Ingrese número...">
                            </div>
                            <button id="btnSearch" class="btn btn-primary w-100 mt-2 fw-semibold" type="button">
                                <i class="fas fa-search me-1"></i> Buscar Cliente
                            </button>
                        </div>

                        <div class="card bg-light border-0 p-3 mb-3">
                            <div class="mb-3">
                                <label for="felName" class="form-label fw-semibold text-secondary small text-uppercase mb-1">Nombre del Cliente</label>
                                <input type="text" id="felName" class="form-control bg-white" placeholder="Nombre completo...">
                            </div>
                            <div class="mb-0">
                                <label for="felAddr" class="form-label fw-semibold text-secondary small text-uppercase mb-1">Dirección</label>
                                <input type="text" id="felAddr" class="form-control bg-white" value="CIUDAD" placeholder="Dirección...">
                            </div>
                        </div>

                        <div class="row g-2 mt-2">
                            <div class="col-6">
                                <button type="button" class="btn btn-secondary w-100 close-modal" data-bs-dismiss="modal">Cancelar</button>
                            </div>
                            <div class="col-6">
                                <button type="button" id="btnCertify" class="btn btn-success w-100 fw-bold" disabled>Certificar Venta</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        this.attachEvents(modal);
    }

    showMessage(msg, type = 'info') {
        const el = document.getElementById('felStatus');
        if (!el) return;
        el.className = `alert alert-${type === 'error' ? 'danger' : (type === 'success' ? 'success' : 'info')} text-center p-2 mb-3`;
        el.textContent = msg;
        el.classList.remove('d-none');
    }

    attachEvents(modal) {
        // Enlazar los botones para ocultar el modal
        modal.querySelectorAll('.close-modal').forEach(b => {
            b.onclick = () => {
                if (this.modalInstance) this.modalInstance.hide();
            };
        });

        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');
        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 = 'CIUDAD';
            }
            this.checkReady();
        };

        btnSearch.onclick = async () => {
            if (!inputNit.value) return;
            btnSearch.innerHTML = `<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Buscando...`;
            btnSearch.disabled = true;

            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", "warning");
                }
            } catch (e) {
                console.error(e);
                this.showMessage("❌ Error al consultar NIT", "error");
            }
            
            btnSearch.innerHTML = `<i class="fas fa-search me-1"></i> Buscar Cliente`;
            btnSearch.disabled = false;
            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 = `<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Procesando...`;

            // Deshabilitar todos los botones de cierre durante la llamada
            modal.querySelectorAll('.close-modal').forEach(b => {
                b.disabled = true;
                b.classList.add('disabled');
            });

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

                // Filtrado de productos exentos y 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) {
                    this.showMessage("🚀 Facturando exentos (1 de 2)...", "info");
                    const result1 = await this.certifyInvoice(itemsExentos, buyerData, inputDate.value, "1 de 2");
                    if (!result1.success) {
                        throw new Error(result1.error || "Error en factura exenta (1)");
                    }

                    await new Promise(resolve => setTimeout(resolve, 1000));

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

                    this.showMessage("✅ ¡Ambas facturas certificadas!", "success");
                    this.printMultipleTickets([result1.data, result2.data]);

                } else {
                    this.showMessage("🚀 Conectando con la SAT...", "info");
                    const result = await this.certifyInvoice(this.itemsToInvoice, buyerData, inputDate.value);
                    if (result.success) {
                        this.printTicket(result.data);
                        this.showMessage("✅ ¡Factura Certificada!", "success");
                    } else {
                        throw new Error(result.error || "Error en certificación de la SAT");
                    }
                }

                // Recargar el DOM de ventas del POS
                setTimeout(() => {
                    if (this.modalInstance) this.modalInstance.hide();
                    
                    // Invocar las funciones de recarga globales si existen
                    if (typeof loadUltimas3Ventas === 'function') loadUltimas3Ventas();
                    if (typeof loadUltimasVentas === 'function') loadUltimasVentas();
                    if (typeof loadSalesOfDay === 'function') loadSalesOfDay();
                    
                    this.showGlobalToast("Facturación realizada con éxito", "success");
                }, 1500);

            } catch (error) {
                this.showMessage("❌ " + error.message, "error");
                btnCertify.disabled = false;
                btnCertify.innerHTML = "Certificar Venta";
                
                modal.querySelectorAll('.close-modal').forEach(b => {
                    b.disabled = false;
                    b.classList.remove('disabled');
                });
            }
        };
    }

    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 (!btn) return;
        const nameVal = document.getElementById('felName').value.trim();
        const nitVal = document.getElementById('felNit').value.trim();
        
        if (nameVal && nitVal) {
            btn.disabled = false;
        } else {
            btn.disabled = true;
        }
    }

    showGlobalToast(message, type) {
        if (typeof showToast === 'function') {
            showToast(message, type);
        } else {
            alert(message);
        }
    }

    async reprintInvoice(ventaId) {
        try {
            // Deshabilitar temporalmente los botones de reimprimir para evitar doble clic
            const btn = document.querySelector(`.reimprimir-factura-btn[data-id="${ventaId}"]`);
            const originalHtml = btn ? btn.innerHTML : '';
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`;
            }

            const response = await fetch(`api/fel/reimprimir.php?venta_id=${ventaId}`);
            const data = await response.json();

            if (btn) {
                btn.disabled = false;
                btn.innerHTML = originalHtml;
            }

            if (data.success && data.facturas && data.facturas.length > 0) {
                if (data.facturas.length > 1) {
                    this.printMultipleTickets(data.facturas);
                } else {
                    this.printTicket(data.facturas[0]);
                }
            } else {
                this.showGlobalToast(data.error || 'No se encontraron facturas guardadas para esta venta', 'warning');
            }
        } catch (error) {
            console.error('Error reprinting invoice:', error);
            this.showGlobalToast('Error de comunicación con el servidor', 'danger');
        }
    }

    printMultipleTickets(invoicesData) {
        const fmt = (num) => "Q" + parseFloat(num).toFixed(2);
        let allInvoicesHtml = '';

        invoicesData.forEach((data, index) => {
            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>`;
            });

            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;" class="text-center">Documento Tributario Electrónico</div>
                    <div class="text-center bold" style="font-size: 14px; margin-bottom: 5px;">FACTURA</div>
                    
                    <div>
                        <span class="data-label">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 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;">DESCRIPCIÓN</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}
            `;
        });

        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(this.getTicketTemplate(allInvoicesHtml));
        win.document.close();
    }

    printTicket(data) {
        const fmt = (num) => "Q" + parseFloat(num).toFixed(2);
        
        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>`;
        });

        const ticketHtml = `
            <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;" class="text-center">Documento Tributario Electrónico</div>
                <div class="text-center bold" style="font-size: 14px; margin-bottom: 5px;">FACTURA</div>
                
                <div>
                    <span class="data-label">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 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;">DESCRIPCIÓN</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>
        `;

        const uniqueWindowName = 'PrintTicket_' + Date.now();
        const win = window.open('', uniqueWindowName, 'width=400,height=600');

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

        win.document.write(this.getTicketTemplate(ticketHtml));
        win.document.close();
    }

    getTicketTemplate(contentHtml) {
        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Factura de Venta</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: 15px; font-weight: 700; border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 4px 0; margin-top: 5px; display:flex; justify-content:space-between; }
                    
                    .footer { margin-top: 15px; font-size: 9px; text-align: center; color: #333; }
                    
                    .invoice-section { margin-bottom: 10px; }
                    .invoice-separator { margin: 20px 0; }
                    
                    @media print {
                        .invoice-separator {
                            page-break-after: avoid;
                        }
                    }
                </style>
            </head>
            <body>
                ${contentHtml}
                <script>
                    window.onload = function() {
                        setTimeout(function() {
                            window.print();
                            window.onafterprint = function() {
                                window.close();
                            };
                            setTimeout(function() {
                                window.close();
                            }, 200);
                        }, 500);
                    }
                </script>
            </body>
            </html>
        `;
    }
}

const fel = new FEL();
