<?php
include 'files/guardiankey.php';
include_once 'db/db_connection.php'; 

// --- LÓGICA DE DATOS: LEADS DESCARTADOS ---
function fetchDiscardedLeads($pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT id, first_name, last_name, company, email, phone, mobile, source, status, 
                   lost_reason, updated_at
            FROM leads 
            WHERE status IN ('Descartado', 'Perdida')
            ORDER BY updated_at DESC
        ");
        $stmt->execute();
        $leads_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $formatted_leads = [];
        foreach ($leads_raw as $lead) {
            $name = trim($lead['first_name'] . ' ' . $lead['last_name']);
            $formatted_leads[] = [
                'id' => $lead['id'],
                'name' => $name,
                'first_name' => $lead['first_name'],
                'last_name' => $lead['last_name'],
                'email' => $lead['email'],
                'phone_mobile' => $lead['mobile'] ?? $lead['phone'], 
                'company' => $lead['company'] ?? '',
                'source' => $lead['source'] ?? 'N/A',
                'discard_reason' => $lead['lost_reason'] ?? $lead['status'], 
                'discard_date' => date('Y-m-d', strtotime($lead['updated_at'])), 
                'status_final' => $lead['status'] 
            ];
        }
        return $formatted_leads;

    } catch (PDOException $e) {
        error_log("Error al cargar leads descartados: " . $e->getMessage());
        return []; 
    }
}

$discarded_leads = fetchDiscardedLeads($pdo);
$total_discarded = count($discarded_leads);

// =================================================================
// LÓGICA KPI: RAZÓN Y FUENTE PRINCIPAL DE PÉRDIDA
// =================================================================

$reason_counts = [];
$source_counts = [];

foreach ($discarded_leads as $lead) {
    // Contar razones de descarte
    $reason = $lead['discard_reason'] ?? 'Sin especificar';
    $reason_counts[$reason] = ($reason_counts[$reason] ?? 0) + 1;

    // Contar fuentes
    $source = $lead['source'] ?? 'N/A';
    $source_counts[$source] = ($source_counts[$source] ?? 0) + 1;
}

// Determinar la razón principal
$most_frequent_reason = ['name' => 'N/A', 'count' => 0];
if (!empty($reason_counts)) {
    arsort($reason_counts);
    $most_frequent_reason['name'] = array_key_first($reason_counts);
    $most_frequent_reason['count'] = $reason_counts[$most_frequent_reason['name']];
}

// Determinar la fuente principal
$most_frequent_source = ['name' => 'N/A', 'count' => 0];
if (!empty($source_counts)) {
    arsort($source_counts);
    $most_frequent_source['name'] = array_key_first($source_counts);
    $most_frequent_source['count'] = $source_counts[$most_frequent_source['name']];
}


// Extraer fuentes, razones y estados únicos para los filtros
$sources = array_unique(array_column($discarded_leads, 'source'));
$sources = array_filter($sources);
sort($sources);

$reasons = array_unique(array_column($discarded_leads, 'discard_reason'));
$reasons = array_filter($reasons);
sort($reasons);

$final_statuses = array_unique(array_column($discarded_leads, 'status_final'));
sort($final_statuses);

// Codificar datos para JavaScript (usado por el panel lateral)
$discarded_leads_json = json_encode($discarded_leads);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centro de Leads Descartados - FlowCRM™</title>
    <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">

    <?php include 'files/gtm-head.php'; ?>
    <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="style.css">
    <script src="files/header-manager.js"></script>
</head>

<body class="font-barlow"
    data-page-title="Centro De Prospectos Descartados"
    data-page-subtitle="Archivo De Clientes Potenciales Para Análisis Y Reactivación"
    data-page-icon="archive">

    <div id="toast-container" class="toast-container"></div>
    <?php include 'files/gtm-body.php'; ?>

