<?php
/**
 * BACKEND FINAL: Fechas en Español + Nombres Reales
 */
header('Content-Type: application/json; charset=utf-8');

// CORRECCIÓN ÚNICA: Iniciar sesión si no está activa para evitar Error 401
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// MANTENEMOS TU ESTRUCTURA ORIGINAL
require_once __DIR__ . '/../core/api.php'; 

// Aseguramos que los formateadores estén disponibles
if (!function_exists('formatLongDate')) {
    $formattersPath = __DIR__ . '/../core/formatters.php';
    if (file_exists($formattersPath)) require_once $formattersPath;
}

$user_id = $_SESSION['user_id'] ?? 1;
$period_id = $_GET['id'] ?? date('Y-m'); 

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

try {
    // Configuración de Fechas
    $startDate = $period_id . '-01';
    $endDate = date('Y-m-t', strtotime($startDate)); 
    
    $startFull = $startDate . ' 00:00:00';
    $endFull = $endDate . ' 23:59:59';

    // 1. GENERACIÓN DE FECHAS EN ESPAÑOL
    $meses = [
        1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', 5 => 'Mayo', 6 => 'Junio',
        7 => 'Julio', 8 => 'Agosto', 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
    ];
    $mesNumero = (int)date('n', strtotime($startDate));
    $anio = date('Y', strtotime($startDate));
    $tituloMes = mb_strtoupper($meses[$mesNumero] . ' ' . $anio); 

    if (function_exists('formatLongDate')) {
        $rangoTexto = formatLongDate($startDate) . ' al ' . formatLongDate($endDate);
    } else {
        $rangoTexto = "$startDate al $endDate"; 
    }
    $rangoTexto = ucwords($rangoTexto);

    $isCurrentMonth = (date('Y-m') === $period_id);
    $daysLeftText = $isCurrentMonth 
        ? "Reporte En curso (Faltan " . ((int)date('t') - (int)date('d')) . " días)" 
        : "Periodo Finalizado";

    // --- 2. LEADS ---
    $sqlLeads = "SELECT first_name, last_name, company, source, created_at, status FROM leads WHERE created_at BETWEEN :start AND :end ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sqlLeads);
    $stmt->execute([':start' => $startFull, ':end' => $endFull]);
    $leadsList = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $sourcesData = [];
    foreach($leadsList as $lead) {
        $src = $lead['source'] ?: 'Desconocido';
        if(!isset($sourcesData[$src])) $sourcesData[$src] = 0;
        $sourcesData[$src]++;
    }
    arsort($sourcesData);

    // --- 3. CLIENTES ---
    $sqlClients = "SELECT first_name, last_name, company, created_at FROM clients WHERE created_at BETWEEN :start AND :end ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sqlClients);
    $stmt->execute([':start' => $startFull, ':end' => $endFull]);
    $clientsList = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $leadsCount = count($leadsList);
    $clientsCount = count($clientsList);
    $conversionRate = ($leadsCount > 0) ? round(($clientsCount / $leadsCount) * 100, 1) : 0;

    // --- 4. CITAS ---
    $sqlAppt = "
        SELECT ua.appointment_date, ua.appointment_time, ua.status,
               COALESCE(NULLIF(c.first_name, ''), NULLIF(l.first_name, '')) as first_name,
               COALESCE(NULLIF(c.last_name, ''), NULLIF(l.last_name, '')) as last_name,
               COALESCE(NULLIF(c.company, ''), NULLIF(l.company, '')) as company
        FROM unique_appointments ua
        LEFT JOIN clients c ON ua.client_id = c.id
        LEFT JOIN leads l ON ua.lead_id = l.id
        WHERE ua.appointment_date BETWEEN :start AND :end 
        AND ua.recurring_parent_id IS NULL
        ORDER BY ua.appointment_date DESC
    ";
    $stmt = $pdo->prepare($sqlAppt);
    $stmt->execute([':start' => $startDate, ':end' => $endDate]);
    $appointmentsList = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // --- 5. COTIZACIONES ---
    $sqlEst = "
        SELECT e.external_id, e.total_amount, e.status, e.estimate_date,
               COALESCE(NULLIF(c.first_name, ''), NULLIF(l.first_name, '')) as first_name,
               COALESCE(NULLIF(c.last_name, ''), NULLIF(l.last_name, '')) as last_name
        FROM quotes e
        LEFT JOIN clients c ON e.client_id = c.id
        LEFT JOIN leads l ON e.lead_id = l.id
        WHERE e.estimate_date BETWEEN :start AND :end
        ORDER BY e.estimate_date DESC
    ";
    $stmt = $pdo->prepare($sqlEst);
    $stmt->execute([':start' => $startDate, ':end' => $endDate]);
    $estimatesList = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // --- 6. GRÁFICAS ---
    $daysInMonth = (int)date('t', strtotime($startDate));
    $chartLabels = [];
    $chartLeads = array_fill(0, $daysInMonth, 0);
    $chartAppts = array_fill(0, $daysInMonth, 0);

    for($i = 1; $i <= $daysInMonth; $i++) {
        $chartLabels[] = $i; 
    }

    foreach($leadsList as $l) {
        $d = (int)date('d', strtotime($l['created_at']));
        if($d <= $daysInMonth) $chartLeads[$d-1]++;
    }
    foreach($appointmentsList as $a) {
        $d = (int)date('d', strtotime($a['appointment_date']));
        if($d <= $daysInMonth) $chartAppts[$d-1]++;
    }

    $response = [
        'period_info' => [
            'id' => $period_id,
            'label' => $tituloMes,
            'range' => $rangoTexto,
            'status_text' => $daysLeftText,
            'is_active' => $isCurrentMonth
        ],
        'metrics' => [
            'leads' => $leadsCount,
            'clients' => $clientsCount,
            'conversion' => $conversionRate
        ],
        'leads_list' => array_slice($leadsList, 0, 100),
        'clients_list' => array_slice($clientsList, 0, 50),
        'appointments_list' => $appointmentsList,
        'estimates_list' => $estimatesList,
        'chart_data' => [
            'labels' => $chartLabels,
            'leads' => $chartLeads,
            'appointments' => $chartAppts,
            'sources' => $sourcesData
        ]
    ];

    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Error: ' . $e->getMessage()]);
}
?>