<?php
session_start();
include '../../script/conexion.php';
require '../general/validacion.php';

date_default_timezone_set('America/Bogota');

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function nf0($value)
{
    return number_format((float)$value, 0, ',', '.');
}

function buildQueryParams(array $params)
{
    foreach ($params as $key => $value) {
        if ($value === '' || $value === null) {
            unset($params[$key]);
        }
    }
    return http_build_query($params);
}

$q         = trim($_GET['q'] ?? '');
$categoria = trim($_GET['categoria'] ?? '');
$segmento  = trim($_GET['segmento'] ?? '');
$stock     = trim($_GET['stock'] ?? '');
$orden     = trim($_GET['orden'] ?? 'referencia_asc');

$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$porPagina = 30;
$offset = ($pagina - 1) * $porPagina;

/*
|--------------------------------------------------------------------------
| Filtros
|--------------------------------------------------------------------------
*/
$where = [];
$where[] = "1=1";

if ($q !== '') {
    $qSql = $conn->real_escape_string($q);
    $where[] = "(
        p.referencia LIKE '%$qSql%' OR
        p.codigo LIKE '%$qSql%' OR
        p.categoria LIKE '%$qSql%' OR
        p.referencia_segmento LIKE '%$qSql%' OR
        p.color LIKE '%$qSql%' OR
        p.color2 LIKE '%$qSql%'
    )";
}

if ($categoria !== '') {
    $categoriaSql = $conn->real_escape_string($categoria);
    $where[] = "p.categoria = '$categoriaSql'";
}

if ($segmento !== '') {
    $segmentoSql = $conn->real_escape_string($segmento);
    $where[] = "p.referencia_segmento = '$segmentoSql'";
}

if ($stock === 'positivo') {
    $where[] = "COALESCE(s.total_stock, 0) > 0";
} elseif ($stock === 'cero') {
    $where[] = "COALESCE(s.total_stock, 0) = 0";
} elseif ($stock === 'negativo') {
    $where[] = "COALESCE(s.total_stock, 0) < 0";
}

$whereSql = implode(' AND ', $where);

$orderMap = [
    'referencia_asc'  => 'p.referencia ASC',
    'referencia_desc' => 'p.referencia DESC',
    'codigo_asc'      => 'p.codigo ASC, p.referencia ASC',
    'stock_desc'      => 'COALESCE(s.total_stock, 0) DESC, p.referencia ASC',
    'stock_asc'       => 'COALESCE(s.total_stock, 0) ASC, p.referencia ASC',
    'categoria_asc'   => 'p.categoria ASC, p.referencia ASC',
];

$orderSql = $orderMap[$orden] ?? $orderMap['referencia_asc'];

$fromBase = "
    FROM producto p
    INNER JOIN (
        SELECT referencia_producto, SUM(cantidad) AS total_stock
        FROM alm_referencia_disponible
        GROUP BY referencia_producto
    ) s ON s.referencia_producto = p.referencia
";

/*
|--------------------------------------------------------------------------
| Opciones filtros
|--------------------------------------------------------------------------
*/
$categorias = [];
$queryCategorias = $conn->query("SELECT DISTINCT categoria FROM producto WHERE categoria <> '' ORDER BY categoria ASC");
if ($queryCategorias && $queryCategorias->num_rows > 0) {
    while ($row = $queryCategorias->fetch_assoc()) {
        $categorias[] = $row['categoria'];
    }
}

$segmentos = [];
$querySegmentos = $conn->query("SELECT DISTINCT referencia_segmento FROM producto WHERE referencia_segmento <> '' ORDER BY referencia_segmento ASC");
if ($querySegmentos && $querySegmentos->num_rows > 0) {
    while ($row = $querySegmentos->fetch_assoc()) {
        $segmentos[] = $row['referencia_segmento'];
    }
}