<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>
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white p-4 flex justify-between items-center sticky top-0 z-20 shadow-sm">
             <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"> <h2 id="page-title"></h2> <p id="page-subtitle"></p> </div>
        </header>

    <div id="content-area" class="p-4 md:p-8 bg-[var(--color-background)] space-y-8">

             <div>
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-6">

                    <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
                        <i data-lucide="archive" class="w-12 h-12 text-gray-700"></i>
                        <div>
                            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">TOTAL ARCHIVADOS</h3>
                            <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_discarded; ?></p>
                        </div>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-secondary)]">
                        <i data-lucide="alert-triangle" class="w-12 h-12 text-gray-700"></i>
                        <div>
                            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">PRINCIPAL RAZÓN DE PÉRDIDA</h3>
                            <p class="text-3xl font-black text-[var(--color-secondary)] uppercase mb-1"><?php echo htmlspecialchars($most_frequent_reason['name']); ?></p>
                            <p class="text-sm text-gray-400 mt-1 uppercase">Ocurrencias: <?php echo $most_frequent_reason['count']; ?></p>
                        </div>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="compass" class="w-12 h-12 text-gray-700"></i>
                        <div>
                            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">FUENTE PRINCIPAL DE PÉRDIDA</h3>
                            <p class="text-3xl font-black text-[var(--color-primary)] uppercase mb-1"><?php echo htmlspecialchars($most_frequent_source['name']); ?></p>
                            <p class="text-sm text-gray-400 mt-1 uppercase">Leads: <?php echo $most_frequent_source['count']; ?></p>
                        </div>
                    </div>

                </div>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-[var(--color-primary)]">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                    <div>
                        <label for="filter-source" class="block text-sm font-black uppercase text-gray-700 mb-1">Filtrar por Fuente</label>
                        <select id="filter-source" name="filter-source" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todas las Fuentes --</option>
                            <?php foreach ($sources as $source): ?>
                                <option value="<?php echo htmlspecialchars($source); ?>"><?php echo htmlspecialchars($source); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="filter-reason" class="block text-sm font-semibold uppercase text-gray-700 mb-1">Filtrar por Razón</label>
                        <select id="filter-reason" name="filter-reason" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todas las Razones --</option>
                             <?php foreach ($reasons as $reason): ?>
                                 <option value="<?php echo htmlspecialchars($reason); ?>"><?php echo htmlspecialchars($reason); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="filter-status" class="block text-sm font-semibold uppercase text-gray-700 mb-1">Filtrar por Resultado</label>
                        <select id="filter-status" name="filter-status" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todos los Resultados --</option>
                            <?php foreach ($final_statuses as $status): ?>
                                <option value="<?php echo htmlspecialchars($status); ?>"><?php echo htmlspecialchars($status); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <button onclick="resetFilters()" class="w-full md:w-auto bg-[var(--color-secondary)] text-white font-black uppercase py-2 px-4 rounded-lg text-sm flex items-center justify-center">
                            <i data-lucide="rotate-ccw" class="w-4 h-4 mr-2"></i> Limpiar Filtros
                        </button>
                    </div>
                </div>
            </div>

            <div>
                <h3 class="text-3xl font-black text-[var(--color-primary)] mb-4 uppercase flex items-center"><i data-lucide="list-x" class="w-6 h-6 mr-2"></i>Listado de Leads Descartados</h3>

                <div class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-[var(--color-secondary)]">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left text-gray-700 responsive-stack" id="discarded-leads-table">
                            <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                                <tr>
                                    <th scope="col" class="py-3 px-4">Nombre</th>
                                    <th scope="col" class="py-3 px-4">Fuente</th>
                                    <th scope="col" class="py-3 px-4">Razón y Resultado</th>
                                    <th scope="col" class="py-3 px-4">Fecha Archivo</th>
                                    <th scope="col" class="py-3 px-4 text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($discarded_leads)): ?>
                                    <tr class="bg-white border-b">
                                        <td colspan="5" class="py-4 px-4 text-center text-gray-500 italic">No hay leads descartados en el archivo.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($discarded_leads as $lead): ?>
                                        <tr class="bg-white border-b hover:bg-gray-50 transition-colors duration-150" 
                                            data-source="<?php echo htmlspecialchars($lead['source']); ?>" 
                                            data-reason="<?php echo htmlspecialchars($lead['discard_reason']); ?>"
                                            data-status="<?php echo htmlspecialchars($lead['status_final']); ?>">
                                            
                                            <td class="py-3 px-4 font-semibold text-gray-900" data-label="Nombre"><?php echo htmlspecialchars($lead['name']); ?></td>
                                            <td class="py-3 px-4" data-label="Fuente"><?php echo htmlspecialchars($lead['source']); ?></td>
                                            <td class="py-3 px-4" data-label="Razón y Resultado">
                                                 <span class="font-bold text-sm text-<?php echo ($lead['status_final'] == 'Ganada' ? 'emerald-600' : '[var(--color-secondary)]'); ?>">
                                                    <?php echo htmlspecialchars(strtoupper($lead['status_final'])); ?>
                                                </span>
                                                <span class="block text-xs text-gray-500 mt-0.5" title="Razón de pérdida">
                                                    <?php echo htmlspecialchars($lead['discard_reason']); ?>
                                                </span>
                                            </td>
                                            <td class="py-3 px-4" data-label="Fecha Archivo"><?php echo date('d M Y', strtotime($lead['discard_date'])); ?></td>
                                            <td class="py-3 px-4 text-center space-x-2 actions-cell" data-label="Acciones">
                                                <button
                                                    onclick="openDiscardedPanel(<?php echo $lead['id']; ?>)"
                                                    class="inline-flex items-center text-[var(--color-primary)] hover:text-[var(--color-secondary)] transition-colors duration-150 p-1.5 rounded-md hover:bg-gray-100"
                                                    title="Ver Detalles">
                                                    <i data-lucide="eye" class="w-4 h-4"></i>
                                                    <span class="sr-only">Ver Detalles</span>
                                                </button>
                                                <button
                                                    onclick="openDeleteModal(<?php echo $lead['id']; ?>, '<?php echo htmlspecialchars(addslashes($lead['name'])); ?>')"
                                                    class="inline-flex items-center text-[var(--color-secondary)] hover:text-[var(--color-secondary)] transition-colors duration-150 p-1.5 rounded-md hover:bg-[var(--color-secondary)]"
                                                    title="Eliminar Permanentemente">
                                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                                    <span class="sr-only">Eliminar</span>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </main>
