<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Ops Center - <?php echo htmlspecialchars($client_info['business_name']); ?> <?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">

    <style>
        body { font-family: 'Barlow', sans-serif; background-color: #f9fafb; /* Gris muy claro igual que booking */ }
        .card-transition { transition: all 0.3s ease; }
        
        /* Clases de utilidad de marca */
        .text-primary { color: var(--color-primary); }
        .border-highlight { border-color: var(--color-highlight); }

        /* Animación de Pulso para "En Vivo" */
        .live-indicator {
            width: 10px; height: 10px; background-color: #ef4444; border-radius: 50%;
            box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
            animation: pulse-red 2s infinite;
        }
        @keyframes pulse-red {
            0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
            70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
            100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
        }
    </style>
</head>
<body class="min-h-screen flex flex-col">

    <header class="bg-white shadow-sm sticky top-0 z-50 border-b-4 border-[var(--color-highlight)]">
        <div class="max-w-7xl mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center gap-4">
                <?php if(!empty($client_info['logo_url'])): ?>
                    <img src="<?php echo $client_info['logo_url']; ?>" class="h-10 md:h-12 object-contain">
                <?php endif; ?>
                
                <div class="hidden md:block pl-4 border-l-2 border-gray-200">
                    <h1 class="text-2xl font-black text-[var(--color-primary)] uppercase tracking-wide">
                        Live Ops Center
                    </h1>
                    <div class="flex items-center gap-2 text-xs font-bold text-red-500 uppercase tracking-wider">
                        <div class="live-indicator"></div> Real-Time Connection
                    </div>
                </div>
            </div>
            
            <div class="text-right">
                <p class="text-sm text-gray-500 font-bold uppercase" id="current-date"></p>
                <p class="text-2xl font-black text-[var(--color-primary)] font-mono leading-none" id="current-time">--:--:--</p>
            </div>
        </div>
    </header>

    <main class="flex-grow p-6 max-w-7xl mx-auto w-full">
            
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white rounded-xl p-5 shadow-md border border-gray-100">
                <p class="text-xs text-gray-500 uppercase font-bold tracking-wider">Active Staff</p>
                <p class="text-4xl font-black text-green-600 mt-1" id="stat-active">0</p>
            </div>
            <div class="bg-white rounded-xl p-5 shadow-md border border-gray-100">
                <p class="text-xs text-gray-500 uppercase font-bold tracking-wider">In Service</p>
                <p class="text-4xl font-black text-blue-600 mt-1" id="stat-busy">0</p>
            </div>
            <div class="bg-white rounded-xl p-5 shadow-md border border-gray-100">
                <p class="text-xs text-gray-500 uppercase font-bold tracking-wider">Completed Today</p>
                <p class="text-4xl font-black text-[var(--color-highlight)] mt-1" id="stat-completed">0</p>
            </div>
            <div class="bg-white rounded-xl p-5 shadow-md border border-gray-100">
                <p class="text-xs text-gray-500 uppercase font-bold tracking-wider">Offline</p>
                <p class="text-4xl font-black text-gray-400 mt-1" id="stat-offline">0</p>
            </div>
        </div>

        <div id="staff-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div class="col-span-full text-center py-20 text-gray-400 animate-pulse flex flex-col items-center">
                <i data-lucide="satellite" class="w-16 h-16 mb-4 opacity-30 text-[var(--color-primary)]"></i>
                <span class="font-bold uppercase tracking-widest">Establishing Satellite Connection...</span>
            </div>
        </div>

    </main>

    <footer class="bg-[var(--color-primary)] text-white py-8 shadow-inner border-t-4 border-[var(--color-highlight)]">
        <div class="max-w-7xl mx-auto px-6 lg:px-10 text-center">
            <p class="text-base font-semibold text-white/80">
                © <?php echo date('Y'); ?> <?php echo htmlspecialchars($client_info['business_name'] ?? 'Flow Cleaning Services LLC'); ?>. All Rights Reserved
            </p>
            <div class="mt-4 pt-2 border-t border-white/10 mx-auto max-w-sm">
                <p class="font-bold text-sm text-white/70 flex items-center justify-center gap-1.5">
                    Powered by <i data-lucide="shield-check" class="w-4 h-4 text-green-400"></i>
                    <span class="font-black text-[var(--color-highlight)] tracking-wide">
                        FlowCRM™
                    </span>
                </p>
            </div>
        </div>
    </footer>

<script>
    // Reloj del Sistema
    function updateTime() {
        const now = new Date();
        document.getElementById('current-time').innerText = now.toLocaleTimeString();
        document.getElementById('current-date').innerText = now.toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
    }
    setInterval(updateTime, 1000);
    updateTime();

    // MOTOR DE ACTUALIZACIÓN (AJAX)
    async function fetchLiveData() {
        try {
            const res = await fetch('db/live-monitor-data.php');
            const response = await res.json();
            
            if (response.success) {
                renderDashboard(response.data);
                updateStats(response.data);
            }
        } catch (error) {
            console.error("Connection error:", error);
        }
    }

    function updateStats(data) {
        let active = 0, busy = 0, completed = 0, offline = 0;
        data.forEach(s => {
            if (s.status === 'offline') offline++;
            else {
                active++;
                if (s.activity && s.activity.type === 'working') busy++;
                if (s.activity && s.activity.type === 'completed') completed++;
            }
        });
        document.getElementById('stat-active').innerText = active;
        document.getElementById('stat-busy').innerText = busy;
        document.getElementById('stat-completed').innerText = completed; 
        document.getElementById('stat-offline').innerText = offline;
    }

    function renderDashboard(staffList) {
        const container = document.getElementById('staff-grid');
        if (staffList.length === 0) {
            container.innerHTML = `
                <div class="col-span-full text-center py-12 bg-white rounded-xl shadow-sm border border-dashed border-gray-300">
                    <p class="text-gray-400 font-bold uppercase">No staff members found.</p>
                </div>`;
            return;
        }
        container.innerHTML = staffList.map(staff => createStaffCard(staff)).join('');
        lucide.createIcons();
    }

    // GENERADOR DE TARJETAS (Adaptado al tema claro)
    function createStaffCard(staff) {
        const isOffline = staff.status === 'offline';
        
        // Bordes y estados adaptados a fondo blanco
        let cardBorderClass = isOffline ? 'border-gray-300' : 'border-green-500';
        let statusBadge = isOffline 
            ? `<span class="bg-gray-200 text-gray-600 text-[10px] font-black px-2 py-1 rounded uppercase tracking-wide">Offline</span>` 
            : `<span class="bg-green-100 text-green-700 text-[10px] font-black px-2 py-1 rounded uppercase tracking-wide flex items-center gap-1"><span class="w-2 h-2 bg-green-600 rounded-full animate-pulse"></span> Online</span>`;

        let content = '';

        // ESCENARIO 1: OFFLINE (Gris claro)
        if (isOffline) {
            content = `
                <div class="mt-4 bg-gray-50 p-4 rounded-lg text-center border border-dashed border-gray-200">
                    <i data-lucide="moon" class="w-8 h-8 text-gray-300 mx-auto mb-2"></i>
                    <p class="text-sm text-gray-400 font-bold uppercase">Off Duty</p>
                </div>
            `;
        } 
        // ESCENARIO 2: ONLINE PERO SIN ACTIVIDAD (Amarillo suave)
        else if (!staff.activity) {
            cardBorderClass = 'border-yellow-400';
            content = `
                <div class="mt-4 bg-yellow-50 p-4 rounded-lg text-center border border-yellow-100">
                    <i data-lucide="coffee" class="w-8 h-8 text-yellow-500 mx-auto mb-2"></i>
                    <p class="text-sm text-yellow-700 font-bold uppercase">Available / Idle</p>
                    <p class="text-xs text-yellow-600/70 mt-1 font-mono">Clock In: ${staff.clock_in_time}</p>
                </div>
            `;
        }
        // ESCENARIO 3: TRABAJANDO (Azul suave)
        else if (staff.activity.type === 'working') {
            cardBorderClass = 'border-blue-500';
            content = `
                <div class="mt-4 bg-blue-50 p-4 rounded-lg border border-blue-100 relative overflow-hidden">
                    <div class="absolute top-0 right-0 p-2 opacity-10"><i data-lucide="map-pin" class="w-16 h-16 text-blue-600"></i></div>
                    <p class="text-[10px] text-blue-600 font-bold uppercase mb-1">Servicing Client:</p>
                    <h3 class="text-lg font-black text-[var(--color-primary)] truncate">${staff.activity.client}</h3>
                    <p class="text-xs text-gray-500 flex items-center gap-1 mt-1 font-medium"><i data-lucide="map" class="w-3 h-3"></i> ${staff.activity.address}</p>
                    
                    <div class="mt-3 flex items-center gap-2 text-xs font-bold text-blue-700 bg-blue-100 p-2 rounded border border-blue-200">
                        <i data-lucide="clock" class="w-3 h-3"></i> Started: ${staff.activity.time}
                    </div>
                </div>
            `;
        }
        // ESCENARIO 4: COMPLETADO (Color Highlight)
        else if (staff.activity.type === 'completed') {
            // Usamos estilos inline para el borde dinámico del highlight ya que tailwind no pilla la variable en la clase border-[var...]
            const stars = '★'.repeat(staff.activity.rating) + '☆'.repeat(5 - staff.activity.rating);
            
            // Usamos un estilo base, luego aplicamos borde dinámico
            content = `
                <div class="mt-4 bg-[var(--color-highlight)]/10 p-4 rounded-lg border border-[var(--color-highlight)]/30 relative">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-[10px] text-[var(--color-primary)] font-bold uppercase mb-1">Job Completed!</p>
                            <h3 class="text-lg font-black text-[var(--color-primary)] truncate">${staff.activity.client}</h3>
                        </div>
                        <i data-lucide="check-circle-2" class="w-6 h-6 text-green-600"></i>
                    </div>
                    
                    <div class="mt-3 pt-3 border-t border-black/5">
                        <p class="text-xs text-gray-500 uppercase font-bold">Client Approval:</p>
                        <div class="flex items-center justify-between mt-1">
                            <span class="text-yellow-500 text-lg tracking-widest drop-shadow-sm">${stars}</span>
                            <span class="text-[10px] text-gray-400 font-mono">${staff.activity.verified_at}</span>
                        </div>
                        ${staff.activity.feedback ? `<p class="text-xs text-gray-600 italic mt-2 border-l-2 border-[var(--color-highlight)] pl-2">"${staff.activity.feedback}"</p>` : ''}
                    </div>
                </div>
            `;
            
            // Forzamos el borde highlight para completado
            cardBorderClass = 'border-[var(--color-highlight)]';
        }

        // FOTO
        const photoUrl = staff.photo && staff.photo !== 'placeholder' ? staff.photo : 'img/default-avatar.png';

        return `
            <div class="bg-white rounded-xl p-5 border-l-8 ${cardBorderClass} shadow-lg hover:shadow-xl transition-all card-transition border-t border-r border-b border-gray-100">
                <div class="flex items-center gap-4">
                    <div class="relative">
                        <img src="${photoUrl}" class="w-14 h-14 rounded-full object-cover border-2 border-gray-100 shadow-sm">
                        ${isOffline ? '' : '<div class="absolute bottom-0 right-0 w-3.5 h-3.5 bg-green-500 border-2 border-white rounded-full"></div>'}
                    </div>
                    <div>
                        <h2 class="text-lg font-black text-[var(--color-primary)] leading-tight uppercase">${staff.name}</h2>
                        <p class="text-xs text-gray-400 font-bold uppercase mb-1 tracking-wide">${staff.role}</p>
                        ${statusBadge}
                    </div>
                </div>
                ${content}
            </div>
        `;
    }

    // Actualizar cada 10 segundos
    fetchLiveData(); 
    setInterval(fetchLiveData, 10000); 

</script>
<script src="files/toast.js"></script>
</body>
</html>