<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Reportes y Estadísticas', 'reportes');
?>
<script src="assets/js/tailwind.js"></script>
<script>tailwind.config={corePlugins:{preflight:false},theme:{extend:{fontFamily:{sans:['Inter','system-ui','sans-serif']}}}}</script>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>
<script src="assets/js/chart.umd.min.js"></script>
<script src="assets/js/jspdf.umd.min.js"></script>
<script src="assets/js/jspdf.plugin.autotable.min.js"></script>
<script src="assets/js/xlsx.full.min.js"></script>
<style>
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-track{background:#1e293b;border-radius:8px}
::-webkit-scrollbar-thumb{background:#475569;border-radius:8px}
.glass{background:var(--card-bg);backdrop-filter:blur(20px);border:1px solid var(--border-color)}
.tab-btn{transition:all .2s}
.tab-btn.active{background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff}
</style>

<div class="relative z-10 max-w-[98%] mx-auto px-4 py-6" style="background:var(--card-bg); color:var(--text-primary); border-radius:var(--radius-lg); min-height:80vh;">
    <header class="glass rounded-2xl p-6 mb-6 flex justify-between items-center flex-wrap gap-3">
        <div><h1 class="text-2xl font-bold text-white m-0">Reportes y Estad&iacute;sticas</h1><p class="text-slate-400 text-sm mt-1 m-0">An&aacute;lisis de ventas, compras, utilidad y productos</p></div>
    </header>

    <!-- Tabs -->
    <div class="flex gap-2 mb-6 flex-wrap" id="tabContainer">
        <button class="tab-btn active" data-tab="resumen"><i class="bi bi-speedometer2 me-1"></i> Dashboard</button>
        <button class="tab-btn" data-tab="ventas"><i class="bi bi-cart-check me-1"></i> Ventas</button>
        <button class="tab-btn" data-tab="compras"><i class="bi bi-box-seam me-1"></i> Compras</button>
        <button class="tab-btn" data-tab="utilidad"><i class="bi bi-graph-up-arrow me-1"></i> Utilidad</button>
        <button class="tab-btn" data-tab="productos"><i class="bi bi-capsule me-1"></i> Productos</button>
        <button class="tab-btn" data-tab="gastos"><i class="bi bi-wallet2 me-1"></i> Gastos</button>
    </div>

    <!-- ====== TAB: RESUMEN ====== -->
    <div class="tab-content" id="tab-resumen">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6" id="resumenCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Ventas Mensuales</h3><canvas id="chartVentasMensual" height="200"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Utilidad Mensual</h3><canvas id="chartUtilidadMensual" height="200"></canvas></div>
        </div>
    </div>

    <!-- ====== TAB: VENTAS ====== -->
    <div class="tab-content hidden" id="tab-ventas">
        <section class="glass rounded-2xl p-5 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Desde</label><input type="date" id="vfDesde" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-indigo-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Hasta</label><input type="date" id="vfHasta" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-indigo-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Sucursal</label><select id="vfSucursal" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-indigo-500"><option value="">Todas</option></select></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Pago</label><select id="vfPago" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-indigo-500"><option value="">Todos</option><option value="1">Efectivo</option><option value="2">Tarjeta</option><option value="3">Mixto</option></select></div>
                <div class="flex gap-2"><button onclick="cargarVentas()" class="py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 border-0 cursor-pointer text-xs"><i class="bi bi-search"></i></button><button onclick="exportVentasPDF()" class="py-2.5 px-3 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs" title="PDF"><i class="bi bi-filetype-pdf"></i></button><button onclick="exportVentasXLSX()" class="py-2.5 px-3 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs" title="Excel"><i class="bi bi-file-earmark-excel"></i></button></div>
            </div>
        </section>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="ventasCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Ventas por D&iacute;a</h3><canvas id="chartVentasDiario" height="200"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Por Sucursal</h3><canvas id="chartVentasSucursal" height="200"></canvas></div>
        </div>
        <div class="glass rounded-2xl overflow-hidden">
            <div class="overflow-x-auto"><table class="w-full text-left border-collapse text-xs">
                <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase"><th class="p-3">Fecha</th><th class="p-3 text-right">Transacciones</th><th class="p-3 text-right">Total</th><th class="p-3 text-right">Efectivo</th><th class="p-3 text-right">Tarjeta</th><th class="p-3 text-right">Descuentos</th></tr></thead>
                <tbody id="ventasTable" class="divide-y divide-slate-800/60"></tbody>
            </table></div>
        </div>
    </div>

    <!-- ====== TAB: COMPRAS ====== -->
    <div class="tab-content hidden" id="tab-compras">
        <section class="glass rounded-2xl p-5 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Desde</label><input type="date" id="cfDesde" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-amber-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Hasta</label><input type="date" id="cfHasta" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-amber-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Proveedor</label><select id="cfProveedor" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-amber-500"><option value="">Todos</option></select></div>
                <div></div>
                <div class="flex gap-2"><button onclick="cargarCompras()" class="py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-amber-600 to-orange-600 border-0 cursor-pointer text-xs"><i class="bi bi-search"></i></button><button onclick="exportComprasPDF()" class="py-2.5 px-3 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs" title="PDF"><i class="bi bi-filetype-pdf"></i></button><button onclick="exportComprasXLSX()" class="py-2.5 px-3 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs" title="Excel"><i class="bi bi-file-earmark-excel"></i></button></div>
            </div>
        </section>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="comprasCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Compras por Mes</h3><canvas id="chartComprasMensual" height="200"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Por Proveedor</h3><canvas id="chartComprasProveedor" height="200"></canvas></div>
        </div>
        <div class="glass rounded-2xl overflow-hidden">
            <div class="overflow-x-auto"><table class="w-full text-left border-collapse text-xs">
                <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase"><th class="p-3">Mes</th><th class="p-3 text-right">Transacciones</th><th class="p-3 text-right">Total</th></tr></thead>
                <tbody id="comprasTable" class="divide-y divide-slate-800/60"></tbody>
            </table></div>
        </div>
    </div>

    <!-- ====== TAB: UTILIDAD ====== -->
    <div class="tab-content hidden" id="tab-utilidad">
        <section class="glass rounded-2xl p-5 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Desde</label><input type="date" id="ufDesde" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-emerald-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Hasta</label><input type="date" id="ufHasta" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-emerald-500"></div>
                <div></div>
                <div class="flex gap-2"><button onclick="cargarUtilidad()" class="py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 border-0 cursor-pointer text-xs"><i class="bi bi-search"></i></button><button onclick="exportUtilidadPDF()" class="py-2.5 px-3 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs" title="PDF"><i class="bi bi-filetype-pdf"></i></button><button onclick="exportUtilidadXLSX()" class="py-2.5 px-3 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs" title="Excel"><i class="bi bi-file-earmark-excel"></i></button></div>
            </div>
        </section>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6" id="utilidadCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Top Productos por Utilidad</h3><canvas id="chartUtilTop" height="260"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Tendencia Mensual</h3><canvas id="chartUtilTrend" height="260"></canvas></div>
        </div>
        <div class="glass rounded-2xl overflow-hidden">
            <div class="overflow-x-auto"><table class="w-full text-left border-collapse text-xs">
                <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase"><th class="p-3">Producto</th><th class="p-3 text-right">Qty</th><th class="p-3 text-right">Venta</th><th class="p-3 text-right">Costo</th><th class="p-3 text-right">Utilidad</th></tr></thead>
                <tbody id="utilidadTable" class="divide-y divide-slate-800/60"></tbody>
            </table></div>
        </div>
    </div>

    <!-- ====== TAB: PRODUCTOS ====== -->
    <div class="tab-content hidden" id="tab-productos">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6" id="productosCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Top 10 M&aacute;s Vendidos</h3><canvas id="chartTopVendidos" height="260"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Menos Vendidos (con Stock)</h3><canvas id="chartLentos" height="260"></canvas></div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Productos Pr&oacute;ximos a Vencer</h3>
                <div class="overflow-x-auto max-h-60 overflow-y-auto"><table class="w-full text-left border-collapse text-xs">
                    <thead><tr class="text-slate-400 font-bold uppercase border-b border-slate-700"><th class="p-2">Producto</th><th class="p-2">Lote</th><th class="p-2">Vence</th><th class="p-2 text-right">Stock</th></tr></thead>
                    <tbody id="porVencerTable" class="divide-y divide-slate-800/60"></tbody>
                </table></div>
            </div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Productos Vencidos</h3>
                <div class="overflow-x-auto max-h-60 overflow-y-auto"><table class="w-full text-left border-collapse text-xs">
                    <thead><tr class="text-slate-400 font-bold uppercase border-b border-slate-700"><th class="p-2">Producto</th><th class="p-2">Lote</th><th class="p-2">Vence</th><th class="p-2 text-right">Stock</th></tr></thead>
                    <tbody id="vencidosTable" class="divide-y divide-slate-800/60"></tbody>
                </table></div>
            </div>
        </div>
        <div class="flex gap-2 mb-4"><button onclick="exportProductosPDF()" class="py-2 px-4 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs"><i class="bi bi-filetype-pdf me-1"></i>PDF</button><button onclick="exportProductosXLSX()" class="py-2 px-4 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs"><i class="bi bi-file-earmark-excel me-1"></i>Excel</button></div>
    </div>

    <!-- ====== TAB: GASTOS ====== -->
    <div class="tab-content hidden" id="tab-gastos">
        <section class="glass rounded-2xl p-5 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Desde</label><input type="date" id="gfDesde" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-rose-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Hasta</label><input type="date" id="gfHasta" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-rose-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Categor&iacute;a</label><select id="gfCategoria" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-rose-500"><option value="">Todas</option></select></div>
                <div></div>
                <div class="flex gap-2"><button onclick="cargarGastosReporte()" class="py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-rose-600 to-red-600 border-0 cursor-pointer text-xs"><i class="bi bi-search"></i></button><button onclick="exportGastosPDF()" class="py-2.5 px-3 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs" title="PDF"><i class="bi bi-filetype-pdf"></i></button><button onclick="exportGastosXLSX()" class="py-2.5 px-3 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs" title="Excel"><i class="bi bi-file-earmark-excel"></i></button></div>
            </div>
        </section>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="gastosCards"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Gastos por Mes</h3><canvas id="chartGastosMensual" height="200"></canvas></div>
            <div class="glass rounded-2xl p-5"><h3 class="text-sm font-bold text-white mb-3">Por Categor&iacute;a</h3><canvas id="chartGastosCategoria" height="200"></canvas></div>
        </div>
        <div class="glass rounded-2xl overflow-hidden">
            <div class="overflow-x-auto"><table class="w-full text-left border-collapse text-xs">
                <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase"><th class="p-3">Mes</th><th class="p-3 text-right">Transacciones</th><th class="p-3 text-right">Total</th></tr></thead>
                <tbody id="gastosTable" class="divide-y divide-slate-800/60"></tbody>
            </table></div>
        </div>
    </div>
</div>

<script>
let charts = {};
const COLORS = ['#6366f1','#8b5cf6','#ec4899','#ef4444','#f59e0b','#10b981','#06b6d4','#3b82f6','#84cc16','#d946ef'];

function esc(t) { if(!t)return''; const d=document.createElement('div'); d.textContent=t; return d.innerHTML; }

function destroyChart(key) { if(charts[key]) { charts[key].destroy(); delete charts[key]; } }

// Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.tab-content').forEach(tc => tc.classList.add('hidden'));
        document.getElementById('tab-' + btn.dataset.tab).classList.remove('hidden');
        if (btn.dataset.tab==='resumen') cargarResumen();
        if (btn.dataset.tab==='ventas') cargarVentas();
        if (btn.dataset.tab==='compras') cargarCompras();
        if (btn.dataset.tab==='utilidad') cargarUtilidad();
        if (btn.dataset.tab==='productos') cargarProductos();
        if (btn.dataset.tab==='gastos') cargarGastosReporte();
    });
});