</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-[var(--color-secondary)]"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ELIMINACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">
            ¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR PERMANENTEMENTE A 
            <span id="delete-lead-name-display" class="font-semibold text-[var(--color-secondary)]"></span>? ESTA ACCIÓN NO SE PUEDE DESHACER.
        </p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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 w-full sm:w-auto" 
                onclick="closeModal('confirmDeleteModal')">
                CANCELAR
            </button>
            <button 
                type="button" 
                class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" 
                id="confirm-delete-button">
                CONFIRMAR
            </button>
        </div>
    </div>
</div>

<div id="confirmReactivateModal" 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="shuffle" class="w-16 h-16 text-[var(--color-primary)]"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-secondary)] mb-4 uppercase">CONFIRMAR REACTIVACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">
            ¿ESTÁS SEGURO DE REACTIVAR EL LEAD 
            <span id="reactivate-lead-name-display" class="font-semibold text-[var(--color-primary)]"></span>?
            SU ESTADO SE CAMBIARÁ A "EN SEGUIMIENTO".
        </p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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 w-full sm:w-auto" 
                onclick="closeModal('confirmReactivateModal')">
                CANCELAR
            </button>
            <button 
                type="button" 
                class="btn-primary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" 
                id="confirm-reactivate-button">
                CONFIRMAR
            </button>
        </div>
    </div>
</div>

<div id="discarded-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300 opacity-0 pointer-events-none" onclick="closeDiscardedPanel()"></div>

