<?php
// full-leads-profile.php
require_once(__DIR__ . '/core/init.php');
$logo_url_for_spinner = htmlspecialchars($branding['favicon'] ?? ''); 
$logo_url_main = htmlspecialchars($logo_url ?? '');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Perfil De Prospecto 360 <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" 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>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
 
    <style>
        .fbi-overlay {
            position: fixed; inset: 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; } }
        
        #results-dropdown {
            position: absolute; width: 100%; bg: 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="Buscador Perfil De Prospecto 360"
    data-page-subtitle="Información detallada para seguimiento de prospectos"
    data-page-icon="target">
    
    <div id="toast-container" class="toast-container"></div>
    <?php include 'files/gtm-body.php'; ?>  

<div class="relative min-h-screen md:flex">
    <?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">

        <main 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 <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" 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">Busqueda Avanzada</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 Prospecto..." 
            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>

        <button id="clear-search" class="absolute right-4 top-1/2 transform -translate-y-1/2 hidden
                                         text-gray-400 hover:text-[var(--color-secondary)] transition-colors duration-200
                                         focus:outline-none" 
                title="Limpiar búsqueda">
            <i data-lucide="x-circle" class="w-6 h-6"></i>
        </button>
    </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 transition-all duration-300 whitespace-nowrap
               focus:outline-none"
        title="Buscar Cliente">
        <i data-lucide="user-search" class="w-5 h-5 mr-2"></i> Buscar Lead
    </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">
                            <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">
                                <span id="p-initials">--</span>
                            </div>
                            <div class="text-center md:text-left flex-1">
                                <h2 id="p-name" class="text-4xl font-black text-gray-800 uppercase leading-none mb-1">...</h2>
                                <p id="p-company" class="text-xl text-[var(--color-secondary)] font-bold mb-2">...</p>
                                <span id="p-status-badge" class="px-3 py-1 rounded-full text-xs font-bold uppercase bg-gray-200 text-gray-600">...</span>
                            </div>
                            <div id="p-loyalty-metric" class="text-right p-4 bg-gray-50 rounded-lg shadow-inner border border-gray-200">
                                <p class="text-xs uppercase font-black text-gray-500 mb-1">Prioridad De Seguimiento</p>
                                <p class="text-2xl font-black uppercase text-[var(--color-secondary)] leading-none" id="p-priority">--</p>
                            </div>
                            <div class="flex gap-2 hidden">
                                 <a id="btn-wa" href="#" target="_blank" class="p-3 bg-[var(--color-success)] text-white rounded-lg hover:bg-[var(--color-success)]"><i data-lucide="message-circle"></i></a>
                                 <a id="btn-tel" href="#" class="p-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"><i data-lucide="phone"></i></a>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        
                        <div class="space-y-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-[var(--color-primary)] uppercase">Información Contacto</h3>
                                <p><span id="p-code-creation" class="text-md uppercase font-bold text-[var(--color-secondary)]"></span></p>
                                <ul class="space-y-4 text-md font-medium text-gray-600 mt-4">
                                    <li class="flex gap-3"><i data-lucide="mail" class="text-[var(--color-secondary)] w-5"></i> <span id="p-email">--</span></li>
                                    <li class="flex gap-3"><i data-lucide="phone" class="text-[var(--color-secondary)] w-5"></i> <span id="p-phone-main">--</span></li>
                                    <li class="flex gap-3"><i data-lucide="smartphone" class="text-[var(--color-secondary)] w-5"></i> <span id="p-mobile">--</span></li>
                                    <li class="flex gap-3"><i data-lucide="map-pin" class="text-[var(--color-secondary)] w-5"></i> <span id="p-address">--</span></li>
                                    <li class="flex gap-3"><i data-lucide="database" class="text-[var(--color-secondary)] w-5"></i> Fuente: <span id="p-source" class="font-bold">--</span></li>
                                </ul>
                            </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-[var(--color-primary)] uppercase mb-4 border-b pb-2 flex items-center gap-2">
                                    <i data-lucide="activity" class="w-5 h-5 text-[var(--color-secondary)]"></i> Estado Actual
                                </h3>
                                <div id="lead-status-container">
                                    <div class="text-gray-400 italic text-md">--</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-[var(--color-primary)] uppercase mb-4 border-b pb-2 flex items-center gap-2">
                                    <i data-lucide="briefcase" class="w-5 h-5 text-[var(--color-secondary)]"></i> Servicios De Interés
                                </h3>
                                <div id="list-services" class="space-y-2">
                                    <div class="text-gray-400 italic text-md">Sin servicios definidos</div>
                                </div>
                            </div>
                            
                        </div>

                        <div class="lg:col-span-2 space-y-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-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                                    <i data-lucide="clipboard-list" class="w-6 h-6 text-[var(--color-secondary)]"></i> Cotizaciones Solicitadas
                                </h3>
                                <div id="list-estimates" class="space-y-2 mt-4"></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-[var(--color-primary)] uppercase mb-4 flex gap-2">
                                    <i data-lucide="calendar" class="w-6 h-6 text-[var(--color-secondary)]"></i> Citas Agendadas
                                </h3>
                                <div id="list-appointments" class="space-y-2"></div>
                            </div>

                            <div id="notes-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                                <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2">
                                    <i data-lucide="sticky-note" class="w-6 h-6 text-[var(--color-secondary)]"></i> Notas de Seguimiento
                                </h3>
                                <div id="list-notes" class="space-y-3"></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-[var(--color-primary)] uppercase mb-4 flex gap-2">
                                    <i data-lucide="check-square" class="w-6 h-6 text-[var(--color-secondary)]"></i> Tareas Pendientes
                                </h3>
                                <div id="list-tasks" class="space-y-2"></div>
                            </div>
                            
                        </div>
                    </div>
                </div>  
                
    <?php @include 'brand/powered.php'; ?>
        
            </main>
        </div>
    </div>

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

        // Formato de Fechas
        const formatDateUserFriendly = (dateString) => {
            if (!dateString) return '--';
            try {
                const datePart = dateString.split(' ')[0];
                const date = new Date(datePart.replace(/-/g, '/'));
                const options = { day: '2-digit', month: 'long', year: 'numeric' };
                let formattedDate = date.toLocaleDateString('es-ES', options);
                return formattedDate.replace(' de ', ' ');
            } catch { return dateString.split(' ')[0] || '--'; }
        };

        const formatNumberWithCommas = (number) => {
            if (typeof number !== 'number') return number;
            return number.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        };

        // Búsqueda
        searchInput.addEventListener('input', (e) => {
            const val = e.target.value.trim();
            clearTimeout(debounceTimer);
            dropdown.innerHTML = '';
            dropdown.classList.add('hidden');

            if(val.length < 2) return;
            inputLoading.classList.remove('hidden');

            debounceTimer = setTimeout(() => {
                // LLAMADA AL NUEVO ENDPOINT DE LEADS
                fetch(`db/search-leads.php?q=${encodeURIComponent(val)}`)
                    .then(res => res.json())
                    .then(data => {
                        inputLoading.classList.add('hidden');
                        renderDropdown(data);
                    });
            }, 300);
        });

        function renderDropdown(list) {
            if(list.length === 0) 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";
                const fullName = `${item.first_name || ''} ${item.last_name || ''}`.trim();
                
                div.innerHTML = `
                    <div>
                        <div class="font-bold text-gray-800 uppercase">${fullName || item.company}</div>
                        <div class="text-md text-gray-500">${item.company || 'Prospecto'} (${item.source})</div>
                    </div>
                    <span class="text-lg font-black px-2 py-1 rounded text-white bg-[var(--color-highlight)]">LEAD</span>
                `;
                
                div.addEventListener('click', () => {
                    dropdown.classList.add('hidden');
                    searchInput.value = fullName || item.company;
                    startFBILoading(item.id);
                });
                dropdown.appendChild(div);
            });
        }

        function startFBILoading(id) {
            fbiScreen.classList.remove('hidden');
            profileView.classList.add('hidden');
            
            const steps = [
                { t: "CONECTANDO...", s: "Accediendo a base de prospectos" },
                { t: "ANALIZANDO...", s: "Recuperando historial y cotizaciones" },
                { t: "CARGANDO...", s: "Generando perfil 360" }
            ];
            let step = 0;
            const fbiText = document.getElementById('fbi-text');
            const fbiSub = document.getElementById('fbi-subtext');

            const interval = setInterval(() => {
                if(step < steps.length) {
                    fbiText.innerText = steps[step].t;
                    fbiSub.innerText = steps[step].s;
                    step++;
                }
            }, 600);

            // LLAMADA AL NUEVO ENDPOINT DE DETALLE LEAD
            fetch(`db/get-leads-profile.php?id=${id}`)
                .then(res => res.json())
                .then(data => {
                    setTimeout(() => {
                        clearInterval(interval);
                        if(data.error) {
                            alert(`Error: ${data.error}`);
                            fbiScreen.classList.add('hidden');
                            return;
                        }
                        renderProfileData(data);
                        fbiScreen.classList.add('hidden');
                        profileView.classList.remove('hidden');
                    }, 2000); 
                })
                .catch(error => {
                    clearInterval(interval);
                    alert(`Error: ${error.message}`);
                    fbiScreen.classList.add('hidden');
                });
        }

        function renderProfileData(data) {
            const p = data.profile;
            if (!p) return alert("Error cargando perfil");
            const info = data.lead_info;

            const initials = (firstName, lastName) => {
                const first = (firstName || 'X')[0];
                const last = (lastName || 'X')[0];
                return (first + last).toUpperCase();
            };

            const statusColor = (status) => {
                if (!status) return 'bg-gray-100 text-gray-800';
                const s = status.toLowerCase();
                if(s.includes('ganada') || s.includes('convertida') || s.includes('nuevo')) return 'bg-[var(--color-success)]/[0.2] text-[var(--color-success)]';
                if(s.includes('perdida') || s.includes('descartado')) return 'bg-[var(--color-secondary)] text-white';
                return 'bg-[var(--color-highlight)]/[0.2] text-[var(--color-highlight)]';
            };

            // Header
            const fullName = `${p.first_name || ''} ${p.last_name || ''}`.trim();
            document.getElementById('p-name').innerText = fullName || p.company || 'PROSPECTO';
            document.getElementById('p-company').innerText = p.company || 'Sin Empresa';
            document.getElementById('p-initials').innerText = initials(p.first_name || p.company, p.last_name);
            document.getElementById('p-status-badge').innerText = info.status || 'NUEVO';
            
            // Priority (Mapeo visual)
            const priority = info.priority || 'Normal';
            const priorityEl = document.getElementById('p-priority');
            priorityEl.innerText = priority;
            if(priority === 'Alta') priorityEl.className = "text-1xl font-black uppercase text-[var(--color-secondary)] leading-none";
            else if(priority === 'Baja') priorityEl.className = "text-2xl font-black uppercase text-gray-500 leading-none";
            else priorityEl.className = "text-2xl font-black uppercase text-[var(--color-highlight)] leading-none";

            // Botones
            const num = (p.mobile || p.phone || '').replace(/[^0-9]/g, '');
            document.getElementById('btn-wa').href = num ? `https://wa.me/${num}` : '#';
            document.getElementById('btn-tel').href = num ? `tel:${num}` : '#';

            // Contacto
            document.getElementById('p-email').innerText = p.email || '--';
            document.getElementById('p-phone-main').innerText = p.phone || '--';
            document.getElementById('p-mobile').innerText = p.mobile || '--';
            const address = [p.street_address, p.city, p.state_province, p.zip_code].filter(Boolean).join(', ');
            document.getElementById('p-address').innerText = address || '--';
            document.getElementById('p-source').innerText = info.source || '--';
            document.getElementById('p-code-creation').innerText = p.created_at ? `Registrado: ${formatDateUserFriendly(p.created_at)}` : '';

            // Estado (Reemplazo de Ruta)
            const statusContainer = document.getElementById('lead-status-container');
            statusContainer.innerHTML = `
                <div class="p-3 bg-[var(--color-highlight)]/[0.1] rounded-lg">
                    <p class="font-bold text-gray-800 uppercase">${info.status}</p>
                    ${info.lost_reason ? `<p class="text-xs text-[var(--color-secondary)] mt-1">Motivo: ${info.lost_reason}</p>` : ''}
                </div>
            `;

            // Servicios de Interés
            const servContainer = document.getElementById('list-services');
            servContainer.innerHTML = '';
            if (data.services_interest && data.services_interest.length > 0) {
                data.services_interest.forEach(s => {
                    servContainer.innerHTML += `<div class="p-2 bg-[var(--color-secondary)]/[0.1] text-[var(--color-primary)] text-md rounded font-bold">${s}</div>`;
                });
            } else {
                servContainer.innerHTML = '<div class="text-gray-400 italic text-md">No especificado</div>';
            }

            // Cotizaciones
            const estContainer = document.getElementById('list-estimates');
            estContainer.innerHTML = '';
            if (data.estimates && data.estimates.length > 0) {
                data.estimates.forEach(e => {
                    const st = e.status_seguimiento || e.status;
                    estContainer.innerHTML += `
                        <div class="flex justify-between border-b border-gray-100 py-2 items-center">
                            <span class="font-bold text-gray-700">#${e.external_id} (${formatDateUserFriendly(e.estimate_date)})</span>
                            <div class="text-right">
                                <span class="block font-black text-gray-900">$${formatNumberWithCommas(Number(e.total_amount))}</span>
                                <span class="text-xs uppercase font-bold px-2 py-0.5 rounded ${statusColor(st)}">${st}</span>
                            </div>
                        </div>`;
                });
            } else {
                estContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin cotizaciones.</div>';
            }

            // Citas
            const appContainer = document.getElementById('list-appointments');
            appContainer.innerHTML = '';
            if (data.appointments && data.appointments.length > 0) {
                data.appointments.forEach(a => {
                    appContainer.innerHTML += `
                        <div class="flex justify-between items-center border-b border-gray-100 py-2">
                            <div class="text-md font-bold text-gray-700">
                                ${formatDateUserFriendly(a.appointment_date)} (${a.appointment_time.substring(0,5)})
                            </div>
                            <span class="text-xs font-bold uppercase bg-gray-100 text-gray-600 px-2 py-0.5 rounded">${a.status}</span>
                        </div>`;
                });
            } else {
                appContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin citas agendadas.</div>';
            }

            // Notas
            const notesContainer = document.getElementById('list-notes');
            notesContainer.innerHTML = '';
            if (data.notes && data.notes.length > 0) {
                data.notes.forEach(n => {
                    notesContainer.innerHTML += `
                        <div class="p-3 bg-gray-100 rounded-lg">
                            <p class="text-md text-gray-800">${n.content}</p>
                            <span class="block text-xs text-gray-500 mt-1">${formatDateUserFriendly(n.created_at)}</span>
                        </div>`;
                });
            } else {
                notesContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin notas.</div>';
            }

            // Tareas
            const tasksContainer = document.getElementById('list-tasks');
            tasksContainer.innerHTML = '';
            if (data.tasks && data.tasks.length > 0) {
                data.tasks.forEach(t => {
                    const priorityClass = t.priority === 'Alta' ? 'text-[var(--color-secondary)]' : 'text-gray-600';
                    tasksContainer.innerHTML += `
                        <div class="p-2 border border-gray-100 rounded bg-white">
                            <span class="font-bold ${priorityClass}">${t.title}</span>
                            <span class="text-xs float-right text-gray-500">Vence: ${formatDateUserFriendly(t.due_date)}</span>
                        </div>`;
                });
            } else {
                tasksContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin tareas pendientes.</div>';
            }

            lucide.createIcons();
        }
    </script>
</body>
</html>