<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'data' => []];

try {
    require_once __DIR__ . '/../core/api.php';
    global $pdo;

    if (isset($_GET['term'])) {
        $term = trim($_GET['term']);
        
        if (strlen($term) < 2) {
             $response['message'] = 'Término muy corto';
             echo json_encode($response);
             exit;
        }

        $sql = "SELECT id, first_name, last_name 
                FROM clients 
                WHERE (first_name LIKE :term1 OR last_name LIKE :term2 OR CONCAT_WS(' ', first_name, last_name) LIKE :term3) 
                LIMIT 10";
                
        $stmt = $pdo->prepare($sql);
        
        $like_term = '%' . $term . '%';
        $stmt->execute([
            ':term1' => $like_term,
            ':term2' => $like_term,
            ':term3' => $like_term
        ]);
        
        $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $response['success'] = true;
        $response['data'] = $clients;

    } else {
        $response['message'] = 'Término no proporcionado';
    }

} catch (PDOException $e) {
    $response['message'] = 'Error de base de datos: ' . $e->getMessage();
    error_log("Error PDO en complaints-search-clients.php: " . $e->getMessage());
} catch (Exception $e) {
    $response['message'] = 'Error crítico: ' . $e->getMessage();
    error_log("Error general en complaints-search-clients.php: " . $e->getMessage());
}

if (ob_get_level() > 0) {
    ob_end_clean(); 
}

echo json_encode($response);
exit;