<aside id="discarded-panel" class="fixed top-0 right-0 h-full w-full lg:w-[450px] bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out flex flex-col shadow-2xl">
    <div class="p-4 bg-[var(--color-primary)] border-b border-gray-200 flex-shrink-0 flex justify-between items-center ">
        <h3 class="text-xl font-black text-[var(--color-highlight)] flex items-center">
            <i data-lucide="user-x" class="w-5 h-5 mr-2 text-[var(--color-highlight)]"></i>
            DETALLES DEL LEAD ARCHIVADO
        </h3>
        <button class="text-gray-400 hover:text-[var(--color-secondary)] p-1 rounded-full transition-colors duration-200" onclick="closeDiscardedPanel()">
            <i data-lucide="x" class="w-6 h-6"></i>
        </button>
    </div>
    <div class="p-4 overflow-y-auto flex-grow space-y-6">
        <div id="panel-content-area" class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-[var(--color-secondary)] space-y-4">
             <div class="border-b pb-3 mb-3">
                 <h4 class="text-lg font-black text-[var(--color-secondary)] flex items-center mb-1">
                     <i data-lucide="user" class="w-5 h-5 mr-2"></i>
                     <span id="panel-discarded-name"></span>
                 </h4>
                 <p class="text-sm text-gray-600 font-semibold flex items-center">
                     <i data-lucide="compass" class="w-4 h-4 mr-1.5 text-gray-500"></i>Fuente: <span id="panel-discarded-source" class="ml-1 font-medium text-gray-700"></span>
                 </p>
                 <p class="text-xs font-light text-gray-400 mt-1 text-right">ID: <span id="panel-discarded-id"></span></p>
             </div>
             <div>
                 <p class="text-sm font-semibold text-gray-700 mb-1 flex items-center"><i data-lucide="info" class="w-4 h-4 mr-1.5 text-[var(--color-secondary)]"></i>Resultado y Razón:</p>
                 <p class="text-base font-medium" id="panel-discarded-reason"></p>
             </div>
             <div>
                 <p class="text-sm font-semibold text-gray-700 mb-1 flex items-center"><i data-lucide="calendar-x" class="w-4 h-4 mr-1.5 text-gray-500"></i>Fecha de Archivo:</p>
                 <p class="text-base font-medium text-gray-800" id="panel-discarded-date"></p>
             </div>
             <div class="border-t pt-3">
                 <h5 class="text-sm font-bold text-[var(--color-primary)] mb-2">Información de Contacto</h5>
                 <p class="text-sm text-gray-700 mb-1 flex items-center"><i data-lucide="mail" class="w-4 h-4 mr-1.5 text-gray-500"></i>Email: <span id="panel-discarded-email" class="ml-1 break-all"></span></p>
                 <p class="text-sm text-gray-700 mb-1 flex items-center"><i data-lucide="phone" class="w-4 h-4 mr-1.5 text-gray-500"></i>Celular/Teléfono: <span id="panel-discarded-phone-mobile" class="ml-1"></span></p>
                 <p class="text-sm text-gray-700 flex items-center"><i data-lucide="building" class="w-4 h-4 mr-1.5 text-gray-500"></i>Empresa: <span id="panel-discarded-company" class="ml-1"></span></p>
             </div>
              <div class="border-t pt-3">
                 <h5 class="text-sm font-bold text-[var(--color-primary)] mb-2 flex items-center"><i data-lucide="history" class="w-4 h-4 mr-1.5"></i>Historial de Notas</h5>
                 <div id="panel-discarded-notes" class="space-y-2 text-xs text-gray-600 max-h-40 overflow-y-auto pr-2">
                     <p class="italic text-gray-500">No hay notas disponibles para este lead.</p>
                 </div>
             </div>
        </div>
    </div>
    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0">
        <button 
            id="reactivate-lead-btn" 
            onclick="reactivateLead()"
            class="w-full bg-[var(--color-primary)] text-white font-black py-2.5 uppercase px-4 rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300 ease-in-out hover:bg-[var(--color-highlight)]">
            <i data-lucide="shuffle" class="w-5 h-5 mr-2 inline-block"></i>
            REACTIVAR LEAD (EN SEGUIMIENTO)
        </button>
    </div>
</aside>

<script>
// *** DATOS GLOBALES ***
const discardedLeadsData = <?php echo $discarded_leads_json; ?>;
let currentLeadIdToReactivate = null; 
let currentLeadIdToDelete = null;

// =================================================================
// FUNCIONES DE UTILIDAD (MODAL Y TOAST)
// (Mantengo las funciones aquí por si no existen en otro archivo)
// =================================================================

// Asumo la existencia de showToast.
// Asumo la existencia de openModal y closeModal.

function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const modalBox = modal.querySelector('div:first-of-type');
    modal.classList.remove('hidden');
    // Forzar reflow y aplicar transiciones
    setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
    lucide.createIcons();
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const modalBox = modal.querySelector('div:first-of-type');
    modalBox.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 300);
}

// =================================================================
// FUNCIÓN PRINCIPAL DE INTERACCIÓN (PANEL LATERAL)
// =================================================================

