<?php 
// 1. Verificación de conexión y moneda
if(!isset($conn)) require_once 'db.php';
$config = $conn->query("SELECT * FROM configuracion LIMIT 1")->fetch_assoc();
$moneda = $config['moneda'] ?? 'S/';
?>

<style>
    .kpi-card { transition: all 0.3s ease; border: none; border-radius: 12px; }
    .kpi-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important; }
    .icon-box { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; }
    .table-vencimientos thead { position: sticky; top: 0; background: white; z-index: 10; }
    .list-ranking .list-group-item { border: none; border-bottom: 1px solid #f1f1f1; }
</style>

<div class="container-fluid py-3">
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card kpi-card shadow-sm h-100 bg-white border-start border-5 border-success">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small fw-bold text-uppercase">Ventas Hoy</span>
                        <div class="icon-box bg-success bg-opacity-10 text-success"><i class="fas fa-cash-register"></i></div>
                    </div>
                    <h3 class="fw-bold m-0"><?php echo $moneda; ?> <span id="kpi-ventas">0.00</span></h3>
                    <small id="kpi-ventas-count" class="text-muted">0 transacciones</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card kpi-card shadow-sm h-100 bg-white border-start border-5 border-primary">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small fw-bold text-uppercase">Ticket Promedio</span>
                        <div class="icon-box bg-primary bg-opacity-10 text-primary"><i class="fas fa-receipt"></i></div>
                    </div>
                    <h3 class="fw-bold m-0"><?php echo $moneda; ?> <span id="kpi-ticket">0.00</span></h3>
                    <small class="text-muted">Promedio por cliente</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card kpi-card shadow-sm h-100 bg-white border-start border-5 border-danger">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small fw-bold text-uppercase">Gastos Hoy</span>
                        <div class="icon-box bg-danger bg-opacity-10 text-danger"><i class="fas fa-wallet"></i></div>
                    </div>
                    <h3 class="fw-bold m-0 text-danger"><?php echo $moneda; ?> <span id="kpi-gastos">0.00</span></h3>
                    <small id="kpi-gastos-count" class="text-muted">0 registros</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card kpi-card shadow-sm h-100 bg-white border-start border-5 border-warning">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small fw-bold text-uppercase">Stock Bajo</span>
                        <div class="icon-box bg-warning bg-opacity-10 text-warning"><i class="fas fa-exclamation-triangle"></i></div>
                    </div>
                    <h3 class="fw-bold m-0 text-warning" id="kpi-stock">0</h3>
                    <small class="text-muted">Productos por agotarse</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white py-3 border-0 d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold m-0 text-dark"><i class="fas fa-hourglass-half text-danger me-2"></i>Control de Vencimientos (60 días)</h5>
                </div>
                <div class="table-responsive" style="max-height: 400px;">
                    <table class="table table-hover align-middle m-0 table-vencimientos">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3">Medicamento</th>
                                <th>Fecha Caducidad</th>
                                <th class="text-center">Días Restantes</th>
                                <th class="text-end pe-3">Estado</th>
                            </tr>
                        </thead>
                        <tbody id="vencimientos-list">
                            <tr><td colspan="4" class="text-center py-5"><div class="spinner-border spinner-border-sm text-primary"></div> Cargando alertas...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white py-3 border-0">
                    <h5 class="fw-bold m-0 text-dark"><i class="fas fa-chart-line text-primary me-2"></i>Lo Más Vendido</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush list-ranking" id="ranking-list">
                        <div class="text-center py-5 text-muted small">
                            <div class="spinner-border spinner-border-sm text-primary mb-2"></div><br>
                            Calculando ventas...
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    actualizarDashboard();
});

// Guardamos la moneda de PHP en una variable segura de JS
const monedaSistema = "<?php echo $moneda; ?>";