/*
|--------------------------------------------------------------------------
| Tallas globales
|--------------------------------------------------------------------------
*/
$tallas = [];
$queryTallas = $conn->query("SELECT DISTINCT talla FROM alm_referencia_disponible ORDER BY CAST(talla AS UNSIGNED) ASC, talla ASC");
if ($queryTallas && $queryTallas->num_rows > 0) {
    while ($row = $queryTallas->fetch_assoc()) {
        $tallas[] = (string)$row['talla'];
    }
}

/*
|--------------------------------------------------------------------------
| Resumen general
|--------------------------------------------------------------------------
*/
$stats = [
    'total_refs'        => 0,
    'total_unidades'    => 0,
    'refs_positivas'    => 0,
    'refs_cero'         => 0,
    'refs_negativas'    => 0,
    'tallas'            => count($tallas),
];

$sqlStats = "
    SELECT
        COUNT(*) AS total_refs,
        COALESCE(SUM(COALESCE(s.total_stock, 0)), 0) AS total_unidades,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) > 0 THEN 1 ELSE 0 END) AS refs_positivas,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) = 0 THEN 1 ELSE 0 END) AS refs_cero,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) < 0 THEN 1 ELSE 0 END) AS refs_negativas
    $fromBase
    WHERE $whereSql
";
$queryStats = $conn->query($sqlStats);
if ($queryStats && $queryStats->num_rows > 0) {
    $rowStats = $queryStats->fetch_assoc();
    $stats['total_refs']     = (int)($rowStats['total_refs'] ?? 0);
    $stats['total_unidades'] = (float)($rowStats['total_unidades'] ?? 0);
    $stats['refs_positivas'] = (int)($rowStats['refs_positivas'] ?? 0);
    $stats['refs_cero']      = (int)($rowStats['refs_cero'] ?? 0);
    $stats['refs_negativas'] = (int)($rowStats['refs_negativas'] ?? 0);
}

$totalPaginas = max(1, (int)ceil($stats['total_refs'] / $porPagina));
if ($pagina > $totalPaginas) {
    $pagina = $totalPaginas;
    $offset = ($pagina - 1) * $porPagina;
}

/*
|--------------------------------------------------------------------------
| Referencias paginadas
|--------------------------------------------------------------------------
*/
$productos = [];
$sqlProductos = "
    SELECT
        p.referencia,
        p.codigo,
        p.categoria,
        p.referencia_segmento,
        p.color,
        p.color2,
        p.bicolor,
        p.clase,
        p.peso,
        p.alm_precio_unidad,
        p.foto1,
        COALESCE(s.total_stock, 0) AS total_stock
    $fromBase
    WHERE $whereSql
    ORDER BY $orderSql
    LIMIT $offset, $porPagina
";
$queryProductos = $conn->query($sqlProductos);
if ($queryProductos && $queryProductos->num_rows > 0) {
    while ($row = $queryProductos->fetch_assoc()) {
        $productos[$row['referencia']] = $row;
    }
}

/*
|--------------------------------------------------------------------------
| Colores solo para referencias visibles
|--------------------------------------------------------------------------
*/
$rgbPorColor = [];
$coloresNecesarios = [];

foreach ($productos as $prod) {
    if (!empty($prod['color'])) {
        $coloresNecesarios[$prod['color']] = true;
    }
    if (!empty($prod['color2'])) {
        $coloresNecesarios[$prod['color2']] = true;
    }
}

if (!empty($coloresNecesarios)) {
    $listaColores = array_map(function ($c) use ($conn) {
        return "'" . $conn->real_escape_string($c) . "'";
    }, array_keys($coloresNecesarios));

    $sqlColores = "SELECT color, rgb FROM color WHERE color IN (" . implode(',', $listaColores) . ")";
    $queryColores = $conn->query($sqlColores);
    if ($queryColores && $queryColores->num_rows > 0) {
        while ($row = $queryColores->fetch_assoc()) {
            $rgbPorColor[$row['color']] = $row['rgb'];
        }
    }
}

