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

try {
    session_start();
    require_once '../core/api.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, 
            COALESCE(i_last.total_amount, 0.00) as service_value,
            c.frequency,
            c.start_week,
            c.visit_week
        FROM clients c
        LEFT JOIN (
            -- Subconsulta para encontrar el total_amount de la factura más reciente de cada cliente
            SELECT i1.client_id, i1.total_amount
            FROM invoices i1
            INNER JOIN (
                SELECT client_id, MAX(invoice_date) as max_date
                FROM invoices
                WHERE client_id IS NOT NULL 
                GROUP BY client_id
            ) AS i2
            ON i1.client_id = i2.client_id AND i1.invoice_date = i2.max_date
        ) AS i_last ON c.id = i_last.client_id
        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;
?>