<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Inteligencia de Negocios', 'bi');
?>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
:root {
  --surface-card: #ffffff;
  --border-color: #e2e8f0;
  --text-primary: #2F2F2F;
  --text-secondary: #64748b;
  --accent-color: #0891b2;
  --bi-primary: #0891b2;
}

.bi-container { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }
.bi-topbar { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-bottom: 1.5rem; }
.bi-topbar h1 { font-size: 1.5rem; font-weight: 800; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem; margin: 0; }
.bi-topbar h1 small { font-size: 0.875rem; font-weight: 400; color: var(--text-secondary); }

.btn { display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.5rem 1.25rem; border-radius: 0.75rem; font-size: 0.8rem; font-weight: 700; border: none; cursor: pointer; transition: all 0.15s; text-decoration: none; }
.btn-primary { background: var(--accent-color); color: #fff; }
.btn-primary:hover { background: #0e7490; }
.btn-amber { background: #d97706; color: #fff; }
.btn-amber:hover { background: #b45309; }
.btn-purple { background: #7c3aed; color: #fff; }
.btn-purple:hover { background: #6d28d9; }
.btn-emerald { background: #059669; color: #fff; }
.btn-emerald:hover { background: #047857; }
.btn-outline { background: transparent; color: var(--text-secondary); border: 1px solid var(--border-color); }
.btn-outline:hover { background: #f8fafc; color: var(--text-primary); }
.btn-sm { padding: 0.35rem 0.75rem; font-size: 0.75rem; }

.bi-tabs { display: flex; gap: 0.25rem; border-bottom: 2px solid var(--border-color); margin-bottom: 1.5rem; overflow-x: auto; }
.bi-tab { padding: 0.6rem 1.25rem; font-size: 0.85rem; font-weight: 600; color: var(--text-secondary); border: none; background: none; cursor: pointer; white-space: nowrap; border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all 0.15s; }
.bi-tab:hover { color: var(--text-primary); }
.bi-tab.active { color: var(--bi-primary); border-bottom-color: var(--bi-primary); }

.bi-card { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1.5rem; margin-bottom: 1rem; }
.bi-card-title { font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-secondary); margin-bottom: 1rem; }

.bi-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 0.75rem; margin-bottom: 1.5rem; }
.bi-stat { background: #f8fafc; border: 1px solid var(--border-color); border-radius: 0.75rem; padding: 1rem; text-align: center; }
.bi-stat-label { font-size: 0.7rem; text-transform: uppercase; font-weight: 700; color: var(--text-secondary); letter-spacing: 0.03em; margin-bottom: 0.25rem; }
.bi-stat-value { font-size: 1.5rem; font-weight: 800; line-height: 1.3; }
.bi-stat-sub { font-size: 0.75rem; color: var(--text-secondary); }

.bi-grid-2 { display: grid; grid-template-columns: 1fr; gap: 1rem; margin-bottom: 1.5rem; }
@media (min-width: 768px) { .bi-grid-2 { grid-template-columns: 1fr 1fr; } }

table.bi-data { width: 100%; border-collapse: collapse; }
table.bi-data thead th { padding: 0.65rem 0.75rem; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-secondary); border-bottom: 2px solid var(--border-color); text-align: left; white-space: nowrap; }
table.bi-data tbody td { padding: 0.5rem 0.75rem; font-size: 0.85rem; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
table.bi-data tbody tr:hover { background: #f8fafc; }
table.bi-data thead.sticky th { position: sticky; top: 0; background: var(--surface-card); z-index: 1; }

.filter-row { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 1rem; }
.filter-row select, .filter-row input { padding: 0.5rem 0.75rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.85rem; }
.filter-row input[type="number"] { width: 100px; }
.filter-row select:focus, .filter-row input:focus { outline: none; border-color: var(--accent-color); }

.tab-content { display: none; }
.tab-content.active { display: block; }

.text-green { color: #059669; }
.text-amber { color: #d97706; }
.text-red { color: #dc2626; }
.text-muted { color: var(--text-secondary); }
.text-center { text-align: center; }
.font-mono { font-family: 'Courier New', monospace; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.scroll-y { max-height: 60vh; overflow-y: auto; }

.badge { display: inline-flex; align-items: center; gap: 0.3rem; padding: 0.2rem 0.55rem; border-radius: 1rem; font-size: 0.6rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.03em; }
.badge-red { background: #fce4ec; color: #b71c1c; }
.badge-amber { background: #fef3c7; color: #92400e; }
.badge-yellow { background: #fef9c3; color: #854d0e; }
.badge-green { background: #d1fae5; color: #065f46; }

.chart-wrap { position: relative; width: 100%; min-height: 250px; }
</style>

<div class="bi-container">

  <div class="bi-topbar">
    <h1><i class="bi bi-graph-up-arrow"></i> Inteligencia de Negocios <small>Predicción de quiebres, estacionalidad y alertas de compra</small></h1>
  </div>

  <div class="bi-tabs">
    <button class="bi-tab active" data-tab="dashboard" onclick="switchTab('dashboard')"><i class="bi bi-speedometer2"></i> Dashboard</button>
    <button class="bi-tab" data-tab="quiebres" onclick="switchTab('quiebres')"><i class="bi bi-exclamation-triangle"></i> Predicción Quiebres</button>
    <button class="bi-tab" data-tab="estacionalidad" onclick="switchTab('estacionalidad')"><i class="bi bi-calendar4-week"></i> Estacionalidad</button>
    <button class="bi-tab" data-tab="alertas" onclick="switchTab('alertas')"><i class="bi bi-cart-check"></i> Alertas de Compra</button>
  </div>

  <!-- ===== DASHBOARD ===== -->
  <div id="tab-dashboard" class="tab-content active">
    <div class="filter-row">
      <select id="dashDias" onchange="cargarDashboard()">
        <option value="7">7 días</option><option value="30" selected>30 días</option>
        <option value="90">90 días</option><option value="365">1 año</option>
      </select>
    </div>
    <div id="dashContent"><div class="text-center text-muted" style="padding:2rem;">Cargando...</div></div>
  </div>

  <!-- ===== QUIEBRES ===== -->
  <div id="tab-quiebres" class="tab-content">
    <div class="filter-row">
      <select id="qDias">
        <option value="30">30 días</option><option value="60">60 días</option><option value="90" selected>90 días</option>
      </select>
      <select id="qFiltro">
        <option value="todas">Todas las alertas</option>
        <option value="agotado">Agotados</option><option value="critico">Críticos</option>
        <option value="por_agotarse">Por agotarse</option><option value="atencion">Atención</option>
      </select>
      <button class="btn btn-amber btn-sm" onclick="cargarQuiebres()"><i class="bi bi-search"></i> Analizar</button>
    </div>
    <div id="quiebresContent"><div class="text-center text-muted" style="padding:2rem;">Cargando...</div></div>
  </div>

  <!-- ===== ESTACIONALIDAD ===== -->
  <div id="tab-estacionalidad" class="tab-content">
    <div class="filter-row">
      <input type="number" id="esAnio" value="<?=date('Y')?>" style="width:100px;">
      <select id="esCategoria">
        <option value="0">Todas las categorías</option>
      </select>
      <button class="btn btn-purple btn-sm" onclick="cargarEstacionalidad()"><i class="bi bi-search"></i> Analizar</button>
    </div>
    <div id="estacionalidadContent"><div class="text-center text-muted" style="padding:2rem;">Cargando...</div></div>
  </div>

  <!-- ===== ALERTAS DE COMPRA ===== -->
  <div id="tab-alertas" class="tab-content">
    <div class="filter-row">
      <select id="alFiltro">
        <option value="todas">Todas</option><option value="urgente">Urgentes</option>
        <option value="programar">Programar</option><option value="optimo">Óptimo</option>
      </select>
      <button class="btn btn-emerald btn-sm" onclick="cargarAlertas()"><i class="bi bi-lightning"></i> Analizar</button>
    </div>
    <div id="alertasContent"><div class="text-center text-muted" style="padding:2rem;">Cargando...</div></div>
  </div>
</div>

<script src="assets/js/chart.umd.min.js"></script>
<script src="assets/js/sweetalert2.min.js"></script>
<script>
const charts = {};
let currentTabBI = 'dashboard';

function switchTab(tab) {
    currentTabBI = tab;
    document.querySelectorAll('.bi-tab').forEach(b => b.classList.remove('active'));
    document.querySelector(`.bi-tab[data-tab="${tab}"]`)?.classList.add('active');
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    document.getElementById(`tab-${tab}`)?.classList.add('active');
    if (tab === 'dashboard') cargarDashboard();
    if (tab === 'quiebres') cargarQuiebres();
    if (tab === 'estacionalidad') cargarEstacionalidad();
    if (tab === 'alertas') cargarAlertas();
}

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

// Chart defaults for light theme
Chart.defaults.color = '#64748b';
Chart.defaults.font.size = 10;

// ===================== DASHBOARD =====================
async function cargarDashboard() {
    const dias = document.getElementById('dashDias').value;
    const c = document.getElementById('dashContent');
    c.innerHTML = '<div class="text-center text-muted" style="padding:2rem;">Cargando...</div>';
    try {
        const r = await fetch(`api/bi/index.php?action=resumen&dias=${dias}${sucursalFilter()}`);
        const d = await r.json();
        if (!d.success) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${d.error}</p>`; return; }
        const data = d.data;

        let html = `
        <div class="bi-stats">
            <div class="bi-stat"><div class="bi-stat-label">Ventas</div><div class="bi-stat-value">${data.ventas.total_ventas}</div><div class="bi-stat-sub">Q${data.ventas.total_vendido.toFixed(2)}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Ticket Promedio</div><div class="bi-stat-value">Q${data.ventas.ticket_promedio.toFixed(2)}</div><div class="bi-stat-sub">${data.ventas.unidades_vendidas} unidades</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Stock Bajo</div><div class="bi-stat-value" style="color:#d97706;">${data.inventario.bajo_stock}</div><div class="bi-stat-sub">productos</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Agotados</div><div class="bi-stat-value" style="color:#dc2626;">${data.inventario.agotados}</div><div class="bi-stat-sub">productos sin stock</div></div>
        </div>
        <div class="bi-grid-2">
            <div class="bi-card"><div class="bi-card-title">Ventas por Sucursal</div><div class="chart-wrap"><canvas id="chartSucursales"></canvas></div></div>
            <div class="bi-card"><div class="bi-card-title">Top 10 Productos</div><div class="chart-wrap"><canvas id="chartTopProductos"></canvas></div></div>
        </div>
        <div class="bi-card">
            <div class="bi-card-title">Top Productos Más Vendidos</div>
            <div class="scroll-y">
            <table class="bi-data"><thead class="sticky"><tr><th>Producto</th><th class="num">Cantidad</th><th class="num">Total</th></tr></thead><tbody>`;
        (data.top_productos||[]).slice(0, 10).forEach(p => {
            html += `<tr><td style="font-weight:600;">${p.nombre||'S/N'}</td><td class="num">${p.cantidad}</td><td class="num text-green">Q${parseFloat(p.total).toFixed(2)}</td></tr>`;
        });
        html += `</tbody></table></div></div>`;
        c.innerHTML = html;

        // Chart: Ventas por sucursal
        destroyChart('sucursales');
        const sucLabels = (data.ventas_por_sucursal||[]).map(s => s.nombre.replace(/^\([^)]+\)\s*/,''));
        const sucVentas = (data.ventas_por_sucursal||[]).map(s => parseInt(s.ventas));
        const sucTotal = (data.ventas_por_sucursal||[]).map(s => parseFloat(s.total));
        charts.sucursales = new Chart(document.getElementById('chartSucursales'), {
            type: 'bar', data: {
                labels: sucLabels,
                datasets: [
                    { label: 'Ventas', data: sucVentas, backgroundColor: '#06b6d4', borderRadius: 4 },
                    { label: 'Total (Q)', data: sucTotal, backgroundColor: '#10b981', borderRadius: 4, yAxisID: 'y1' }
                ]
            }, options: {
                responsive: true, maintainAspectRatio: true,
                plugins: { legend: { labels: { font: {size:10} } } },
                scales: {
                    x: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y1: { position: 'right', ticks: { font: {size:9} }, grid: { display:false } }
                }
            }
        });

        // Chart: Top productos
        destroyChart('topProductos');
        const topLabels = (data.top_productos||[]).slice(0, 10).map(p => (p.nombre||'S/N').substring(0,20));
        const topData = (data.top_productos||[]).slice(0, 10).map(p => parseFloat(p.total));
        charts.topProductos = new Chart(document.getElementById('chartTopProductos'), {
            type: 'bar', data: {
                labels: topLabels,
                datasets: [{ label: 'Total Q', data: topData, backgroundColor: '#8b5cf6', borderRadius: 4 }]
            }, options: {
                indexAxis: 'y', responsive: true, maintainAspectRatio: true,
                plugins: { legend: { display:false } },
                scales: {
                    x: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y: { ticks: { font: {size:8} }, grid: { display:false } }
                }
            }
        });
    } catch(e) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}

// ===================== QUIEBRES =====================
async function cargarQuiebres() {
    const dias = document.getElementById('qDias').value;
    const filtro = document.getElementById('qFiltro').value;
    const c = document.getElementById('quiebresContent');
    c.innerHTML = '<div class="text-center text-muted" style="padding:2rem;">Analizando...</div>';
    try {
        const r = await fetch(`api/bi/index.php?action=quiebres&dias_historial=${dias}${sucursalFilter()}`);
        const d = await r.json();
        if (!d.success) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${d.error}</p>`; return; }
        const data = d.data;
        const prods = data.productos||[];
        const stats = data.stats||{};

        let html = `
        <div class="bi-stats">
            <div class="bi-stat"><div class="bi-stat-label">Agotados</div><div class="bi-stat-value" style="color:#dc2626;">${stats.agotados||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Críticos</div><div class="bi-stat-value" style="color:#dc2626;">${stats.criticos||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Por agotarse</div><div class="bi-stat-value" style="color:#d97706;">${stats.por_agotarse||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Atención</div><div class="bi-stat-value" style="color:#ca8a04;">${stats.atencion||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">OK</div><div class="bi-stat-value" style="color:#059669;">${stats.ok||0}</div></div>
        </div>
        <div class="scroll-y">
        <table class="bi-data"><thead class="sticky"><tr>
            <th>Producto</th><th class="num">Stock</th><th class="num">Mínimo</th>
            <th class="num">Vel/día</th><th class="num">Días rest.</th><th class="num">Lead time</th>
            <th class="num">Pto.Reorden</th><th class="text-center">Alerta</th></tr></thead><tbody>`;
        let count = 0;
        prods.forEach(p => {
            if (filtro !== 'todas' && p.alerta !== filtro) return;
            if (count++ >= 200) return;
            const badge = p.alerta==='agotado'?'<span class="badge badge-red">AGOTADO</span>':
                p.alerta==='critico'?'<span class="badge badge-red">CRÍTICO</span>':
                p.alerta==='por_agotarse'?'<span class="badge badge-amber">⚠ POR AGOTARSE</span>':
                p.alerta==='atencion'?'<span class="badge badge-yellow">ATENCIÓN</span>':
                '<span class="badge badge-green">OK</span>';
            const stockColor = p.stock_actual<=0 ? '#dc2626' : (p.stock_actual<=p.stock_minimo ? '#d97706' : 'var(--text-primary)');
            const diasColor = p.dias_restantes<10 ? '#dc2626' : (p.dias_restantes<30 ? '#d97706' : 'var(--text-primary)');
            html += `<tr>
                <td><div style="font-weight:600;">${p.producto||''}</div><div class="text-muted" style="font-size:0.7rem;">${p.codigo||''} ${p.sucursal?'· '+p.sucursal:''}</div></td>
                <td class="num" style="font-weight:700;color:${stockColor};">${p.stock_actual}</td>
                <td class="num text-muted">${p.stock_minimo}</td>
                <td class="num text-muted">${p.velocidad_diaria}</td>
                <td class="num" style="font-weight:${p.dias_restantes<10?'700':'400'};color:${diasColor};">${p.dias_restantes>=999?'∞':p.dias_restantes}</td>
                <td class="num text-muted">${p.lead_time}</td>
                <td class="num text-muted">${p.punto_reorden}</td>
                <td class="text-center">${badge}</td></tr>`;
        });
        html += `</tbody></table>`;
        if (count===0) html = '<p class="text-muted text-center" style="padding:2rem;">No hay productos con esta clasificación</p>';
        c.innerHTML = html;
    } catch(e) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}

// ===================== ESTACIONALIDAD =====================
async function cargarEstacionalidad() {
    const anio = document.getElementById('esAnio').value;
    const cat = document.getElementById('esCategoria').value;
    const c = document.getElementById('estacionalidadContent');
    c.innerHTML = '<div class="text-center text-muted" style="padding:2rem;">Cargando...</div>';
    try {
        const r = await fetch(`api/bi/index.php?action=estacionalidad&anio=${anio}&categoria_id=${cat}${sucursalFilter()}`);
        const d = await r.json();
        if (!d.success) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${d.error}</p>`; return; }
        const data = d.data;

        let html = `
        <div class="bi-grid-2">
            <div class="bi-card"><div class="bi-card-title">Ventas Mensuales ${data.anio} vs ${data.anio_anterior}</div><div class="chart-wrap"><canvas id="chartMensual"></canvas></div></div>
            <div class="bi-card"><div class="bi-card-title">Ventas por Día de la Semana</div><div class="chart-wrap"><canvas id="chartSemana"></canvas></div></div>
        </div>
        <div class="bi-card">
            <div class="bi-card-title">Ventas por Categoría</div>
            <div class="scroll-y">
            <table class="bi-data"><thead class="sticky"><tr><th>Categoría</th><th class="num">Ventas</th><th class="num">Unidades</th><th class="num">Total</th></tr></thead><tbody>`;
        (data.categorias_ventas||[]).forEach(cat => {
            html += `<tr><td style="font-weight:600;">${cat.nombre}</td><td class="num">${cat.ventas}</td><td class="num">${cat.unidades}</td><td class="num text-green">Q${parseFloat(cat.total).toFixed(2)}</td></tr>`;
        });
        html += `</tbody></table></div></div>`;
        c.innerHTML = html;

        const meses = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
        const actual = Array(12).fill(0);
        (data.mensual||[]).forEach(m => { actual[m.mes-1] = parseFloat(m.total_vendido); });
        const anterior = Array(12).fill(0);
        (data.anterior||[]).forEach(m => { anterior[m.mes-1] = parseFloat(m.total_vendido); });

        destroyChart('mensual');
        charts.mensual = new Chart(document.getElementById('chartMensual'), {
            type: 'bar', data: {
                labels: meses,
                datasets: [
                    { label: `${data.anio}`, data: actual, backgroundColor: '#8b5cf6', borderRadius: 4 },
                    { label: `${data.anio_anterior}`, data: anterior, backgroundColor: '#cbd5e1', borderRadius: 4 }
                ]
            }, options: {
                responsive: true, maintainAspectRatio: true,
                plugins: { legend: { labels: { font: {size:10} } } },
                scales: {
                    x: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } }
                }
            }
        });

        const diasSem = ['','Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];
        destroyChart('semana');
        charts.semana = new Chart(document.getElementById('chartSemana'), {
            type: 'bar', data: {
                labels: (data.semana||[]).map(s => diasSem[s.dia]||''),
                datasets: [
                    { label: 'Ventas', data: (data.semana||[]).map(s => parseInt(s.ventas)), backgroundColor: '#06b6d4', borderRadius: 4 },
                    { label: 'Total Q', data: (data.semana||[]).map(s => parseFloat(s.total)), backgroundColor: '#10b981', borderRadius: 4, yAxisID: 'y1' }
                ]
            }, options: {
                responsive: true, maintainAspectRatio: true,
                plugins: { legend: { labels: { font: {size:10} } } },
                scales: {
                    x: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y: { ticks: { font: {size:9} }, grid: { color: 'rgba(148,163,184,0.15)' } },
                    y1: { position: 'right', ticks: { font: {size:9} }, grid: { display:false } }
                }
            }
        });
    } catch(e) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}

// ===================== ALERTAS DE COMPRA =====================
async function cargarAlertas() {
    const filtro = document.getElementById('alFiltro').value;
    const c = document.getElementById('alertasContent');
    c.innerHTML = '<div class="text-center text-muted" style="padding:2rem;">Analizando...</div>';
    try {
        const r = await fetch('api/bi/index.php?action=alertas_compras');
        const d = await r.json();
        if (!d.success) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${d.error}</p>`; return; }
        const data = d.data;
        const alertas = data.alertas||[];
        const stats = data.stats||{};

        let html = `
        <div class="bi-stats">
            <div class="bi-stat"><div class="bi-stat-label">Urgentes</div><div class="bi-stat-value" style="color:#dc2626;">${stats.urgentes||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Programar</div><div class="bi-stat-value" style="color:#d97706;">${stats.programar||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Óptimo</div><div class="bi-stat-value" style="color:#059669;">${stats.optimo||0}</div></div>
            <div class="bi-stat"><div class="bi-stat-label">Inversión Total</div><div class="bi-stat-value" style="font-size:1.2rem;">Q${(stats.inversion_total||0).toFixed(2)}</div></div>
        </div>
        <div class="scroll-y">
        <table class="bi-data"><thead class="sticky"><tr>
            <th>Producto</th><th class="num">Stock</th><th class="num">Vel/día</th>
            <th class="num">Días rest.</th><th class="num">Lead time</th>
            <th class="num">Sugerido</th><th>Proveedor</th>
            <th class="num">Costo U.</th><th class="num">Inversión</th>
            <th class="text-center">Urgencia</th></tr></thead><tbody>`;
        let count = 0;
        alertas.forEach(a => {
            if (filtro !== 'todas' && a.urgencia !== filtro) return;
            if (count++ >= 200) return;
            const badge = a.urgencia==='urgente'?'<span class="badge badge-red">🔴 URGENTE</span>':
                a.urgencia==='programar'?'<span class="badge badge-amber">🟡 PROGRAMAR</span>':
                '<span class="badge badge-green">🟢 ÓPTIMO</span>';
            html += `<tr>
                <td><div style="font-weight:600;">${a.producto||''}</div><div class="text-muted" style="font-size:0.7rem;">${a.codigo||''} ${a.categoria?'· '+a.categoria:''}</div></td>
                <td class="num" style="font-weight:700;color:${a.stock_actual<=0?'#dc2626':'var(--text-primary)'};">${a.stock_actual}</td>
                <td class="num text-muted">${a.velocidad_diaria}</td>
                <td class="num" style="font-weight:${a.dias_restantes<10?'700':'400'};color:${a.dias_restantes<10?'#dc2626':'var(--text-primary)'};">${a.dias_restantes>=999?'∞':a.dias_restantes}</td>
                <td class="num text-muted">${a.lead_time}</td>
                <td class="num" style="font-weight:700;color:var(--accent-color);">${a.cantidad_sugerida}</td>
                <td class="text-muted">${a.proveedor||'N/A'}</td>
                <td class="num text-muted">Q${(a.costo_unitario||0).toFixed(2)}</td>
                <td class="num" style="color:#d97706;">Q${(a.inversion_estimada||0).toFixed(2)}</td>
                <td class="text-center">${badge}</td></tr>`;
        });
        html += `</tbody></table>`;
        if (count===0) html = '<p class="text-muted text-center" style="padding:2rem;">No hay alertas con este filtro</p>';
        c.innerHTML = html;
    } catch(e) { c.innerHTML = `<p style="color:#dc2626;font-size:0.85rem;">${e.message}</p>`; }
}

// Init
document.addEventListener('DOMContentLoaded', async () => {
    try {
        const r = await fetch('api/bi/index.php?action=estacionalidad&anio=<?=date('Y')?>');
        const d = await r.json();
        if (d.success && d.data.categorias) {
            const sel = document.getElementById('esCategoria');
            d.data.categorias.forEach(c => { sel.innerHTML += `<option value="${c.id}">${c.nombre}</option>`; });
        }
    } catch(e) {}
    cargarDashboard();
});
</script>
<?php renderFooter(); ?>

