<?php
ob_start();
require_once __DIR__ . '/../core/api.php';

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

header('Content-Type: application/json');

$response = ['success' => false, 'message' => 'Error desconocido'];

try {
    if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
        throw new Exception('ID de cliente inválido.');
    }
    $client_id = (int)$_GET['id'];

    $stmt = $pdo->prepare("
        SELECT 
            c.*,
            (SELECT GROUP_CONCAT(s.name SEPARATOR ', ') 
             FROM client_services cs 
             JOIN services s ON cs.service_id = s.id 
             WHERE cs.client_id = c.id) as services_list
        FROM clients c
        WHERE c.id = :id 
        LIMIT 1
    ");
    $stmt->execute([':id' => $client_id]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$client) {
        throw new Exception('Cliente no encontrado en la base de datos.');
    }

    $stmt_inv = $pdo->prepare("
        SELECT id, external_id, invoice_date, status, total_amount, due_date 
        FROM invoices 
        WHERE client_id = :id 
        ORDER BY invoice_date DESC 
        LIMIT 10
    ");
    $stmt_inv->execute([':id' => $client_id]);
    $invoices = $stmt_inv->fetchAll(PDO::FETCH_ASSOC);

    $stmt_appt = $pdo->prepare("
        SELECT id, appointment_date, appointment_time, status, notes 
        FROM unique_appointments 
        WHERE client_id = :id 
        ORDER BY appointment_date DESC 
        LIMIT 5
    ");
    $stmt_appt->execute([':id' => $client_id]);
    $appointments = $stmt_appt->fetchAll(PDO::FETCH_ASSOC);

    $stmt_tasks = $pdo->prepare("
        SELECT id, title, due_date, priority, status, description 
        FROM tasks 
        WHERE client_id = :id AND status != 'completed'
        ORDER BY due_date ASC
    ");
    $stmt_tasks->execute([':id' => $client_id]);
    $tasks = $stmt_tasks->fetchAll(PDO::FETCH_ASSOC);

    $stmt_est = $pdo->prepare("
        SELECT id, external_id, estimate_date, status, total_amount 
        FROM quotes 
        WHERE client_id = :id 
        ORDER BY estimate_date DESC 
        LIMIT 5
    ");
    $stmt_est->execute([':id' => $client_id]);
    $estimates = $stmt_est->fetchAll(PDO::FETCH_ASSOC);

    $response = [
        'success' => true,
        'client' => $client,
        'data' => [
            'invoices' => $invoices,
            'appointments' => $appointments,
            'tasks' => $tasks,
            'estimates' => $estimates
        ]
    ];

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
    error_log("Error en get_client_details.php: " . $e->getMessage());
}

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