<?php
require 'db.php';

// --- 1. Leer parámetros ---
$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 ---
$sqlWhere = " WHERE 1=1 ";
$params = [];
if (!empty($search)) {
    $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. Preparar datos para respuesta ---
$html_table = '';
$html_pagination = '';
$queryString = http_build_query(['search' => $search, 'lab' => $lab]);

// --- 7. Generar HTML para la Tabla ---
if (count($products) > 0) {
    foreach ($products as $product) {
        $html_table .= '<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">';
        $html_table .= '<td class="px-6 py-4 font-mono text-gray-600 dark:text-gray-300">' . htmlspecialchars($product['CodigoInterno']) . '</td>';
        $html_table .= '<th scope="row" class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">' . htmlspecialchars($product['NombreComercial']) . '</th>';
        $html_table .= '<td class="px-6 py-4">' . htmlspecialchars($product['laboratorio']) . '</td>';
        $html_table .= '<td class="px-6 py-4">';
        $html_table .= '<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="' . $product['id'] . '">';
        $html_table .= '<option value="0"' . ($product['id_categoria'] == NULL ? ' selected' : '') . '>Seleccionar categoría...</option>';
        foreach ($categories as $category) {
            $selected = ($product['id_categoria'] == $category['id']) ? ' selected' : '';
            $html_table .= '<option value="' . $category['id'] . '"' . $selected . '>' . htmlspecialchars($category['nombre']) . '</option>';
        }
        $html_table .= '</select>';
        $html_table .= '</td>';
        $html_table .= '<td class="px-6 py-4 saving-indicator" style="width: 50px;"></td>';
        $html_table .= '</tr>';
    }
} else {
    $html_table .= '<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>';
}

// --- 8. Generar HTML para la Paginación ---
if ($totalPages > 1) {
    $firstItem = ($page - 1) * $perPage + 1;
    $lastItem = min($page * $perPage, $totalProducts);
    
    $prevDisabled = ($page <= 1) ? 'opacity-50 cursor-not-allowed' : '';
    $nextDisabled = ($page >= $totalPages) ? 'opacity-50 cursor-not-allowed' : '';
    
    $prevLink = '?page=' . ($page - 1) . '&' . $queryString;
    $nextLink = '?page=' . ($page + 1) . '&' . $queryString;

    $html_pagination = <<<HTML
    <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">$firstItem</span> a <span class="font-medium">$lastItem</span> de <span class="font-medium">$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="$prevLink" 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 $prevDisabled">
                        <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 $page de $totalPages
                    </span>
                    <a href="$nextLink" 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 $nextDisabled">
                        <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>
HTML;
}

// --- 9. Devolver JSON ---
header('Content-Type: application/json');
echo json_encode([
    'html_table' => $html_table,
    'html_pagination' => $html_pagination
]);
?>