function actualizarDashboard() {
    // 1. CARGAR KPIs PRINCIPALES
    fetch('api.php?task=dashboard_kpis')
    .then(r => r.json())
    .then(d => {
        if(d.error) throw new Error(d.error);
        
        // Asignamos evitando que un nulo rompa el JS
        let v_tot = d.ventas_hoy?.total || 0;
        let v_can = d.ventas_hoy?.cantidad || 0;
        let g_tot = d.gastos_hoy?.total || 0;
        let g_can = d.gastos_hoy?.cantidad || 0;
        let t_pro = d.ticket_promedio || 0;
        let s_baj = d.stock_bajo || 0;

        document.getElementById('kpi-ventas').innerText = parseFloat(v_tot).toFixed(2);
        document.getElementById('kpi-ventas-count').innerText = v_can + ' transacciones';
        document.getElementById('kpi-ticket').innerText = parseFloat(t_pro).toFixed(2);
        document.getElementById('kpi-gastos').innerText = parseFloat(g_tot).toFixed(2);
        document.getElementById('kpi-gastos-count').innerText = g_can + ' registros';
        document.getElementById('kpi-stock').innerText = s_baj;
    })
    .catch(err => {
        console.error("Error cargando KPIs:", err);
    });

    // 2. CARGAR VENCIMIENTOS
    fetch('api.php?task=get_notifications')
    .then(r => r.json())
    .then(data => {
        let html = '';
        if(!data || data.length === 0 || data.error) {
            html = '<tr><td colspan="4" class="text-center py-4 text-muted fw-bold">Todo en orden. No hay vencimientos próximos.</td></tr>';
        } else {
            data.forEach(p => {
                let badgeClass = 'bg-success'; 
                let rowClass = '';
                
                if(p.dias <= 15) { 
                    badgeClass = 'bg-danger'; 
                    rowClass = 'table-danger'; 
                } else if(p.dias <= 30) { 
                    badgeClass = 'bg-warning text-dark'; 
                }

                html += `
                <tr class="${rowClass}">
                    <td class="ps-3">
                        <div class="fw-bold small text-uppercase">${p.nombre}</div>
                    </td>
                    <td><span class="text-muted small"><i class="far fa-calendar-alt me-1"></i>${p.fecha_caducidad}</span></td>
                    <td class="text-center fw-bold">${p.dias}</td>
                    <td class="text-end pe-3">
                        <span class="badge ${badgeClass} px-3 rounded-pill">
                            ${p.dias <= 0 ? 'CADUCADO' : 'POR VENCER'}
                        </span>
                    </td>
                </tr>`;
            });
        }
        document.getElementById('vencimientos-list').innerHTML = html;
    })
    .catch(err => console.error("Error vencimientos:", err));

    // 3. CARGAR RANKING DE PRODUCTOS (Corregido para eliminar el bloqueo de pantalla)
    fetch('api.php?task=get_popular_products')
    .then(r => r.json())
    .then(data => {
        let html = '';
        if(!data || data.length === 0 || data.error) {
            html = '<div class="p-4 text-center text-muted fw-bold">Aún no hay ventas registradas.</div>';
        } else {
            data.slice(0, 5).forEach((p, idx) => {
                html += `
                <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                    <div class="d-flex align-items-center">
                        <div class="fw-bold text-primary me-3">#${idx + 1}</div>
                        <div>
                            <div class="fw-bold small text-truncate" style="max-width: 150px;">${p.nombre}</div>
                            <small class="text-muted">${p.vendidos} unidades</small>
                        </div>
                    </div>
                    <span class="badge bg-light text-dark border">${monedaSistema} ${parseFloat(p.precio_venta).toFixed(2)}</span>
                </div>`;
            });
        }
        document.getElementById('ranking-list').innerHTML = html;
    })
    .catch(err => {
        console.error("Error populares:", err);
        document.getElementById('ranking-list').innerHTML = '<div class="p-3 text-center text-danger fw-bold">Error al cargar ranking</div>';
    });
}
</script>