<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
$pdo = getDBConnection();

$q = trim($_GET['q'] ?? '');

try {
    if (strlen($q) < 1) {
        // Return top labs by product count
        $stmt = $pdo->query("SELECT laboratorio, COUNT(*) as total 
            FROM productos WHERE laboratorio IS NOT NULL AND laboratorio != '' 
            GROUP BY laboratorio ORDER BY total DESC LIMIT 30");
    } else {
        $stmt = $pdo->prepare("SELECT laboratorio, COUNT(*) as total 
            FROM productos WHERE laboratorio LIKE ? AND laboratorio IS NOT NULL AND laboratorio != ''
            GROUP BY laboratorio ORDER BY total DESC LIMIT 20");
        $stmt->execute(["%$q%"]);
    }
    
    echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
