<?php
ob_start(); // Iniciar el búfer de salida al inicio del script
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

// --- Obtener el mes y año seleccionados para el dashboard (desde URL o por defecto el actual) ---
$selected_leads_year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$selected_leads_month = isset($_GET['month']) ? (int)$_GET['month'] : date('n'); // 'n' para mes sin ceros iniciales (1-12)

// Nombres de los meses en español
$month_names_spanish = [
    1 => "ENERO", 2 => "FEBRERO", 3 => "MARZO", 4 => "ABRIL", 5 => "MAYO", 6 => "JUNIO",
    7 => "JULIO", 8 => "AGOSTO", 9 => "SEPTIEMBRE", 10 => "OCTUBRE", 11 => "NOVIEMBRE", 12 => "DICIEMBRE"
];
$current_report_leads_month_name = $month_names_spanish[$selected_leads_month];

// --- Datos DUMMY para Leads (INYECTADOS DIRECTAMENTE AQUÍ) ---
$leads_from_db = [
    [
        'id' => 1,
        'name' => 'Luisa Fernández',
        'email' => 'luisa.f@ejemplo.com',
        'phone' => '5551112233',
        'message' => 'Interesada en el paquete Standard de CRM.', 
        'source' => 'Web',
        'status' => 'New',
        'created_at' => '2024-07-10 09:00:00' // Este mes
    ],
    [
        'id' => 2,
        'name' => 'Roberto Gómez',
        'email' => 'roberto.g@ejemplo.com',
        'phone' => '5554445566',
        'message' => 'Necesita una demo del CRM Profesional.',
        'source' => 'Referencia',
        'status' => 'Contacted',
        'created_at' => '2024-07-05 14:30:00' // Este mes
    ],
    [
        'id' => 3,
        'name' => 'Marta Sánchez',
        'email' => 'marta.s@ejemplo.com',
        'phone' => null, 
        'message' => 'Consulta sobre precios de la versión Avanzada.',
        'source' => 'Web',
        'status' => 'Qualified',
        'created_at' => '2024-06-28 11:00:00' // Mes anterior
    ],
    [
        'id' => 4,
        'name' => 'Diego Torres',
        'email' => 'diego.t@ejemplo.com',
        'phone' => '5557778899',
        'message' => 'Quiere saber si el CRM se integra con otras herramientas.',
        'source' => 'Redes Sociales',
        'status' => 'Converted',
        'created_at' => '2024-06-15 10:15:00' // Mes anterior, convertido
    ],
    [
        'id' => 5,
        'name' => 'Elena Ruíz',
        'email' => 'elena.r@ejemplo.com',
        'phone' => '5550001122',
        'message' => 'No responde a correos, posible lead frío.',
        'source' => 'Google Ads',
        'status' => 'Unqualified',
        'created_at' => '2024-05-20 16:00:00' // Mes anterior
    ],
    [
        'id' => 6,
        'name' => 'Francisco Solís',
        'email' => 'francisco.s@ejemplo.com',
        'phone' => '5552223344',
        'message' => 'Interesado en una prueba gratuita del CRM.',
        'source' => 'Google Ads',
        'status' => 'New',
        'created_at' => '2024-07-12 10:00:00' // Este mes
    ],
    [
        'id' => 7,
        'name' => 'Gabriela Castro',
        'email' => 'gabriela.c@ejemplo.com',
        'phone' => '5556667788',
        'message' => 'Buscando una solución de CRM para su pequeña empresa.',
        'source' => 'SEO',
        'status' => 'New',
        'created_at' => '2024-07-01 08:30:00' // Este mes
    ],
    [
        'id' => 8,
        'name' => 'Héctor Vargas',
        'email' => 'hector.v@ejemplo.com',
        'phone' => '5559990011',
        'message' => 'Necesita más información sobre el soporte post-venta.',
        'source' => 'Web',
        'status' => 'Converted',
        'created_at' => '2024-05-10 09:45:00' // Mes anterior
    ],
];


// --- Datos DUMMY para Métricas de Leads (por mes seleccionado) ---
$total_leads = count($leads_from_db); // Total de leads en el array dummy

$new_leads_month = 0;
$converted_leads_month = 0;

// Calcular métricas para el mes seleccionado
foreach ($leads_from_db as $lead) {
    $lead_date = new DateTime($lead['created_at']);
    if ((int)$lead_date->format('Y') === $selected_leads_year && (int)$lead_date->format('n') === $selected_leads_month) {
        $new_leads_month++; // Contamos los nuevos leads creados en ese mes

        // Contar leads por estado para el mes seleccionado
        if ($lead['status'] === 'Converted') {
            $converted_leads_month++;
        }
    }
}

