<?php
require_once __DIR__ . '/../../includes/layout.php';
$version = '20260523';
renderHeader('Alertas de Inventario', 'alertas_inventario');
$pdo = getDBConnection();
?>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
:root {
    --alerta-stock-bajo: #f97316;
    --alerta-sin-stock: #ef4444;
    --alerta-por-vencer: #eab308;
    --alerta-vencido: #dc2626;
    --alerta-ajuste: #8b5cf6;
}

.al-container { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }

.al-topbar {
    display: flex; flex-wrap: wrap; align-items: center; gap: 1rem;
    margin-bottom: 1.5rem;
}
.al-topbar h1 {
    font-size: 1.5rem; font-weight: 800; color: var(--text-primary);
    display: flex; align-items: center; gap: 0.5rem; margin: 0;
}

.al-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-left: auto; }
.al-actions select, .al-actions button {
    padding: 0.5rem 1rem; border-radius: 0.75rem; border: 1px solid var(--border-color);
    background: var(--surface-card); color: var(--text-primary); font-size: 0.875rem;
    cursor: pointer;
}
.al-actions select:focus { outline: none; border-color: var(--accent-color); }

/* Summary cards row */
.summary-row {
    display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 1rem; margin-bottom: 1.5rem;
}
.summary-card {
    background: var(--surface-card); border: 1px solid var(--border-color);
    border-radius: 1rem; padding: 1.25rem; cursor: pointer; transition: all 0.2s;
    position: relative; overflow: hidden;
}
.summary-card:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,0,0,0.12); }
.summary-card.active { border-left: 4px solid var(--sc-accent); }
.summary-card .sc-icon {
    position: absolute; right: 1rem; top: 1rem; font-size: 1.75rem; opacity: 0.15;
}
.summary-card .sc-count { font-size: 2rem; font-weight: 800; margin: 0; }
.summary-card .sc-label { font-size: 0.8rem; color: var(--text-secondary); margin: 0.25rem 0 0 0; }

/* Tables */
.al-section { display: none; }
.al-section.active { display: block; }

.al-table-wrap {
    background: var(--surface-card); border: 1px solid var(--border-color);
    border-radius: 1rem; overflow: auto; max-height: 70vh;
}
.al-table-wrap table { width: 100%; border-collapse: collapse; min-width: 650px; }
.al-table-wrap thead { position: sticky; top: 0; z-index: 2; }
.al-table-wrap th {
    background: var(--surface-card); padding: 0.75rem 1rem;
    font-size: 0.75rem; 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;
}
.al-table-wrap td {
    padding: 0.75rem 1rem; font-size: 0.875rem;
    border-bottom: 1px solid var(--border-color); vertical-align: middle;
}
.al-table-wrap tr:hover { background: rgba(0,0,0,0.02); }