// ============== RESUMEN ==============
async function cargarResumen() {
    try {
        const res = await fetch('api/reportes/resumen.php?sucursal_id='+getSucursalId());
        const d = await res.json();
        if (d.success) {
            const r = d.data;
            document.getElementById('resumenCards').innerHTML = `
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Ventas Hoy</div><div class="text-xl font-extrabold text-emerald-400 mt-1">Q ${r.ventas_hoy.toFixed(2)}</div><div class="text-xs text-slate-500 mt-1">${r.count_ventas_hoy} transacciones</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Ventas del Mes</div><div class="text-xl font-extrabold text-indigo-400 mt-1">Q ${r.ventas_mes.toFixed(2)}</div><div class="text-xs text-slate-500 mt-1">Utilidad: Q ${r.utilidad_mes.toFixed(2)}</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Gastos del Mes</div><div class="text-xl font-extrabold text-rose-400 mt-1">Q ${r.gastos_mes.toFixed(2)}</div><div class="text-xs text-slate-500 mt-1">Compras: Q ${r.compras_mes.toFixed(2)}</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Cuentas por Pagar</div><div class="text-xl font-extrabold text-amber-400 mt-1">Q ${r.cuentas_pagar.toFixed(2)}</div><div class="text-xs text-slate-500 mt-1">Top suc: ${esc(r.top_sucursal)}</div></div>
            `;
        }
    } catch(e) { console.error(e); }

    // Charts de tendencia mensual (vía utilidad API)
    try {
        const r2 = await fetch('api/reportes/utilidad.php?top=5'+sucursalFilter());
        const d2 = await r2.json();
        if (!d2.success) return;
        const tr = d2.data.tendencia_mensual.slice().reverse();
        destroyChart('vm');
        const vm = document.getElementById('chartVentasMensual');
        if (vm) {
            charts.vm = new Chart(vm, {type:'bar',data:{labels:tr.map(t=>t.mes),datasets:[{label:'Ventas',data:tr.map(t=>parseFloat(t.ventas)),backgroundColor:'#6366f1',borderRadius:4},{label:'Utilidad',data:tr.map(t=>parseFloat(t.utilidad)),backgroundColor:'#10b981',borderRadius:4}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
        destroyChart('um');
        const um = document.getElementById('chartUtilidadMensual');
        if (um) {
            charts.um = new Chart(um, {type:'line',data:{labels:tr.map(t=>t.mes),datasets:[{label:'Utilidad',data:tr.map(t=>parseFloat(t.utilidad)),borderColor:'#10b981',backgroundColor:'rgba(16,185,129,0.1)',fill:true,tension:0.3},{label:'Costo',data:tr.map(t=>parseFloat(t.costo)),borderColor:'#ef4444',backgroundColor:'rgba(239,68,68,0.1)',fill:true,tension:0.3}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== VENTAS ==============
async function cargarVentas() {
    const p = new URLSearchParams();
    if (document.getElementById('vfDesde').value) p.append('fecha_desde', document.getElementById('vfDesde').value);
    if (document.getElementById('vfHasta').value) p.append('fecha_hasta', document.getElementById('vfHasta').value);
    if (document.getElementById('vfSucursal').value) p.append('sucursal_id', document.getElementById('vfSucursal').value);
    if (document.getElementById('vfPago').value) p.append('tipo_pago', document.getElementById('vfPago').value);
    try {
        const res = await fetch('api/reportes/ventas.php?'+p.toString()+sucursalFilter()); const d = await res.json();
        if (!d.success) return; const r = d.data;
        document.getElementById('ventasCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Total</div><div class="text-xl font-extrabold text-white mt-1">Q ${r.totales.total.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Transacciones</div><div class="text-xl font-extrabold text-indigo-400 mt-1">${r.totales.transacciones}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Promedio por Venta</div><div class="text-xl font-extrabold text-amber-400 mt-1">Q ${r.totales.transacciones>0?(r.totales.total/r.totales.transacciones).toFixed(2):'0.00'}</div></div>
        `;
        document.getElementById('ventasTable').innerHTML = r.diario.map(dv => '<tr class="hover:bg-slate-800/5"><td class="p-3 text-slate-300">'+dv.fecha+'</td><td class="p-3 text-right text-slate-400">'+dv.transacciones+'</td><td class="p-3 text-right text-white font-bold">Q '+parseFloat(dv.total).toFixed(2)+'</td><td class="p-3 text-right text-emerald-400">Q '+parseFloat(dv.efectivo).toFixed(2)+'</td><td class="p-3 text-right text-blue-400">Q '+parseFloat(dv.tarjeta).toFixed(2)+'</td><td class="p-3 text-right text-rose-400">Q '+parseFloat(dv.descuentos).toFixed(2)+'</td></tr>').join('');
        destroyChart('vd');
        const vd = document.getElementById('chartVentasDiario');
        if (vd && r.diario.length) {
            const rev = r.diario.slice().reverse();
            charts.vd = new Chart(vd, {type:'line',data:{labels:rev.map(t=>t.fecha.slice(5)),datasets:[{label:'Total',data:rev.map(t=>parseFloat(t.total)),borderColor:'#6366f1',backgroundColor:'rgba(99,102,241,0.1)',fill:true,tension:0.3}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
        destroyChart('vs');
        const vs = document.getElementById('chartVentasSucursal');
        if (vs && r.por_sucursal.length) {
            charts.vs = new Chart(vs, {type:'doughnut',data:{labels:r.por_sucursal.map(t=>t.sucursal),datasets:[{data:r.por_sucursal.map(t=>parseFloat(t.total)),backgroundColor:COLORS}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8',boxWidth:12}},title:{display:true,text:'Q '+r.totales.total.toFixed(2),color:'#e2e8f0'}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== COMPRAS ==============
async function cargarCompras() {
    const p = new URLSearchParams();
    if (document.getElementById('cfDesde').value) p.append('fecha_desde', document.getElementById('cfDesde').value);
    if (document.getElementById('cfHasta').value) p.append('fecha_hasta', document.getElementById('cfHasta').value);
    if (document.getElementById('cfProveedor').value) p.append('proveedor_id', document.getElementById('cfProveedor').value);
    try {
        const res = await fetch('api/reportes/compras.php?'+p.toString()+sucursalFilter()); const d = await res.json();
        if (!d.success) return; const r = d.data;
        document.getElementById('comprasCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Total Compras</div><div class="text-xl font-extrabold text-white mt-1">Q ${r.totales.total.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Transacciones</div><div class="text-xl font-extrabold text-amber-400 mt-1">${r.totales.transacciones}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Cr&eacute;dito</div><div class="text-xl font-extrabold text-rose-400 mt-1">${r.por_pago.find(t=>t.tipo_pago==='credito')?'Q '+parseFloat(r.por_pago.find(t=>t.tipo_pago==='credito').total).toFixed(2):'Q 0.00'}</div></div>
        `;
        document.getElementById('comprasTable').innerHTML = r.mensual.map(c => '<tr class="hover:bg-slate-800/5"><td class="p-3 text-slate-300">'+c.mes+'</td><td class="p-3 text-right text-slate-400">'+c.transacciones+'</td><td class="p-3 text-right text-white font-bold">Q '+parseFloat(c.total).toFixed(2)+'</td></tr>').join('');
        destroyChart('cm');
        const cm = document.getElementById('chartComprasMensual');
        if (cm && r.mensual.length) {
            const rev = r.mensual.slice().reverse();
            charts.cm = new Chart(cm, {type:'bar',data:{labels:rev.map(t=>t.mes),datasets:[{label:'Compras',data:rev.map(t=>parseFloat(t.total)),backgroundColor:'#f59e0b',borderRadius:4}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
        destroyChart('cp');
        const cp = document.getElementById('chartComprasProveedor');
        if (cp && r.por_proveedor.length) {
            charts.cp = new Chart(cp, {type:'doughnut',data:{labels:r.por_proveedor.map(t=>t.proveedor),datasets:[{data:r.por_proveedor.map(t=>parseFloat(t.total)),backgroundColor:COLORS}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8',boxWidth:12}}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== UTILIDAD ==============
async function cargarUtilidad() {
    const p = new URLSearchParams(); p.append('top', '20');
    if (document.getElementById('ufDesde').value) p.append('fecha_desde', document.getElementById('ufDesde').value);
    if (document.getElementById('ufHasta').value) p.append('fecha_hasta', document.getElementById('ufHasta').value);
    try {
        const res = await fetch('api/reportes/utilidad.php?'+p.toString()+sucursalFilter()); const d = await res.json();
        if (!d.success) return; const r = d.data;
        document.getElementById('utilidadCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Ventas</div><div class="text-xl font-extrabold text-indigo-400 mt-1">Q ${r.totales.ventas.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Costo</div><div class="text-xl font-extrabold text-rose-400 mt-1">Q ${r.totales.costo.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Utilidad</div><div class="text-xl font-extrabold text-emerald-400 mt-1">Q ${r.totales.utilidad.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Margen</div><div class="text-xl font-extrabold text-amber-400 mt-1">${r.totales.margen}%</div></div>
        `;
        document.getElementById('utilidadTable').innerHTML = r.top_productos.slice(0,20).map(u => '<tr class="hover:bg-slate-800/5"><td class="p-3 text-white font-medium">'+esc(u.producto)+'</td><td class="p-3 text-right text-slate-400">'+u.qty+'</td><td class="p-3 text-right text-indigo-400">Q '+parseFloat(u.venta_total).toFixed(2)+'</td><td class="p-3 text-right text-rose-400">Q '+parseFloat(u.costo_total).toFixed(2)+'</td><td class="p-3 text-right text-emerald-400 font-bold">Q '+parseFloat(u.utilidad).toFixed(2)+'</td></tr>').join('');
        destroyChart('ut');
        const ut = document.getElementById('chartUtilTop');
        if (ut && r.top_productos.length) {
            charts.ut = new Chart(ut, {type:'bar',data:{labels:r.top_productos.slice(0,10).map(t=>t.producto.length>20?t.producto.slice(0,20)+'...':t.producto),datasets:[{label:'Utilidad',data:r.top_productos.slice(0,10).map(t=>parseFloat(t.utilidad)),backgroundColor:'#10b981',borderRadius:4},{label:'Venta',data:r.top_productos.slice(0,10).map(t=>parseFloat(t.venta_total)),backgroundColor:'#6366f1',borderRadius:4}]},options:{responsive:true,indexAxis:'y',plugins:{legend:{labels:{color:'#94a3b8',boxWidth:12}}},scales:{x:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}},y:{ticks:{color:'#64748b',font:{size:8}}}}}});
        }
        destroyChart('utt');
        const utt = document.getElementById('chartUtilTrend');
        if (utt && r.tendencia_mensual.length) {
            const rev = r.tendencia_mensual.slice().reverse();
            charts.utt = new Chart(utt, {type:'line',data:{labels:rev.map(t=>t.mes),datasets:[{label:'Ventas',data:rev.map(t=>parseFloat(t.ventas)),borderColor:'#6366f1',backgroundColor:'rgba(99,102,241,0.1)',fill:true,tension:0.3},{label:'Costo',data:rev.map(t=>parseFloat(t.costo)),borderColor:'#ef4444',backgroundColor:'rgba(239,68,68,0.1)',fill:true,tension:0.3},{label:'Utilidad',data:rev.map(t=>parseFloat(t.utilidad)),borderColor:'#10b981',backgroundColor:'rgba(16,185,129,0.1)',fill:true,tension:0.3}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== PRODUCTOS ==============
async function cargarProductos() {
    try {
        const res = await fetch('api/reportes/productos.php?top=10'+sucursalFilter()); const d = await res.json();
        if (!d.success) return; const r = d.data;
        document.getElementById('productosCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Productos Activos</div><div class="text-xl font-extrabold text-white mt-1">${r.total_productos}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Unidades en Stock</div><div class="text-xl font-extrabold text-indigo-400 mt-1">${r.total_unidades.toLocaleString()}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Pr&oacute;ximos a Vencer</div><div class="text-xl font-extrabold text-amber-400 mt-1">${r.por_vencer.length}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Vencidos</div><div class="text-xl font-extrabold text-rose-400 mt-1">${r.vencidos.length}</div></div>
        `;
        document.getElementById('porVencerTable').innerHTML = r.por_vencer.map(p => '<tr class="hover:bg-slate-800/5"><td class="p-2 text-white">'+esc(p.producto)+'</td><td class="p-2 text-slate-400">'+esc(p.codigo_lote)+'</td><td class="p-2 text-amber-400 font-bold">'+p.fechavencimiento+'</td><td class="p-2 text-right text-slate-400">'+p.stock+'</td></tr>').join('') || '<tr><td class="p-4 text-slate-500 text-center" colspan="4">Ninguno</td></tr>';
        document.getElementById('vencidosTable').innerHTML = r.vencidos.map(p => '<tr class="hover:bg-slate-800/5"><td class="p-2 text-white">'+esc(p.producto)+'</td><td class="p-2 text-slate-400">'+esc(p.codigo_lote)+'</td><td class="p-2 text-rose-400 font-bold">'+p.fechavencimiento+'</td><td class="p-2 text-right text-slate-400">'+p.stock+'</td></tr>').join('') || '<tr><td class="p-4 text-slate-500 text-center" colspan="4">Ninguno</td></tr>';
        destroyChart('tv');
        const tv = document.getElementById('chartTopVendidos');
        if (tv && r.top_vendidos.length) {
            charts.tv = new Chart(tv, {type:'bar',data:{labels:r.top_vendidos.map(t=>t.producto.length>20?t.producto.slice(0,20)+'...':t.producto),datasets:[{label:'Unidades',data:r.top_vendidos.map(t=>parseInt(t.qty_vendida)),backgroundColor:COLORS[0],borderRadius:4}]},options:{responsive:true,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',font:{size:8}}}}}});
        }
        destroyChart('le');
        const le = document.getElementById('chartLentos');
        if (le && r.lentos.length) {
            const lt = r.lentos.filter(t=>parseInt(t.stock)>0).slice(0,10);
            charts.le = new Chart(le, {type:'bar',data:{labels:lt.map(t=>t.producto.length>20?t.producto.slice(0,20)+'...':t.producto),datasets:[{label:'Stock',data:lt.map(t=>parseInt(t.stock)),backgroundColor:COLORS[2],borderRadius:4},{label:'Vendidos (6m)',data:lt.map(t=>parseInt(t.qty_vendida)),backgroundColor:COLORS[3],borderRadius:4}]},options:{responsive:true,indexAxis:'y',plugins:{legend:{labels:{color:'#94a3b8',boxWidth:12}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',font:{size:8}}}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== GASTOS ==============
async function cargarGastosReporte() {
    const p = new URLSearchParams();
    if (document.getElementById('gfDesde').value) p.append('fecha_desde', document.getElementById('gfDesde').value);
    if (document.getElementById('gfHasta').value) p.append('fecha_hasta', document.getElementById('gfHasta').value);
    if (document.getElementById('gfCategoria').value) p.append('categoria_id', document.getElementById('gfCategoria').value);
    try {
        const res = await fetch('api/reportes/gastos.php?'+p.toString()+sucursalFilter()); const d = await res.json();
        if (!d.success) return; const r = d.data;
        document.getElementById('gastosCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Total Gastos</div><div class="text-xl font-extrabold text-white mt-1">Q ${r.totales.total.toFixed(2)}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Transacciones</div><div class="text-xl font-extrabold text-rose-400 mt-1">${r.totales.transacciones}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Promedio/Gasto</div><div class="text-xl font-extrabold text-amber-400 mt-1">Q ${r.totales.transacciones>0?(r.totales.total/r.totales.transacciones).toFixed(2):'0.00'}</div></div>
        `;
        document.getElementById('gastosTable').innerHTML = r.mensual.map(g => '<tr class="hover:bg-slate-800/5"><td class="p-3 text-slate-300">'+g.mes+'</td><td class="p-3 text-right text-slate-400">'+g.transacciones+'</td><td class="p-3 text-right text-white font-bold">Q '+parseFloat(g.total).toFixed(2)+'</td></tr>').join('');
        destroyChart('gm');
        const gm = document.getElementById('chartGastosMensual');
        if (gm && r.mensual.length) {
            const rev = r.mensual.slice().reverse();
            charts.gm = new Chart(gm, {type:'bar',data:{labels:rev.map(t=>t.mes),datasets:[{label:'Gastos',data:rev.map(t=>parseFloat(t.total)),backgroundColor:'#ef4444',borderRadius:4}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8'}}},scales:{x:{ticks:{color:'#64748b'}},y:{ticks:{color:'#64748b',callback:v=>'Q'+v.toFixed(0)}}}}});
        }
        destroyChart('gc');
        const gc = document.getElementById('chartGastosCategoria');
        if (gc && r.por_categoria.length) {
            charts.gc = new Chart(gc, {type:'doughnut',data:{labels:r.por_categoria.map(t=>t.categoria),datasets:[{data:r.por_categoria.map(t=>parseFloat(t.total)),backgroundColor:COLORS}]},options:{responsive:true,plugins:{legend:{labels:{color:'#94a3b8',boxWidth:12}}}}});
        }
    } catch(e) { console.error(e); }
}

// ============== EXPORT HELPERS ==============
function getDateRange() {
    const h = new Date(); h.setDate(h.getDate()-30);
    return { desde: document.querySelector('#vfDesde')?.value||h.toISOString().slice(0,10), hasta: document.querySelector('#vfHasta')?.value||new Date().toISOString().slice(0,10) };
}

function nombreMes(m) {
    const meses = { '01':'Ene','02':'Feb','03':'Mar','04':'Abr','05':'May','06':'Jun','07':'Jul','08':'Ago','09':'Sep','10':'Oct','11':'Nov','12':'Dic' };
    return meses[m.slice(5,7)]+' '+m.slice(0,4);
}

function genPDF(title, columns, rows, filename) {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF({orientation: rows.length>20?'landscape':'portrait'});
    doc.setFontSize(16); doc.text(title, 14, 20);
    doc.setFontSize(8); doc.text('Generado: '+new Date().toLocaleString('es-GT'), 14, 27);
    doc.autoTable({head:[columns],body:rows,startY:32,styles:{fontSize:7,halign:'center'},headStyles:{fillColor:[99,102,241],fontSize:7},alternateRowStyles:{fillColor:[240,240,245]}});
    doc.save(filename+'.pdf');
}

function genXLSX(title, columns, rows, filename) {
    const wb = XLSX.utils.book_new();
    const data = [columns, ...rows];
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, title.slice(0,31));
    XLSX.writeFile(wb, filename+'.xlsx');
}

// Ventas Export
function getVentasData() {
    const rows = []; const tb = document.getElementById('ventasTable')?.querySelectorAll('tr');
    if (tb) tb.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim(), td[4].textContent.trim(), td[5].textContent.trim()]); });
    return rows;
}
function exportVentasPDF() { const d = getVentasData(); genPDF('Reporte de Ventas',['Fecha','Transacciones','Total','Efectivo','Tarjeta','Descuentos'],d,'ventas'); }
function exportVentasXLSX() { const d = getVentasData(); genXLSX('Ventas',['Fecha','Transacciones','Total','Efectivo','Tarjeta','Descuentos'],d,'ventas'); }

// Compras Export
function getComprasData() {
    const rows = []; const tb = document.getElementById('comprasTable')?.querySelectorAll('tr');
    if (tb) tb.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim()]); });
    return rows;
}
function exportComprasPDF() { const d = getComprasData(); genPDF('Reporte de Compras',['Mes','Transacciones','Total'],d,'compras'); }
function exportComprasXLSX() { const d = getComprasData(); genXLSX('Compras',['Mes','Transacciones','Total'],d,'compras'); }

// Utilidad Export
function getUtilidadData() {
    const rows = []; const tb = document.getElementById('utilidadTable')?.querySelectorAll('tr');
    if (tb) tb.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim(), td[4].textContent.trim()]); });
    return rows;
}
function exportUtilidadPDF() { const d = getUtilidadData(); genPDF('Reporte de Utilidad',['Producto','Qty','Venta','Costo','Utilidad'],d,'utilidad'); }
function exportUtilidadXLSX() { const d = getUtilidadData(); genXLSX('Utilidad',['Producto','Qty','Venta','Costo','Utilidad'],d,'utilidad'); }

// Productos Export
function getProductosData() {
    const pv = []; const tb1 = document.getElementById('porVencerTable')?.querySelectorAll('tr');
    if (tb1) tb1.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) pv.push(['Por Vencer',td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim()]); });
    const vc = []; const tb2 = document.getElementById('vencidosTable')?.querySelectorAll('tr');
    if (tb2) tb2.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) vc.push(['Vencido',td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim()]); });
    return pv.concat(vc);
}
function exportProductosPDF() { const d = getProductosData(); genPDF('Inventario - Proximos a Vencer',['Estado','Producto','Lote','Vence','Stock'],d,'productos'); }
function exportProductosXLSX() { const d = getProductosData(); genXLSX('Productos',['Estado','Producto','Lote','Vence','Stock'],d,'productos'); }

// Gastos Export
function getGastosData() {
    const rows = []; const tb = document.getElementById('gastosTable')?.querySelectorAll('tr');
    if (tb) tb.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim()]); });
    return rows;
}
function exportGastosPDF() { const d = getGastosData(); genPDF('Reporte de Gastos',['Mes','Transacciones','Total'],d,'gastos'); }
function exportGastosXLSX() { const d = getGastosData(); genXLSX('Gastos',['Mes','Transacciones','Total'],d,'gastos'); }

// Init
async function init() {
    cargarResumen();
    try {
        const r = await fetch('api/reportes/ventas.php?fecha_desde='+new Date(Date.now()-365*86400000).toISOString().slice(0,10));
        const d = await r.json();
        if (d.success) {
            const sucs = [...new Set(d.data.por_sucursal.map(s=>s.sucursal))];
            const sel = document.getElementById('vfSucursal');
            sucs.forEach(s => { const o = document.createElement('option'); o.value = d.data.por_sucursal.find(sv=>sv.sucursal===s)?.sucursal_||''; o.value=s; o.textContent=s; sel.appendChild(o); });
        }
    } catch(e) {}
    try {
        const res = await fetch('api/proveedores/listar.php?activo=1');
        const d = await res.json();
        if (d.success) { const sel2 = document.getElementById('cfProveedor'); d.data.forEach(p => { const o = document.createElement('option'); o.value = p.id; o.textContent = p.nombre; sel2.appendChild(o); }); }
    } catch(e) {}
    try {
        const res = await fetch('api/gastos/categorias/listar.php');
        const d = await res.json();
        if (d.success) { const sel3 = document.getElementById('gfCategoria'); d.data.forEach(c => { const o = document.createElement('option'); o.value = c.id; o.textContent = c.nombre; sel3.appendChild(o); }); }
    } catch(e) {}
}
init();
</script>
<?php renderFooter(); ?>