function openDiscardedPanel(leadId) {
    const lead = discardedLeadsData.find(l => l.id == leadId);
    if (!lead) {
        if(typeof showToast === 'function') showToast("No se pudo cargar la información del lead.", 'error');
        return;
    }

    // 1. Guardar el ID actual (Restaurado)
    currentLeadIdToReactivate = leadId; 
    
    // 2. Rellenar campos estáticos
    document.getElementById('panel-discarded-name').textContent = lead.name || 'N/A';
    document.getElementById('panel-discarded-source').textContent = lead.source || 'N/A';
    document.getElementById('panel-discarded-id').textContent = lead.id;
    
    const reasonTextElement = document.getElementById('panel-discarded-reason');
    const statusClass = lead.status_final === 'Ganada' ? 'emerald-600' : '[var(--color-secondary)]';
    reasonTextElement.innerHTML = 
        `<span class="font-black text-white px-2 py-0.5 rounded-md bg-${statusClass}">
            ${lead.status_final.toUpperCase()}:
        </span> 
        <span class="font-medium text-gray-700 ml-2">${lead.discard_reason || 'Sin especificar'}</span>`;
        
    const discardDate = new Date(lead.discard_date + 'T00:00:00'); 
    document.getElementById('panel-discarded-date').textContent = discardDate.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' }) || 'N/A';
    
    document.getElementById('panel-discarded-email').textContent = lead.email || '--';
    document.getElementById('panel-discarded-phone-mobile').textContent = lead.phone_mobile || '--';
    document.getElementById('panel-discarded-company').textContent = lead.company || '--';

    // 3. Lógica para cargar notas (AJAX)
    const notesContainer = document.getElementById('panel-discarded-notes');
    notesContainer.innerHTML = '<p class="text-gray-500 italic text-xs">Cargando notas...</p>';
    fetch(`db/leads-get-notes.php?lead_id=${leadId}`) 
        .then(response => response.json())
        .then(data => {
            notesContainer.innerHTML = ''; 
            if (data.success && data.notes.length > 0) {
                data.notes.forEach(note => {
                    const noteDiv = document.createElement('div');
                    noteDiv.className = 'bg-gray-50 p-2 rounded-md border-l-2 border-[var(--color-primary)]';
                    noteDiv.innerHTML = `<div class="flex justify-between text-xs text-gray-500 mb-0.5"><span>${new Date(note.created_at).toLocaleDateString('es-ES')}</span></div><p>${note.content}</p>`;
                    notesContainer.appendChild(noteDiv);
                });
            } else {
                notesContainer.innerHTML = '<p class="italic text-gray-500">No hay notas registradas para este lead.</p>';
            }
            lucide.createIcons();
        })
        .catch(error => {
            console.error('Error al cargar notas:', error);
            notesContainer.innerHTML = '<p class="italic text-[var(--color-secondary)]">Error al cargar historial de notas.</p>';
        });

    // 4. Mostrar panel
    const discardedPanel = document.getElementById('discarded-panel');
    const discardedPanelOverlay = document.getElementById('discarded-panel-overlay');
    discardedPanel.classList.remove('translate-x-full');
    discardedPanelOverlay.classList.remove('opacity-0', 'pointer-events-none');
    discardedPanelOverlay.classList.add('opacity-100');
    lucide.createIcons(); 
}

function closeDiscardedPanel() {
    const discardedPanel = document.getElementById('discarded-panel');
    const discardedPanelOverlay = document.getElementById('discarded-panel-overlay');
    discardedPanel.classList.add('translate-x-full');
    discardedPanelOverlay.classList.remove('opacity-100');
    discardedPanelOverlay.classList.add('opacity-0', 'pointer-events-none');
}

// =================================================================
// LÓGICA DE REACTIVACIÓN (MODAL)
// =================================================================
function reactivateLead() {
    const lead = discardedLeadsData.find(l => l.id == currentLeadIdToReactivate);

    if (!currentLeadIdToReactivate || !lead) {
        if(typeof showToast === 'function') showToast("Error: No hay lead seleccionado para reactivar.", 'error');
        return;
    }
    
    // 1. Ocultar el panel lateral
    closeDiscardedPanel(); 

    // 2. Rellenar y abrir el modal de confirmación
    const nameDisplay = document.getElementById('reactivate-lead-name-display');
    if(nameDisplay) nameDisplay.textContent = lead.name;

    openModal('confirmReactivateModal');
}

