<?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'] ?? '');
$clase     = trim($_GET['clase'] ?? '');
$color     = trim($_GET['color'] ?? '');
$stock     = trim($_GET['stock'] ?? '');
$orden     = trim($_GET['orden'] ?? 'referencia_asc');

$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$registro_por_pagina = 20;
$start_from = ($pagina - 1) * $registro_por_pagina;

$where = [];
$where[] = "1=1";

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

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

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

if ($color !== '') {
    $color_sql = $conn->real_escape_string($color);
    $where[] = "(p.color = '$color_sql' OR p.color2 = '$color_sql')";
}

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',
    'precio_desc'     => 'p.alm_precio_unidad DESC, p.referencia ASC',
    'precio_asc'      => 'p.alm_precio_unidad 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',
];

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

$fromSql = "
    FROM producto p
    LEFT JOIN (
        SELECT referencia_producto, SUM(cantidad) AS total_stock
        FROM alm_referencia_disponible
        GROUP BY referencia_producto
    ) s ON s.referencia_producto = p.referencia
    LEFT JOIN color c1 ON c1.color = p.color
    LEFT JOIN color c2 ON c2.color = p.color2
";

/*
|--------------------------------------------------------------------------
| Opciones de 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'];
    }
}

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

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

/*
|--------------------------------------------------------------------------
| Resumen
|--------------------------------------------------------------------------
*/
$stats = [
    'total_productos' => 0,
    'con_stock'       => 0,
    'sin_stock'       => 0,
    'stock_negativo'  => 0,
    'unidades_totales'=> 0,
    'precio_promedio' => 0,
];

$sqlStats = "
    SELECT
        COUNT(*) AS total_productos,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) > 0 THEN 1 ELSE 0 END) AS con_stock,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) = 0 THEN 1 ELSE 0 END) AS sin_stock,
        SUM(CASE WHEN COALESCE(s.total_stock, 0) < 0 THEN 1 ELSE 0 END) AS stock_negativo,
        COALESCE(SUM(COALESCE(s.total_stock, 0)), 0) AS unidades_totales,
        COALESCE(AVG(p.alm_precio_unidad), 0) AS precio_promedio
    $fromSql
    WHERE $whereSql
";
$queryStats = $conn->query($sqlStats);
if ($queryStats && $queryStats->num_rows > 0) {
    $rowStats = $queryStats->fetch_assoc();
    $stats['total_productos']  = (int)($rowStats['total_productos'] ?? 0);
    $stats['con_stock']        = (int)($rowStats['con_stock'] ?? 0);
    $stats['sin_stock']        = (int)($rowStats['sin_stock'] ?? 0);
    $stats['stock_negativo']   = (int)($rowStats['stock_negativo'] ?? 0);
    $stats['unidades_totales'] = (float)($rowStats['unidades_totales'] ?? 0);
    $stats['precio_promedio']  = (float)($rowStats['precio_promedio'] ?? 0);
}

$total_pages = max(1, (int)ceil($stats['total_productos'] / $registro_por_pagina));
if ($pagina > $total_pages) {
    $pagina = $total_pages;
    $start_from = ($pagina - 1) * $registro_por_pagina;
}

/*
|--------------------------------------------------------------------------
| Lista paginada
|--------------------------------------------------------------------------
*/
$productos = [];
$sqlProductos = "
    SELECT
        p.*,
        COALESCE(s.total_stock, 0) AS total_stock,
        c1.rgb AS rgb_color1,
        c2.rgb AS rgb_color2
    $fromSql
    WHERE $whereSql
    ORDER BY $orderSql
    LIMIT $start_from, $registro_por_pagina
";
$queryProductos = $conn->query($sqlProductos);
if ($queryProductos && $queryProductos->num_rows > 0) {
    while ($row = $queryProductos->fetch_assoc()) {
        $productos[] = $row;
    }
}

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