/*
|--------------------------------------------------------------------------
| Matriz de tallas solo de la página actual
|--------------------------------------------------------------------------
*/
$matrix = [];
$totalesPorTallaPagina = array_fill_keys($tallas, 0);
$totalPaginaUnidades = 0;

if (!empty($productos)) {
    $refs = array_keys($productos);
    $refsSql = array_map(function ($ref) use ($conn) {
        return "'" . $conn->real_escape_string($ref) . "'";
    }, $refs);

    foreach ($refs as $ref) {
        $matrix[$ref] = array_fill_keys($tallas, 0);
    }

    $sqlMatrix = "
        SELECT referencia_producto, talla, SUM(cantidad) AS cantidad
        FROM alm_referencia_disponible
        WHERE referencia_producto IN (" . implode(',', $refsSql) . ")
        GROUP BY referencia_producto, talla
    ";
    $queryMatrix = $conn->query($sqlMatrix);
    if ($queryMatrix && $queryMatrix->num_rows > 0) {
        while ($row = $queryMatrix->fetch_assoc()) {
            $ref = (string)$row['referencia_producto'];
            $talla = (string)$row['talla'];
            $cantidad = (float)$row['cantidad'];

            if (isset($matrix[$ref][$talla])) {
                $matrix[$ref][$talla] = $cantidad;
                $totalesPorTallaPagina[$talla] += $cantidad;
            }
        }
    }

    foreach ($productos as $prod) {
        $totalPaginaUnidades += (float)$prod['total_stock'];
    }
}

$queryBase = [
    'q'         => $q,
    'categoria' => $categoria,
    'segmento'  => $segmento,
    'stock'     => $stock,
    'orden'     => $orden,
];

