<?php
ob_start();
session_start();

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

try { if(isset($pdo)) $pdo->exec("set names utf8mb4"); } catch(Exception $e) {}

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

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

try {
    $term = "%" . trim($q) . "%";

    $sql = "
        (SELECT id, first_name, last_name, phone, email, street_address, 'Cliente' as type
         FROM clients 
         WHERE user_id = :uid1 
         AND (first_name LIKE :term1 OR last_name LIKE :term2 OR phone LIKE :term3 OR email LIKE :term4))
        UNION ALL
        (SELECT id, first_name, last_name, phone, email, street_address, 'Prospecto' as type
         FROM leads 
         WHERE user_id = :uid2 
         AND (first_name LIKE :term5 OR last_name LIKE :term6 OR phone LIKE :term7 OR email LIKE :term8))
        LIMIT 15
    ";
    
    $stmt = $pdo->prepare($sql);
    $params = [
        ':uid1' => $user_id, ':term1' => $term, ':term2' => $term, ':term3' => $term, ':term4' => $term,
        ':uid2' => $user_id, ':term5' => $term, ':term6' => $term, ':term7' => $term, ':term8' => $term
    ];
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $final_results = [];
    foreach ($results as $row) {
        if ($row['type'] === 'Prospecto') {
            $row['last_name'] = ($row['last_name'] ?? '') . ' (Lead)';
        }
        $final_results[] = $row;
    }
    
    echo json_encode($final_results);

} catch (Exception $e) {
    error_log("Error en client-search.php: " . $e->getMessage());
    echo json_encode([]);
}