<?php
require_once __DIR__ . '/../../includes/layout.php';

$pdo = getDBConnection();
$active_branch_id = (int)($_GET['sucursal_id'] ?? 0);

// Obtener todas las sucursales para el filtro
try {
    $stmt = $pdo->query("SELECT * FROM sucursales ORDER BY nombre ASC");
    $sucursales = $stmt->fetchAll();
} catch (Exception $e) {
    $sucursales = [];
}

renderHeader('Certificación FEL', 'facturas_sat');
?>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">

<style>
    .report-wrap {
        max-width: 1400px;
        margin: 0 auto;
        padding: 1.5rem;
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    .report-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 0.5rem;
        flex-wrap: wrap;
        gap: 1rem;
    }
    .report-header h1 {
        font-size: 1.75rem;
        font-weight: 800;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .filters-card {
        background: var(--surface-elevated);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 1.25rem 1.5rem;
    }
    .filters-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 1.25rem;
        align-items: end;
    }
    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.35rem;
    }
    .filter-label {
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: var(--text-secondary);
    }
    .filter-input {
        width: 100%;
        padding: 0.6rem 0.85rem;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border);
        background: var(--surface);
        color: var(--text-primary);
        font-size: 0.875rem;
        outline: none;
        transition: border-color var(--transition), box-shadow var(--transition);
        box-sizing: border-box;
    }
    .filter-input:focus {
        border-color: var(--accent-color);
        box-shadow: var(--focus-ring);
    }
    .btn-export-excel-green {
        background: rgba(16, 185, 129, 0.1) !important;
        color: #10b981 !important;
        border: 1px solid rgba(16, 185, 129, 0.2) !important;
        font-weight: 700 !important;
        height: 38px;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all var(--transition) !important;
        white-space: nowrap;
        border-radius: var(--radius-sm);
        padding: 0 1rem;
    }
    .btn-export-excel-green:hover {
        background: #10b981 !important;
        color: var(--primary) !important;
        border-color: #10b981 !important;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
    }
    
    /* CSS Fade In Up Animation */
    @keyframes fadeInUp {
        0% { opacity: 0; transform: translateY(20px); }
        100% { opacity: 1; transform: translateY(0); }
    }
    .animate-fade-in-up {
        animation: fadeInUp 0.4s ease-out forwards;
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 12px;
        height: 12px;
    }
    ::-webkit-scrollbar-track {
        background: #1e293b;
        border-radius: 8px;
    }
    ::-webkit-scrollbar-thumb {
        background: #475569;
        border-radius: 8px;
    }
    ::-webkit-scrollbar-thumb:hover {
        background: #64748b;
    }
    
    /* modal */
    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(2, 6, 17, 0.8) !important;
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        animation: fadeIn 0.2s ease-out;
    }
    .modal-overlay.active {
        display: flex;
    }
    .modal-container {
        background: var(--surface-elevated);
        border-radius: var(--radius-lg);
        width: 90%;
        max-width: 480px;
        box-shadow: var(--shadow-xl);
        border: 1px solid var(--border-color);
        display: flex;
        flex-direction: column;
    }
    .modal-header {
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-header h2 {
        font-size: 1.15rem;
        font-weight: 700;
        margin: 0;
    }
    .modal-close {
        background: none;
        border: none;
        font-size: 1.5rem;
        cursor: pointer;
        color: var(--text-light);
    }
    .modal-body {
        padding: 1.5rem;
    }
    .modal-footer {
        padding: 1rem 1.5rem;
        border-top: 1px solid var(--border);
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
    }
    .badge-soft-success {
        background: rgba(34, 197, 94, 0.12);
        color: var(--success);
        border: 1px solid rgba(34, 197, 94, 0.25);
    }
    .badge-soft-primary {
        background: rgba(59, 130, 246, 0.12);
        color: #60a5fa;
        border: 1px solid rgba(59, 130, 246, 0.25);
    }
    .badge-soft-muted {
        background: var(--surface-hover);
        color: var(--text-secondary);
        border: 1px solid var(--border);
    }
</style>

<div class="report-wrap animate-fade-in-up">
    
    <!-- HEADER -->
    <div class="report-header">
        <div>
            <h1 style="font-size: 1.5rem; font-family: 'League Spartan'; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 0.5rem;">
                <i class="fas fa-file-invoice-dollar" style="color:var(--accent-color); margin-right:0.5rem;"></i>
                Certificación FEL (SAT)
            </h1>
            <p style="color: var(--text-secondary); margin-top: 0.35rem; font-size: 0.875rem; margin-bottom: 0;">Consulta y certificación de facturas electrónicas de ventas de POS</p>
        </div>
        <div style="display: flex; align-items: center; gap: 0.75rem;">
            <button onclick="openClientSearchModal()" class="btn btn-primary" style="height: 38px;">
                <i class="bi bi-search-heart"></i> Consultar NIT / CUI
            </button>
        </div>
    </div>

    <!-- FILTROS INTELIGENTES -->
    <div class="filters-card">
        <h5 style="font-size: 0.875rem; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 1rem 0; display: flex; align-items: center; gap: 0.5rem;">
            <i class="bi bi-funnel-fill" style="color: var(--accent-color);"></i> Filtros Inteligentes
        </h5>
        
        <div class="filters-grid">
            <div class="filter-group">
                <label class="filter-label">Sucursal</label>
                <select id="sucursal" class="filter-input">
                    <option value="">Todas las Sucursales</option>
                    <?php foreach ($sucursales as $suc): ?>
                        <option value="<?php echo $suc['id']; ?>" <?php echo ($suc['id'] == $active_branch_id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($suc['nombre']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Fecha Desde</label>
                <input type="date" id="fecha_inicio" class="filter-input" value="<?php echo date('Y-m-d'); ?>">
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Fecha Hasta</label>
                <input type="date" id="fecha_fin" class="filter-input" value="<?php echo date('Y-m-d'); ?>">
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Estado de Factura</label>
                <select id="estado_filtro" class="filter-input">
                    <option value="" selected>Todos los registros</option>
                    <option value="POS_FACTURADO_PENDIENTE">Por Certificar (POS)</option>
                    <option value="FEL_CERTIFICADO">Ya Certificados (FEL)</option>
                    <option value="POS_SIN_FACTURAR">Solo POS (No facturables)</option>
                </select>
            </div>
            
            <div class="filter-group">
                <button class="btn btn-primary" style="height: 38px; width: 100%;" onclick="filtrar()">
                    <i class="bi bi-search"></i> Actualizar
                </button>
            </div>
        </div>
    </div>

    <!-- CONTENEDOR DE RESULTADOS Y SHIMMER -->
    <div id="resultado" class="animate-fade-in-up" style="margin-top: 1rem;">
        <!-- Spinner inicial -->
        <div style="text-align: center; padding: 4rem;">
            <i class="fas fa-spinner fa-pulse" style="font-size: 2rem; margin-bottom: 0.75rem; display: block; color: var(--accent-color);"></i>
            <p style="color: var(--text-secondary); font-weight: 700; font-size: 0.85rem; text-transform: uppercase; margin: 0; letter-spacing: 0.05em;">Consultando datos...</p>
        </div>
    </div>
</div>

<!-- MODAL CONSULTA CLIENTE NIT -->
<div id="clientModal" class="modal-overlay">
    <div class="modal-container">
        <div class="modal-header">
            <h2 style="font-size: 1.15rem; font-weight: 700; margin: 0;">Consultar NIT / CUI en SAT</h2>
            <button onclick="closeClientSearchModal()" class="modal-close">&times;</button>
        </div>
        <div class="modal-body" style="display: flex; flex-direction: column; gap: 1.25rem;">
            <div class="filter-group">
                <label class="filter-label">Identificador</label>
                <div style="display: flex; gap: 0.5rem; width: 100%;">
                    <input type="text" id="query_nit" placeholder="Ej. 12345678 o CUI" class="filter-input" style="flex: 1;">
                    <button onclick="searchClientNIT()" class="btn btn-primary" style="height: 38px;">Buscar</button>
                </div>
            </div>
            <div id="nitResult" class="hidden" style="padding: 1rem; border-radius: 8px; border: 1px solid var(--border); background: rgba(210, 200, 221, 0.04);">
                <div style="font-size: 0.7rem; font-weight: 700; text-transform: uppercase; color: var(--text-secondary); letter-spacing: 0.05em; margin-bottom: 0.25rem;">Nombre obtenido:</div>
                <div id="nitResultName" style="font-size: 0.9rem; font-weight: bold; color: var(--success);">---</div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="closeClientSearchModal()" class="btn btn-ghost" style="height: 38px;">Cerrar</button>
        </div>
    </div>
</div>

<script>
class FEL {
    constructor() {
        this.logoUrl = 'https://icon-library.com/images/billing-icon-png/billing-icon-png-12.jpg';
    }

    async openModal(ventaId) {
        await this.certifyDirect(ventaId.toString());
    }

    async openUnifiedModal() {
        const checks = document.querySelectorAll('.venta-check:checked');
        if (checks.length === 0) {
            this.showToast('⚠️ Por favor, seleccione al menos una venta.', 'info');
            return;
        }

        const ids = Array.from(checks).map(c => c.value).join(',');
        await this.certifyDirect(ids);
    }

    async certifyDirect(ids) {
        this.showToast('🚀 Procesando certificación FEL...', 'info', 0);
        
        try {
            const payload = {
                venta_id: ids,
                sucursal_id: document.getElementById('sucursal')?.value || '<?php echo $active_branch_id; ?>',
                fecha_emision: document.getElementById('fecha_inicio')?.value || '',
                buyer: {
                    taxID: 'CF',
                    name: 'CONSUMIDOR FINAL',
                    address: 'CIUDAD',
                    type: 'CF'
                }
            };

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

            const result = await res.json();
            
            if (result.success) {
                this.showToast('✅ ¡Factura Electrónica Exitosa!', 'success');
                if (Array.isArray(result.data)) {
                    result.data.forEach(d => this.printTicket(d));
                } else {
                    this.printTicket(result.data);
                }
                
                // Actualizar lista
                filtrar();
            } else {
                throw new Error(result.error || "Error desconocido");
            }

        } catch (error) {
            this.showToast("❌ Error: " + error.message, "error");
            console.error(error);
        }
    }

    showToast(msg, type = 'info', duration = 4000) {
        let toast = document.getElementById('felToast');
        if (!toast) {
            toast = document.createElement('div');
            toast.id = 'felToast';
            toast.style.cssText = 'position:fixed; bottom:30px; left:50%; transform:translateX(-50%); z-index:10000; padding:15px 30px; border-radius:12px; font-weight:600; font-family:"Inter", sans-serif; box-shadow:0 10px 25px rgba(0,0,0,0.4); transition: all 0.3s;';
            document.body.appendChild(toast);
        }

        toast.style.display = 'block';
        toast.style.opacity = '1';
        toast.textContent = msg;
        
        // Colors
        if (type === 'error') { 
            toast.style.background = '#fee2e2'; 
            toast.style.color = '#991b1b'; 
            toast.style.border = '1px solid #fca5a5';
        } else if (type === 'success') { 
            toast.style.background = '#d1fae5'; 
            toast.style.color = '#065f46'; 
            toast.style.border = '1px solid #6ee7b7';
        } else { 
            toast.style.background = '#dbeafe'; 
            toast.style.color = '#1e40af'; 
            toast.style.border = '1px solid #93c5fd';
        }

        if (duration > 0) {
            setTimeout(() => { 
                toast.style.opacity = '0'; 
                setTimeout(() => toast.style.display = 'none', 300); 
            }, duration);
        }
    }

    printTicket(data) {
        const fmt = (num) => "Q" + parseFloat(num).toFixed(2);
        const dateObj = new Date(data.fecha);
        const fechaCompleta = dateObj.toLocaleString('es-GT');

        let itemsHtml = '';
        data.items.forEach(item => {
            const qty = item.Qty ? parseFloat(item.Qty) : 1;
            const desc = item.Description || 'Producto';
            const total = item.Totals?.TotalItem ? parseFloat(item.Totals.TotalItem) : 0;
            itemsHtml += `
                <tr>
                    <td style="text-align:center;">${qty}</td>
                    <td style="padding-left:5px;">${desc}</td>
                    <td style="text-align:right;">${fmt(total)}</td>
                </tr>`;
        });

        const win = window.open('', '_blank', 'width=400,height=600');
        win.document.write(`
            <html>
            <head>
                <style>
                    body { font-family: monospace; font-size: 11px; width: 72mm; padding: 5px; background: #fff; color: #000; }
                    .text-center { text-align: center; }
                    .bold { font-weight: bold; }
                    hr { border: none; border-top: 1px dashed #000; margin: 10px 0; }
                    table { width: 100%; border-collapse: collapse; }
                </style>
            </head>
            <body onload="window.print(); window.onafterprint = function() { window.close(); }">
                <div class="text-center bold" style="font-size: 14px;">${data.emisor.nombre}</div>
                <div class="text-center">${data.emisor.direccion}</div>
                <div class="text-center bold">NIT: ${data.emisor.nit}</div>
                <hr>
                <div class="text-center">FACTURA ELECTRÓNICA</div>
                <div class="text-center bold">${data.uuid}</div>
                <div class="text-center">Serie: ${data.serie} No: ${data.numero}</div>
                <div class="text-center">Fecha: ${fechaCompleta}</div>
                <hr>
                <div>CLIENTE: ${data.receptor.Name}</div>
                <div>NIT/CUI: ${data.receptor.TaxID}</div>
                <hr>
                <table>
                    <thead><tr><th>CANT</th><th style="text-align:left;">DESC</th><th style="text-align:right;">TOTAL</th></tr></thead>
                    <tbody>${itemsHtml}</tbody>
                </table>
                <hr>
                <div style="display:flex; justify-content:space-between; font-size:14px;" class="bold">
                    <span>TOTAL:</span><span>${fmt(data.total)}</span>
                </div>
                <hr>
                <div class="text-center" style="font-size: 9px;">Certificador: DIGIFACT<br>*** GRACIAS POR SU COMPRA ***</div>
            </body>
            </html>
        `);
        win.document.close();
    }
}

window.fel = new FEL();

window.onload = function() {
    filtrar();
};

function filtrar() {
    const container = document.getElementById("resultado");
    const data = {
        sucursal: document.getElementById('sucursal').value,
        fecha_inicio: document.getElementById('fecha_inicio').value,
        fecha_fin: document.getElementById('fecha_fin').value,
        estado_filtro: document.getElementById('estado_filtro').value
    };

    container.style.opacity = '0.5';

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "api/facturas_sat/fetch_data.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onload = function () {
        container.style.opacity = '1';
        container.innerHTML = this.responseText;
        actualizarResumen();
    };
    xhr.send(new URLSearchParams(data).toString());
}

function actualizarResumen() {
    const meta = document.getElementById('data-meta');
    if (!meta) return;

    const fmt = (val) => "Q" + parseFloat(val).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    
    const tc = document.getElementById('total_por_certificar');
    const tcert = document.getElementById('total_certificados');
    const tnof = document.getElementById('total_no_facturables');

    if (tc) tc.textContent = fmt(meta.dataset.porCertificar);
    if (tcert) tcert.textContent = fmt(meta.dataset.certificados);
    if (tnof) tnof.textContent = fmt(meta.dataset.noFacturables);
}

function exportarExcel() {
    const data = {
        sucursal: document.getElementById('sucursal').value,
        fecha_inicio: document.getElementById('fecha_inicio').value,
        fecha_fin: document.getElementById('fecha_fin').value,
        estado_filtro: document.getElementById('estado_filtro').value
    };
    window.open(`api/facturas_sat/export_excel.php?${new URLSearchParams(data).toString()}`, "_blank");
}

// Modal and Search Client functions
function openClientSearchModal() {
    document.getElementById('clientModal').classList.add('active');
    document.getElementById('query_nit').value = '';
    document.getElementById('nitResult').classList.add('hidden');
}

function closeClientSearchModal() {
    document.getElementById('clientModal').classList.remove('active');
}

async function searchClientNIT() {
    const nit = document.getElementById('query_nit').value.trim();
    if (!nit) return;

    try {
        const res = await fetch('api/facturas_sat/lookup_nit.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ identifier: nit })
        });
        const result = await res.json();
        
        const resDiv = document.getElementById('nitResult');
        const resName = document.getElementById('nitResultName');
        resDiv.classList.remove('hidden');
        
        if (result.success) {
            resName.textContent = result.data.name;
            resName.className = "";
            resName.style.fontSize = "0.9rem";
            resName.style.fontWeight = "bold";
            resName.style.color = "var(--success)";
        } else {
            resName.textContent = "No encontrado o inválido";
            resName.className = "";
            resName.style.fontSize = "0.9rem";
            resName.style.fontWeight = "bold";
            resName.style.color = "var(--danger)";
        }
    } catch(err) {
        console.error(err);
    }
}

// Checkboxes event listener
document.getElementById('resultado').addEventListener('change', function(e) {
    if (e.target.classList.contains('venta-check')) {
        actualizarTotalSeleccion();
    }
});

function actualizarTotalSeleccion() {
    const checks = document.querySelectorAll('.venta-check:checked');
    const container = document.getElementById('seleccion-total-container');
    const badge = document.getElementById('seleccion-total-badge');
    
    if (!container || !badge) return;

    if (checks.length === 0) {
        container.style.display = 'none';
        return;
    }

    let total = 0;
    checks.forEach(c => {
        total += parseFloat(c.dataset.monto || 0);
    });

    container.style.display = 'block';
    badge.textContent = "Q" + total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}
</script>

<?php
renderFooter();
?>
