<?php
require 'db.php';

// --- 1. Leer parámetros de búsqueda y paginación ---
$search = $_GET['search'] ?? '';
$lab = $_GET['lab'] ?? '';
$page = isset($_GET['page']) && (int)$_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// --- 2. Preparar consulta SQL dinámica ---
$sqlWhere = " WHERE 1=1 ";
$params = [];

if (!empty($search)) {
    // Buscamos en ambas columnas
    $sqlWhere .= " AND (NombreComercial LIKE ? OR CodigoInterno LIKE ?) ";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if (!empty($lab)) {
    $sqlWhere .= " AND laboratorio LIKE ? ";
    $params[] = "%$lab%";
}

// --- 3. Obtener Total (CON FILTROS) ---
$stmt_count = $pdo->prepare("SELECT COUNT(*) FROM productos $sqlWhere");
$stmt_count->execute($params);
$totalProducts = $stmt_count->fetchColumn();
$totalPages = ceil($totalProducts / $perPage);

// --- 4. Obtener Productos (CON FILTROS y Paginación) ---
$sqlOrderLimit = " ORDER BY NombreComercial LIMIT $perPage OFFSET $offset";
$stmt_prod = $pdo->prepare("SELECT id, CodigoInterno, NombreComercial, laboratorio, id_categoria FROM productos $sqlWhere $sqlOrderLimit");
$stmt_prod->execute($params);
$products = $stmt_prod->fetchAll();

// --- 5. Obtener Categorías (para los dropdowns) ---
$stmt_cat = $pdo->query("SELECT id, nombre FROM categorias ORDER BY nombre");
$categories = $stmt_cat->fetchAll();

// --- 6. Calcular info de paginación ---
$firstItem = ($totalProducts > 0) ? ($page - 1) * $perPage + 1 : 0;
$lastItem = min($page * $perPage, $totalProducts);

// Para los enlaces de paginación, mantenemos los filtros
$queryString = http_build_query(['search' => $search, 'lab' => $lab]);

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestor de Inventario</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style> /* (Estilos del loader/spinner - sin cambios) */
        .loader {
            width: 1.25rem; height: 1.25rem; border: 2px solid #f3f3f3;
            border-top: 2px solid #3b82f6; border-radius: 50%;
            animation: spin 1s linear infinite; display: inline-block; margin-left: 0.5rem;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 font-sans">
    <main class="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <header class="flex items-center space-x-4 mb-8">
            <div class="p-3 bg-blue-100 dark:bg-blue-900/50 rounded-lg">
                <svg class="w-8 h-8 text-blue-600 dark:text-blue-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                </svg>
            </div>
            <h1 class="text-3xl sm:text-4xl font-bold text-gray-900 dark:text-white tracking-tight">
                Gestor de Inventario de Productos
            </h1>
        </header>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <div class="mb-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="w-5 h-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                    </div>
                    <input
                      type="text"
                      id="search-input"
                      name="search"
                      placeholder="Buscar por código o nombre..."
                      value="<?php echo htmlspecialchars($search); ?>"
                      class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                    />
                </div>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="w-5 h-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L16 11.414V16a1 1 0 01-.293.707l-2 2A1 1 0 0113 18v-6.586l-3.707-3.707A1 1 0 019 7V4z" /></svg>
                    </div>
                    <input
                      type="text"
                      id="lab-filter-input"
                      name="lab"
                      placeholder="Filtrar por laboratorio..."
                      value="<?php echo htmlspecialchars($lab); ?>"
                      class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                    />
                </div>
            </div>

            <div class="overflow-x-auto" id="product-table-container">
                <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                    <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
                        <tr>
                            <th scope="col" class="px-6 py-3">Código Interno</th>
                            <th scope="col" class="px-6 py-3">Nombre del Producto</th>
                            <th scope="col" class="px-6 py-3">Laboratorio</th>
                            <th scope="col" class="px-6 py-3">Categoría</th>
                            <th scope="col" class="px-6 py-3"></th>
                        </tr>
                    </thead>
                    <tbody id="product-table-body">
                        <?php if (count($products) > 0): ?>
                            <?php foreach ($products as $product): ?>
                            <tr class="product-row bg-white dark:bg-gray-800 border-b dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">
                                <td class="px-6 py-4 font-mono text-gray-600 dark:text-gray-300"><?php echo htmlspecialchars($product['CodigoInterno']); ?></td>
                                <th scope="row" class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap"><?php echo htmlspecialchars($product['NombreComercial']); ?></th>
                                <td class="px-6 py-4"><?php echo htmlspecialchars($product['laboratorio']); ?></td>
                                <td class="px-6 py-4">
                                    <select class="category-select w-full p-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-50 dark:bg-gray-700 focus:ring-blue-500 focus:border-blue-500 text-sm" data-product-id="<?php echo $product['id']; ?>">
                                        <option value="0" <?php echo ($product['id_categoria'] == NULL) ? 'selected' : ''; ?>>Seleccionar categoría...</option>
                                        <?php foreach ($categories as $category): ?>
                                            <option value="<?php echo $category['id']; ?>" <?php echo ($product['id_categoria'] == $category['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($category['nombre']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td class="px-6 py-4 saving-indicator" style="width: 50px;"></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr id="no-results-row" class="bg-white dark:bg-gray-800">
                                <td colspan="5" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                                    No se encontraron productos que coincidan con su búsqueda.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div id="pagination-container">
                <?php if ($totalPages > 1): ?>
                <div class="flex items-center justify-between mt-6 px-4 py-3 sm:px-6">
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-gray-700 dark:text-gray-400">
                                Mostrando <span class="font-medium"><?php echo $firstItem; ?></span> a <span class="font-medium"><?php echo $lastItem; ?></span> de <span class="font-medium"><?php echo $totalProducts; ?></span> resultados
                            </p>
                        </div>
                        <div>
                            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                <a href="?page=<?php echo $page - 1; ?>&<?php echo $queryString; ?>" class="pagination-link relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 <?php echo ($page <= 1) ? 'opacity-50 cursor-not-allowed' : ''; ?>">
                                    <span class="sr-only">Anterior</span>
                                    <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" /></svg>
                                </a>
                                <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-700 dark:text-gray-300">
                                  Página <?php echo $page; ?> de <?php echo $totalPages; ?>
                                </span>
                                <a href="?page=<?php echo $page + 1; ?>&<?php echo $queryString; ?>" class="pagination-link relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 <?php echo ($page >= $totalPages) ? 'opacity-50 cursor-not-allowed' : ''; ?>">
                                    <span class="sr-only">Siguiente</span>
                                    <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" /></svg>
                                </a>
                            </nav>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
    <script src="js/main.js"></script>
</body>
</html>