<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
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>Gestión de Rutas <?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'] ?? ''); ?>">
    <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>
    <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="Análisis De Rendimiento De Rutas"
data-page-subtitle="Observación De Rentabilidad y Capacidad De Staff"
data-page-icon="map">
    
<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">

        <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 Ruta..." 
            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> Analizar Ruta
    </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">
                                <i data-lucide="map-pin" class="w-12 h-12"></i>
                            </div>
                            <div class="text-center md:text-left flex-1">
                                <h2 id="r-name" class="text-4xl font-black text-gray-800 uppercase leading-none mb-1">...</h2>
                                <p id="r-day" class="text-2xl text-[var(--color-secondary)] font-bold">...</p>
                                <span id="r-status" class="px-3 py-1 rounded-full text-xs font-bold uppercase bg-gray-200 text-gray-600">ACTIVA</span>
                            </div>
                            
                            <div class="flex items-center gap-3 p-4 bg-gray-50 rounded-lg border border-gray-200">
                                <img id="r-staff-photo" src="brand/img/Placeholder.webp" class="w-12 h-12 rounded-full object-cover">
                                <div class="text-right">
                                    <p class="text-xs uppercase font-black text-gray-500">Staff Asignado</p>
                                    <p id="r-staff-name" class="text-lg font-bold text-gray-800">--</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6 mb-6">
                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <div class="flex justify-between items-center">
                                <div>
                                    <p class="text-gray-700 text-lg font-black uppercase">Valor Mensual Ruta</p>
                                    <p class="text-3xl font-black text-[var(--color-success)]">$<span id="kpi-value">0.00</span></p>
                                </div>
                                <i data-lucide="wallet" class="w-10 h-10 text-[var(--color-secondary)] opacity-20"></i>
                            </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">
                                <div>
                                    <p class="text-gray-700 text-lg font-black uppercase">Duración Estimada</p>
                                    <p class="text-3xl font-black text-blue-600"><span id="kpi-time">0</span> <span class="text-sm text-gray-400">Hrs</span></p>
                                </div>
                                <i data-lucide="clock" class="w-10 h-10 text-[var(--color-secondary)] opacity-20"></i>
                            </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">
                                <div>
                                    <p class="text-gray-700 text-lg font-black uppercase">Total Clientes</p>
                                    <p class="text-3xl font-black text-[var(--color-highlight)]" id="kpi-clients">0</p>
                                </div>
                                <i data-lucide="users" class="w-10 h-10 text-[var(--color-secondary)] opacity-20"></i>
                            </div>
                        </div>
                    </div>

                    <div id="capacity-alert" class="hidden mb-6 p-4 rounded-xl border-l-8 shadow-md flex items-center gap-4 bg-white">
                        <div id="capacity-icon-container"></div>
                        <div class="flex-1">
                            <div class="flex justify-between">
                                <h4 class="font-black text-2xl uppercase" id="capacity-title"></h4>
                                <p class="text-lg font-black uppercase"><span id="capacity-percent">0</span>% Ocupado</p>
                            </div>
                            <p class="text-md font-bold text-gray-600" id="capacity-msg"></p>
                            <div class="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                                <div id="capacity-bar" class="h-2.5 rounded-full" style="width: 0%"></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-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                            <i data-lucide="list" class="w-6 h-6 text-[var(--color-secondary)]"></i> Itinerario De Clientes
                        </h3>
                        <div class="overflow-x-auto">
                            <table class="w-full text-left border-collapse">
                                <thead>
                                    <tr class="text-gray-500 border-b-2 border-gray-100">
                                        <th class="p-3 text-xs uppercase font-bold">#</th>
                                        <th class="p-3 text-xs uppercase font-bold">Cliente</th>
                                        <th class="p-3 text-xs uppercase font-bold">Dirección</th>
                                        <th class="p-3 text-xs uppercase font-bold text-right">Tiempo</th>
                                        <th class="p-3 text-xs uppercase font-bold text-right">Valor</th>
                                    </tr>
                                </thead>
                                <tbody id="clients-table-body" class="text-sm text-gray-700">
                                    </tbody>
                            </table>
                        </div>
                    </div>

                </div>
                
    <?php @include 'brand/powered.php'; ?>


            </main>
        </div>
