<?php
ob_start();
session_start();
header('Content-Type: application/json');
$response = ['status' => 'error', 'message' => 'ERROR POR DEFECTO'];

try {
    require_once('../files/guardiankey.php');
    require_once('db_connection.php');
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $userId = $_SESSION['user_id'] ?? null;
    $clientId = $_GET['client_id'] ?? null;

    if (empty($userId) || empty($clientId)) {
        throw new Exception('ERROR DE SESIÓN O ID DE CLIENTE NO PROPORCIONADO');
    }

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

    $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');
    }

    $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;

    $stmt_services = $pdo->prepare("
        SELECT s.name, s.price FROM client_services cs JOIN services s ON cs.service_id = s.id
        WHERE cs.client_id = ? ORDER BY s.name ASC
    ");
    $stmt_services->execute([$clientId]);
    $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, '.', '');

    $thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
    $stmt_appts = $pdo->prepare("
        SELECT appointment_date, appointment_time, status FROM unique_appointments
        WHERE client_id = ? AND appointment_date >= ? ORDER BY appointment_date DESC, appointment_time DESC LIMIT 5
    ");
    $stmt_appts->execute([$clientId, $thirtyDaysAgo]);
    $clientData['appointments'] = $stmt_appts->fetchAll(PDO::FETCH_ASSOC);

    $stmt_invoices = $pdo->prepare("
        SELECT external_id, invoice_date, total_amount, status FROM invoices
        WHERE client_id = ? AND status IN ('enviada') ORDER BY invoice_date DESC LIMIT 5
    ");
    $stmt_invoices->execute([$clientId]);
    $clientData['invoices'] = $stmt_invoices->fetchAll(PDO::FETCH_ASSOC);

    $response = ['status' => 'success', 'data' => $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'];
} catch (Exception $e) {
     error_log("Error en client-route-details-read.php: " . $e->getMessage());
     $response = ['status' => 'error', 'message' => $e->getMessage()];
}

ob_end_clean();
echo json_encode($response);
exit;
?>