<?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 
            l.*, 
            u.full_name as owner_name,
            u.profile_photo_url as owner_photo
        FROM leads l 
        LEFT JOIN users u ON l.user_id = u.user_id 
        WHERE l.id = :id
    ";
    
    $stmt = $pdo->prepare($sqlProfile);
    $stmt->execute([':id' => $id]);
    $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$response['profile']) {
         echo json_encode(['error' => 'Lead no encontrado.']); exit;
    }

    $response['lead_info'] = [
        'source' => $response['profile']['source'],
        'priority' => $response['profile']['priority'],
        'status' => $response['profile']['status'],
        'lost_reason' => $response['profile']['lost_reason']
    ];

    // COTIZACIONES (QUOTES - Corregido de 'estimates' y eliminada 'status_seguimiento')
    $stmt = $pdo->prepare("SELECT external_id, total_amount, status, estimate_date FROM quotes WHERE lead_id = :id ORDER BY estimate_date DESC");
    $stmt->execute([':id' => $id]);
    $response['estimates'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    $stmt = $pdo->prepare("
        SELECT DISTINCT s.name 
        FROM services s 
        JOIN unique_appointments ua ON s.id = ua.service_id 
        WHERE ua.lead_id = :id
    ");
    $stmt->execute([':id' => $id]);
    $response['services_interest'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $stmt = $pdo->prepare("SELECT content, created_at FROM lead_notes WHERE lead_id = :id ORDER BY created_at DESC");
    $stmt->execute([':id' => $id]);
    $response['notes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    $response['invoices'] = []; 
    $response['projects'] = [];
    $response['financial_summary'] = [
        'total_spent' => 0.00,
        'total_invoices' => 0
    ];

    echo json_encode($response);

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