</div>

    <script>
        lucide.createIcons();
        
        // Rutas de API centralizadas para estandarización
        const API_ENDPOINTS = {
            SEARCH_ROUTES: 'db/search-routes.php',
            GET_ROUTE_PROFILE: 'db/get-routes-profile.php',
        };

        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;

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

            debounceTimer = setTimeout(() => {
                // Usa la constante para la URL
                fetch(`${API_ENDPOINTS.SEARCH_ROUTES}?q=${encodeURIComponent(val)}`)
                    .then(res => res.json())
                    .then(data => {
                        inputLoading.classList.add('hidden');
                        dropdown.innerHTML = '';
                        if(data.length > 0) {
                            dropdown.classList.remove('hidden');
                            data.forEach(item => {
                                const div = document.createElement('div');
                                div.className = "result-item p-3 border-b border-gray-100 cursor-pointer hover:bg-gray-50 flex justify-between items-center";
                                div.innerHTML = `
                                    <div>
                                        <div class="font-bold text-gray-800">${item.route_name}</div>
                                        <div class="text-xs text-gray-500">${item.route_day} - Staff: ${item.staff_name || 'Sin Asignar'}</div>
                                    </div>
                                    <i data-lucide="chevron-right" class="text-gray-400 w-4 h-4"></i>
                                `;
                                div.onclick = () => loadRoute(item.id);
                                dropdown.appendChild(div);
                            });
                            lucide.createIcons();
                        }
                    })
                    .catch(err => {
                        inputLoading.classList.add('hidden');
                        console.error(err);
                    });
            }, 300);
        });

        function loadRoute(id) {
            dropdown.classList.add('hidden');
            fbiScreen.classList.remove('hidden');
            profileView.classList.add('hidden');

            // Usa la constante para la URL
            fetch(`${API_ENDPOINTS.GET_ROUTE_PROFILE}?id=${id}`)
                .then(res => res.json())
                .then(data => {
                    setTimeout(() => {
                        if(data.error) {
                            alert(data.error);
                            fbiScreen.classList.add('hidden');
                            return;
                        }
                        renderRoute(data);
                        fbiScreen.classList.add('hidden');
                        profileView.classList.remove('hidden');
                    }, 1500);
                })
                .catch(err => {
                    alert("Error cargando ruta. Verifica que db/get-routes-profile.php exista.");
                    fbiScreen.classList.add('hidden');
                    console.error(err);
                });
        }

        function renderRoute(data) {
            const r = data.route;
            const m = data.metrics;
            const cap = data.capacity;

            // Header
            document.getElementById('r-name').innerText = r.route_name;
            document.getElementById('r-day').innerText = r.route_day;
            document.getElementById('r-staff-name').innerText = r.first_name ? `${r.first_name} ${r.last_name}` : 'Sin Asignar';
            // Lógica para usar foto de perfil o placeholder
            const staffPhotoUrl = r.profile_photo_url && r.profile_photo_url.trim() !== '' 
                                ? r.profile_photo_url 
                                : 'brand/img/Placeholder.webp';
            document.getElementById('r-staff-photo').src = staffPhotoUrl;

            // KPIs
            document.getElementById('kpi-value').innerText = m.total_value;
            // Formato de tiempo HH:MM con relleno
            const minutes = m.total_time_minutes;
            const hours = m.total_time_hours;
            const timeFormat = `${hours}:${String(minutes).padStart(2,'0')}`;
            document.getElementById('kpi-time').innerText = timeFormat;
            document.getElementById('kpi-clients').innerText = m.total_clients;

            // Capacity Logic
            const capAlert = document.getElementById('capacity-alert');
            const capBar = document.getElementById('capacity-bar');
            
            capAlert.classList.remove('hidden', 'bg-red-50', 'bg-yellow-50', 'bg-green-50', 'border-red-500', 'border-yellow-500', 'border-green-500');
            
            let colorClass = 'bg-[var(--color-success)]';
            let title = "CAPACIDAD ÓPTIMA";
            
            if(cap.status === 'OVERLOAD') {
                capAlert.classList.add('bg-red-50', 'border-red-500');
                colorClass = 'bg-red-600';
                title = "¡SOBRECARGA DETECTADA!";
            } else if(cap.status === 'WARNING') {
                capAlert.classList.add('bg-yellow-50', 'border-yellow-500');
                colorClass = 'bg-yellow-500';
                title = "PRECAUCIÓN: ALTA OCUPACIÓN";
            } else {
                capAlert.classList.add('bg-green-50', 'border-green-500');
            }

            document.getElementById('capacity-title').innerText = title;
            document.getElementById('capacity-msg').innerText = cap.message;
            document.getElementById('capacity-percent').innerText = cap.occupation_percent;
            
            capBar.style.width = `${Math.min(cap.occupation_percent, 100)}%`;
            capBar.className = `h-2.5 rounded-full ${colorClass}`;

            // Table
            const tbody = document.getElementById('clients-table-body');
            tbody.innerHTML = '';
            if(data.clients.length > 0) {
                data.clients.forEach((c, idx) => {
                    const tr = document.createElement('tr');
                    tr.className = "border-b border-gray-100 hover:bg-gray-50";
                    tr.innerHTML = `
                        <td class="p-3 font-bold text-gray-400">${idx + 1}</td>
                        <td class="p-3">
                            <div class="font-bold text-gray-800">${c.first_name} ${c.last_name}</div>
                            <div class="text-xs text-gray-500">${c.company || 'Residencial'}</div>
                        </td>
                        <td class="p-3 text-gray-600">${c.street_address || '--'}</td>
                        <td class="p-3 text-right font-mono">${c.service_time} min</td>
                        <td class="p-3 text-right font-black text-gray-800">$${c.service_value}</td>
                    `;
                    tbody.appendChild(tr);
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="5" class="p-4 text-center text-gray-400 italic">Ruta sin clientes asignados</td></tr>';
            }
            
            lucide.createIcons();
        }
    </script>
</body>
</html>