<?php
ob_start();
session_start();
header('Content-Type: application/json');

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

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

$response = ['status' => 'error', 'message' => 'ERROR POR DEFECTO'];

try {
    if (!isset($pdo)) {
        throw new Exception('La variable de conexión $pdo no está definida');
    }

    $userId = $_SESSION['user_id'] ?? 1;
    $clientId = filter_var($_GET['client_id'] ?? null, FILTER_VALIDATE_INT); 

    if (!$clientId) {
        throw new Exception('ID DE CLIENTE NO PROPORCIONADO');
    }

    $clientData = ['client' => null, 'services' => [], 'total_service_value' => 0.00, 'appointments' => [], 'invoices' => []];

    // 2. Consulta Principal (clients)
    $stmt_client = $pdo->prepare("
        SELECT id, first_name, last_name, street_address, city, state_province, zip_code, service_time
        FROM clients WHERE id = ? AND user_id = ?
    ");
    $stmt_client->execute([$clientId, $userId]);
    $client = $stmt_client->fetch(PDO::FETCH_ASSOC);

    if (!$client) {
        throw new Exception('CLIENTE NO ENCONTRADO O NO AUTORIZADO');
    }

    $client['name'] = trim($client['first_name'] . ' ' . $client['last_name']);
    $client['address'] = $client['street_address'];

    $addressParts = array_filter([$client['street_address'], $client['city'], $client['state_province'], $client['zip_code']]);
    $client['full_address'] = empty($addressParts) ? 'SIN DIRECCIÓN REGISTRADA' : implode(', ', $addressParts);
    
    $clientData['client'] = $client;

    // 3. Servicios Asignados (client_services)
    $stmt_services = $pdo->prepare("
        SELECT s.name, s.price FROM client_services cs 
        JOIN services s ON cs.service_id = s.id
        JOIN clients c ON cs.client_id = c.id
        WHERE cs.client_id = ? AND c.user_id = ? ORDER BY s.name ASC
    ");
    $stmt_services->execute([$clientId, $userId]);
    $serviceResults = $stmt_services->fetchAll(PDO::FETCH_ASSOC);

    $totalServiceValue = 0.00;
    $serviceNames = [];
    foreach ($serviceResults as $service) {
        $serviceNames[] = $service['name'];
        $totalServiceValue += (float)$service['price'];
    }
    $clientData['services'] = $serviceNames;
    $clientData['total_service_value'] = number_format($totalServiceValue, 2, '.', '');

    // 4. Citas Recientes (unique_appointments)
    $thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
    $stmt_appts = $pdo->prepare("
        SELECT ua.appointment_date, ua.appointment_time, ua.status FROM unique_appointments ua
        WHERE ua.client_id = ? AND ua.appointment_date >= ? ORDER BY ua.appointment_date DESC, ua.appointment_time DESC LIMIT 5
    ");
    // Se elimina la sub-condición c.user_id = ? ya que el client_id ya está validado contra user_id en la consulta principal.
    $stmt_appts->execute([$clientId, $thirtyDaysAgo]);
    $clientData['appointments'] = $stmt_appts->fetchAll(PDO::FETCH_ASSOC);

    // 5. Facturas Pendientes (invoices)
    $stmt_invoices = $pdo->prepare("
        SELECT external_id, invoice_date, total_amount, status FROM invoices
        WHERE client_id = ? AND user_id = ? AND status IN ('enviada') ORDER BY invoice_date DESC LIMIT 5
    ");
    // Se elimina el join a clients c, ya que la tabla invoices contiene user_id
    $stmt_invoices->execute([$clientId, $userId]);
    $clientData['invoices'] = $stmt_invoices->fetchAll(PDO::FETCH_ASSOC);

    $response = array_merge(['status' => 'success'], $clientData);

} catch (PDOException $e) {
    error_log("Error PDO en client-route-details-read.php: " . $e->getMessage());
    $response = ['status' => 'error', 'message' => 'ERROR DE BASE DE DATOS: ' . $e->getMessage()];
} catch (Exception $e) {
     error_log("Error en client-route-details-read.php: " . $e->getMessage());
     $response = ['status' => 'error', 'message' => $e->getMessage()];
}

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

echo json_encode($response);
exit;