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

$pdo = getDBConnection();

// Config de sucursal (usamos sucursal 1 como fallback para valores generales)
try {
    $stmtConfig = $pdo->query("SELECT * FROM sucursal_configuracion WHERE sucursal_id = 1");
    $config = $stmtConfig->fetch();
} catch (Exception $e) {
    $config = false;
}
if (!$config) {
    $config = ['gastos_fijos_mensuales' => 0, 'dias_operativos_mes' => 30, 'margen_ganancia_defecto' => 30, 'moneda_simbolo' => 'Q'];
}

// Alertas summary (globales, no dependen de sucursal)
$stock_bajo_count = 0;
$vencimientos_count = 0;
try {
    $s1 = $pdo->query("SELECT COUNT(*) FROM inventario_sucursal WHERE stock_total <= stock_minimo AND stock_minimo > 0");
    $stock_bajo_count = intval($s1->fetchColumn());
    $s2 = $pdo->query("SELECT COUNT(*) FROM compras_detalle WHERE fecha_vencimiento IS NOT NULL
        AND fecha_vencimiento BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
        AND fecha_vencimiento > '2000-01-01'");
    $vencimientos_count = intval($s2->fetchColumn());
} catch (Exception $e) {}

// Pedidos pendientes
$pedidos_pendientes = 0;
try {
    $sp = $pdo->query("SELECT COUNT(*) FROM pedidos WHERE estado='pendiente'");
    $pedidos_pendientes = intval($sp->fetchColumn());
} catch (Exception $e) {}

renderHeader('Dashboard', 'dashboard');
?>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
.db-wrap { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }

/* Header */
.db-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; margin-bottom: 1.5rem; gap: 1rem; }
.db-header h1 { font-size: 1.5rem; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 0.5rem; }
.db-header .date-badge { font-size: 0.8rem; color: var(--text-secondary); background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 2rem; padding: 0.4rem 1rem; }

/* KPI row */
.kpi-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
.kpi-card {
    background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1.25rem;
    padding: 1.25rem 1.5rem; position: relative; overflow: hidden;
}
.kpi-card .kpi-icon { position: absolute; right: 1rem; top: 1rem; font-size: 1.5rem; opacity: 0.12; }
.kpi-card .kpi-label { font-size: 0.75rem; text-transform: uppercase; font-weight: 600; color: var(--text-secondary); letter-spacing: 0.04em; }
.kpi-card .kpi-value { font-size: 1.75rem; font-weight: 800; margin: 0.25rem 0; }
.kpi-card .kpi-sub { font-size: 0.75rem; color: var(--text-secondary); }

