<?php
// full-growth-dashboard.php
require_once(__DIR__ . '/core/init.php');

// Verificación de existencia para evitar un warning/error si $logo_url no está definido
$logo_url_main = htmlspecialchars($logo_url ?? ''); 

// Es una buena práctica asegurar que la hora del servidor es correcta antes de usar date().
// Aunque no está en el ámbito de un "arreglo de error", es una nota de buenas prácticas.
$current_period_default = date('Y-m'); 
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Reporte de Crecimiento Empresarial <?php echo htmlspecialchars($branding['full_title'] ?? 'Dashboard'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? ''); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? ''); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url ?? ''); ?>"> 

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        /* CORRECCIÓN: 'inset: 0;' es sintaxis de Tailwind o CSS moderna. Si es CSS puro, es mejor ser explícito: */
        .fbi-overlay {
            position: fixed; 
            top: 0; 
            right: 0; 
            bottom: 0; 
            left: 0; 
            background: var(--color-primary); 
            z-index: 9999;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
        }
        .loading-container {
            position: relative;
            width: 200px; 
            height: 200px; 
            margin-bottom: 20px;
        }
        .radar {
            width: 100%; height: 100%; 
            border: 2px solid rgba(158,20,40,0.2);
            border-top: 4px solid var(--color-secondary); 
            border-radius: 50%;
            animation: spin 1s linear infinite;
            box-shadow: 0 0 15px rgba(158,20,40,0.5);
            position: absolute;
            top: 0; left: 0;
        }
        .logo-center {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%);
            width: 70%; 
            height: 70%; 
            border-radius: 50%;
            background-color: white; 
            padding: 5px;
            object-fit: contain;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        .blink { animation: blinker 1s linear infinite; }
        @keyframes blinker { 50% { opacity: 0; } }
        
        /* CORRECCIÓN: Las propiedades Tailwind como 'bg: white;' no son CSS estándar. Se reemplazaron con sintaxis CSS pura. */
        #results-dropdown {
            position: absolute; 
            width: 100%; 
            background-color: white; 
            z-index: 50;
            max-height: 300px; overflow-y: auto; border: 1px solid #e2e8f0;
            border-radius: 0.5rem; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        }
        .result-item:hover { background-color: #f1f5f9; cursor: pointer; }

        .chart-bar-container {
            display: flex;
            align-items: flex-end;
            gap: 4px;
            height: 150px;
            padding-top: 10px;
            margin-top: 10px;
        }
        .chart-bar {
            width: 8.33%; 
            background-color: var(--color-secondary);
            transition: height 0.5s ease-out;
            border-top-left-radius: 2px;
            border-top-right-radius: 2px;
            position: relative;
            cursor: pointer;
        }
        .chart-bar-label {
            position: absolute;
            bottom: -20px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            font-weight: bold;
            color: #64748b;
        }
        .chart-bar-tooltip {
            position: absolute;
            top: -30px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #1f2937;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: bold;
            white-space: nowrap;
            opacity: 0;
            transition: opacity 0.2s;
            pointer-events: none;
        }
        .chart-bar:hover .chart-bar-tooltip {
            opacity: 1;
        }
    </style>
</head>
<body data-page-title="Dashboard de Crecimiento"
data-page-subtitle="Análisis de Ventas y Conversión"
data-page-icon="pie-chart">
    <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>
    <div id="task-panel-overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
    
    <?php include 'menu.php'; ?>
    
    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-md 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">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="fbi-screen" class="fbi-overlay hidden">
            <div class="loading-container">
                <div class="radar"></div>
                                <img src="<?php echo htmlspecialchars($biz['logo_url'] ?? ''); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="logo-center">
            </div>
            <div id="fbi-text" class="text-2xl font-bold uppercase tracking-widest mb-2 text-white">INICIANDO...</div>
            <div id="fbi-subtext" class="text-md uppercase font-semibold text-gray-400 ">Esperando conexión segura</div>
        </div>

                <div class="flex min-h-screen">
                        <div class="flex-1 p-6 md:p-10"> 
                <div class="flex flex-col items-center text-center mb-8">
                    <?php if (!empty($biz['logo_url'])): ?>
                        <div class="max-w-60 mb-4 flex items-center justify-center">
                            <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo" class="max-w-full max-h-full object-contain">
                        </div>
                    <?php endif; ?>
                    <h1 class="text-4xl font-black uppercase text-[var(--color-primary)] mb-2">Reporte De Rendimiento</h1>
                </div>

                <div class="max-w-3xl mx-auto mb-10 relative">
                    <div class="relative max-w-xl mx-auto">
                        <div class="flex items-center w-full shadow-lg rounded-2xl overflow-hidden border-2 border-gray-200 focus-within:border-[var(--color-secondary)] transition-all duration-300">
                            <div class="relative flex-grow">
                                <input type="text" id="search-input" class="w-full h-14 p-4 pl-14 pr-4 bg-white focus:outline-none text-base font-semibold text-gray-700 placeholder-gray-500 border-none ring-0" placeholder="Buscar Por Fecha..." autocomplete="off">
                                <i data-lucide="search" class="absolute left-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400 pointer-events-none"></i>
                                <div id="input-loading" class="absolute right-4 top-1/2 transform -translate-y-1/2 hidden"><i data-lucide="loader-2" class="w-6 h-6 animate-spin text-indigo-500"></i></div>
                            </div>
                            <button id="trigger-search-button" class="flex items-center justify-center h-14 px-6 bg-[var(--color-secondary)] uppercase text-white font-bold hover:bg-opacity-90 focus:outline-none"><i data-lucide="user-search" class="w-5 h-5 mr-2"></i> Ver Reporte</button>
                        </div>
                    </div> 
                    
             <div id="results-dropdown" class="bg-white hidden mt-1"></div>
            </div>

            <div id="profile-view" class="hidden animate-fade-in">
                        <div class="bg-white rounded-2xl shadow-xl overflow-hidden mb-6 border-t-4 border-[var(--color-secondary)]">
                            <div class="p-8 flex flex-col md:flex-row items-center gap-6 justify-between">
                                <div class="flex items-center gap-4">
                                    <div class="w-24 h-24 bg-[var(--color-secondary)] rounded-full flex items-center justify-center text-3xl font-black text-white border-4 border-white shadow"><i data-lucide="calendar" class="w-8 h-8 text-white"></i></div>
                                    <div>
                                        <h2 id="p-month" class="text-3xl font-black text-gray-800 uppercase leading-none">...</h2>
                                        <div class="flex flex-col"><p id="p-range" class="text-md text-gray-500 font-bold mt-1">...</p><p id="p-status-text" class="text-md font-black text-[var(--color-secondary)] mt-1 uppercase animate-pulse">...</p></div>
                                    </div>
                                </div>
                                <div class="text-right bg-gray-50 p-4 rounded-xl border border-gray-100 min-w-[200px]">
                                    <p class="text-xs font-black text-gray-700 uppercase tracking-wider mb-2">Top Fuentes De Tráfico</p>
                                    <div id="top-sources-list" class="space-y-1"><span class="text-sm text-gray-400 italic">Cargando...</span></div>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                             <h3 class="font-black text-2xl text-gray-800 uppercase flex gap-2 items-center mb-4"><i data-lucide="activity" class="w-5 h-5 text-[var(--color-secondary)]"></i> Actividad Diaria</h3>
                            <div class="w-full h-64"><canvas id="dailyChart"></canvas></div>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
                            <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                                <div class="flex justify-between items-center mb-4 border-b pb-2"><h3 class="font-black text-2xl text-[var(--color-primary)] uppercase flex gap-2 items-center"><i data-lucide="user-plus" class="w-5 h-5 text-[var(--color-secondary)]"></i> Leads Nuevos</h3><span class="bg-[var(--color-highlight)] text-black px-3 py-1 rounded-full text-sm font-bold" id="count-leads">0</span></div>
                                <div class="no-scroll-list"><table class="w-full text-left"><thead class="text-xs text-gray-500 uppercase bg-gray-50 border-b"><tr><th class="p-3">Nombre</th><th class="p-3">Fuente</th><th class="p-3 text-right">Fecha</th></tr></thead><tbody id="list-leads" class="text-sm"></tbody></table></div>
                            </div>

                            <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                                <div class="flex justify-between items-center mb-4 border-b pb-2"><h3 class="font-black text-2xl text-[var(--color-primary)] uppercase flex gap-2 items-center"><i data-lucide="check-circle" class="w-5 h-5 text-[var(--color-secondary)]"></i> Clientes</h3><div class="flex items-center gap-3"><div class="text-right"><p class="text-[10px] text-gray-400 uppercase font-bold">Convsión De Clientes</p><p class="text-lg font-black text-[var(--color-secondary)]" id="conversion-rate">0%</p></div><span class="bg-[var(--color-success)] text-white px-3 py-1 rounded-full text-md font-bold" id="count-clients">0</span></div></div>
                                <div class="no-scroll-list"><table class="w-full text-left"><thead class="text-xs text-gray-500 uppercase bg-gray-50 border-b"><tr><th class="p-3">Cliente</th><th class="p-3 text-right">Fecha</th></tr></thead><tbody id="list-clients" class="text-sm"></tbody></table></div>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                                <h3 class="font-black text-2xl text-gray-800 uppercase mb-4 flex gap-2 items-center border-b pb-3"><i data-lucide="calendar" class="w-5 h-5 text-[var(--color-secondary)]"></i> Citas Agendadas</h3>
                                <div id="list-appointments" class="grid grid-cols-1 gap-2 no-scroll-list"></div>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                                <h3 class="font-black text-2xl text-gray-800 uppercase mb-4 flex gap-2 items-center border-b pb-3"><i data-lucide="clipboard-list" class="w-5 h-5 text-[var(--color-secondary)]"></i> Cotizaciones</h3>
                                <div id="list-estimates" class="grid grid-cols-1 gap-2 no-scroll-list"></div>
                            </div>
                        </div>
                    </div>  
                        <?php @include 'brand/powered.php'; ?>
                </div>
        
                    </div>

    </main> </div> <script>
    lucide.createIcons();
    const searchInput = document.getElementById('search-input');
    const dropdown = document.getElementById('results-dropdown');
    const fbiScreen = document.getElementById('fbi-screen');
    const profileView = document.getElementById('profile-view');
    const inputLoading = document.getElementById('input-loading');
    let debounceTimer;
    let myChart = null; 

    const formatDate = (str) => {
        if(!str) return '-';
        const d = new Date(str.replace(/-/g, '/')); 
        if(isNaN(d.getTime())) return str; 
        const day = d.getDate();
        const month = d.toLocaleString('es-ES', { month: 'short' });
        return `${day} de ${month.charAt(0).toUpperCase() + month.slice(1)}`;
    };

    document.addEventListener('DOMContentLoaded', () => {
        loadReport('<?php echo $current_period_default; ?>'); 
    });

    const performSearch = (val) => {
        clearTimeout(debounceTimer);
        dropdown.innerHTML = ''; 
        inputLoading.classList.remove('hidden');
        // SUGERENCIA: Añadir un chequeo para val.trim().length === 0 para un mejor manejo del "focus"
        fetch(`db/search-growth-periods.php?q=${encodeURIComponent(val)}`)
            .then(res => res.json())
            .then(data => {
                inputLoading.classList.add('hidden');
                renderDropdown(data);
            })
            .catch(err => { console.error(err); inputLoading.classList.add('hidden'); });
    };

    searchInput.addEventListener('input', (e) => { 
        // Lógica de debounce para evitar demasiadas peticiones al escribir
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => performSearch(e.target.value.trim()), 300); 
    });
    
    // CORRECCIÓN: Se añade el chequeo de trim() para evitar la búsqueda si solo hay espacios.
    searchInput.addEventListener('focus', () => { if(searchInput.value.trim() === '') performSearch(''); }); 

    // Agregar un event listener para ocultar el dropdown cuando se hace click fuera
    document.addEventListener('click', (e) => {
        if (!document.querySelector('.max-w-3xl.mx-auto.mb-10.relative').contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });

    function renderDropdown(list) {
        dropdown.innerHTML = ''; 
        if(!list || list.length === 0) { dropdown.classList.add('hidden'); return; }
        dropdown.classList.remove('hidden');
        list.forEach(item => {
            const div = document.createElement('div');
            div.className = "result-item p-3 border-b border-gray-100 flex justify-between items-center cursor-pointer hover:bg-gray-50";
            div.innerHTML = `<span class="font-bold text-gray-700">${item.name}</span><i data-lucide="chevron-right" class="text-gray-400 w-4 h-4"></i>`;
            div.onclick = () => { 
                dropdown.classList.add('hidden'); 
                searchInput.value = item.name; 
                loadReport(item.id); 
            };
            dropdown.appendChild(div);
        });
        lucide.createIcons();
    }

    document.getElementById('trigger-search-button').addEventListener('click', () => {
        // En caso de querer forzar la carga del reporte con el valor actual del input
        loadReport(searchInput.value.trim()); 
    });


    function loadReport(id) {
        if(!id || id.length === 0) {
            alert("Debe seleccionar o buscar un periodo válido.");
            return;
        }
        fbiScreen.classList.remove('hidden');
        profileView.classList.add('hidden');
        
        fetch(`db/get-growth-periods.php?id=${id}`)
            .then(async response => {
                if (!response.ok) {
                    // SUGERENCIA: Mejorar el manejo de errores de status 4xx/5xx
                    throw new Error("Error de autorización o conexión (Status " + response.status + ")");
                }
                return response.json();
            })
            .then(data => {
                setTimeout(() => {
                    // CORRECCIÓN/MEJORA: Comprobación de datos recibidos antes de usarlos
                    if(!data || !data.period_info || !data.chart_data || !data.metrics) {
                        console.warn("Datos incompletos/incorrectos recibidos:", data);
                        throw new Error("Datos incompletos recibidos del servidor.");
                    }
                    renderDashboard(data);
                    fbiScreen.classList.add('hidden');
                    profileView.classList.remove('hidden');
                }, 800);
            })
            .catch(err => {
                console.error("Dashboard Error:", err);
                alert("No se pudo cargar el reporte: " + err.message);
                fbiScreen.classList.add('hidden');
            });
    }

    function renderDashboard(data) {
        document.getElementById('p-month').innerText = data.period_info.label || 'Mes Actual';
        document.getElementById('p-range').innerText = data.period_info.range;
        const statusText = document.getElementById('p-status-text');
        statusText.innerText = data.period_info.status_text;
        // CORRECCIÓN/MEJORA: Asegurar que la clase CSS 'animate-pulse' solo se aplique si está activo.
        statusText.className = data.period_info.is_active ? "text-md font-black bg-[var(--color-secondary)] text-white mt-1 px-3 py-1 rounded-full uppercase animate-pulse" : "text-sm font-bold text-gray-400 mt-1 uppercase"; 

        const sourcesDiv = document.getElementById('top-sources-list');
        sourcesDiv.innerHTML = '';
        const srcs = data.chart_data.sources || {};
        const keys = Object.keys(srcs);
        if(keys.length > 0) {
            keys.slice(0, 3).forEach(k => {
                sourcesDiv.innerHTML += `<div class="flex justify-between text-sm"><span class="font-bold text-gray-600">${k}</span><span class="font-black text-[var(--color-primary)]">${srcs[k]} Leads</span></div>`;
            });
        } else { sourcesDiv.innerHTML = '<span class="text-xs text-gray-400">Sin datos</span>'; }

        const ctx = document.getElementById('dailyChart').getContext('2d');
        if(myChart) myChart.destroy();
        myChart = new Chart(ctx, {
            type: 'line',
            data: {
                // CORRECCIÓN/MEJORA: Asegurar que los datos de la gráfica sean arrays para Chart.js
                labels: data.chart_data.labels || [],
                datasets: [
                    { label: 'Leads', data: data.chart_data.leads || [], borderColor: '#2563eb', backgroundColor: 'rgba(37, 99, 235, 0.1)', borderWidth: 2, fill: true, tension: 0.3 },
                    { label: 'Citas', data: data.chart_data.appointments || [], borderColor: '#10b981', backgroundColor: 'transparent', borderWidth: 2, borderDash: [5, 5], tension: 0.3 }
                ]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
        });

        // Se usa parseInt o parseFloat con ?? 0 para garantizar que sea un número.
        document.getElementById('count-leads').innerText = parseInt(data.metrics.leads) || 0; 
        const leadBody = document.getElementById('list-leads'); leadBody.innerHTML = '';
        (data.leads_list || []).forEach(l => {
            leadBody.innerHTML += `<tr class="border-b border-gray-50 hover:bg-gray-50"><td class="p-3 font-bold text-gray-700 text-md">${l.first_name || ''} ${l.last_name || ''}<div class="text-xs text-gray-400 font-normal">${l.company || ''}</div></td><td class="p-3 text-xs text-gray-500">${l.source || 'Web'}</td><td class="p-3 text-right text-xs font-mono text-gray-500">${formatDate(l.created_at)}</td></tr>`;
        });

        // Se usa parseInt o parseFloat con ?? 0 para garantizar que sea un número.
        document.getElementById('count-clients').innerText = parseInt(data.metrics.clients) || 0; 
        // Conversión a string para mostrar el '%'
        document.getElementById('conversion-rate').innerText = (parseFloat(data.metrics.conversion) || 0) + '%'; 
        const clientBody = document.getElementById('list-clients'); clientBody.innerHTML = '';
        (data.clients_list || []).forEach(c => {
            // CORRECCIÓN/MEJORA: Uso del operador '||' en los campos para evitar mostrar 'undefined'
            clientBody.innerHTML += `<tr class="border-b border-gray-50 hover:bg-green-50"><td class="p-3 font-bold text-gray-800 text-sm">${c.first_name || ''} ${c.last_name || ''}<div class="text-xs text-[var(--color-success)] font-bold">${c.company || 'Cliente'}</div></td><td class="p-3 text-right text-xs font-mono text-gray-500">${formatDate(c.created_at)}</td></tr>`;
        });

        const apptList = document.getElementById('list-appointments'); apptList.innerHTML = '';
        (data.appointments_list || []).forEach(a => {
            // CORRECCIÓN/MEJORA: Uso del operador '||' en los campos para evitar mostrar 'undefined'
            let dn = (a.first_name || '') + ' ' + (a.last_name || ''); if(!dn.trim()) dn = a.company || 'Prospecto';
            apptList.innerHTML += `<div class="p-3 border-l-4 border-[var(--color-highlight)] bg-gray-50 rounded shadow-sm"><div class="font-bold text-gray-800 text-sm">${dn}</div><div class="flex justify-between text-xs text-gray-500 mt-2"><span><i data-lucide="clock" class="w-3 h-3 inline"></i> ${formatDate(a.appointment_date)}</span><span class="uppercase font-black text-[var(--color-secondary)]">${a.status || 'Pendiente'}</span></div></div>`;
        });

        const estList = document.getElementById('list-estimates'); estList.innerHTML = '';
        (data.estimates_list || []).forEach(e => {
            // CORRECCIÓN/MEJORA: Uso del operador '||' en los campos para evitar mostrar 'undefined'
            let dn = (e.first_name || '') + ' ' + (e.last_name || ''); if(!dn.trim()) dn = 'Prospecto';
            estList.innerHTML += `<div class="flex justify-between items-center p-3 border-b border-gray-200 bg-white rounded hover:bg-gray-50"><div><div class="font-bold text-gray-700 text-sm">${dn}</div><div class="text-xs text-gray-400">#${e.external_id || 'N/A'}</div></div><div class="text-right"><div class="text-xs text-gray-500">${formatDate(e.estimate_date)}</div><div class="text-[10px] uppercase font-black text-[var(--color-secondary)]">${e.status || 'Pendiente'}</div></div></div>`;
        });
        lucide.createIcons();
    }
</script>
</body>
</html>