async function confirmReactivateLogic() {
    const leadId = currentLeadIdToReactivate;

    if (!leadId) {
        closeModal('confirmReactivateModal');
        return;
    }
    
    if(typeof showToast === 'function') showToast("Reactivando lead...", 'info');
    closeModal('confirmReactivateModal');

    try {
        const response = await fetch('db/leads-update-status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                id: leadId, 
                status: 'En Seguimiento', 
                lost_reason: null // Limpiar la razón de pérdida/descarte en la DB
            })
        });
        const data = await response.json();

        if (data.success) {
            if(typeof showToast === 'function') showToast("Lead reactivado con éxito. Será visible en el panel de Leads en Seguimiento.", 'success');
            
            setTimeout(() => {
                 location.reload(); 
            }, 500);

        } else {
            if(typeof showToast === 'function') showToast(`Error al reactivar: ${data.message || 'Error desconocido'}`, 'error');
        }
    } catch (error) {
        console.error('Error de conexión al reactivar:', error);
        if(typeof showToast === 'function') showToast("Error de conexión al servidor.", 'error');
    }
}

// =================================================================
// LÓGICA DE ELIMINACIÓN (MODAL)
// =================================================================
function openDeleteModal(leadId, leadName) {
    currentLeadIdToDelete = leadId;
    
    const nameDisplay = document.getElementById('delete-lead-name-display');
    if(nameDisplay) nameDisplay.textContent = leadName;

    openModal('confirmDeleteModal');
}

async function confirmDeleteLogic() {
    const leadId = currentLeadIdToDelete;

    if (!leadId) {
        closeModal('confirmDeleteModal');
        return;
    }
    
    if(typeof showToast === 'function') showToast("Eliminando lead permanentemente...", 'info');
    closeModal('confirmDeleteModal');

    try {
        const response = await fetch('db/leads-delete.php', { // Usamos leads-delete.php, asumiendo que elimina permanentemente
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: leadId })
        });
        const data = await response.json();

        if (data.success) {
            if(typeof showToast === 'function') showToast("Lead eliminado permanentemente.", 'success');
            
            setTimeout(() => {
                 location.reload(); 
            }, 500);

        } else {
            if(typeof showToast === 'function') showToast(`Error al eliminar: ${data.message || 'Error desconocido'}`, 'error');
        }
    } catch (error) {
        console.error('Error de conexión al eliminar:', error);
        if(typeof showToast === 'function') showToast("Error de conexión al servidor.", 'error');
    }
}

// =================================================================
// FILTROS Y EVENT LISTENERS
// =================================================================

function filterTable() {
    const sourceFilter = document.getElementById('filter-source').value;
    const reasonFilter = document.getElementById('filter-reason').value;
    const statusFilter = document.getElementById('filter-status') ? document.getElementById('filter-status').value : ''; 
    
    const tableBody = document.getElementById('discarded-leads-table').querySelector('tbody');
    const rows = tableBody.querySelectorAll('tr');
    let visibleCount = 0;

    rows.forEach(row => {
        if (row.querySelector('td[colspan="5"]')) {
            row.style.display = 'none'; 
            return;
        }

        const source = row.dataset.source;
        const reason = row.dataset.reason;
        const status = row.dataset.status ? row.dataset.status.toUpperCase() : '';
        
        let show = true;

        if (sourceFilter && source !== sourceFilter) { show = false; }
        if (reasonFilter && reason !== reasonFilter) { show = false; }
        if (statusFilter && statusFilter.toUpperCase() !== status) { show = false; }

        row.style.display = show ? '' : 'none';
        if (show) visibleCount++;
    });

    const noResultsRow = tableBody.querySelector('td[colspan="5"]');
    if (noResultsRow) {
        const noResultsTr = noResultsRow.closest('tr');
        if (visibleCount === 0 && rows.length > 1) {
            noResultsTr.style.display = '';
            noResultsRow.textContent = "No hay leads que coincidan con los filtros seleccionados.";
        } else {
            noResultsTr.style.display = 'none';
        }
    }
}

function resetFilters() {
    document.getElementById('filter-source').value = '';
    document.getElementById('filter-reason').value = '';
    const statusSelect = document.getElementById('filter-status');
    if(statusSelect) statusSelect.value = '';
    filterTable();
    lucide.createIcons();
}

document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();

    // Event Listeners para los botones de confirmación de los modales
    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    if (confirmDeleteButton) {
        confirmDeleteButton.addEventListener('click', confirmDeleteLogic);
    }
    
    const confirmReactivateButton = document.getElementById('confirm-reactivate-button');
    if (confirmReactivateButton) {
        confirmReactivateButton.addEventListener('click', confirmReactivateLogic);
    }

    // Lógica menú móvil
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (mobileMenuButton && sidebar && sidebarOverlay) {
        mobileMenuButton.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
    }

    filterTable();
});
</script>
</body>
</html>