<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php'; 

$user_id = $_SESSION['user_id'] ?? 1;
$id = $_GET['id'] ?? null;

if (!$id) { 
    echo json_encode(['error' => 'No ID proporcionado']); 
    exit; 
}

$response = [];

try {
    $sqlProfile = "
        SELECT 
            c.*, 
            CONCAT(s.first_name, ' ', s.last_name) as staff_name, 
            s.profile_photo_url as staff_photo, 
            s.id as staff_id,
            c.route_id as direct_route_id
        FROM clients c 
        LEFT JOIN staff s ON c.staff_id = s.id 
        WHERE c.id = :id
    ";
    
    $stmt = $pdo->prepare($sqlProfile);
    $stmt->execute([':id' => $id]);
    $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$response['profile']) {
         echo json_encode(['error' => 'Cliente no encontrado en la base de datos.']); exit;
    }

    $response['route_info'] = null;
    $routeId = $response['profile']['direct_route_id'] ?? null;
    $staffId = $response['profile']['staff_id'] ?? null;

    if ($routeId) {
        $stmt = $pdo->prepare("SELECT route_name, route_day FROM routes WHERE id = :rid LIMIT 1");
        $stmt->execute([':rid' => $routeId]);
        $response['route_info'] = $stmt->fetch(PDO::FETCH_ASSOC);
    } elseif ($staffId) {
        $stmt = $pdo->prepare("SELECT route_name, route_day FROM routes WHERE staff_id = :sid AND is_active = 1 LIMIT 1");
        $stmt->execute([':sid' => $staffId]);
        $response['route_info'] = $stmt->fetch(PDO::FETCH_ASSOC);
    }

    $stmt = $pdo->prepare("SELECT SUM(total_amount) as total_spent FROM invoices WHERE client_id = :id AND status = 'pagada'");
    $stmt->execute([':id' => $id]);
    $totalSpent = $stmt->fetch(PDO::FETCH_ASSOC)['total_spent'] ?? 0;
    
    $response['financial_summary'] = [
        'total_spent' => number_format((float)$totalSpent, 2, '.', ''),
        'total_invoices' => 0,
    ];

    $stmt = $pdo->prepare("SELECT external_id, total_amount, status, invoice_date FROM invoices WHERE client_id = :id ORDER BY invoice_date DESC");
    $stmt->execute([':id' => $id]);
    $invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $response['invoices'] = $invoices;
    $response['financial_summary']['total_invoices'] = count($invoices);

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

    $stmt = $pdo->prepare("SELECT title, status, created_at FROM complaints WHERE client_id = :id ORDER BY created_at DESC");
    $stmt->execute([':id' => $id]);
    $response['complaints'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

    $stmt = $pdo->prepare("SELECT s.name FROM services s JOIN client_services cs ON s.id = cs.service_id WHERE cs.client_id = :id");
    $stmt->execute([':id' => $id]);
    $response['services'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $stmt = $pdo->prepare("SELECT content, created_at FROM client_notes WHERE client_id = :id ORDER BY created_at DESC");
    $stmt->execute([':id' => $id]);
    $response['notes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT p.name, p.status, p.start_date, p.due_date, s.name as service_name FROM projects p JOIN services s ON p.service_id = s.id WHERE p.client_id = :id ORDER BY p.due_date DESC");
    $stmt->execute([':id' => $id]);
    $response['projects'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($response);

} catch (Exception $e) {
    error_log("Error en get-clients-profile.php: " . $e->getMessage());
    echo json_encode(['error' => 'Ocurri¨® un error al cargar los datos del cliente.']); 
}
?>