<?php
/**
 * Módulo: Business Intelligence v2.2 - Full Data Sync & Performance
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso denegado.");
}

$prefijo = $_SESSION['IDUg'] ?? '1'; 
$tb_ventas_c  = $prefijo . "-Ventas_Cabecera";
$tb_ventas_d  = $prefijo . "-Ventas_Detalle";
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    :root { 
        --bg: #f8fafc; --panel: #ffffff; --accent: #3b82f6; --dark: #1e293b; 
    }

    html, body { height: 100%; margin: 0; padding: 0; background-color: var(--bg); font-family: 'Segoe UI', Tahoma, sans-serif; overflow: hidden; }
    
    /* Contenedor Full Screen */
    .bi-container { display: flex; flex-direction: column; height: 100vh; width: 100vw; }

    /* Header y Toolbar Compactos */
    .bi-header { background: var(--dark); color: #fff; padding: 12px 25px; display: flex; justify-content: space-between; align-items: center; border-bottom: 4px solid var(--accent); flex-shrink: 0; }
    .bi-toolbar { background: #fff; padding: 10px 25px; border-bottom: 1px solid #e2e8f0; display: flex; gap: 15px; align-items: center; flex-shrink: 0; }

    /* Contenido Principal con Scroll */
    .bi-scrollable { flex: 1; overflow-y: auto; padding: 20px; box-sizing: border-box; }

    /* Estilo de KPIs (Cuadros de Resumen) */
    .kpi-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 15px; margin-bottom: 20px; }
    .kpi-card { background: #fff; border-radius: 12px; padding: 15px; display: flex; align-items: center; gap: 15px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
    .kpi-icon { width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: #fff; flex-shrink: 0; }

    /* Gráficas Principales */
    .charts-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 20px; }
    .chart-panel { background: #fff; border-radius: 12px; padding: 15px; border: 1px solid #e2e8f0; height: 380px; display: flex; flex-direction: column; }

    /* Rankings */
    .ranking-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    .rank-panel { background: #fff; border-radius: 12px; padding: 15px; border: 1px solid #e2e8f0; }
    .rank-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #f1f5f9; font-size: 0.95rem; }
    .rank-item:last-child { border: none; }
    .rank-idx { width: 28px; height: 28px; background: var(--bg); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 0.75rem; color: var(--accent); margin-right: 12px; flex-shrink: 0; }

    @media (max-width: 1024px) { 
        .charts-grid, .ranking-grid { grid-template-columns: 1fr; }
        html, body { overflow: auto; }
        .bi-container { height: auto; }
    }
</style>

<div class="bi-container">
    <header class="bi-header">
        <h2 class="m-0"><i class="fas fa-chart-pie mr-2"></i>ESTADÍSTICAS DE VENTA</h2>
        <div class="text-right"><span class="badge badge-info">Sincronizado en tiempo real</span></div>
    </header>

    <div class="bi-toolbar">
        <div class="input-group" style="max-width: 500px;">
            <div class="input-group-prepend"><span class="input-group-text bg-white">Del:</span></div>
            <input type="date" id="f-start" class="form-control" value="<?php echo date('Y-m-01'); ?>">
            <div class="input-group-prepend"><span class="input-group-text bg-white">Al:</span></div>
            <input type="date" id="f-end" class="form-control" value="<?php echo date('Y-m-d'); ?>">
        </div>
        <button class="btn btn-primary px-4 font-weight-bold" onclick="refreshBI()"><i class="fas fa-sync-alt mr-2"></i>REGENERAR REPORTES</button>
    </div>

    <div class="bi-scrollable">
        <div class="kpi-row">
            <div class="kpi-card">
                <div class="kpi-icon" style="background:#10b981"><i class="fas fa-money-bill-wave"></i></div>
                <div><small class="text-muted font-weight-bold">INGRESOS TOTALES</small><h3 class="m-0 font-weight-bold" id="txt-total">$ 0.00</h3></div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon" style="background:#3b82f6"><i class="fas fa-receipt"></i></div>
                <div><small class="text-muted font-weight-bold">TICKETS CERRADOS</small><h3 class="m-0 font-weight-bold" id="txt-qty">0</h3></div>
            </div>
            <div class="kpi-card" style="border-left: 5px solid #f59e0b;">
                <div class="kpi-icon" style="background:#f59e0b"><i class="fas fa-medal"></i></div>
                <div><small class="text-muted font-weight-bold">PRODUCTO ESTRELLA</small><h4 class="m-0 font-weight-bold" id="txt-star" style="font-size: 1rem;">--</h4></div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon" style="background:#8b5cf6"><i class="fas fa-user-check"></i></div>
                <div><small class="text-muted font-weight-bold">MEJOR VENDEDOR</small><h4 class="m-0 font-weight-bold" id="txt-user" style="font-size: 1rem;">--</h4></div>
            </div>
        </div>

        <div class="charts-grid">
            <div class="chart-panel">
                <h6 class="font-weight-bold border-bottom pb-2">Tendencia Diaria de Ventas</h6>
                <div style="flex:1;"><canvas id="chartLine"></canvas></div>
            </div>
            <div class="chart-panel">
                <h6 class="font-weight-bold border-bottom pb-2">Distribución de Pagos</h6>
                <div style="flex:1;"><canvas id="chartPie"></canvas></div>
            </div>
        </div>

        <div class="ranking-grid">
            <div class="rank-panel">
                <h6 class="font-weight-bold border-bottom pb-3"><i class="fas fa-fire text-danger mr-2"></i>Top 10 Productos Más Vendidos</h6>
                <div id="list-products-top"></div>
            </div>
            <div class="rank-panel">
                <h6 class="font-weight-bold border-bottom pb-3"><i class="fas fa-users text-primary mr-2"></i>Facturación por Vendedor (ID)</h6>
                <div id="list-users-top"></div>
            </div>
        </div>
    </div>
</div>

<script>
    const DB = "MS_Datos";
    const TABS = { c: "<?php echo $tb_ventas_c; ?>", d: "<?php echo $tb_ventas_d; ?>" };
    let cL = null, cP = null;

    document.addEventListener('DOMContentLoaded', refreshBI);

    async function apiRequest(endpoint, sql) {
        const formData = new FormData();
        formData.append('sql', sql);
        formData.append('db', DB);
        const res = await fetch(`../librerias/AJAX/${endpoint}`, { method: 'POST', body: formData });
        const json = await res.json();
        return Array.isArray(json.data) ? json.data : (Array.isArray(json) ? json : []);
    }

    async function refreshBI() {
        const start = document.getElementById('f-start').value;
        const end = document.getElementById('f-end').value;

        Swal.fire({ title: 'Procesando Inteligencia...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        try {
            // 1. TENDENCIA
            const trend = await apiRequest('Select.php', `SELECT DATE(Fecha) as d, SUM(Total) as t FROM \`${TABS.c}\` WHERE DATE(Fecha) BETWEEN '${start}' AND '${end}' GROUP BY d ORDER BY d ASC`);
            renderLine(trend);

            // 2. PAGOS
            const pays = await apiRequest('Select.php', `SELECT Metodo_Pago as m, COUNT(*) as q FROM \`${TABS.c}\` WHERE DATE(Fecha) BETWEEN '${start}' AND '${end}' GROUP BY m`);
            renderPie(pays);

            // 3. TOP PRODUCTOS (CORREGIDO)
            const prods = await apiRequest('Select.php', `
                SELECT d.Nombre_Producto as n, SUM(d.Cantidad) as q 
                FROM \`${TABS.d}\` d JOIN \`${TABS.c}\` v ON d.ID_Venta = v.ID_Venta 
                WHERE DATE(v.Fecha) BETWEEN '${start}' AND '${end}' 
                GROUP BY d.Nombre_Producto ORDER BY q DESC LIMIT 10`);
            
            fillRankList('list-products-top', prods, 'n', 'q', 'Uds');
            if(prods.length > 0) document.getElementById('txt-star').innerText = prods[0].n;
            else document.getElementById('txt-star').innerText = "Sin Datos";

            // 4. TOP VENDEDORES
            const users = await apiRequest('Select.php', `SELECT IDU_Usuario as u, SUM(Total) as t FROM \`${TABS.c}\` WHERE DATE(Fecha) BETWEEN '${start}' AND '${end}' GROUP BY u ORDER BY t DESC LIMIT 10`);
            fillRankList('list-users-top', users, 'u', 't', '$', true);
            if(users.length > 0) document.getElementById('txt-user').innerText = `ID: ${users[0].u}`;
            else document.getElementById('txt-user').innerText = "Sin Datos";

            // 5. RESUMEN KPI
            const kpi = await apiRequest('Select.php', `SELECT SUM(Total) as t, COUNT(*) as q FROM \`${TABS.c}\` WHERE DATE(Fecha) BETWEEN '${start}' AND '${end}'`);
            document.getElementById('txt-total').innerText = `$ ${parseFloat(kpi[0]?.t || 0).toLocaleString(undefined, {minimumFractionDigits: 2})}`;
            document.getElementById('txt-qty').innerText = kpi[0]?.q || 0;

            Swal.close();
        } catch (e) {
            Swal.fire('Error', 'No se pudo generar el reporte.', 'error');
        }
    }

    function fillRankList(id, data, labelKey, valueKey, suffix, isPre = false) {
        const el = document.getElementById(id);
        el.innerHTML = '';
        if (!Array.isArray(data) || data.length === 0) {
            el.innerHTML = '<div class="text-center text-muted my-4">No hay datos para mostrar</div>';
            return;
        }
        data.forEach((it, i) => {
            const val = parseFloat(it[valueKey]).toLocaleString();
            el.innerHTML += `
                <div class="rank-item">
                    <div class="d-flex align-items-center">
                        <span class="rank-idx">${i+1}</span>
                        <span class="font-weight-bold text-dark">${it[labelKey]}</span>
                    </div>
                    <span class="badge badge-light border" style="font-size: 0.9rem;">${isPre ? suffix : ''} ${val} ${isPre ? '' : suffix}</span>
                </div>`;
        });
    }

    function renderLine(data) {
        const ctx = document.getElementById('chartLine').getContext('2d');
        if(cL) cL.destroy();
        cL = new Chart(ctx, {
            type: 'line',
            data: { 
                labels: data.map(x=>x.d), 
                datasets: [{ label:'Ingresos ($)', data:data.map(x=>x.t), borderColor:'#3b82f6', backgroundColor:'rgba(59, 130, 246, 0.1)', fill:true, tension:0.4 }] 
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } }
        });
    }

    function renderPie(data) {
        const ctx = document.getElementById('chartPie').getContext('2d');
        if(cP) cP.destroy();
        cP = new Chart(ctx, {
            type: 'doughnut',
            data: { 
                labels: data.map(x=>x.m || 'Indefinido'), 
                datasets: [{ data:data.map(x=>x.q), backgroundColor:['#10b981','#3b82f6','#f59e0b','#ef4444','#8b5cf6'] }] 
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
        });
    }
</script>