/* Badges */
.alert-badge {
    display: inline-flex; align-items: center; gap: 0.35rem;
    padding: 0.25rem 0.75rem; border-radius: 1rem; font-size: 0.75rem;
    font-weight: 600; white-space: nowrap;
}
.alert-badge-danger { background: #fef2f2; color: #dc2626; }
.alert-badge-warning { background: #fffbeb; color: #d97706; }
.alert-badge-info { background: #eff6ff; color: #2563eb; }
.alert-badge-success { background: #f0fdf4; color: #16a34a; }
.alert-badge-purple { background: #f5f3ff; color: #7c3aed; }

.alert-count-dot {
    display: inline-flex; align-items: center; justify-content: center;
    min-width: 1.5rem; height: 1.5rem; border-radius: 1rem;
    font-size: 0.7rem; font-weight: 700; padding: 0 0.4rem;
}

.al-empty {
    text-align: center; padding: 3rem 1rem; color: var(--text-secondary);
}
.al-empty i { font-size: 3rem; opacity: 0.3; margin-bottom: 0.75rem; display: block; }

/* Responsive filters row */
.filter-row {
    display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center;
    margin-bottom: 1rem;
}
.filter-chip-group { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.filter-chip {
    padding: 0.4rem 1rem; border-radius: 2rem; border: 1px solid var(--border-color);
    font-size: 0.8rem; cursor: pointer; transition: all 0.2s;
    background: transparent; color: var(--text-secondary);
}
.filter-chip:hover { border-color: var(--accent-color); color: var(--accent-color); }
.filter-chip.active { background: var(--accent-color); color: white; border-color: var(--accent-color); }

@media (max-width: 768px) {
    .al-container { padding: 1rem; }
    .summary-row { grid-template-columns: repeat(2, 1fr); }
    .al-actions { margin-left: 0; width: 100%; }
    .al-actions select { flex: 1; }
}

/* Animations */
@keyframes fadeSlideIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
.al-section.active { animation: fadeSlideIn 0.3s ease-out; }

/* Progress bar for stock */
.stock-bar { display: flex; align-items: center; gap: 0.75rem; }
.stock-bar-track { flex: 1; height: 6px; background: #e5e7eb; border-radius: 3px; overflow: hidden; }
.stock-bar-fill { height: 100%; border-radius: 3px; transition: width 0.5s; }
</style>

<?php
function icon($name) {
    return '<i class="bi bi-'.$name.'"></i>';
}
?>

<div class="al-container">
    <!-- Top bar -->
    <div class="al-topbar">
        <h1><?= icon('bell-fill') ?> Alertas de Inventario</h1>
        <div class="al-actions">
            <select id="alSucursal" onchange="reloadAll()">
                <option value="0">Todas las sucursales</option>
                <?php foreach($pdo->query("SELECT id,nombre FROM sucursales ORDER BY nombre") as $s): ?>
                    <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['nombre']) ?></option>
                <?php endforeach; ?>
            </select>
            <button onclick="reloadAll()" class="btn py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 border-0 transition-all cursor-pointer flex items-center gap-2"><i class="bi bi-arrow-clockwise"></i> Actualizar</button>
        </div>
    </div>

    <!-- Summary cards -->
    <div class="summary-row" id="summaryCards">
        <div class="summary-card" onclick="switchTab('stock_bajo')" data-tab="stock_bajo">
            <div class="sc-icon"><i class="bi bi-exclamation-triangle-fill" style="color:#f97316"></i></div>
            <p class="sc-count" id="cnt_stock_bajo">-</p>
            <p class="sc-label">Stock bajo mínimo</p>
        </div>
        <div class="summary-card" onclick="switchTab('sin_stock')" data-tab="sin_stock">
            <div class="sc-icon"><i class="bi bi-x-circle-fill" style="color:#ef4444"></i></div>
            <p class="sc-count" id="cnt_sin_stock">-</p>
            <p class="sc-label">Sin stock</p>
        </div>
        <div class="summary-card" onclick="switchTab('por_vencer')" data-tab="vencimientos">
            <div class="sc-icon"><i class="bi bi-calendar-exclamation-fill" style="color:#eab308"></i></div>
            <p class="sc-count" id="cnt_por_vencer">-</p>
            <p class="sc-label">Por vencer (30d)</p>
        </div>
        <div class="summary-card" onclick="switchTab('vencidos')" data-tab="vencidos">
            <div class="sc-icon"><i class="bi bi-calendar-x-fill" style="color:#dc2626"></i></div>
            <p class="sc-count" id="cnt_vencidos">-</p>
            <p class="sc-label">Vencidos</p>
        </div>
        <div class="summary-card" onclick="switchTab('ajustes')" data-tab="ajustes">
            <div class="sc-icon"><i class="bi bi-tools" style="color:#8b5cf6"></i></div>
            <p class="sc-count" id="cnt_ajustes_mes">-</p>
            <p class="sc-label">Ajustes (30d)</p>
        </div>
    </div>

    <!-- Filter row (contextual) -->
    <div class="filter-row" id="filterRow">
        <span style="font-size:0.8rem;font-weight:600;color:var(--text-secondary)">FILTRO RÁPIDO:</span>
        <div class="filter-chip-group" id="filterChips"></div>
    </div>

    <!-- Sections -->
    <div id="alSections">
        <!-- Stock bajo -->
        <div class="al-section" id="sec_stock_bajo">
            <div class="al-table-wrap">
                <table>
                    <thead><tr>
                        <th>Código</th><th>Producto</th><th>Sucursal</th><th>Stock</th><th>Mínimo</th><th>Faltante</th><th>Progreso</th>
                    </tr></thead>
                    <tbody id="tb_stock_bajo"><tr><td colspan="7" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>

        <!-- Sin stock -->
        <div class="al-section" id="sec_sin_stock">
            <div class="al-table-wrap">
                <table>
                    <thead><tr>
                        <th>Código</th><th>Producto</th><th>Sucursal</th><th>Stock</th><th>Categoría</th>
                    </tr></thead>
                    <tbody id="tb_sin_stock"><tr><td colspan="5" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>

        <!-- Por vencer -->
        <div class="al-section" id="sec_vencimientos">
            <div class="al-table-wrap">
                <table>
                    <thead><tr>
                        <th>Código</th><th>Producto</th><th>Vencimiento</th><th>Días rest.</th><th>Proveedor/Lote</th><th>Origen</th>
                    </tr></thead>
                    <tbody id="tb_vencimientos"><tr><td colspan="6" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>

        <!-- Vencidos -->
        <div class="al-section" id="sec_vencidos">
            <div class="al-table-wrap">
                <table>
                    <thead><tr>
                        <th>Código</th><th>Producto</th><th>Vencimiento</th><th>Días vencido</th><th>Lote</th>
                    </tr></thead>
                    <tbody id="tb_vencidos"><tr><td colspan="5" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>

        <!-- Ajustes -->
        <div class="al-section" id="sec_ajustes">
            <div class="al-table-wrap">
                <table>
                    <thead><tr>
                        <th>Fecha</th><th>Código</th><th>Producto</th><th>Sucursal</th>
                        <th>Tipo</th><th>Cant.</th><th>Motivo</th><th>Usuario</th>
                    </tr></thead>
                    <tbody id="tb_ajustes"><tr><td colspan="8" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
let activeTab = 'stock_bajo';
let sucursal = 0;

document.addEventListener('DOMContentLoaded', () => {
    syncSucursalSelect('alSucursal');
    reloadAll();
    // Click first card
    document.querySelector('.summary-card')?.classList.add('active');
});

async function reloadAll() {
    sucursal = parseInt(document.getElementById('alSucursal').value);
    await loadResumen();
    switchTab(activeTab);
}

async function loadResumen() {
    try {
        const r = await fetch(`api/alertas/index.php?action=resumen&sucursal_id=${sucursal}`);
        const d = await r.json();
        if (d.success) {
            d.data.forEach(item => {
                const el = document.getElementById('cnt_' + item.id);
                if (el) {
                    el.textContent = item.count;
                    // Color the count
                    el.style.color = item.color;
                }
            });
        }
    } catch(e) {}
}

function switchTab(tab) {
    activeTab = tab;
    // Update cards
    document.querySelectorAll('.summary-card').forEach(c => c.classList.toggle('active', c.dataset.tab === tab));
    // Update sections
    document.querySelectorAll('.al-section').forEach(s => s.classList.remove('active'));
    const sec = document.getElementById('sec_' + tab);
    if (sec) sec.classList.add('active');
    // Load data
    loadTab(tab);
}

async function loadTab(tab) {
    const tbody = document.getElementById('tb_' + tab);
    if (!tbody) return;

    tbody.innerHTML = '<tr><td colspan="8" class="al-empty"><i class="bi bi-hourglass-split"></i> Cargando...</td></tr>';

    try {
        const r = await fetch(`api/alertas/index.php?action=${tab}&sucursal_id=${sucursal}`);
        const d = await r.json();
        if (!d.success) throw new Error(d.message);

        const data = d.data;
        if (!data || data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="al-empty"><i class="bi bi-check-circle-fill" style="color:#16a34a"></i> Todo en orden, sin alertas.</td></tr>';
            return;
        }

        let html = '';
        data.forEach(row => {
            switch (tab) {
                case 'stock_bajo':
                    const pct = Math.max(0, Math.min(100, row.stock_total > 0 ? (row.stock_total / row.stock_minimo) * 100 : 0));
                    const barColor = pct < 25 ? '#ef4444' : pct < 60 ? '#f97316' : '#eab308';
                    html += `<tr>
                        <td><strong>${esc(row.codigo)}</strong></td>
                        <td>${esc(row.producto)}</td>
                        <td>${esc(row.sucursal)}</td>
                        <td style="font-weight:700;color:${barColor}">${row.stock_total}</td>
                        <td>${row.stock_minimo}</td>
                        <td style="color:#ef4444;font-weight:700">-${row.faltante}</td>
                        <td><div class="stock-bar"><div class="stock-bar-track"><div class="stock-bar-fill" style="width:${pct}%;background:${barColor}"></div></div><span style="font-size:0.75rem;min-width:2.5rem">${Math.round(pct)}%</span></div></td>
                    </tr>`;
                    break;

                case 'sin_stock':
                    html += `<tr>
                        <td><strong>${esc(row.codigo)}</strong></td>
                        <td>${esc(row.producto)}</td>
                        <td>${esc(row.sucursal)}</td>
                        <td><span class="alert-badge alert-badge-danger">${row.stock_total}</span></td>
                        <td>${esc(row.categoria || '-')}</td>
                    </tr>`;
                    break;

                case 'vencimientos':
                    const dias = parseInt(row.dias_restantes);
                    const badgeClass = dias < 0 ? 'alert-badge-danger' : dias <= 15 ? 'alert-badge-danger' : dias <= 30 ? 'alert-badge-warning' : 'alert-badge-info';
                    const label = dias < 0 ? `Vencido (${Math.abs(dias)}d)` : `${dias} días`;
                    const origenIcon = row.origen === 'lote' ? 'bi-box-seam-fill' : 'bi-cart-fill';
                    html += `<tr>
                        <td><strong>${esc(row.codigo)}</strong></td>
                        <td>${esc(row.producto)}</td>
                        <td>${esc(row.fecha_vencimiento)}</td>
                        <td><span class="alert-badge ${badgeClass}">${label}</span></td>
                        <td style="font-size:0.8rem">${esc(row.proveedor || '-')}</td>
                        <td><span class="alert-badge alert-badge-info"><i class="${origenIcon}"></i> ${esc(row.origen)}</span></td>
                    </tr>`;
                    break;

                case 'vencidos':
                    const dv = parseInt(row.dias_vencido);
                    html += `<tr>
                        <td><strong>${esc(row.codigo)}</strong></td>
                        <td>${esc(row.producto)}</td>
                        <td>${esc(row.fecha_vencimiento)}</td>
                        <td><span class="alert-badge alert-badge-danger">${dv} días</span></td>
                        <td>${esc(row.lote || '-')}</td>
                    </tr>`;
                    break;

                case 'ajustes':
                    const tipo = row.tipo_ajuste || 'default';
                    const tipoBadge = tipo === 'entrada' ? 'alert-badge-success' : tipo === 'salida' ? 'alert-badge-warning' : 'alert-badge-info';
                    html += `<tr>
                        <td style="white-space:nowrap">${esc(row.fecha_ajuste)}</td>
                        <td><strong>${esc(row.codigo)}</strong></td>
                        <td>${esc(row.producto)}</td>
                        <td>${esc(row.sucursal)}</td>
                        <td><span class="alert-badge ${tipoBadge}">${esc(tipo)}</span></td>
                        <td style="font-weight:700">${row.cantidad_ajustada ?? '-'}</td>
                        <td style="font-size:0.8rem;max-width:200px;overflow:hidden;text-overflow:ellipsis">${esc(row.motivo || '-')}</td>
                        <td>${esc(row.usuario || '-')}</td>
                    </tr>`;
                    break;
            }
        });

        tbody.innerHTML = html;
    } catch(e) {
        tbody.innerHTML = `<tr><td colspan="8" class="al-empty"><i class="bi bi-exclamation-circle-fill" style="color:#ef4444"></i> Error: ${esc(e.message)}</td></tr>`;
    }
}

function esc(s) {
    if (!s) return '-';
    const d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
}
</script>

<?php renderFooter(); ?>

