<?php
require_once __DIR__ . '/../../includes/layout.php';
renderHeader('Inventario en Tiempo Real', 'inventario_tiempo_real');

$pdo = getDBConnection();

// Obtener todas las sucursales para el select de filtrado
try {
    $sucursales = $pdo->query("SELECT id, nombre FROM sucursales ORDER BY id")->fetchAll();
} catch (Exception $e) {
    $sucursales = [];
}

// Obtener sucursal por defecto desde la url o la cookie (0 para Todas)
$active_sucursal = isset($_GET['sucursal_id']) ? (int)$_GET['sucursal_id'] : 0;
?>

<style>
.report-wrap {
    max-width: 1400px;
    margin: 0 auto;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}
.report-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 0.5rem;
}
.report-header h1 {
    font-size: 1.75rem;
    font-weight: 800;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

/* Premium Export Buttons */
.btn-export-excel-green {
    background: rgba(16, 185, 129, 0.1) !important;
    color: #10b981 !important;
    border: 1px solid rgba(16, 185, 129, 0.2) !important;
    font-weight: 700 !important;
    height: 38px;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.8rem;
    cursor: pointer;
    transition: all var(--transition) !important;
    white-space: nowrap;
}
.btn-export-excel-green:hover {
    background: #10b981 !important;
    color: var(--primary) !important;
    border-color: #10b981 !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

.btn-export-excel-red {
    background: rgba(239, 68, 68, 0.1) !important;
    color: #ef4444 !important;
    border: 1px solid rgba(239, 68, 68, 0.2) !important;
    font-weight: 700 !important;
    height: 38px;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.8rem;
    cursor: pointer;
    transition: all var(--transition) !important;
    white-space: nowrap;
}
.btn-export-excel-red:hover {
    background: #ef4444 !important;
    color: var(--primary) !important;
    border-color: #ef4444 !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
}

.search-box-wrapper {
    position: relative;
}
.vencimientos-container {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem;
    max-width: 250px;
}
.venc-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.65rem;
    padding: 0.15rem 0.4rem;
    border-radius: 4px;
    font-weight: 600;
}
.venc-active {
    background: rgba(16, 185, 129, 0.12);
    color: #10b981;
    border: 1px solid rgba(16, 185, 129, 0.2);
}
.venc-warning {
    background: rgba(245, 158, 11, 0.12);
    color: #f59e0b;
    border: 1px solid rgba(245, 158, 11, 0.2);
}
.venc-expired {
    background: rgba(239, 68, 68, 0.12);
    color: #ef4444;
    border: 1px solid rgba(239, 68, 68, 0.2);
}
.total-row {
    background: var(--primary-light) !important;
    font-weight: bold;
    border-top: 2px solid var(--border-dark);
}
.stock-val-highlight {
    font-weight: 700;
    color: var(--text-primary);
}
.stock-val-zero {
    color: var(--text-muted);
    font-weight: normal;
}
</style>

<div class="report-wrap animate-fade-in">
    <div class="report-header">
        <div>
            <h1 style="font-size: 1.5rem; font-family: 'League Spartan'; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 0.5rem;">
                <i class="fas fa-clock" style="color:var(--accent-color); margin-right:0.5rem;"></i>
                Inventario en Tiempo Real
            </h1>
        </div>
    </div>

    <!-- Barra de Filtros y Acciones -->
    <div class="filters-card">
        <!-- Fila 1: Filtros principales (Sucursal y Buscador) -->
        <div style="display: flex; gap: 1.5rem; align-items: flex-end; width: 100%; margin-bottom: 1.25rem; flex-wrap: wrap;">
            <!-- Selector de Sucursal -->
            <div class="form-group" style="width: 260px; margin: 0; flex-shrink: 0;">
                <label class="form-label" for="filtroSucursal">Sucursal</label>
                <select class="input-select" id="filtroSucursal" style="width: 100%;">
                    <option value="0" <?= $active_sucursal === 0 ? 'selected' : '' ?>>🌐 Todas las sucursales (Consolidado)</option>
                    <?php foreach ($sucursales as $suc): ?>
                        <option value="<?= (int)$suc['id'] ?>" <?= $active_sucursal === (int)$suc['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($suc['nombre']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <!-- Buscador -->
            <div class="form-group search-box-wrapper" style="flex: 1; min-width: 280px; margin: 0;">
                <label class="form-label" for="buscarProducto">Buscar Producto</label>
                <div style="position: relative;">
                    <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); pointer-events: none;"></i>
                    <input type="text" class="input-text" id="buscarProducto" placeholder="Buscar por código, código de barras, nombre comercial o laboratorio..." autocomplete="off" style="width: 100%; padding-left: 2.5rem !important;">
                </div>
            </div>
        </div>

        <!-- Fila 2: Existencias y Exportación -->
        <div style="display: flex; gap: 1.5rem; align-items: center; flex-wrap: wrap;">
            <!-- Solo con existencias -->
            <div style="display: flex; align-items: center; height: 38px;">
                <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.85rem; font-weight: 600; color: var(--text-primary); cursor: pointer; user-select: none; margin: 0;">
                    <input type="checkbox" id="filtroExistencias" checked style="width: 18px; height: 18px; accent-color: var(--accent-color); cursor: pointer; margin: 0;">
                    <span>Solo con existencias</span>
                </label>
            </div>
            <!-- Botones Excel -->
            <div style="display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap;">
                <button onclick="exportarExcel(1)" class="btn btn-export-excel-green">
                    <i class="fas fa-file-excel"></i> Exportar Facturado
                </button>
                <button onclick="exportarExcel(0)" class="btn btn-export-excel-red">
                    <i class="fas fa-file-excel"></i> Exportar Sin Factura
                </button>
            </div>
        </div>
    </div>

    <!-- Métricas del Inventario -->
    <div class="grid-stats" style="margin-bottom: 0.5rem;">
        <!-- Card 1: Productos -->
        <div class="card" style="padding: 1.25rem 1.5rem; display: flex; align-items: center; gap: 1rem;">
            <div style="background: rgba(210, 200, 221, 0.08); width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: var(--accent-color); font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-box"></i>
            </div>
            <div>
                <div style="font-size: 0.75rem; color: var(--text-secondary); text-transform: uppercase; font-weight: 700; letter-spacing: 0.05em;">Productos Registrados</div>
                <div style="font-size: 1.5rem; font-weight: 800; font-family: 'League Spartan'; color: var(--text-primary); margin-top: 0.15rem;" id="totalItemsCount">0</div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.15rem;">Catálogo activo</div>
            </div>
        </div>

        <!-- Card 2: Stock Total -->
        <div class="card" style="padding: 1.25rem 1.5rem; display: flex; align-items: center; gap: 1rem;">
            <div style="background: rgba(34, 197, 94, 0.08); width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: var(--success); font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-cubes"></i>
            </div>
            <div style="flex-grow: 1; min-width: 0;">
                <div style="font-size: 0.75rem; color: var(--text-secondary); text-transform: uppercase; font-weight: 700; letter-spacing: 0.05em;">Existencias en Stock</div>
                <div style="font-size: 1.5rem; font-weight: 800; font-family: 'League Spartan'; color: var(--text-primary); margin-top: 0.15rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" id="totalStockText">0 u.</div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.15rem;" id="totalStockBreakdown">Facturado: 0 | Sin Factura: 0</div>
            </div>
        </div>

        <!-- Card 3: Valoración Total -->
        <div class="card" style="padding: 1.25rem 1.5rem; display: flex; align-items: center; gap: 1rem;">
            <div style="background: rgba(124, 58, 237, 0.08); width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: #7c3aed; font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-coins"></i>
            </div>
            <div style="flex-grow: 1; min-width: 0;">
                <div style="font-size: 0.75rem; color: var(--text-secondary); text-transform: uppercase; font-weight: 700; letter-spacing: 0.05em;">Valoración del Inventario</div>
                <div style="font-size: 1.5rem; font-weight: 800; font-family: 'League Spartan'; color: var(--text-primary); margin-top: 0.15rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" id="totalValorizadoText">Q 0.00</div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.15rem;" id="totalValorizadoBreakdown">Facturado: Q 0.00 | Sin Factura: Q 0.00</div>
            </div>
        </div>
    </div>

    <!-- Tabla de Resultados -->
    <div class="card">
        <div class="table-wrapper">
            <table class="table-premium" id="tablaInventario">
                <thead id="tablaHeader">
                    <!-- Se carga dinámicamente por JavaScript -->
                </thead>
                <tbody id="tablaBody">
                    <tr>
                        <td colspan="12" style="text-align: center; color: var(--text-muted); padding: 3rem;">
                            <i class="fas fa-spinner fa-pulse" style="font-size: 2rem; margin-bottom: 0.75rem; display: block; color: var(--accent-color);"></i>
                            Cargando inventario en tiempo real...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Controles de Paginación -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--border-color);">
            <div style="font-size: 0.8rem; color: var(--text-light);" id="paginationInfo">
                Mostrando 0 - 0 de 0 registros
            </div>
            <div class="pagination" id="paginationControls" style="display: flex; gap: 0.25rem;">
                <!-- Botones dinámicos -->
            </div>
        </div>
    </div>
</div>

<script src="js/inventario/inventario_tiempo_real.js?v=<?= $assetVersion ?>"></script>
<?php renderFooter(); ?>