// --- Datos DUMMY para el Gráfico de Comparación Mensual de Leads ---
$leads_monthly_chart_labels = [];
$leads_new_monthly_data = [];
$leads_converted_monthly_data = [];

// Generar datos para los últimos 6 meses (simulados)
for ($i = 5; $i >= 0; $i--) {
    $date = new DateTime("{$selected_leads_year}-{$selected_leads_month}-01");
    $date->modify("-{$i} months");
    $month_label = $month_names_spanish[(int)$date->format('n')];
    $leads_monthly_chart_labels[] = $month_label;

    // Simular datos de leads para cada mes pasado
    $new_leads_sim = rand(15, 40);
    $converted_leads_sim = rand(5, floor($new_leads_sim / 2));
    
    // Ajustar los datos si es el mes actual para que coincidan con las métricas calculadas
    if ((int)$date->format('Y') === $selected_leads_year && (int)$date->format('n') === $selected_leads_month) {
        $new_leads_sim = $new_leads_month; // Usar el conteo real del mes seleccionado
        $converted_leads_sim = $converted_leads_month; // Usar el conteo real del mes seleccionado
    }

    $leads_new_monthly_data[] = $new_leads_sim;
    $leads_converted_monthly_data[] = $converted_leads_sim;
}

// --- Recopilar fuentes únicas para el filtro ---
$unique_sources = [];
foreach ($leads_from_db as $lead) {
    if (!empty($lead['source']) && !in_array($lead['source'], $unique_sources)) {
        $unique_sources[] = $lead['source'];
    }
}
sort($unique_sources); // Ordenar alfabéticamente
$unique_sources_json = json_encode($unique_sources);


// --- Meses disponibles para el dropdown (simulados) ---
$available_months_for_dropdown = [];
$current_year_for_dropdown = date('Y');
for ($y = $current_year_for_dropdown; $y >= $current_year_for_dropdown - 1; $y--) { // Últimos 2 años
    for ($m = 12; $m >= 1; $m--) {
        // Solo meses hasta el actual si es el año actual
        if ($y == $current_year_for_dropdown && $m > date('n')) {
            continue;
        }
        $available_months_for_dropdown[] = [
            'year' => $y,
            'month' => $m,
            'label' => $month_names_spanish[$m] . ' ' . $y
        ];
    }
}


// Convertir los datos a JSON para JavaScript
$leads_json = json_encode($leads_from_db); // Estos son los leads dummy para la tabla.

$leads_metrics_json = json_encode([
    'total_leads' => $total_leads,
    'new_leads_month' => $new_leads_month,
    'converted_leads_month' => $converted_leads_month,
]);

$leads_monthly_chart_json = json_encode([
    'labels' => $leads_monthly_chart_labels,
    'new_data' => $leads_new_monthly_data,
    'converted_data' => $leads_converted_monthly_data,
]);

$available_months_for_dropdown_json = json_encode($available_months_for_dropdown);
$selected_leads_month_js = json_encode($selected_leads_month);
$selected_leads_year_js = json_encode($selected_leads_year);


// Manejo de notificaciones de sesión
$notification_message = '';
$notification_type = '';
if (isset($_SESSION['notification'])) {
    $notification_message = $_SESSION['notification']['message'];
    $notification_type = $_SESSION['notification']['type'];
    unset($_SESSION['notification']);
}
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Leads | Gestión de Prospectos</title>
    <meta name="description" content="Gestión de leads y prospectos en LocalCRM.">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">


    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script> 
    
</head>
<body data-page-title="GESTIÓN DE LEADS"
      data-page-subtitle="TODOS LOS PROSPECTOS GENERADOS"
      data-page-icon="funnel-dollar">


<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="lead-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden md:hidden"></div>


