<?php

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php'; 

$user_id = $_SESSION['user_id'] ?? 1;
$q = $_GET['q'] ?? '';

if (strlen($q) < 2) { echo json_encode([]); exit; }

$term = "%" . $q . "%";

// Buscamos SOLO en Clientes
$sql = "
    SELECT 
        id, 
        first_name, 
        last_name, 
        company, 
        email, 
        'client' as type 
    FROM clients 
    WHERE user_id = :uid1 AND (
        first_name LIKE :t1 OR 
        last_name LIKE :t2 OR 
        company LIKE :t3
    )
    LIMIT 20";

$stmt = $pdo->prepare($sql);
$stmt->execute([':uid1'=>$user_id, ':t1'=>$term, ':t2'=>$term, ':t3'=>$term]);

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Aseguramos que la columna 'type' se envíe como 'client' para el frontend
$finalResponse = array_map(function($row) {
    $row['type'] = 'client';
    return $row;
}, $results);

echo json_encode($finalResponse);
?>