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

try {
    session_start();
    require_once('db_connection.php');
    require_once('../files/guardiankey.php'); 

    $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
    $term = isset($_GET['term']) ? '%' . trim($_GET['term']) . '%' : '%';

    if (!$userId) {
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode([]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT 
            c.id, 
            CONCAT(c.first_name, ' ', c.last_name) as name, 
            c.street_address as address,
            c.service_details as service,
            c.service_time, 
            (
                SELECT i.total_amount 
                FROM invoices i 
                WHERE i.client_id = c.id 
                ORDER BY i.invoice_date DESC 
                LIMIT 1
            ) as service_value,
            c.frequency,
            c.start_week,
            c.visit_week
        FROM clients c
        WHERE c.user_id = ? AND CONCAT(c.first_name, ' ', c.last_name) LIKE ?
        LIMIT 10
    ");
    $stmt->execute([$userId, $term]);
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response = $clients;

} catch (PDOException $e) {
    error_log("Error PDO en routes-search-clients.php: " . $e->getMessage());
    $response = ['error' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    $response = ['error' => 'ERROR CRITICO'];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>