<?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container" id="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            <section id="leads-overview-section" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="funnel" class="w-7 h-7 text-[var(--color-primary)]"></i> RESUMEN DE LEADS - <span id="leads-report-month-name"><?php echo $current_report_leads_month_name; ?></span>
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">ESTADÍSTICAS CLAVE DE PROSPECTOS.</p>
                        </div>
                        <div class="flex items-center gap-2">
                            <label for="leads-month-filter" class="text-gray-700 text-sm font-bold uppercase hidden md:block">Ver Mes:</label>
                            <select id="leads-month-filter" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                                </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
                            <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">TOTAL LEADS</h3>
                                <p id="total-leads-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                            </div>
                        </div>
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-green-500">
                            <i data-lucide="user-plus" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">LEADS NUEVOS (MES)</h3>
                                <p id="new-leads-month" class="text-5xl font-bold text-green-700">0</p>
                            </div>
                        </div>
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-blue-500">
                            <i data-lucide="user-check" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">LEADS CONVERTIDOS (MES)</h3>
                                <p id="converted-leads-month" class="text-5xl font-bold text-blue-700">0</p>
                            </div>
                        </div>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                        <h3 class="text-xl font-extrabold text-gray-800 flex items-center gap-2 mb-4">
                            <i data-lucide="bar-chart" class="w-6 h-6 text-[var(--color-primary)]"></i> TENDENCIA DE LEADS (ÚLTIMOS 6 MESES)
                        </h3>
                        <div class="relative h-72"><canvas id="leadsMonthlyComparisonChart"></canvas></div>
                    </div>
                </div>
            </section>

            <section id="leads-list-section" class="leads-section mt-8">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="funnel-dollar" class="w-7 h-7 text-[var(--color-primary)]"></i> LISTA COMPLETA DE LEADS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">TODOS LOS PROSPECTOS CAPTADOS EN EL SISTEMA.</p>
                        </div>
                        <div class="flex gap-2">
                            <button id="addLeadBtnTop" class="btn-cta text-white font-bold py-2 px-4 rounded-lg inline-flex items-center justify-center">
                                <i class="fas fa-plus mr-2"></i>AÑADIR LEAD
                            </button>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row justify-end items-end md:items-center gap-4 mb-4">
                        <select id="lead-source-filter" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="all">TODAS LAS FUENTES</option>
                            </select>
                        <button id="downloadLeadsBtn" class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm">
                            <i data-lucide="download" class="w-4 h-4 mr-2"></i> DESCARGAR
                        </button>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white border border-gray-200 rounded-lg shadow-sm">
                            <thead>
                                <tr class="bg-gray-100 text-gray-600 uppercase text-sm leading-normal">
                                    <th class="py-3 px-6 text-left">ID</th>
                                    <th class="py-3 px-6 text-left">Nombre</th>
                                    <th class="py-3 px-6 text-left">Email</th>
                                    <th class="py-3 px-6 text-left">Teléfono</th>
                                    <th class="py-3 px-6 text-left">Fuente</th>
                                    <th class="py-3 px-6 text-left">Fecha</th>
                                    <th class="py-3 px-6 text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="leadsTableBody" class="text-gray-700 text-sm font-light">
                                <?php if (empty($leads_from_db)): ?>
                                    <tr>
                                        <td colspan="7" class="py-3 px-6 text-center">No hay leads registrados.</td> </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="leadPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 id="leadPanelTitle" class="text-2xl font-bold text-[var(--color-primary)]">AÑADIR NUEVO LEAD</h3>
            <button onclick="closeLeadPanel()" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="leadForm" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="leadId" name="id">
            <div>
                <label for="leadName" class="block text-sm font-medium text-gray-700">Nombre</label>
                <input type="text" id="leadName" name="name" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm">
            </div>
            <div>
                <label for="leadEmail" class="block text-sm font-medium text-gray-700">Email</label>
                <input type="email" id="leadEmail" name="email" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm">
            </div>
            <div>
                <label for="leadPhone" class="block text-sm font-medium text-gray-700">Teléfono</label>
                <input type="tel" id="leadPhone" name="phone" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm">
            </div>
            <div>
                <label for="leadMessage" class="block text-sm font-medium text-gray-700">Mensaje</label>
                <textarea id="leadMessage" name="message" rows="3" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm"></textarea>
            </div>
            <div>
                <label for="leadSource" class="block text-sm font-medium text-gray-700">Fuente</label>
                <input type="text" id="leadSource" name="source" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm" value="Manual">
            </div>
            <div>
                <label for="leadStatus" class="block text-sm font-medium text-gray-700">Estado</label>
                <select id="leadStatus" name="status" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[var(--color-highlight)] focus:border-[var(--color-highlight)] sm:text-sm">
                    <option value="New">Nuevo</option>
                    <option value="Contacted">Contactado</option>
                    <option value="Qualified">Calificado</option>
                    <option value="Unqualified">No Calificado</option>
                    <option value="Converted">Convertido a Cliente</option>
                </select>
            </div>
        </form>
        <div class="flex justify-end space-x-4 pt-6 flex-shrink-0">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeLeadPanel()">CANCELAR</button>
            <button type="submit" form="leadForm" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR LEAD</button>
        </div>
    </div>