$desde = $stats['total_refs'] > 0 ? ($offset + 1) : 0;
$hasta = min($offset + $porPagina, $stats['total_refs']);
?>
<!doctype html>
<html lang="es" class="light-theme">
<head>
    <?php include '../general/libreria-css.php'; ?>

    <style>
        :root {
            --page-bg: #f6f8fb;
            --card-bg: #ffffff;
            --text-main: #1f2937;
            --text-soft: #6b7280;
            --line: #e5e7eb;
            --primary: #111827;
            --primary-soft: rgba(17, 24, 39, .06);
            --success-soft: rgba(34, 197, 94, .12);
            --warning-soft: rgba(245, 158, 11, .12);
            --danger-soft: rgba(239, 68, 68, .12);
            --info-soft: rgba(59, 130, 246, .12);
            --shadow: 0 10px 30px rgba(15, 23, 42, .06);
            --radius: 18px;
        }

        body {
            background: var(--page-bg);
            color: var(--text-main);
        }

        .page-title-card,
        .filter-card,
        .stats-card,
        .list-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body,
        .filter-card .card-body,
        .list-card .card-body {
            padding: 1.25rem 1.35rem;
        }

        .page-title-main {
            font-size: 1.55rem;
            font-weight: 800;
            margin-bottom: .2rem;
            letter-spacing: .2px;
        }

        .page-subtitle {
            color: var(--text-soft);
            margin: 0;
            font-size: .95rem;
        }

        .page-badges {
            display: flex;
            flex-wrap: wrap;
            gap: .5rem;
            margin-top: .8rem;
        }

        .info-chip {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .45rem .75rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .82rem;
            color: var(--text-main);
            font-weight: 600;
        }

        .label-soft {
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            color: var(--text-soft);
            font-weight: 700;
            margin-bottom: .45rem;
        }

        .btn-modern {
            border-radius: 12px;
            padding: .72rem 1rem;
            font-weight: 800;
        }

        .stats-card .card-body {
            padding: 1rem 1.1rem;
        }

        .stats-icon {
            width: 44px;
            height: 44px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-soft);
            color: var(--primary);
            font-size: 1.05rem;
            margin-bottom: .85rem;
        }

        .stats-title {
            font-size: .78rem;
            color: var(--text-soft);
            text-transform: uppercase;
            letter-spacing: .08em;
            margin-bottom: .35rem;
            font-weight: 700;
        }

        .stats-value {
            font-size: 1.35rem;
            font-weight: 800;
            line-height: 1.1;
            color: var(--text-main);
        }

        .stats-note {
            font-size: .8rem;
            color: var(--text-soft);
            margin-top: .35rem;
        }

        .section-head {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }

        .section-title {
            font-size: 1rem;
            font-weight: 800;
            margin-bottom: .15rem;
        }

        .section-subtitle {
            color: var(--text-soft);
            font-size: .88rem;
            margin: 0;
        }

        .table-modern {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table-modern thead th {
            background: #f8fafc;
            color: #334155;
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            font-weight: 800;
            border-bottom: 1px solid var(--line);
            border-top: 0;
            white-space: nowrap;
            padding: .78rem .62rem;
        }

        .table-modern tbody td,
        .table-modern tfoot th,
        .table-modern tfoot td {
            padding: .8rem .62rem;
            vertical-align: middle;
            border-color: #eef2f7;
            white-space: nowrap;
        }

        .table-modern tbody tr:hover {
            background: #fafcff;
        }

        .product-box {
            width: 60px;
            height: 60px;
            border-radius: 16px;
            overflow: hidden;
            border: 1px solid #e5e7eb;
            background: #fff;
            flex: 0 0 60px;
        }

        .ref-main {
            font-weight: 800;
            color: #111827;
        }

        .ref-sub {
            color: var(--text-soft);
            font-size: .82rem;
        }

        .chip-soft {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .38rem .65rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .76rem;
            color: var(--text-main);
            font-weight: 700;
        }

        .color-dot {
            width: 14px;
            height: 14px;
            border-radius: 999px;
            display: inline-block;
            border: 1px solid rgba(15, 23, 42, .12);
            margin-left: .4rem;
            vertical-align: middle;
        }

        .qty-positive {
            text-align: center;
            font-weight: 800;
            color: #0369a1;
            background: rgba(59, 130, 246, .08);
        }

        .qty-negative {
            text-align: center;
            font-weight: 800;
            color: #b91c1c;
            background: rgba(239, 68, 68, .08);
        }

        .qty-neutral {
            text-align: center;
            font-weight: 700;
            color: #64748b;
        }

        .stock-positive {
            color: #15803d;
            font-weight: 800;
        }

        .stock-zero {
            color: #64748b;
            font-weight: 800;
        }

        .stock-negative {
            color: #b91c1c;
            font-weight: 800;
        }

        .btn-detail {
            width: 38px;
            height: 38px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #e5e7eb;
            color: #111827;
            background: #fff;
            text-decoration: none;
            transition: all .18s ease;
        }

        .btn-detail:hover {
            background: #111827;
            color: #fff;
            border-color: #111827;
        }

        .pagination .page-link {
            border-radius: 12px !important;
            margin: 0 .15rem;
            border: 1px solid #e5e7eb;
            color: #111827;
            font-weight: 700;
        }

        .pagination .page-item.active .page-link {
            background: #111827;
            border-color: #111827;
            color: #fff;
        }

        .pagination .page-item.disabled .page-link {
            color: #9ca3af;
        }

        .empty-state {
            border: 1px dashed #cbd5e1;
            border-radius: 18px;
            padding: 2rem 1rem;
            text-align: center;
            background: #fff;
        }

        .empty-state i {
            font-size: 2rem;
            color: #94a3b8;
            margin-bottom: .75rem;
        }

        .empty-state h5 {
            font-weight: 800;
            margin-bottom: .35rem;
        }

        .empty-state p {
            color: var(--text-soft);
            margin-bottom: 0;
        }

        @media print {
            .d-print-none,
            .wrapper aside,
            .top-header,
            .pagination {
                display: none !important;
            }

            body {
                background: #fff !important;
            }

            .page-title-card,
            .filter-card,
            .stats-card,
            .list-card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php echo include '../general/menu.php'; ?>

        <div class="page-content-wrapper">
            <div class="page-content">

                <nav aria-label="breadcrumb" class="mb-3 d-print-none">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item">
                            <a href="../inicio/inicio.php">
                                <ion-icon name="home-outline"></ion-icon>
                            </a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Inventario</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Inventario</div>
                        <p class="page-subtitle">
                            Vista rápida del inventario por referencia y talla, optimizada para cargar más rápido y con filtros reales de servidor.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-boxes-stacked"></i>
                                Referencias: <?= nf0($stats['total_refs']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-ruler-combined"></i>
                                Tallas: <?= nf0($stats['tallas']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-warehouse"></i>
                                Unidades: <?= nf0($stats['total_unidades']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="card filter-card mb-3 d-print-none">
                    <div class="card-body">
                        <form method="GET" action="inventario.php">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-4">
                                    <label class="label-soft">Buscar</label>
                                    <input type="text" class="form-control" name="q" value="<?= h($q) ?>" placeholder="Referencia, código, color o categoría">
                                </div>

                                <div class="col-md-2">
                                    <label class="label-soft">Categoría</label>
                                    <select class="single-select form-control" name="categoria">
                                        <option value="">Todas</option>
                                        <?php foreach ($categorias as $item): ?>
                                            <option value="<?= h($item) ?>" <?= $categoria === $item ? 'selected' : '' ?>>
                                                <?= h($item) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <label class="label-soft">Segmento</label>
                                    <select class="single-select form-control" name="segmento">
                                        <option value="">Todos</option>
                                        <?php foreach ($segmentos as $item): ?>
                                            <option value="<?= h($item) ?>" <?= $segmento === $item ? 'selected' : '' ?>>
                                                <?= h($item) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <label class="label-soft">Stock</label>
                                    <select class="form-control" name="stock">
                                        <option value="">Todos</option>
                                        <option value="positivo" <?= $stock === 'positivo' ? 'selected' : '' ?>>Positivo</option>
                                        <option value="cero" <?= $stock === 'cero' ? 'selected' : '' ?>>En cero</option>
                                        <option value="negativo" <?= $stock === 'negativo' ? 'selected' : '' ?>>Negativo</option>
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <label class="label-soft">Ordenar</label>
                                    <select class="form-control" name="orden">
                                        <option value="referencia_asc" <?= $orden === 'referencia_asc' ? 'selected' : '' ?>>Referencia A-Z</option>
                                        <option value="referencia_desc" <?= $orden === 'referencia_desc' ? 'selected' : '' ?>>Referencia Z-A</option>
                                        <option value="codigo_asc" <?= $orden === 'codigo_asc' ? 'selected' : '' ?>>Código</option>
                                        <option value="stock_desc" <?= $orden === 'stock_desc' ? 'selected' : '' ?>>Stock mayor</option>
                                        <option value="stock_asc" <?= $orden === 'stock_asc' ? 'selected' : '' ?>>Stock menor</option>
                                        <option value="categoria_asc" <?= $orden === 'categoria_asc' ? 'selected' : '' ?>>Categoría</option>
                                    </select>
                                </div>

                                <div class="col-md-12">
                                    <div class="d-flex gap-2 flex-wrap">
                                        <button class="btn btn-dark btn-modern" type="submit">
                                            <i class="fas fa-search me-1"></i> Filtrar
                                        </button>
                                        <a href="inventario.php" class="btn btn-outline-secondary btn-modern">
                                            Restablecer
                                        </a>
                                        <a href="javascript:window.print()" class="btn btn-outline-dark btn-modern">
                                            <i class="fas fa-print me-1"></i> Imprimir
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-boxes-stacked"></i></div>
                                <div class="stats-title">Referencias filtradas</div>
                                <div class="stats-value"><?= nf0($stats['total_refs']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-check-circle"></i></div>
                                <div class="stats-title">Stock positivo</div>
                                <div class="stats-value text-success"><?= nf0($stats['refs_positivas']) ?></div>
                                <div class="stats-note">Referencias con saldo disponible</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-minus-circle"></i></div>
                                <div class="stats-title">En cero</div>
                                <div class="stats-value"><?= nf0($stats['refs_cero']) ?></div>
                                <div class="stats-note">Referencias sin saldo</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-triangle-exclamation"></i></div>
                                <div class="stats-title">Stock negativo</div>
                                <div class="stats-value text-danger"><?= nf0($stats['refs_negativas']) ?></div>
                                <div class="stats-note">Referencias con inconsistencia</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card list-card">
                    <div class="card-body">
                        <div class="section-head">
                            <div>
                                <div class="section-title">Inventario por referencia</div>
                                <p class="section-subtitle">
                                    Mostrando <?= nf0($desde) ?> - <?= nf0($hasta) ?> de <?= nf0($stats['total_refs']) ?> referencias.
                                </p>
                            </div>
                        </div>

                        <?php if (empty($productos)): ?>
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <h5>Sin resultados</h5>
                                <p>No se encontraron referencias con los filtros seleccionados.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-modern align-middle table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Foto</th>
                                            <th>Referencia</th>
                                            <th class="text-center">Categoría</th>
                                            <?php foreach ($tallas as $talla): ?>
                                                <th class="text-center p-2"><?= h($talla) ?></th>
                                            <?php endforeach; ?>
                                            <th class="text-center">Total</th>
                                            <th class="text-center">Detalle</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($productos as $ref => $prod): ?>
                                            <?php
                                            $totalRef = (float)$prod['total_stock'];
                                            $stockClass = 'stock-zero';
                                            if ($totalRef > 0) {
                                                $stockClass = 'stock-positive';
                                            } elseif ($totalRef < 0) {
                                                $stockClass = 'stock-negative';
                                            }
                                            ?>
                                            <tr>
                                                <td class="text-center">
                                                    <div class="product-box mx-auto">
                                                        <?php if ($prod['foto1'] === 'NO APLICA' || $prod['foto1'] === ''): ?>
                                                            <img src="../../../innovasuelas/img/camara.jpg" alt="" style="object-fit: contain; width:100%; height:100%;">
                                                        <?php else: ?>
                                                            <a href="javascript:window.open('../../../innovasuelas/img-producto/<?= h($prod['foto1']) ?>','','width=1200,height=700,left=100,top=10,toolbar=yes');void 0">
                                                                <img src="../../../innovasuelas/img-producto/<?= h($prod['foto1']) ?>" alt="" style="object-fit: contain; width:100%; height:100%;">
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>

                                                <td>
                                                    <div class="ref-main"><?= h($ref) ?></div>
                                                    <div class="ref-sub"><?= h($prod['codigo']) ?> · <?= h($prod['referencia_segmento']) ?></div>
                                                    <div class="d-flex gap-2 flex-wrap mt-1">
                                                        <span class="chip-soft">
                                                            <i class="fas fa-palette"></i>
                                                            <?= h($prod['color']) ?>
                                                            <?php if (!empty($rgbPorColor[$prod['color']])): ?>
                                                                <span class="color-dot" style="background: <?= h($rgbPorColor[$prod['color']]) ?>;"></span>
                                                            <?php endif; ?>
                                                        </span>

                                                        <?php if (!empty($prod['color2']) && strtoupper($prod['color2']) !== 'NO APLICA'): ?>
                                                            <span class="chip-soft">
                                                                <i class="fas fa-palette"></i>
                                                                <?= h($prod['color2']) ?>
                                                                <?php if (!empty($rgbPorColor[$prod['color2']])): ?>
                                                                    <span class="color-dot" style="background: <?= h($rgbPorColor[$prod['color2']]) ?>;"></span>
                                                                <?php endif; ?>
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>

                                                <td class="text-center"><?= h($prod['categoria']) ?></td>

                                                <?php foreach ($tallas as $talla): ?>
                                                    <?php
                                                    $cant = (float)($matrix[$ref][$talla] ?? 0);
                                                    $tdClass = 'qty-neutral';
                                                    if ($cant > 0) {
                                                        $tdClass = 'qty-positive';
                                                    } elseif ($cant < 0) {
                                                        $tdClass = 'qty-negative';
                                                    }
                                                    ?>
                                                    <td class="<?= $tdClass ?>">
                                                        <?= $cant != 0 ? nf0($cant) : '' ?>
                                                    </td>
                                                <?php endforeach; ?>

                                                <td class="text-center">
                                                    <span class="<?= $stockClass ?>"><?= nf0($totalRef) ?></span>
                                                </td>

                                                <td class="text-center">
                                                    <a class="btn-detail" href="../producto/kardex.php?referencia=<?= urlencode($ref) ?>" target="_blank">
                                                        <i class="fas fa-file-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>

                                    <tfoot>
                                        <tr>
                                            <th colspan="3" class="text-end">Total página</th>
                                            <?php foreach ($tallas as $talla): ?>
                                                <?php
                                                $cant = (float)($totalesPorTallaPagina[$talla] ?? 0);
                                                $class = 'qty-neutral';
                                                if ($cant > 0) {
                                                    $class = 'qty-positive';
                                                } elseif ($cant < 0) {
                                                    $class = 'qty-negative';
                                                }
                                                ?>
                                                <th class="<?= $class ?>"><?= $cant != 0 ? nf0($cant) : '' ?></th>
                                            <?php endforeach; ?>
                                            <th class="text-center <?= $totalPaginaUnidades > 0 ? 'stock-positive' : ($totalPaginaUnidades < 0 ? 'stock-negative' : 'stock-zero') ?>">
                                                <?= nf0($totalPaginaUnidades) ?>
                                            </th>
                                            <th></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($totalPaginas > 1): ?>
                    <div class="d-flex justify-content-end mt-3 d-print-none">
                        <nav aria-label="Paginación inventario">
                            <ul class="pagination mb-0 flex-wrap">
                                <li class="page-item <?= $pagina <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="inventario.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => max(1, $pagina - 1)])) ?>">«</a>
                                </li>

                                <?php
                                $inicio = max(1, $pagina - 2);
                                $fin = min($totalPaginas, $pagina + 2);

                                if ($inicio > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="inventario.php?' . buildQueryParams(array_merge($queryBase, ['pagina' => 1])) . '">1</a></li>';
                                    if ($inicio > 2) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                }

                                for ($i = $inicio; $i <= $fin; $i++):
                                ?>
                                    <li class="page-item <?= $pagina == $i ? 'active' : '' ?>">
                                        <a class="page-link" href="inventario.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => $i])) ?>">
                                            <?= $i ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>

                                <?php
                                if ($fin < $totalPaginas) {
                                    if ($fin < $totalPaginas - 1) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                    echo '<li class="page-item"><a class="page-link" href="inventario.php?' . buildQueryParams(array_merge($queryBase, ['pagina' => $totalPaginas])) . '">' . $totalPaginas . '</a></li>';
                                }
                                ?>

                                <li class="page-item <?= $pagina >= $totalPaginas ? 'disabled' : '' ?>">
                                    <a class="page-link" href="inventario.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => min($totalPaginas, $pagina + 1)])) ?>">»</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>

            </div>
        </div>

        <?php echo include '../general/footer.php'; ?>
    </div>

    <?php echo include '../general/libreria-js.php'; ?>

    <script>
        $(document).ready(function () {
            $('.single-select').select2({
                theme: 'bootstrap4',
                width: '100%'
            });
        });
    </script>
</body>
</html>