/* Progress bar */
.progress-track { height: 6px; background: #e5e7eb; border-radius: 3px; margin-top: 0.75rem; overflow: hidden; }
.progress-fill { height: 100%; border-radius: 3px; transition: width 1s ease; background: linear-gradient(90deg, #22c55e, #16a34a); }

/* Module sections */
.mod-section { margin-bottom: 2rem; }
.mod-section-title {
    font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em;
    color: var(--text-secondary); margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem;
}
.mod-section-title i { font-size: 1rem; }

.mod-grid {
    display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 0.75rem;
}
.mod-tile {
    display: flex; align-items: center; gap: 0.85rem;
    padding: 0.9rem 1rem; background: var(--surface-card); border: 1px solid var(--border-color);
    border-radius: 1rem; text-decoration: none; color: var(--text-primary); transition: all 0.2s;
    position: relative;
}
.mod-tile:hover { transform: translateY(-2px); border-color: var(--accent-color); box-shadow: 0 6px 20px rgba(0,0,0,0.08); }
.mod-tile .mt-icon {
    width: 2.25rem; height: 2.25rem; border-radius: 0.65rem; display: flex;
    align-items: center; justify-content: center; font-size: 1.1rem; flex-shrink: 0;
}
.mod-tile .mt-info { flex: 1; min-width: 0; }
.mod-tile .mt-name { font-size: 0.85rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mod-tile .mt-desc { font-size: 0.7rem; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.mod-tile .mt-badge {
    position: absolute; top: -0.35rem; right: -0.35rem;
    min-width: 1.25rem; height: 1.25rem; border-radius: 1rem;
    font-size: 0.65rem; font-weight: 700; padding: 0 0.3rem;
    display: flex; align-items: center; justify-content: center;
    background: #ef4444; color: white; box-shadow: 0 2px 6px rgba(239,68,68,0.4);
}

/* Contra panel inline */
#contraPanel { display: none; }
#contraPanel .contra-grid { display: grid; grid-template-columns: 340px 1fr; gap: 1.5rem; }
#contraPanel .glass-card { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1.5rem; }
#contraPanel .search-results { border: 1px solid var(--border-color); border-radius: 0.75rem; max-height: 220px; overflow-y: auto; display: none; margin-top: 0.2rem; }
#contraPanel .search-item { padding: 0.6rem; border-bottom: 1px solid var(--border-color); cursor: pointer; font-size: 0.88rem; }
#contraPanel .search-item:hover { background: rgba(148,163,184,0.12); }

.period-btn-group { display: flex; gap: 2px; background: var(--border-color); border-radius: 0.75rem; padding: 2px; }
.period-btn { padding: 0.35rem 0.85rem; border: none; border-radius: 0.65rem; font-size: 0.78rem; font-weight: 600; cursor: pointer; background: transparent; color: var(--text-secondary); transition: all .15s; }
.period-btn.active { background: var(--surface-card); color: var(--text-primary); box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
.period-btn:hover:not(.active) { color: var(--text-primary); }

@media (max-width: 768px) {
    .db-wrap { padding: 1rem; }
    .kpi-row { grid-template-columns: repeat(2, 1fr); }
    .mod-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }
    .db-header { flex-direction: column; align-items: start; }
    #contraPanel .contra-grid { grid-template-columns: 1fr; }
}
</style>

<div class="db-wrap">
    <!-- Header -->
    <div class="db-header">
        <div style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap">
            <h1><i class="bi bi-grid-1x2-fill"></i> Panel de Control</h1>
            <div class="period-btn-group" style="margin-left:0.5rem">
                <button class="period-btn active" id="btnVistaOperativa" onclick="cambiarVistaDashboard('operativa')">Vista Operativa</button>
                <button class="period-btn" id="btnVistaFiscal" onclick="cambiarVistaDashboard('fiscal')">Vista Fiscal (Post-Impuestos)</button>
            </div>
        </div>
        <div style="display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap">
            <!-- Date filter presets -->
            <div class="period-btn-group">
                <button class="period-btn active" data-period="hoy">Hoy</button>
                <button class="period-btn" data-period="semana">Semana</button>
                <button class="period-btn" data-period="mes">Mes</button>
                <button class="period-btn" data-period="anio">Año</button>
            </div>
            <input type="date" id="dashFechaDesde" style="padding:0.4rem 0.6rem;border-radius:0.65rem;border:1px solid var(--border-color);font-size:0.8rem;background:var(--surface-card);color:var(--text-primary)">
            <span style="color:var(--text-muted);font-size:0.8rem">a</span>
            <input type="date" id="dashFechaHasta" style="padding:0.4rem 0.6rem;border-radius:0.65rem;border:1px solid var(--border-color);font-size:0.8rem;background:var(--surface-card);color:var(--text-primary)">
            <button class="period-btn" onclick="cargarDashboard()" title="Filtrar"><i class="bi bi-search"></i></button>
        </div>
    </div>

    <!-- Meta del período (punto de equilibrio) -->
    <div class="kpi-card" id="metaCard" style="margin-bottom:1rem;border-left:4px solid #2563eb">
        <div class="kpi-icon"><i class="bi bi-bullseye" style="color:#2563eb"></i></div>
        <div style="display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:0.5rem">
            <div>
                <div class="kpi-label">Meta <span id="metaPeriodoLabel">del Día</span></div>
                <div class="kpi-value" style="color:#2563eb" id="metaValor">--</div>
            </div>
            <div style="text-align:right">
                <div class="kpi-label">Venta del Período</div>
                <div class="kpi-value" style="color:#059669" id="metaVentaPeriodo">--</div>
            </div>
        </div>
        <div class="progress-track" style="margin-top:0.5rem"><div class="progress-fill" id="metaBarra" style="width:0%"></div></div>
        <div style="display:flex;justify-content:space-between;font-size:0.75rem;margin-top:0.35rem;color:var(--text-secondary)">
            <span id="metaProgreso">--</span>
            <span id="metaFalta" style="font-weight:600">--</span>
        </div>
    </div>

    <!-- KPI Cards (dinámicos) -->
    <div class="kpi-row" id="kpiRow">
        <div class="kpi-card"><div class="kpi-icon"><i class="bi bi-cash-stack" style="color:#059669"></i></div>
            <div class="kpi-label">Ventas</div>
            <div class="kpi-value" style="color:#059669" id="kpiVentas">--</div>
            <div class="kpi-sub"><span id="kpiVentasSub"></span></div>
        </div>
        <div class="kpi-card"><div class="kpi-icon"><i class="bi bi-calculator" style="color:#7c3aed"></i></div>
            <div class="kpi-label">Utilidad Neta</div>
            <div class="kpi-value" style="color:#7c3aed" id="kpiUtilidad">--</div>
            <div class="kpi-sub" id="kpiUtilidadSub"></div>
        </div>
        <div class="kpi-card"><div class="kpi-icon"><i class="bi bi-wallet2" style="color:#dc2626"></i></div>
            <div class="kpi-label">Gastos</div>
            <div class="kpi-value" style="color:#dc2626" id="kpiGastos">--</div>
            <div class="kpi-sub"><span id="kpiGastosSub"></span></div>
        </div>
        <div class="kpi-card"><div class="kpi-icon"><i class="bi bi-cart-check" style="color:#2563eb"></i></div>
            <div class="kpi-label">Transacciones</div>
            <div class="kpi-value" style="color:#2563eb" id="kpiTransacciones">--</div>
            <div class="kpi-sub" id="kpiTransSub"></div>
        </div>
    </div>

    <!-- Últimas Ventas (dinámico) -->
    <div class="mod-section">
        <div class="mod-section-title"><i class="bi bi-receipt"></i> Últimas Ventas</div>
        <div class="table-wrapper">
            <div style="overflow-x:auto">
                <table style="width:100%;border-collapse:collapse" id="ultimasVentasTable">
                    <thead><tr>
                        <th style="padding:0.65rem;border-bottom:2px solid var(--border-color);font-size:0.75rem;font-weight:700;color:var(--text-secondary);text-align:left">#</th>
                        <th style="padding:0.65rem;border-bottom:2px solid var(--border-color);font-size:0.75rem;font-weight:700;color:var(--text-secondary);text-align:left">Fecha</th>
                        <th style="padding:0.65rem;border-bottom:2px solid var(--border-color);font-size:0.75rem;font-weight:700;color:var(--text-secondary);text-align:left">Sucursal</th>
                        <th style="padding:0.65rem;border-bottom:2px solid var(--border-color);font-size:0.75rem;font-weight:700;color:var(--text-secondary);text-align:right">Total</th>
                        <th style="padding:0.65rem;border-bottom:2px solid var(--border-color);font-size:0.75rem;font-weight:700;color:var(--text-secondary);text-align:center">Pago</th>
                    </tr></thead>
                    <tbody id="ultimasVentasBody"><tr><td colspan="5" style="text-align:center;padding:2rem;color:var(--text-muted)">Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modules by Category -->
    <?php
    $modulos = [
        'Inventario' => [
            ['icon'=>'bi-box-seam','bg'=>'#dbeafe','fg'=>'#2563eb','name'=>'Gestión Productos','desc'=>'Stock, costos y catálogo','url'=>'../Gestionproductos/index.html'],
            ['icon'=>'bi-archive','bg'=>'#f3e8ff','fg'=>'#9333ea','name'=>'Kardex','desc'=>'Movimientos de inventario','url'=>'modules/inventario/kardex.php'],
            ['icon'=>'bi-exclamation-triangle','bg'=>'#ffedd5','fg'=>'#ea580c','name'=>'Alertas','desc'=>'Stock bajo y vencimientos','url'=>'modules/inventario/alertas_inventario.php','badge'=>$stock_bajo_count],
            ['icon'=>'bi-sliders2','bg'=>'#e0f2fe','fg'=>'#0284c7','name'=>'Ajustes Inventario','desc'=>'Mermas, robos, sobrantes','url'=>'modules/inventario/ajustes_inventario.php'],
            ['icon'=>'bi-clipboard-check','bg'=>'#fce7f3','fg'=>'#db2777','name'=>'Inventario Inicial','desc'=>'Carga inicial y conteo','url'=>'modules/inventario/inventario_inicial.php'],
            ['icon'=>'bi-clock-history','bg'=>'#dcfce7','fg'=>'#166534','name'=>'Inventario Tiempo Real','desc'=>'Stock consolidado y lotes','url'=>'modules/inventario/inventario_tiempo_real.php'],
            ['icon'=>'bi-calculator-fill','bg'=>'#ffe4e6','fg'=>'#e11d48','name'=>'Cierre de Caja','desc'=>'Cierre e isolibros','url'=>'../IsolibrosADMIN/index.html'],
            ['icon'=>'bi-arrow-repeat','bg'=>'#ccfbf1','fg'=>'#0d9488','name'=>'Sincronizar facturas','desc'=>'Importación XML / PDF','url'=>'../sincfacturapro/index.html'],
        ],
        'Compras & Proveedores' => [
            // ['icon'=>'bi-file-text','bg'=>'#ccfbf1','fg'=>'#0d9488','name'=>'Órdenes de Compra','desc'=>'OC a proveedores','url'=>'modules/compras/ordenes_compra.php'],
            ['icon'=>'bi-truck','bg'=>'#fef08a','fg'=>'#ca8a04','name'=>'Compras','desc'=>'Ingreso a bodega y facturas','url'=>'modules/compras/compras.php'],
            // ['icon'=>'bi-currency-dollar','bg'=>'#fef3c7','fg'=>'#d97706','name'=>'Precios y Márgenes','desc'=>'CPP, márgenes por laboratorio','url'=>'modules/compras/precios.php'],
        ],
        'Ventas & POS' => [
            ['icon'=>'bi-display','bg'=>'#d1fae5','fg'=>'#059669','name'=>'Punto de Venta','desc'=>'Módulo de POS','url'=>'modules/ventas/punto_de_venta.php'],
            ['icon'=>'bi-receipt','bg'=>'#ede9fe','fg'=>'#7c3aed','name'=>'Facturas SAT','desc'=>'Certificación FEL','url'=>'modules/ventas/facturas_sat.php'],
            ['icon'=>'bi-cart','bg'=>'#dbeafe','fg'=>'#2563eb','name'=>'Pedidos','desc'=>'Solicitudes de sucursales','url'=>'modules/ventas/pedidos.php','badge'=>$pedidos_pendientes],
        ],
        'Administración' => [
            ['icon'=>'bi-wallet2','bg'=>'#ffe4e6','fg'=>'#e11d48','name'=>'Reporte Caja Chica','desc'=>'Reporte detallado de movimientos','url'=>'modules/finanzas/caja_chica.php'],
            ['icon'=>'bi-people','bg'=>'#ccfbf1','fg'=>'#0d9488','name'=>'Usuarios / Distribución','desc'=>'Accesos y logística','url'=>'modules/operaciones/usuarios_sucursales.php'],
            ['icon'=>'bi-file-earmark-text','bg'=>'#fce7f3','fg'=>'#db2777','name'=>'Prescripción','desc'=>'Recetas médicas controladas','url'=>'modules/operaciones/prescripcion.php'],
            ['icon'=>'bi-gear','bg'=>'#e5e7eb','fg'=>'#4b5563','name'=>'Configuración','desc'=>'Parámetros del sistema','url'=>'modules/sistema/configuracion.php'],
        ],
        'Inteligencia & Operaciones' => [
            ['icon'=>'bi-database','bg'=>'#f3e8ff','fg'=>'#7c3aed','name'=>'Respaldos BD','desc'=>'Backup de base de datos','url'=>'modules/sistema/backup.php'],
            ['icon'=>'bi-box-arrow-up-right','bg'=>'#fef3c7','fg'=>'#d97706','name'=>'Distribución','desc'=>'Bodega a sucursales','url'=>'modules/operaciones/usuarios_sucursales.php?tab=distribucion'],
        ],
    ];

    foreach ($modulos as $categoria => $mods):
    ?>
    <div class="mod-section">
        <div class="mod-section-title"><i class="bi bi-dot"></i> <?= $categoria ?></div>
        <div class="mod-grid">
            <?php foreach ($mods as $m):
                $badge_html = '';
                if (!empty($m['badge']) && $m['badge'] > 0) {
                    $badge_html = '<span class="mt-badge">'.$m['badge'].'</span>';
                }
                $attrs = '';
                if (!empty($m['id'])) {
                    $attrs = ' id="'.$m['id'].'"';
                }
            ?>
            <a href="<?= $m['url'] ?>" class="mod-tile"<?= $attrs ?>>
                <?= $badge_html ?>
                <div class="mt-icon" style="background:<?= $m['bg'] ?>;color:<?= $m['fg'] ?>">
                    <i class="bi <?= $m['icon'] ?>"></i>
                </div>
                <div class="mt-info">
                    <div class="mt-name"><?= $m['name'] ?></div>
                    <div class="mt-desc"><?= $m['desc'] ?></div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
let contraInit = false;
var dashPeriodo = 'hoy';

document.addEventListener('DOMContentLoaded', () => {


    // Period buttons
    document.querySelectorAll('.period-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            var period = this.getAttribute('data-period');
            if (!period) return; // search button
            document.querySelectorAll('.period-btn').forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            dashPeriodo = period;
            aplicarPeriodo(period);
            cargarDashboard();
        });
    });

    // Date inputs change
    document.getElementById('dashFechaDesde').addEventListener('change', function() {
        document.querySelectorAll('.period-btn').forEach(function(b) { b.classList.remove('active'); });
        dashPeriodo = '';
    });
    document.getElementById('dashFechaHasta').addEventListener('change', function() {
        document.querySelectorAll('.period-btn').forEach(function(b) { b.classList.remove('active'); });
        dashPeriodo = '';
    });

    // Listen for global sucursal change
    var gs = document.getElementById('globalSucursalSelect');
    if (gs) gs.addEventListener('change', function() { cargarDashboard(); });

    // Initial load
    aplicarPeriodo('hoy');
    cargarDashboard();
});

function aplicarPeriodo(period) {
    var hoy = new Date();
    var d = hoy.toISOString().slice(0,10);
    var dsd, hst;
    switch (period) {
        case 'hoy': dsd = d; hst = d; break;
        case 'semana':
            var s = new Date(hoy); s.setDate(s.getDate() - 7);
            dsd = s.toISOString().slice(0,10); hst = d; break;
        case 'mes':
            var m = new Date(hoy); m.setDate(m.getDate() - 30);
            dsd = m.toISOString().slice(0,10); hst = d; break;
        case 'anio':
            var a = new Date(hoy); a.setDate(a.getDate() - 365);
            dsd = a.toISOString().slice(0,10); hst = d; break;
        default: return;
    }
    document.getElementById('dashFechaDesde').value = dsd;
    document.getElementById('dashFechaHasta').value = hst;
}

let vistaDashboard = 'operativa';
window.lastDashboardData = null;

function cambiarVistaDashboard(vista) {
    vistaDashboard = vista;
    document.getElementById('btnVistaOperativa').classList.toggle('active', vista === 'operativa');
    document.getElementById('btnVistaFiscal').classList.toggle('active', vista === 'fiscal');
    renderDashboard();
}

async function cargarDashboard() {
    var sid = getSucursalId();
    var fd = document.getElementById('dashFechaDesde').value;
    var fh = document.getElementById('dashFechaHasta').value;
    if (!fd || !fh) return;

    var url = 'api/dashboard/resumen.php?sucursal_id=' + sid + '&fecha_desde=' + fd + '&fecha_hasta=' + fh;

    try {
        var r = await fetch(url);
        var d = await r.json();
        if (!d.success) throw new Error(d.message || 'Error');

        window.lastDashboardData = d.data;
        renderDashboard();
    } catch(e) {
        console.error(e);
        document.getElementById('kpiVentas').textContent = 'Error';
    }
}

function renderDashboard() {
    if (!window.lastDashboardData) return;
    var data = window.lastDashboardData;
    var isFiscal = (vistaDashboard === 'fiscal');

    // Meta del período
    if (data.meta) {
        var m = data.meta;
        var metaVal = m.meta;
        var ventasPeriodo = m.ventas_periodo;
        var progreso = m.progreso_porcentaje;
        var falta = m.falta_vender;

        if (isFiscal) {
            // Sin 12% IVA
            metaVal = metaVal / 1.12;
            ventasPeriodo = ventasPeriodo / 1.12;
            progreso = metaVal > 0 ? Math.min(100, Math.round((ventasPeriodo / metaVal) * 100 * 10) / 10) : 0;
            falta = Math.max(0, metaVal - ventasPeriodo);
        }

        document.getElementById('metaValor').textContent = 'Q ' + metaVal.toFixed(2);
        document.getElementById('metaVentaPeriodo').textContent = 'Q ' + ventasPeriodo.toFixed(2);
        document.getElementById('metaBarra').style.width = progreso + '%';
        document.getElementById('metaProgreso').textContent = progreso + '% alcanzado';
        
        var faltaEl = document.getElementById('metaFalta');
        if (falta > 0) {
            faltaEl.textContent = 'Faltan Q ' + falta.toFixed(2);
            faltaEl.style.color = '#ef4444';
        } else {
            faltaEl.textContent = '¡Meta superada!';
            faltaEl.style.color = '#16a34a';
        }
        
        // Label según período
        var dias = m.dias_periodo;
        var label = 'del Día';
        if (dias >= 360) label = 'del Año';
        else if (dias >= 28) label = 'del Mes';
        else if (dias >= 7) label = 'de la Semana';
        
        if (isFiscal) {
            label += ' (Sin IVA)';
        }
        document.getElementById('metaPeriodoLabel').textContent = label;
    }

    // KPI cards
    var totalVentas = data.ventas.total;
    if (isFiscal) {
        totalVentas = totalVentas / 1.12;
    }
    document.getElementById('kpiVentas').textContent = 'Q ' + totalVentas.toFixed(2);
    
    var promVenta = data.ventas.promedio;
    if (isFiscal) {
        promVenta = promVenta / 1.12;
    }
    document.getElementById('kpiVentasSub').textContent = data.ventas.transacciones + ' ventas, prom. Q ' + promVenta.toFixed(2) + (isFiscal ? ' (Sin IVA)' : '');

    var utilidadNeta = data.utilidad_neta;
    var subText = '';
    
    if (isFiscal) {
        // En Vista Fiscal:
        // utilidad neta antes de ISR = utilidad_neta / 1.12
        var netBeforeTax = utilidadNeta / 1.12;
        var isr = netBeforeTax > 0 ? (netBeforeTax * 0.25) : 0;
        var netAfterTax = netBeforeTax - isr;

        // Estimación IVA a pagar:
        // IVA Débito (Ventas) = 12% del total de ventas sin IVA
        var ivaDebito = (data.ventas.total * 0.12) / 1.12;
        // Costo estimado de medicamentos vendidos = totalVentas - gross profit
        var comprasEstimadas = data.ventas.total - data.utilidad;
        // IVA Crédito (Compras + Gastos Operativos)
        var ivaCredito = ((comprasEstimadas + data.gastos.total) * 0.12) / 1.12;
        var ivaAPagar = Math.max(0, ivaDebito - ivaCredito);

        document.getElementById('kpiUtilidad').textContent = 'Q ' + netAfterTax.toFixed(2);
        document.getElementById('kpiUtilidad').style.color = (netAfterTax < 0) ? '#ef4444' : '#10b981';
        
        var margenPostImp = totalVentas > 0 ? ((netAfterTax / totalVentas) * 100).toFixed(1) : 0;
        subText = margenPostImp + '% margen post-imp. (ISR Est: Q ' + isr.toFixed(2) + ', IVA Est: Q ' + ivaAPagar.toFixed(2) + ')';
    } else {
        // Vista Operativa
        if (data.ventas.total > 0) {
            var margenNeto = ((utilidadNeta / data.ventas.total) * 100).toFixed(1);
            subText = margenNeto + '% margen neto (Bruta: Q ' + data.utilidad.toFixed(2) + ')';
        } else {
            subText = '0% margen neto';
        }
        document.getElementById('kpiUtilidad').textContent = 'Q ' + utilidadNeta.toFixed(2);
        document.getElementById('kpiUtilidad').style.color = (utilidadNeta < 0) ? '#ef4444' : '#7c3aed';
    }
    document.getElementById('kpiUtilidadSub').textContent = subText;

    var totalGastos = data.gastos.total;
    if (isFiscal) {
        totalGastos = totalGastos / 1.12;
    }
    document.getElementById('kpiGastos').textContent = 'Q ' + totalGastos.toFixed(2);
    document.getElementById('kpiGastosSub').textContent = data.gastos.transacciones + ' transacciones' + (isFiscal ? ' (Sin IVA)' : '');

    document.getElementById('kpiTransacciones').textContent = data.ventas.transacciones;
    
    var promTrans = (data.ventas.total / Math.max(1, data.ventas.transacciones));
    if (isFiscal) {
        promTrans = promTrans / 1.12;
    }
    document.getElementById('kpiTransSub').textContent = 'Q ' + promTrans.toFixed(2) + ' /venta' + (isFiscal ? ' (Sin IVA)' : '');

    // Últimas ventas
    var tb = document.getElementById('ultimasVentasBody');
    if (data.ultimas_ventas && data.ultimas_ventas.length > 0) {
        var html = '';
        data.ultimas_ventas.forEach(function(v) {
            var valTotal = parseFloat(v.total);
            if (isFiscal) {
                valTotal = valTotal / 1.12;
            }
            html += '<tr>' +
                '<td style="padding:0.6rem;border-bottom:1px solid var(--border-color);font-size:0.82rem">#' + v.id + '</td>' +
                '<td style="padding:0.6rem;border-bottom:1px solid var(--border-color);font-size:0.82rem">' + v.fecha_y_hora.slice(0,16) + '</td>' +
                '<td style="padding:0.6rem;border-bottom:1px solid var(--border-color);font-size:0.82rem">' + esc(v.sucursal) + '</td>' +
                '<td style="padding:0.6rem;border-bottom:1px solid var(--border-color);font-size:0.82rem;text-align:right;font-weight:700">Q ' + valTotal.toFixed(2) + '</td>' +
                '<td style="padding:0.6rem;border-bottom:1px solid var(--border-color);font-size:0.82rem;text-align:center"><span style="padding:0.2rem 0.5rem;border-radius:0.5rem;font-size:0.7rem;font-weight:600;background:#e0e7ff;color:#4338ca">' + esc(v.tipo_pago) + '</span></td>' +
                '</tr>';
        });
        tb.innerHTML = html;
    } else {
        tb.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:2rem;color:var(--text-muted)">Sin ventas en este período</td></tr>';
    }
}

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


</script>

<?php renderFooter(); ?>