$desdeRegistro = $stats['total_productos'] > 0 ? ($start_from + 1) : 0;
$hastaRegistro = min($start_from + $registro_por_pagina, $stats['total_productos']);
?>
<!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;
            gap: .5rem;
            flex-wrap: wrap;
            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: .7rem 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: .8rem .65rem;
        }

        .table-modern tbody td {
            padding: .82rem .65rem;
            vertical-align: middle;
            border-color: #eef2f7;
        }

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

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

        .product-name {
            font-weight: 800;
            color: #111827;
            margin-bottom: .15rem;
        }

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

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

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

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

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

        .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;
        }

        .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">Productos</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Productos</div>
                        <p class="page-subtitle">
                            Catálogo general con filtros útiles para buscar por referencia, categoría, clase, color y estado del stock.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-box"></i>
                                Resultados: <?= nf0($stats['total_productos']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-check-circle"></i>
                                Con stock: <?= nf0($stats['con_stock']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-minus-circle"></i>
                                Sin stock: <?= nf0($stats['sin_stock']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-triangle-exclamation"></i>
                                Stock negativo: <?= nf0($stats['stock_negativo']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="card filter-card mb-3 d-print-none">
                    <div class="card-body">
                        <form method="GET" action="producto.php">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-3">
                                    <label class="label-soft">Buscar</label>
                                    <input type="text" class="form-control" name="q" value="<?= h($q) ?>" placeholder="Código, referencia, segmento o color">
                                </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">Clase</label>
                                    <select class="single-select form-control" name="clase">
                                        <option value="">Todas</option>
                                        <?php foreach ($clases as $item): ?>
                                            <option value="<?= h($item) ?>" <?= $clase === $item ? 'selected' : '' ?>>
                                                <?= h($item) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

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

                                <div class="col-md-1">
                                    <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="precio_desc" <?= $orden === 'precio_desc' ? 'selected' : '' ?>>Precio mayor</option>
                                        <option value="precio_asc" <?= $orden === 'precio_asc' ? 'selected' : '' ?>>Precio menor</option>
                                        <option value="stock_desc" <?= $orden === 'stock_desc' ? 'selected' : '' ?>>Stock mayor</option>
                                        <option value="stock_asc" <?= $orden === 'stock_asc' ? 'selected' : '' ?>>Stock menor</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="producto.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-box"></i></div>
                                <div class="stats-title">Productos filtrados</div>
                                <div class="stats-value"><?= nf0($stats['total_productos']) ?></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-warehouse"></i></div>
                                <div class="stats-title">Unidades totales</div>
                                <div class="stats-value"><?= nf0($stats['unidades_totales']) ?></div>
                                <div class="stats-note">Suma del stock 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-dollar-sign"></i></div>
                                <div class="stats-title">Precio promedio</div>
                                <div class="stats-value">$ <?= nf0($stats['precio_promedio']) ?></div>
                                <div class="stats-note">Promedio del precio unidad</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-layer-group"></i></div>
                                <div class="stats-title">Mostrando</div>
                                <div class="stats-value"><?= nf0($desdeRegistro) ?> - <?= nf0($hastaRegistro) ?></div>
                                <div class="stats-note">de <?= nf0($stats['total_productos']) ?> registros</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card list-card">
                    <div class="card-body">
                        <div class="section-head">
                            <div>
                                <div class="section-title">Lista de productos</div>
                                <p class="section-subtitle">
                                    Vista paginada y filtrada del catálogo.
                                </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 productos 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 class="text-center">Segmento</th>
                                            <th class="text-center">Cod</th>
                                            <th>Referencia</th>
                                            <th>Color</th>
                                            <th>Color 2</th>
                                            <th>Bicolor</th>
                                            <th class="text-center">Categoría</th>
                                            <th class="text-center">Clase</th>
                                            <th class="text-end">Peso</th>
                                            <th class="text-end">Precio unidad</th>
                                            <th class="text-center">Cant.</th>
                                            <th class="text-center">Detalle</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($productos as $row): ?>
                                            <?php
                                            $stockClass = 'stock-zero';
                                            if ((float)$row['total_stock'] > 0) {
                                                $stockClass = 'stock-positive';
                                            } elseif ((float)$row['total_stock'] < 0) {
                                                $stockClass = 'stock-negative';
                                            }
                                            ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center gap-3">
                                                        <div class="product-box">
                                                            <?php if ($row['foto1'] === 'NO APLICA' || $row['foto1'] === ''): ?>
                                                                <img src="../../img/camara.jpg" alt="" style="object-fit: contain; width:100%; height:100%;">
                                                            <?php else: ?>
                                                                <img src="../../../innovasuelas/img-producto/<?= h($row['foto1']) ?>" alt="" style="object-fit: contain; width:100%; height:100%;">
                                                            <?php endif; ?>
                                                        </div>
                                                        <div>
                                                            <div class="product-name"><?= h($row['referencia']) ?></div>
                                                            <div class="product-sub"><?= h($row['codigo']) ?> · <?= h($row['referencia_segmento']) ?></div>
                                                        </div>
                                                    </div>
                                                </td>

                                                <td class="text-center"><?= h($row['referencia_segmento']) ?></td>
                                                <td class="text-center"><strong><?= h($row['codigo']) ?></strong></td>
                                                <td><?= h($row['referencia']) ?></td>

                                                <td>
                                                    <?= h($row['color']) ?>
                                                    <?php if (!empty($row['rgb_color1'])): ?>
                                                        <span class="color-dot" style="background: <?= h($row['rgb_color1']) ?>;"></span>
                                                    <?php endif; ?>
                                                </td>

                                                <td>
                                                    <?= h($row['color2']) ?>
                                                    <?php if (!empty($row['rgb_color2'])): ?>
                                                        <span class="color-dot" style="background: <?= h($row['rgb_color2']) ?>;"></span>
                                                    <?php endif; ?>
                                                </td>

                                                <td><?= h($row['bicolor']) ?></td>
                                                <td class="text-center">
                                                    <span class="chip-soft"><?= h($row['categoria']) ?></span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="chip-soft"><?= h($row['clase']) ?></span>
                                                </td>
                                                <td class="text-end"><?= h($row['peso']) ?> g</td>
                                                <td class="text-end">$ <?= nf0($row['alm_precio_unidad']) ?></td>
                                                <td class="text-center">
                                                    <span class="<?= $stockClass ?>"><?= nf0($row['total_stock']) ?></span>
                                                </td>
                                                <td class="text-center">
                                                    <a class="btn-detail" href="kardex.php?referencia=<?= urlencode($row['referencia']) ?>">
                                                        <i class="fas fa-file-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

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

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

                                if ($inicio > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="producto.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="producto.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => $i])) ?>">
                                            <?= $i ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>

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

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

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

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

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