</div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i data-lucide="alert-triangle" class="w-16 h-16 text-red-500"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ACCIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS REALIZAR ESTA ACCIÓN?</p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmDeleteModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>


<script>
// Datos de leads cargados desde PHP (ahora dummy data)
let leads = <?php echo $leads_json; ?>;
let leadsMetrics = <?php echo $leads_metrics_json; ?>;
let leadsMonthlyChartData = <?php echo $leads_monthly_chart_json; ?>;
let availableMonthsForDropdown = <?php echo $available_months_for_dropdown_json; ?>;
let uniqueSources = <?php echo $unique_sources_json; ?>; // Nuevo: Fuentes únicas para el filtro

// Variables para el mes y año seleccionados (inicializados desde PHP)
let selectedLeadsMonth = <?php echo $selected_leads_month_js; ?>;
let selectedLeadsYear = <?php echo $selected_leads_year_js; ?>;


document.addEventListener('DOMContentLoaded', function() {
    console.log("--- Depuración de leads.php ---");
    console.log("Leads cargados:", leads);
    console.log("Leads Metrics:", leadsMetrics);
    console.log("Leads Monthly Chart Data:", leadsMonthlyChartData);
    console.log("Available Months for Dropdown:", availableMonthsForDropdown);
    console.log("Selected Leads Month:", selectedLeadsMonth);
    console.log("Selected Leads Year:", selectedLeadsYear);
    console.log("Unique Sources:", uniqueSources); // Nuevo: Depuración de fuentes únicas


    // --- VARIABLES DOM LOCALES ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    
    // Métricas de Resumen de Leads
    const totalLeadsCountElement = document.getElementById('total-leads-count');
    const newLeadsMonthElement = document.getElementById('new-leads-month');
    const convertedLeadsMonthElement = document.getElementById('converted-leads-month');
    const leadsReportMonthNameDisplay = document.getElementById('leads-report-month-name'); // Para el nombre del mes en el reporte

    // Dropdown de mes para leads
    const leadsMonthFilter = document.getElementById('leads-month-filter');
    // Nuevo: Filtro por fuente
    const leadSourceFilter = document.getElementById('lead-source-filter');

    // Gráfico de Leads
    const leadsMonthlyComparisonChartCtx = document.getElementById('leadsMonthlyComparisonChart')?.getContext('2d');

    // Botones para añadir lead
    const addLeadBtnTop = document.getElementById('addLeadBtnTop'); // Top button
    const downloadLeadsBtn = document.getElementById('downloadLeadsBtn'); // Botón de descarga

    // Elementos del PANEL de lead
    const leadPanel = document.getElementById('leadPanel'); 
    const leadPanelTitle = document.getElementById('leadPanelTitle'); 
    const leadForm = document.getElementById('leadForm');
    const leadIdInput = document.getElementById('leadId');
    const leadNameInput = document.getElementById('leadName');
    const leadEmailInput = document.getElementById('leadEmail');
    const leadPhoneInput = document.getElementById('leadPhone');
    const leadMessageInput = document.getElementById('leadMessage');
    const leadSourceInput = document.getElementById('leadSource');
    const leadStatusSelect = document.getElementById('leadStatus');

    // Tabla de leads
    const leadsTableBody = document.getElementById('leadsTableBody');

    // Modales de confirmación (compartidos)
    const confirmDeleteModal = document.getElementById('confirmDeleteModal');
    const confirmDeleteButton = document.getElementById('confirm-delete-button');

    // Overlay específico para el panel de leads
    const leadPanelOverlay = document.getElementById('lead-panel-overlay');


    // --- FUNCIONES HELPER GLOBALES (reutilizadas) ---

    // Muestra una notificación personalizada
    window.showCustomNotification = function(message, type = 'info', duration = 3000) {
        const toast = document.getElementById('toastNotification');
        const toastMessage = document.getElementById('toastMessage');
        const toastIcon = document.getElementById('toastIcon');
        const toastCloseBtn = document.getElementById('toastCloseBtn');
        let toastTimeout;

        if (!toast || !toastMessage || !toastIcon || !toastCloseBtn) {
            console.warn(`[NOTIFICACION - FALLBACK] Elementos de toast no encontrados. Mensaje: ${type.toUpperCase()}: ${message}`);
            return;
        }

        clearTimeout(toastTimeout);
        toast.className = 'toast-notification'; // Resetear clases
        toastIcon.className = 'fas'; // Resetear icono base

        toastMessage.textContent = message;
        toast.classList.add(type === 'success' ? 'success' : (type === 'error' ? 'error' : 'info'));
        
        if (type === 'success') {
            toastIcon.classList.add('fa-check-circle');
        } else if (type === 'error') {
            toastIcon.classList.add('fa-exclamation-circle');
        } else {
            toastIcon.classList.add('fa-info-circle');
        }

        toast.classList.add('show');
        toastTimeout = setTimeout(() => {
            toast.classList.remove('show');
        }, duration);

        toastCloseBtn.onclick = () => {
            clearTimeout(toastTimeout);
            toast.classList.remove('show');
        };

        console.log(`[NOTIFICACION - ${type.toUpperCase()}] ${message}`);
    };

    // Abre el modal de confirmación (único modal permitido)
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { console.error(`Error: Modal con ID "${modalId}" no encontrado.`); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modal.classList.remove('hidden');
        setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
        console.log(`[leads.php] Modal ${modalId} abierto.`);
    };

    // Cierra el modal de confirmación
    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { console.error(`Error: Modal con ID "${modalId}" no encontrado para cerrar.`); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => { modal.classList.add('hidden'); }, 300);
        console.log(`[leads.php] Modal ${modalId} cerrado.`);
    };
    
    // Función de confirmación general (usa el modal de confirmación)
    window.openConfirmActionModal = function(actionCallback, message = '¿ESTÁS SEGURO DE QUE DESEAS REALIZAR ESTA ACCIÓN?') {
        if (!confirmDeleteButton) { showCustomNotification("Error: Botón de confirmación no encontrado.", 'error'); return; }
        document.getElementById('confirmDeleteModal').querySelector('h3').textContent = 'CONFIRMAR ACCIÓN';
        document.getElementById('confirmDeleteModal').querySelector('p').textContent = message;
        confirmDeleteButton.onclick = () => {
            actionCallback();
            closeModal('confirmDeleteModal');
        };
        openModal('confirmDeleteModal');
    };

    // Función para abrir el panel lateral (reemplaza openModal para leads)
    function openLeadPanel() {
        if (!leadPanel) { console.error('Error: Panel de leads no encontrado.'); return; }
        leadPanel.classList.remove('translate-x-full');
        leadPanelOverlay.classList.remove('hidden'); // Muestra el overlay del panel
        console.log('[leads.php] Panel de leads abierto.');
    }

    // Función para cerrar el panel lateral (reemplaza closeModal para leads)
    window.closeLeadPanel = function() {
        if (!leadPanel) { console.error('Error: Panel de leads no encontrado para cerrar.'); return; }
        leadPanel.classList.add('translate-x-full');
        leadPanelOverlay.classList.add('hidden'); // Oculta el overlay del panel
        console.log('[leads.php] Panel de leads cerrado.');
    };


    // Descarga datos como CSV
    function descargarComoCSV(dataArray, filename) {
        if (dataArray.length === 0) { showCustomNotification('No hay datos para descargar.', 'info'); return; }
        const escapeCSV = (value) => {
            if (value === null || value === undefined) { return ''; }
            value = String(value);
            if (value.search(/("|,|\n)/g) >= 0) { return `"${value.replace(/"/g, '""')}"`; }
            return value;
        };
        
        let headers = Object.keys(dataArray[0]); 
        // Filtra las columnas 'message' y 'status' de los encabezados para el CSV
        headers = headers.filter(header => header !== 'message' && header !== 'status');
        
        const csvRows = [headers.map(h => escapeCSV(h.replace(/_/g, ' ').toUpperCase())).join(',')];
        dataArray.forEach(item => {
            // Asegúrate de que los valores también se filtren para 'message' y 'status'
            const values = headers.map(header => escapeCSV(item[header]));
            csvRows.push(values.join(','));
        });
        const csvContent = csvRows.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url); link.setAttribute('download', filename);
            link.style.visibility = 'hidden'; document.body.appendChild(link);
            link.click(); document.body.removeChild(link);
        }
    }


    // --- FUNCIONES ESPECÍFICAS DE LEADS ---

    function updateLeadsMetricsDisplay() {
        if (totalLeadsCountElement) totalLeadsCountElement.textContent = leadsMetrics.total_leads.toString();
        if (newLeadsMonthElement) newLeadsMonthElement.textContent = leadsMetrics.new_leads_month.toString();
        if (convertedLeadsMonthElement) convertedLeadsMonthElement.textContent = leadsMetrics.converted_leads_month.toString();
        
        // Actualizar el nombre del mes en la tarjeta de resumen
        if (leadsReportMonthNameDisplay) {
            const monthNames = ["ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO",
                                 "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE"];
            leadsReportMonthNameDisplay.textContent = monthNames[selectedLeadsMonth - 1] || 'N/A';
        }
    }

    function populateLeadsMonthFilter() {
        if (!leadsMonthFilter) return;

        leadsMonthFilter.innerHTML = ''; // Limpiar opciones existentes

        availableMonthsForDropdown.forEach(period => {
            const option = document.createElement('option');
            option.value = `${period.year}-${String(period.month).padStart(2, '0')}`; // Formato YYYY-MM
            option.textContent = period.label.toUpperCase();
            if (period.year === selectedLeadsYear && period.month === selectedLeadsMonth) {
                option.selected = true;
            }
            leadsMonthFilter.appendChild(option);
        });
    }

    // Nuevo: Función para poblar el filtro por fuente
    function populateLeadSourceFilter() {
        if (!leadSourceFilter) return;

        leadSourceFilter.innerHTML = '<option value="all">TODAS LAS FUENTES</option>'; // Opción por defecto

        uniqueSources.forEach(source => {
            const option = document.createElement('option');
            option.value = source;
            option.textContent = source.toUpperCase();
            leadSourceFilter.appendChild(option);
        });
    }

    function renderLeadsMonthlyComparisonChart() {
        if (!leadsMonthlyComparisonChartCtx) return;

        const labels = leadsMonthlyChartData.labels;
        const newLeadsData = leadsMonthlyChartData.new_data;
        const convertedLeadsData = leadsMonthlyChartData.converted_data;

        // Destruir el gráfico existente si lo hay para evitar duplicados al recargar
        if (window.leadsChartInstance) {
            window.leadsChartInstance.destroy();
        }

        window.leadsChartInstance = new Chart(leadsMonthlyComparisonChartCtx, {
            type: 'line', // Gráfico de líneas para tendencia
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Leads Nuevos',
                        data: newLeadsData,
                        borderColor: 'var(--color-primary)',
                        backgroundColor: 'rgba(7, 22, 45, 0.1)',
                        tension: 0.3,
                        fill: true
                    },
                    {
                        label: 'Leads Convertidos',
                        data: convertedLeadsData,
                        borderColor: 'var(--color-green)', 
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        tension: 0.3,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Cantidad de Leads'
                        },
                        ticks: {
                            stepSize: 5 
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            font: {
                                family: 'Barlow' 
                            }
                        }
                    }
                }
            }
        });
    }

    function renderLeadsTable() {
        if (!leadsTableBody) return;
        leadsTableBody.innerHTML = ''; // Limpiar tabla

        const selectedSource = leadSourceFilter.value; // Obtener la fuente seleccionada

        // Filtrar leads por fuente si no es "all"
        const filteredLeads = leads.filter(lead => {
            return selectedSource === 'all' || (lead.source && lead.source === selectedSource);
        });


        if (filteredLeads.length === 0) {
            leadsTableBody.innerHTML = `<tr><td colspan="7" class="py-3 px-6 text-center">No hay leads registrados para esta selección.</td></tr>`; // colspan ajustado
            return;
        }

        // Ordenar leads por fecha de creación descendente (más recientes primero)
        const sortedLeads = [...filteredLeads].sort((a, b) => { // Usar filteredLeads aquí
            return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        });

        sortedLeads.forEach(lead => {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-200 hover:bg-gray-50';
            
            // La función getStatusText se mantiene para el formulario de edición/creación
            // pero ya no se usa para mostrar el estado en la tabla.

            row.innerHTML = `
                <td class="py-3 px-6 text-left whitespace-nowrap">${lead.id}</td>
                <td class="py-3 px-6 text-left">${lead.name}</td>
                <td class="py-3 px-6 text-left">${lead.email}</td>
                <td class="py-3 px-6 text-left">${lead.phone || 'N/A'}</td>
                <td class="py-3 px-6 text-left">${lead.source}</td>
                <td class="py-3 px-6 text-left">${new Date(lead.created_at).toLocaleDateString()}</td>
                <td class="py-3 px-6 text-center">
                    <div class="flex item-center justify-center">
                        <button class="w-6 h-6 mr-2 transform hover:text-[var(--color-highlight)] hover:scale-110" title="Editar Lead" onclick="editLead(${lead.id})">
                            <i data-lucide="edit" class="w-5 h-5"></i>
                        </button>
                        <button class="w-6 h-6 mr-2 transform hover:text-red-500 hover:scale-110" title="Eliminar Lead" onclick="deleteLead(${lead.id})">
                            <i data-lucide="trash-2" class="w-5 h-5"></i>
                        </button>
                        <button class="w-6 h-6 transform hover:text-green-500 hover:scale-110" title="Convertir a Cliente" onclick="convertLeadToClient(${lead.id})">
                            <i data-lucide="user-check" class="w-5 h-5"></i>
                        </button>
                    </div>
                </td>
            `;
            leadsTableBody.appendChild(row);
        });
        lucide.createIcons({ container: leadsTableBody }); // Renderizar iconos Lucide
    }

    // Abre el panel para añadir un nuevo lead
    function openAddLeadPanel() { 
        leadPanelTitle.textContent = 'AÑADIR NUEVO LEAD';
        leadForm.reset(); // Limpiar el formulario
        leadIdInput.value = ''; // Asegurarse de que el ID esté vacío para una nueva entrada
        leadSourceInput.value = 'Manual'; // Valor por defecto para leads añadidos manualmente
        leadStatusSelect.value = 'New'; // Estado por defecto
        openLeadPanel(); 
    }

    // Abre el panel para editar un lead existente
    window.editLead = function(id) {
        const leadToEdit = leads.find(lead => lead.id === id);
        if (leadToEdit) {
            leadPanelTitle.textContent = 'EDITAR LEAD';
            leadIdInput.value = leadToEdit.id;
            leadNameInput.value = leadToEdit.name;
            leadEmailInput.value = leadToEdit.email;
            leadPhoneInput.value = leadToEdit.phone || ''; 
            leadMessageInput.value = leadToEdit.message || ''; 
            leadSourceInput.value = leadToEdit.source;
            leadStatusSelect.value = leadToEdit.status;
            openLeadPanel(); 
        } else {
            showCustomNotification('Lead no encontrado.', 'error');
        }
    };

    // Envía el formulario del panel (añadir/editar)
    leadForm.addEventListener('submit', async function(event) {
        event.preventDefault();

        const formData = new FormData(leadForm);
        const leadData = {};
        formData.forEach((value, key) => {
            leadData[key] = value;
        });

        const isEditing = leadData.id !== '';
        
        let result;
        if (isEditing) {
            const index = leads.findIndex(lead => lead.id == leadData.id);
            if (index !== -1) {
                leads[index] = { ...leads[index], ...leadData };
                leads[index].created_at = leads[index].created_at; 
                result = { success: true, message: "Lead actualizado simuladamente." };
            } else {
                result = { success: false, message: "Error: Lead no encontrado para actualizar (simulado)." };
            }
        } else {
            const newId = leads.length > 0 ? Math.max(...leads.map(l => l.id)) + 1 : 1;
            const newLead = {
                id: newId,
                name: leadData.name,
                email: leadData.email,
                phone: leadData.phone || null,
                message: leadData.message || null,
                source: leadData.source,
                status: leadData.status,
                created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') 
            };
            leads.push(newLead);
            result = { success: true, message: "Lead agregado simuladamente." };
        }

        if (result.success) {
            showCustomNotification(result.message, 'success');
            closeLeadPanel(); 
            recalculateMetricsAndUpdateDisplay();
            // Re-poblar el filtro de fuentes y re-renderizar la tabla para mostrar el nuevo lead
            updateUniqueSourcesAndRerender(); 
            renderLeadsMonthlyComparisonChart(); 
        } else {
            showCustomNotification(result.message, 'error');
        }
    });

    // Elimina un lead (simulado)
    window.deleteLead = function(id) {
        openConfirmActionModal(async () => {
            const initialLeadsCount = leads.length;
            leads = leads.filter(lead => lead.id !== id);
            
            if (leads.length < initialLeadsCount) {
                showCustomNotification("Lead eliminado con éxito (simulado).", 'success');
                recalculateMetricsAndUpdateDisplay();
                // Re-poblar el filtro de fuentes y re-renderizar la tabla después de eliminar
                updateUniqueSourcesAndRerender();
                renderLeadsMonthlyComparisonChart();
            } else {
                showCustomNotification("Error: Lead no encontrado para eliminar (simulado).", 'error');
            }
        }, '¿Estás seguro de que deseas eliminar este lead? Esta acción no se puede deshacer.');
    };

    // Convierte un lead a cliente (simulado)
    window.convertLeadToClient = function(id) {
        openConfirmActionModal(async () => {
            const leadToConvert = leads.find(lead => lead.id === id);
            if (leadToConvert) {
                leadToConvert.status = 'Converted';
                showCustomNotification(`Lead "${leadToConvert.name}" convertido a cliente (simulado).`, 'success');
                recalculateMetricsAndUpdateDisplay();
                renderLeadsTable(); // Re-renderiza la tabla después de convertir
                renderLeadsMonthlyComparisonChart();
            } else {
                showCustomNotification("Error: Lead no encontrado para convertir (simulado).", 'error');
            }
        }, '¿Estás seguro de que deseas convertir este lead en un cliente?');
    };

    // NUEVA FUNCIÓN: Recalcula las métricas y actualiza la visualización
    function recalculateMetricsAndUpdateDisplay() {
        leadsMetrics.total_leads = leads.length;
        leadsMetrics.new_leads_month = 0;
        leadsMetrics.converted_leads_month = 0;

        leads.forEach(lead => {
            const lead_date = new Date(lead.created_at);
            if (lead_date.getFullYear() === selectedLeadsYear && (lead_date.getMonth() + 1) === selectedLeadsMonth) {
                leadsMetrics.new_leads_month++;
                if (lead.status === 'Converted') {
                    leadsMetrics.converted_leads_month++;
                }
            }
        });

        let currentMonthChartIndex = leadsMonthlyChartData.labels.findIndex(label => 
            label.includes(new Date(selectedLeadsYear, selectedLeadsMonth -1, 1).toLocaleString('es', { month: 'long' }).toUpperCase())
        );

        if (currentMonthChartIndex !== -1) {
            leadsMonthlyChartData.new_data[currentMonthChartIndex] = leadsMetrics.new_leads_month;
            leadsMonthlyChartData.converted_data[currentMonthChartIndex] = leadsMetrics.converted_leads_month;
        }

        updateLeadsMetricsDisplay();
    }

    // NUEVA FUNCIÓN: Actualiza las fuentes únicas y re-renderiza todo lo que depende
    function updateUniqueSourcesAndRerender() {
        const currentSources = new Set();
        leads.forEach(lead => {
            if (lead.source) {
                currentSources.add(lead.source);
            }
        });
        uniqueSources = Array.from(currentSources).sort(); // Ordenar alfabéticamente
        populateLeadSourceFilter(); // Vuelve a poblar el filtro con las nuevas fuentes
        renderLeadsTable(); // Re-renderiza la tabla con el posible nuevo filtro/datos
    }


    // --- INICIALIZACIÓN DE LA PÁGINA ---

    // Mostrar notificación PHP si existe
    const phpNotificationMessage = "<?php echo addslashes($notification_message); ?>";
    const phpNotificationType = "<?php echo addslashes($notification_type); ?>";
    if (phpNotificationMessage) {
        showCustomNotification(phpNotificationMessage, phpNotificationType);
    }

    // Eventos de la barra lateral (menú móvil)
    const mobileMenuButtonHeader = document.getElementById('mobile-menu-button');
    const sidebarCloseBtnHeader = document.getElementById('sidebarCloseBtn'); 
    if (mobileMenuButtonHeader) mobileMenuButtonHeader.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });
    if (sidebarOverlay) sidebarOverlay.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });
    if (sidebarCloseBtnHeader) sidebarCloseBtnHeader.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });

    // Listener para el overlay del panel de leads para cerrarlo
    if (leadPanelOverlay) {
        leadPanelOverlay.addEventListener('click', closeLeadPanel);
    }

    // Eventos de botones "Añadir Lead" ahora abren el PANEL
    if (addLeadBtnTop) addLeadBtnTop.addEventListener('click', openAddLeadPanel);

    // Inicializar filtros y renderizar
    populateLeadsMonthFilter();
    populateLeadSourceFilter(); 
    renderLeadsTable(); 

    // Actualizar métricas de leads y gráfico
    updateLeadsMetricsDisplay();
    renderLeadsMonthlyComparisonChart();

    // Listener para el dropdown de selección de mes
    if (leadsMonthFilter) {
        leadsMonthFilter.addEventListener('change', function() {
            const [year, month] = this.value.split('-').map(Number);
            window.location.href = `leads.php?year=${year}&month=${month}`;
        });
    }

    // Listener para el filtro de fuente - re-renderiza la tabla
    if (leadSourceFilter) {
        leadSourceFilter.addEventListener('change', renderLeadsTable); 
    }


    // Listener para el botón de descarga
    if (downloadLeadsBtn) {
        downloadLeadsBtn.addEventListener('click', () => {
            descargarComoCSV(leads, `leads_reporte_${selectedLeadsYear}-${selectedLeadsMonth}.csv`);
        });
    }

    // Se re-renderizan los iconos de Lucide al cargar el DOM
    lucide.createIcons();
    console.log("[leads.php] Página de leads inicializada.");
});
</script>
</body>
</html>