<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/../core/init.php');

// ------------------------------------------------------------------------
// 1. CONFIGURACIÓN INICIAL Y CONSTANTES GLOBALES
// ------------------------------------------------------------------------

$businessData = $client_info;
if (!defined('BUSINESS_NAME')) define('BUSINESS_NAME', $businessData['business_name'] ?? 'FlowCRM');
if (!defined('LOGO_FILENAME')) define('LOGO_FILENAME', $businessData['logo_url'] ?? 'img/favicon.png');
if (!defined('WHATSAPP_NUMBER_CLICK')) define('WHATSAPP_NUMBER_CLICK', preg_replace('/[^0-9]/', '', $businessData['whatsapp'] ?? ''));
if (!defined('EMAIL_PRIMARY')) define('EMAIL_PRIMARY', $businessData['email'] ?? 'info@flowcrm.com');
if (!defined('PHONE_PRIMARY_CLICK')) define('PHONE_PRIMARY_CLICK', preg_replace('/[^0-9]/', '', $businessData['phone'] ?? ''));
if (!defined('BUSINESS_TIMEZONE')) define('BUSINESS_TIMEZONE', $businessData['timezone'] ?? '');

// Redirección si no hay sesión (Lógica de Staff)
if (!isset($_SESSION['staff_id'])) {
    header('Location: login.php'); 
    ob_end_flush();
    exit();
}

$staff_id = $_SESSION['staff_id'];
$timezone_db = 'America/Los_Angeles'; 

// Establecer la zona horaria del negocio
if (isset($pdo)) {
    try {
        $stmtBiz = $pdo->query("SELECT timezone FROM business_info LIMIT 1");
        if ($biz = $stmtBiz->fetch(PDO::FETCH_ASSOC)) {
            if (!empty($biz['timezone'])) $timezone_db = $biz['timezone'];
        }
    } catch (Exception $e) { error_log($e->getMessage()); }
}
date_default_timezone_set($timezone_db);

// Definir tiempo actual para toda la lógica
$currentTime = new DateTime('now');
$currentDayName = $currentTime->format('l');

// ---------------------------------------------------------
// 2. CONFIGURACIÓN DE LA EMPRESA (Re-extracción de logo, etc.)
// ---------------------------------------------------------
$company_name = BUSINESS_NAME; 
$logo_url = LOGO_FILENAME; 


// ---------------------------------------------------------
// 3. LOGICA: SUBIDA DE FOTO DE PERFIL (STAFF)
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_photo'])) {
    try {
        $file = $_FILES['profile_photo'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'webp'];
            if (in_array($ext, $allowed)) {
                // Directorio relativo: subir un nivel (../uploads)
                $uploadDir = __DIR__ . '/../uploads/staff/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                
                $newFileName = 'staff_' . $staff_id . '_' . time() . '.' . $ext;
                $destPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($file['tmp_name'], $destPath)) {
                    // Guardar ruta pública en BD
                    $publicPath = 'uploads/staff/' . $newFileName; 
                    
                    // Actualizamos la tabla STAFF (No users, para mantener consistencia)
                    $stmtUpd = $pdo->prepare("UPDATE staff SET profile_photo_url = ? WHERE id = ?");
                    $stmtUpd->execute([$publicPath, $staff_id]);
                    
                    header("Location: dashboard.php");
                    exit;
                }
            }
        }
    } catch (Exception $e) { error_log($e->getMessage()); }
} 

// ---------------------------------------------------------
// 4. LOGICA RELOJ (Clock In/Out)
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    ob_clean();
    header('Content-Type: application/json');
    try {
        if (!isset($pdo)) throw new Exception("Error DB");

        if ($_POST['action'] === 'clock_cancel') {
            $stmtDel = $pdo->prepare("DELETE FROM work_logs WHERE staff_id = ? AND clock_out IS NULL LIMIT 1");
            $stmtDel->execute([$staff_id]);
            echo json_encode(['success' => true, 'message' => 'Entrada eliminada correctamente.']);
            exit;
        }

        if ($_POST['action'] === 'clock_toggle') {
            $stmtCheck = $pdo->prepare("SELECT id, clock_in, TIMESTAMPDIFF(SECOND, clock_in, NOW()) as duracion_segundos FROM work_logs WHERE staff_id = ? AND clock_out IS NULL ORDER BY clock_in DESC LIMIT 1");
            $stmtCheck->execute([$staff_id]);
            $currentLog = $stmtCheck->fetch(PDO::FETCH_ASSOC);

            if ($currentLog) {
                // CLOCK OUT
                $duracion = (int)$currentLog['duracion_segundos'];
                if ($duracion < 1800) {
                    $faltan_min = ceil((1800 - $duracion) / 60);
                    if ($faltan_min < 0) $faltan_min = 0;
                    echo json_encode(['success' => false, 'message' => "Turno muy corto.", 'subtext' => "Mínimo 30 min. Faltan $faltan_min min.", 'show_cancel_option' => true]);
                } else {
                    $stmtUpdate = $pdo->prepare("UPDATE work_logs SET clock_out = NOW(), total_hours = TIMESTAMPDIFF(MINUTE, clock_in, NOW())/60 WHERE id = ?");
                    $stmtUpdate->execute([$currentLog['id']]);
                    echo json_encode(['success' => true, 'message' => 'Turno cerrado exitosamente.']);
                }
            } else {
                // CLOCK IN
                $stmtInsert = $pdo->prepare("INSERT INTO work_logs (staff_id, clock_in) VALUES (?, NOW())");
                $stmtInsert->execute([$staff_id]);
                echo json_encode(['success' => true, 'message' => 'Turno iniciado.']);
            }
        }
    } catch (Exception $e) { echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]); }
    exit;
}
// ob_end_flush() se ejecutará al final.

// ---------------------------------------------------------
// 5. DATOS VISTA Y LÓGICA DE ROLES
// ---------------------------------------------------------
$staff_data = [];
$staff_photo = "placeholder"; 
$global_announcement = "Sin novedades.";
$today_route = [];
$upcoming_appointments = [];
$my_complaints = [];
$docs_global = [];
$docs_personal = [];
$is_working = false;
$my_clients_list = [];

// Saludos y iconos
$hora = date('H');
if ($hora >= 5 && $hora < 12) { $saludo = "Buenos días"; $icono = "sun"; }
elseif ($hora >= 12 && $hora < 19) { $saludo = "Buenas tardes"; $icono = "cloud-sun"; }
else { $saludo = "Buenas noches"; $icono = "moon"; }

// Lógica de Roles (Se necesita para restringir info)
$staff_role = 'employee';
$is_manager = false;
$is_employee_month = false; // Variable nueva

if (isset($pdo)) {
    try {
        // 5.1 Staff, Foto, Rol y EMPLEADO DEL MES (Agregado is_employee_of_month)
        $stmtS = $pdo->prepare("SELECT s.first_name, s.last_name, s.working_days, s.role, s.profile_photo_url, s.email, s.is_employee_of_month 
                                FROM staff s 
                                WHERE s.id = ?");
        $stmtS->execute([$staff_id]);
        $staff_data = $stmtS->fetch(PDO::FETCH_ASSOC);
        
        if ($staff_data) {
            $staff_role = $staff_data['role'] ?? 'employee';
            $is_manager = ($staff_role === 'manager');
            $is_employee_month = ($staff_data['is_employee_of_month'] == 1);
        }
        
        // Ajuste de la foto de perfil 
        if (!empty($staff_data['profile_photo_url'])) {
            $staff_photo = $staff_data['profile_photo_url'];
            if (strpos($staff_photo, 'http') === false && strpos($staff_photo, '../') === false) $staff_photo = "../" . $staff_photo;
        } else {
            $staff_photo = "placeholder"; 
        }

        // 5.2 Estado de Trabajo
        $stmtClock = $pdo->prepare("SELECT id FROM work_logs WHERE staff_id = ? AND clock_out IS NULL LIMIT 1");
        $stmtClock->execute([$staff_id]);
        $is_working = $stmtClock->fetch() ? true : false;

        // 5.3 Avisos Globales
        $stmtN = $pdo->query("SELECT message FROM staff_notifications ORDER BY created_at DESC LIMIT 1");
        if ($row = $stmtN->fetch(PDO::FETCH_ASSOC)) $global_announcement = $row['message'];

        // 5.4 Quejas Asignadas
        $stmtComplaints = $pdo->prepare("SELECT cp.title, cp.description, cp.status, DATE_FORMAT(cp.created_at, '%d/%m/%Y') as fecha, c.first_name, c.last_name 
                                         FROM complaints cp 
                                         JOIN clients c ON cp.client_id = c.id 
                                         WHERE c.staff_id = ? AND cp.status != 'Archivado' 
                                         ORDER BY cp.created_at DESC");
        $stmtComplaints->execute([$staff_id]);
        $my_complaints = $stmtComplaints->fetchAll(PDO::FETCH_ASSOC);

        // 5.5 Lista de Clientes (CONSULTA SEGURA)
        // NOTA: Traemos los datos, pero en el HTML decidimos si mostrarlos o no según $is_manager
        $stmtC = $pdo->prepare("SELECT c.id, CONCAT_WS(' ', c.first_name, c.last_name) as name, 
                                COALESCE(c.street_address, 'Sin dirección') as street_address, 
                                COALESCE(c.city, '') as city, c.phone, c.email
                                FROM clients c 
                                LEFT JOIN route_clients rc ON c.id = rc.client_id 
                                LEFT JOIN routes r ON rc.route_id = r.id 
                                WHERE c.staff_id = ? OR r.staff_id = ? OR r.assigned_staff_id = ? 
                                GROUP BY c.id");
        $stmtC->execute([$staff_id, $staff_id, $staff_id]);
        $my_clients_list = $stmtC->fetchAll(PDO::FETCH_ASSOC);


        // 5.6 Documentos 
        $stmtDocs = $pdo->prepare("SELECT file_name, file_path, staff_id FROM staff_documents WHERE staff_id = ? OR staff_id IS NULL ORDER BY uploaded_at DESC");
        $stmtDocs->execute([$staff_id]);
        $all_docs = $stmtDocs->fetchAll(PDO::FETCH_ASSOC);
        foreach ($all_docs as $doc) {
            $file_path = strpos($doc['file_path'], 'http') === false ? '../' . ltrim($doc['file_path'], './') : $doc['file_path'];
            if (is_null($doc['staff_id'])) {
                $docs_global[] = ['file_name' => $doc['file_name'], 'file_path' => $file_path];
            } else {
                $docs_personal[] = ['file_name' => $doc['file_name'], 'file_path' => $file_path];
            }
        }

        // 5.7 Próximas Citas
        $stmtApp = $pdo->prepare("SELECT ua.id, ua.appointment_date, TIME_FORMAT(ua.appointment_time, '%h:%i %p') as time_f, ua.status, ua.notes, c.first_name, c.last_name, c.street_address, c.city 
                                 FROM unique_appointments ua 
                                 JOIN clients c ON ua.client_id = c.id 
                                 WHERE ua.staff_id = ? AND ua.status IN ('pending', 'confirmed') AND ua.appointment_date >= CURDATE() 
                                 ORDER BY ua.appointment_date ASC LIMIT 5");
        $stmtApp->execute([$staff_id]);
        $upcoming_appointments = $stmtApp->fetchAll(PDO::FETCH_ASSOC);

        // 5.8 Rutas del Día
        $hoy_ingles = date('l');
        $stmtRoute = $pdo->prepare("SELECT r.route_name, c.first_name, c.last_name, c.street_address, c.city, c.phone, rc.order_index 
                                     FROM routes r 
                                     JOIN route_clients rc ON r.id = rc.route_id 
                                     JOIN clients c ON rc.client_id = c.id 
                                     WHERE (r.staff_id = ? OR r.assigned_staff_id = ?) AND r.is_active = 1 AND r.route_day LIKE ? 
                                     ORDER BY rc.order_index ASC");
        $stmtRoute->execute([$staff_id, $staff_id, "%$hoy_ingles%"]);
        $today_route = $stmtRoute->fetchAll(PDO::FETCH_ASSOC);

    } catch (Exception $e) { 
        error_log($e->getMessage()); 
    }
}

$staffName = htmlspecialchars($staff_data['first_name'] ?? 'Colaborador');
$staff_photo_url = $staff_photo; 
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Portal De Miembros De <?php echo htmlspecialchars($branding['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); ?>">

    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="../style.css">
    
    <style>
        .section-container { padding-top: 4rem; padding-bottom: 4rem; }
        .profile-hover { opacity: 0; transition: all 0.3s; }
        .group:hover .profile-hover { opacity: 1; }
        .pulse-active { animation: pulse-red 2s infinite; }
        @keyframes pulse-red { 0% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0.7); } 70% { box-shadow: 0 0 0 15px rgba(220, 38, 38, 0); } 100% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0); } }
        
        .live-indicator {
            width: 8px;
            height: 8px;
            background: var(--color-success);
            border-radius: 50%;
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        
    </style>
</head>
<body class="flex flex-col min-h-screen bg-gray-50">

<div id="overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>

<aside id="clients-panel" class="fixed top-0 right-0 h-full w-full max-w-md bg-white z-50 shadow-2xl transform translate-x-full transition-transform duration-300 flex flex-col">
    <div class="bg-[var(--color-primary)] text-white p-6 flex justify-between items-center border-b-4 border-[var(--color-highlight)]">
        <h2 class="text-2xl font-black uppercase tracking-wide flex items-center gap-3">
            <i data-lucide="users" class="text-[var(--color-highlight)] w-7 h-7"></i> Mis Clientes
        </h2>
        <button id="clients-close-btn" class="p-2 hover:bg-white/10 rounded-full text-white/80 hover:text-white"><i data-lucide="x" class="w-7 h-7"></i></button>
    </div>
    <div class="flex-1 overflow-y-auto p-6 bg-[var(--color-light)] space-y-4">
        <?php if (empty($my_clients_list)): ?>
            <div class="text-center py-10 text-gray-500 font-bold bg-white/50 rounded-xl border-dashed border-2 border-gray-300"><p class="font-bold text-lg">No tienes clientes asignados.</p></div>
        <?php else: ?>
            <?php foreach($my_clients_list as $client): ?>
                <div class="bg-white p-4 rounded-xl shadow-md border-l-4 border-[var(--color-secondary)]">
                    <h3 class="font-black text-lg text-[var(--color-primary)]"><?php echo htmlspecialchars($client['name']); ?></h3>
                    <p class="text-sm text-gray-700 mt-1 flex items-center gap-1.5"><i data-lucide="map-pin" class="w-4 h-4 text-gray-400"></i> <?php echo htmlspecialchars($client['street_address']); ?>, <?php echo htmlspecialchars($client['city']); ?></p>
                    <div class="text-sm mt-3 flex flex-col gap-2">
                        <?php if ($is_manager): ?>
                            <a href="mailto:<?php echo htmlspecialchars($client['email'] ?? ''); ?>" class="font-bold text-gray-800 flex items-center gap-2 p-2 bg-gray-100 rounded hover:bg-gray-200 transition">
                                <i data-lucide="mail" class="w-4 h-4 text-[var(--color-secondary)]"></i> <?php echo htmlspecialchars($client['email'] ?? 'N/A'); ?>
                            </a>
                            <a href="tel:<?php echo htmlspecialchars($client['phone']); ?>" class="font-bold text-white bg-[var(--color-primary)] p-2 rounded text-center flex items-center justify-center gap-2 hover:bg-[var(--color-secondary)] transition">
                                <i data-lucide="phone" class="w-4 h-4"></i> Llamar: <?php echo htmlspecialchars($client['phone']); ?>
                            </a>
                        <?php else: ?>
                            <div class="font-bold text-gray-400 flex items-center gap-2 p-2 bg-gray-100 rounded cursor-not-allowed">
                                <i data-lucide="lock" class="w-4 h-4"></i> Email Privado
                            </div>
                            <div class="font-bold text-gray-400 flex items-center gap-2 p-2 bg-gray-100 rounded cursor-not-allowed">
                                <i data-lucide="lock" class="w-4 h-4"></i> Teléfono Privado
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</aside>

<div id="mobile-nav-panel" class="fixed top-0 right-0 h-full w-full max-w-sm bg-[var(--color-primary)] z-40 shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out flex flex-col lg:hidden">
    
    <div class="p-8 pb-10 flex flex-col items-center justify-center border-b border-white/10 relative">
           <button id="menu-close-btn" class="absolute top-4 left-4 text-white/70 hover:text-white rounded-full hover:bg-white/10 p-1 transition-colors">
             <i data-lucide="x" class="w-7 h-7"></i>
           </button>
        
        <div class="relative group w-28 h-28 rounded-full border-4 border-white/50 shadow-lg ring-2 ring-[var(--color-highlight)] overflow-hidden mb-4 bg-white shadow-xl cursor-pointer shrink-0" onclick="document.getElementById('photo-input-mobile').click()">
             <?php if ($staff_photo_url === 'placeholder'): ?>
                 <div class="w-full h-full flex items-center justify-center bg-[var(--color-secondary)]/50">
                     <i data-lucide="user-circle" class="w-20 h-20 text-white/80"></i>
                 </div>
             <?php else: ?>
                 <img src="<?php echo $staff_photo_url; ?>" alt="Profile Picture" class="w-full h-full object-cover">
             <?php endif; ?>
             <div class="profile-hover absolute inset-0 bg-black/50 flex items-center justify-center text-white">
                  <i data-lucide="camera" class="w-6 h-6"></i>
             </div>
        </div>
        <form id="photo-form-mobile" method="POST" enctype="multipart/form-data" class="hidden">
            <input type="file" name="profile_photo" id="photo-input-mobile" accept="image/*" onchange="document.getElementById('photo-form-mobile').submit()">
        </form>

        <h4 class="text-xl font-medium text-white/80"><?php echo $saludo; ?>,</h4>
        <h3 class="text-3xl font-black text-white"><?php echo $staffName; ?>!</h3>
        
        <?php if ($is_employee_month): ?>
        <div class="mt-4 bg-[var(--color-highlight)] text-[var(--color-primary)] px-4 py-2 rounded-full font-black text-xs uppercase flex items-center gap-2 shadow-lg animate-pulse">
            <i data-lucide="trophy" class="w-4 h-4"></i> Empleado del Mes
        </div>
        <?php endif; ?>
    </div>
    
    <nav class="p-4 flex-1 overflow-y-auto">
        <ul class="flex flex-col space-y-1">
            <li><a href="#dashboard-content-area" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold text-lg uppercase transition-colors" data-target="dashboard"><i data-lucide="layout-dashboard" class="w-6 h-6"></i><span>Dashboard</span></a></li>
            <li><a href="#schedule" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="schedule"><i data-lucide="clock" class="w-6 h-6 text-white/70"></i><span>Horario</span></a></li>
            <li><a href="#agenda" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="agenda"><i data-lucide="calendar-days" class="w-6 h-6 text-white/70"></i><span>Agenda</span></a></li>
            <li><a href="#routes" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="routes"><i data-lucide="map" class="w-6 h-6 text-white/70"></i><span>Rutas</span></a></li>
            <li><a href="#complaints" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="complaints"><i data-lucide="alert-circle" class="w-6 h-6 text-white/70"></i><span>Quejas</span></a></li>
            <li><a href="#documents" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="documents"><i data-lucide="file-text" class="w-6 h-6 text-white/70"></i><span>Documentos</span></a></li>
            <li><a href="#academy" class="mobile-nav-link-staff flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors" data-target="academy"><i data-lucide="graduation-cap" class="w-6 h-6 text-white/70"></i><span>Entrenamiento</span></a></li>
        </ul>
    </nav>
    
    <div class="p-4 border-t border-white/10 flex flex-col gap-2 flex-shrink-0">
        <a href="logout.php" class="flex items-center gap-4 px-4 py-3 rounded-lg text-red-400 hover:text-white font-extrabold text-lg uppercase transition-colors">
            <i data-lucide="log-out" class="w-6 h-6"></i>
            <span>Cerrar Sesión</span>
        </a>
    </div>
</div>


<?php
function generateVerificationLink($pdo, $appointment_id) {
    // 1. Generar un token único y seguro
    $token = bin2hex(random_bytes(32));

    // 2. Guardar el token en la base de datos
    $stmt = $pdo->prepare("UPDATE unique_appointments SET verification_token = ? WHERE id = ?");
    $result = $stmt->execute([$token, $appointment_id]);

    if ($result) {
        // --- AQUÍ COMIENZA LA MAGIA DINÁMICA ---
        
        // a. Detectar el protocolo (HTTP o HTTPS)
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        
        // b. Detectar el dominio actual (ej: localhost, crm.tunegociolocal.com)
        $domain = $_SERVER['HTTP_HOST'];
        
        // c. Construir la URL completa
        $dynamic_link = $protocol . $domain . "/verify-service.php?token=" . $token;
        
        return $dynamic_link;
    }

    return false;
}
?>


<div class="flex min-h-screen">
    <header class="hidden lg:block w-full bg-white fixed top-0 z-20 shadow-lg border-b-4 border-[var(--color-highlight)]">
        <div class="max-w-7xl mx-auto px-6 py-4 flex justify-between items-center">
            <div class="flex items-center gap-3">
                <?php if(!empty($client_info['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($client_info['logo_url']); ?>" class="h-8 md:h-12 object-contain">
                <?php endif; ?>
                
                <div class="pl-3 border-l-2 border-gray-200">
                    <h1 class="text-lg md:text-3xl font-black text-[var(--color-primary)] uppercase tracking-tight leading-none">
                        Portal De Miembros
                    </h1>
                    <div class="flex items-center gap-1.5 text-[10px] md:text-xs font-black text-[var(--color-secondary)] uppercase tracking-wider">
                        <div class="live-indicator"></div> <span class="hidden sm:inline">Conexión </span>En Vivo 
                    </div>
                </div>
            </div>
             <div class="flex items-center gap-3">
                 <button id="clients-toggle-btn-desktop" class="flex items-center justify-center space-x-2 bg-[var(--color-secondary)] hover:bg-red-800 text-white font-black px-4 py-2 rounded-lg transition-colors shadow-md text-sm uppercase">
                     <i data-lucide="users" class="w-5 h-5"></i>
                     <span class="hidden md:inline">Clientes Asignados</span>
                 </button>
                 <div class="show-widget-container hidden">
                    <button class="show-widget-btn flex items-center gap-2 px-4 py-2 rounded-lg bg-green-600 text-white font-extrabold text-sm transition-colors hover:bg-green-700 uppercase shadow-md"
                        data-widget-id="videotutorial">
                        <i data-lucide="eye" class="w-5 h-5"></i>
                        <span>VER VIDEO Presentación</span>
                    </button>
                 </div>
             </div>
        </div>
        <div class="bg-[var(--color-primary)] shadow-inner">
             <nav id="main-nav-desktop" class="max-w-7xl mx-auto px-4">
                 <ul class="flex items-center justify-start gap-1">
                     <li><a href="#dashboard-content-area" class="nav-link-staff flex items-center gap-2 px-6 py-3 border-t-4 border-t-white bg-[var(--color-highlight)] text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-highlight)]/80" data-target="dashboard"><i data-lucide="layout-dashboard" class="w-4 h-4"></i><span>Dashboard</span></a></li>
                     <li><a href="#agenda" class="nav-link-staff flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]" data-target="agenda"><i data-lucide="calendar-days" class="w-4 h-4"></i><span>Citas De Clientes</span></a></li>
                     <li><a href="#routes" class="nav-link-staff flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]" data-target="routes"><i data-lucide="map" class="w-4 h-4"></i><span>Rutas Asignadas</span></a></li>
                     <li><a href="#complaints" class="nav-link-staff flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]" data-target="complaints"><i data-lucide="alert-circle" class="w-4 h-4"></i><span>Quejas De Clientes</span></a></li>
                     <li><a href="#documents" class="nav-link-staff flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]" data-target="documents"><i data-lucide="file-text" class="w-4 h-4"></i><span>Documentos</span></a></li>
                     <li><a href="#academy" class="nav-link-staff flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]" data-target="academy"><i data-lucide="graduation-cap" class="w-4 h-4"></i><span>Entrenamiento</span></a></li>
                     <li class="ml-auto"><a href="logout.php" class="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-600 text-white font-extrabold text-sm transition-colors hover:bg-red-700 uppercase shadow-md"><i data-lucide="log-out" class="w-4 h-4"></i><span>Salir</span></a></li>
                 </ul>
             </nav>
         </div>
    </header>

    <main class="flex-1 pb-20 lg:pt-[8.5rem]">
        <header class="lg:hidden bg-white p-3 flex justify-between items-center sticky top-0 z-20 shadow-lg border-b-4 border-[var(--color-highlight)]">
            <div class="flex items-center gap-3">
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="h-8 w-auto object-contain">
                <span class="text-[var(--color-primary)] font-black uppercase tracking-wider text-sm"><?php echo htmlspecialchars($company_name); ?></span>
            </div>
            <div class="flex items-center gap-2">
                 <button id="clients-toggle-btn-mobile" class="text-[var(--color-primary)] bg-gray-100 hover:bg-gray-200 p-2 rounded-md transition-colors"><i data-lucide="users" class="w-6 h-6"></i></button>
                 <button id="menu-toggle-btn" class="text-[var(--color-primary)] bg-gray-100 hover:bg-gray-200 p-2 rounded-md transition-colors"><i data-lucide="menu" class="w-6 h-6"></i></button>
            </div>
        </header>

<section class="p-6 md:p-10 video-widget bg-[var(--color-primary)] text-white relative overflow-hidden" id="videotutorial">
    <div class="blob bl1"></div><div class="blob bl2"></div>
    <div class="max-w-7xl mx-auto relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center z-10 px-4 sm:px-6">
        <div>
            <span class="chip inline-flex items-center gap-2 text-sm font-black uppercase tracking-widest px-3 py-1 rounded-full bg-[var(--color-highlight)] text-[var(--color-primary)] shadow-sm">
                <i data-lucide="laptop-minimal" class="w-4 h-4"></i> Bienvenido A Tu Plataforma
            </span>
            <h1 class="mt-3 text-3xl md:text-6xl font-black uppercase leading-tight text-[var(--color-highlight)]">
                Cómo Usar Tu Portal De Miembros
            </h1>
            <p class="mt-2 text-white/90 max-w-2xl text-lg">Mira este tutorial de 5 minutos para dominar la plataforma.</p>
            <div class="mt-6 flex flex-wrap gap-3">
                <a href="#dashboard-content-area" class="flex items-center gap-2 bg-[var(--color-secondary)] text-white font-black px-4 py-2 rounded-lg hover:brightness-110 transition shadow-md text-sm uppercase">
                    <i data-lucide="layout-dashboard" class="w-5 h-5"></i> Dashboard
                </a>
                <a href="#agenda" class="flex items-center gap-2 bg-[var(--color-highlight)] text-[var(--color-primary)] font-black px-4 py-2 rounded-lg hover:brightness-110 transition shadow-md text-sm uppercase">
                    <i data-lucide="calendar-days" class="w-5 h-5"></i> Ver Agenda
                </a>
            </div>
        </div>
        <div>
            <div class="w-full">
                <div class="bg-black/40 ring-1 ring-white/10 overflow-hidden">
                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayerStaff" controls controlslist="nodownload" preload="none" poster="<?= htmlspecialchars($video_data_staff['poster_url']) ?>">
                            <source src="<?= htmlspecialchars($video_data_staff['video_url']) ?>" type="video/mp4">
                        </video>
                        <div id="playOverlayStaff" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                            <img src="<?= htmlspecialchars($video_data_staff['poster_url']) ?>" alt="Video Tutorial Staff" class="absolute inset-0 w-full h-full object-cover">
                            <div class="absolute inset-0 w-full h-full bg-black/70 transition-colors group-hover:bg-black/30"></div>
                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-90 group-hover:opacity-100 transition-opacity"></i>
                        </div>
                    </div>
                    <div class="p-4 text-white/90 text-sm flex flex-col md:flex-row md:items-center justify-between gap-2">
                        <span class="inline-flex items-center gap-2">
                            <i data-lucide="play-circle" class="w-4 h-4 text-[var(--color-highlight)]"></i> <b>VIDEO:</b> <?= htmlspecialchars($video_data_staff['title'] ?? 'Tutorial Staff') ?>
                        </span>
                           <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-black text-[var(--color-highlight)] hover:text-white transition-colors py-2 md:py-1 px-2 rounded-md justify-center md:justify-end w-full md:w-auto bg-white/10 md:bg-transparent min-h-[44px] md:min-h-0" data-widget-id="videotutorial" title="Ocultar Video">
                               OCULTAR VIDEO <i data-lucide="square-x" class="w-4 h-4"></i>
                           </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<div class="section-container px-6 lg:px-10 max-w-7xl mx-auto space-y-12">

    <header id="dashboard-content-area" class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
    <div class="lg:col-span-2 space-y-8">
        <div class="bg-white p-8 rounded-2xl shadow-xl ring-1 ring-black/5">
            <div class="inline-flex items-center gap-2 text-[var(--color-primary)] font-bold mb-2 bg-[var(--color-highlight)]/50 px-3 py-1 rounded-full shadow-sm">
                <i data-lucide="layout-dashboard" class="w-4 h-4 text-[var(--color-primary)]"></i>
                <span class="text-xs uppercase tracking-widest font-black">Panel de Control <?php echo htmlspecialchars($company_name); ?></span> 
            </div>
            
            <div class="flex items-center gap-6 mt-2">
                <div class="relative group w-20 h-20 rounded-full overflow-hidden border-4 border-gray-200 shadow-xl ring-2 ring-[var(--color-highlight)] cursor-pointer shrink-0" onclick="document.getElementById('photo-input').click()">
                    <?php if ($staff_photo_url === 'placeholder'): ?>
                        <div class="w-full h-full flex items-center justify-center bg-gray-100 text-[var(--color-primary)]">
                            <i data-lucide="user-circle" class="w-14 h-14 opacity-60"></i>
                        </div>
                    <?php else: ?>
                        <img src="<?php echo $staff_photo_url; ?>" class="w-full h-full object-cover">
                    <?php endif; ?>
                    <div class="profile-hover absolute inset-0 bg-black/50 flex items-center justify-center text-white">
                        <i data-lucide="camera" class="w-6 h-6"></i>
                    </div>
                </div>
                
                <div class="flex-grow min-w-0">
                    <h1 class="font-black text-4xl sm:text-5xl md:text-5xl text-[var(--color-primary)] leading-tight">
                        Hola <span class="text-[var(--color-secondary)]"><?php echo $staffName; ?>!</span>
                             <span id="greeting-display-staff">
                                 <span class="inline-flex items-center gap-3 text-2xl font-black tracking-wide uppercase text-[var(--color-primary)]">
                                     <i data-lucide="<?php echo $icono; ?>" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                                     <span><?php echo $saludo; ?></span>
                                 </span>
                             </span> 
                    </h1>
                </div>
            </div>
            <form id="photo-form" method="POST" enctype="multipart/form-data" class="hidden">
                <input type="file" name="profile_photo" id="photo-input" accept="image/*" onchange="document.getElementById('photo-form').submit()">
            </form>

            <?php if ($is_employee_month): ?>
            <div class="mt-6 bg-yellow-50 border-2 border-yellow-400 rounded-xl p-4 flex items-center gap-4 shadow-md animate-bounce-slow">
                <div class="bg-yellow-400 p-3 rounded-full text-white shadow-lg shrink-0">
                    <i data-lucide="trophy" class="w-8 h-8"></i>
                </div>
                <div>
                    <h3 class="text-xl font-black text-yellow-800 uppercase leading-none mb-1">¡FELICIDADES!</h3>
                    <p class="text-sm font-bold text-yellow-700 uppercase">ERES EL EMPLEADO DEL MES</p>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="bg-[var(--color-primary)] text-white p-6 rounded-2xl shadow-xl ring-1 ring-white/10 relative overflow-hidden">
            <div class="absolute top-0 right-0 w-40 h-40 bg-[var(--color-highlight)] rounded-full opacity-10 -mr-10 -mt-10 blur-2xl"></div>
            <div class="relative z-10 flex gap-4 items-start">
                <div class="bg-white/10 p-3 rounded-lg shrink-0"><i data-lucide="megaphone" class="w-6 h-6 text-[var(--color-highlight)]"></i></div>
                <div>
                    <h3 class="text-[var(--color-highlight)] font-black uppercase text-3xl mb-1">Aviso Importante</h3>
                    <p class="font-medium text-lg leading-relaxed">"<?php echo nl2br(htmlspecialchars($global_announcement)); ?>"</p>
                </div>
            </div>
        </div>
    </div>

    <div class="space-y-6">
        <div class="bg-white p-8 rounded-2xl shadow-xl border-t-8 <?php echo $is_working ? 'border-red-600' : 'border-green-600'; ?> text-center">
            <h3 class="text-gray-500 font-black uppercase tracking-widest text-xs mb-4">Control de Asistencia</h3>
            <div id="clock-display" class="text-4xl font-black text-[var(--color-primary)] mb-6"><?php echo $is_working ? 'EN TURNO' : 'OFFLINE'; ?></div>
            <button id="clock-btn" class="w-full py-4 rounded-xl font-black text-lg uppercase shadow-lg flex items-center justify-center gap-3 transition-all transform hover:scale-[1.02] <?php echo $is_working ? 'bg-red-600 text-white hover:bg-red-700 pulse-active' : 'bg-green-600 text-white hover:bg-green-700'; ?>">
                <i data-lucide="<?php echo $is_working ? 'stop-circle' : 'play-circle'; ?>"></i>
                <span><?php echo $is_working ? 'TERMINAR TURNO' : 'INICIAR TURNO'; ?></span>
            </button>
            <p class="text-xs text-gray-400 mt-4 uppercase">*Mínimo 30 minutos requeridos</p>
            
            <?php if($is_working): ?>
                <button onclick="cancelClock()" class="mt-4 text-red-400 hover:text-red-600 text-xs font-bold underline uppercase tracking-wide block mx-auto">
                    (Cancelar entrada por error)
                </button>
            <?php endif; ?>
        </div>
    </div>
</header>
            
            <hr class="border-t border-gray-300">

<section id="schedule" class="fade-in">
                <div class="mb-8 text-center">
                    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
                         <i data-lucide="clock" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
                         MI JORNADA SEMANAL
                    </h3>
                    <p class="text-gray-600 text-lg uppercase font-medium">DÍAS Y HORARIO LABORAL ASIGNADO</p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                    <div class="md:col-span-2 bg-white p-8 rounded-2xl shadow-xl border-l-8 border-[var(--color-primary)] relative overflow-hidden">
                        <div class="absolute top-0 right-0 opacity-10 m-4"><i data-lucide="calendar-check" class="w-32 h-32 text-[var(--color-secondary)]"></i></div>
                        <h3 class="text-2xl font-black text-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                            <i data-lucide="calendar" class="text-[var(--color-secondary)] w-6 h-6"></i> Días Laborables
                        </h3>
                        <p class="text-xl text-gray-700 font-bold leading-relaxed border-l-4 border-[var(--color-highlight)] pl-4 py-1 bg-[var(--color-light)]/50 rounded-r-md">
                            <?php echo str_replace(',', ', ', htmlspecialchars($staff_data['working_days'] ?? 'No Definido')); ?>
                        </p>
                    </div>
                    <div class="space-y-6">
                        <div class="bg-white p-6 rounded-2xl shadow-xl border-t-4 border-[var(--color-secondary)]">
                             <h4 class="font-bold text-gray-500 uppercase text-xs mb-2 flex items-center gap-2"><i data-lucide="clock" class="w-4 h-4 text-gray-400"></i> Horario De Entrada Y Salida</h4>
                             <div class="text-3xl font-black text-[var(--color-primary)]">08:00 AM <span class="text-gray-300">-</span> 05:00 PM</div>
                             <p class="text-sm uppercase text-gray-500 mt-1">Para <?php echo htmlspecialchars($company_name); ?></p>
                        </div>
                    </div>
                </div>
            </section>

            <hr class="border-t border-gray-300">

<section id="agenda">
    <div class="mb-8 text-center">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="calendar-days" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            PRÓXIMAS CITAS
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">TUS CITAS CONFIRMADAS O PENDIENTES</p>
    </div>
    <?php if (empty($upcoming_appointments)): ?>
        <div class="bg-white p-8 rounded-2xl border-2 border-gray-300 text-center shadow-xl">
            <i data-lucide="octagon-alert" class="w-20 h-20 text-[var(--color-secondary)] mx-auto mb-3 block"></i>
            <p class="text-gray-500 font-black uppercase text-lg">No tienes citas asignadas próximamente.</p>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($upcoming_appointments as $appt): ?>
                <div class="bg-white p-6 rounded-2xl shadow-xl border-l-4 border-[var(--color-highlight)] relative overflow-hidden hover:shadow-2xl transition-shadow">
                    <div class="pl-2">
                        <div class="flex justify-between items-start mb-2">
                            <span class="text-lg font-black text-[var(--color-primary)] flex items-center gap-1.5"><i data-lucide="calendar" class="w-4 h-4 text-[var(--color-secondary)]"></i> <?php echo date("M d, Y", strtotime($appt['appointment_date'])); ?></span>
                            <span class="bg-green-100 text-green-700 text-xs font-black px-3 py-1 rounded-full uppercase flex items-center gap-1">
                                <i data-lucide="check-circle" class="w-4 h-4"></i> <?php echo $appt['status']; ?>
                            </span>
                        </div>
                        <h3 class="text-2xl font-black text-[var(--color-primary)] mb-1 uppercase"><?php echo htmlspecialchars($appt['first_name'] . ' ' . $appt['last_name']); ?></h3>
                        <p class="text-lg text-gray-700 font-bold mb-3 flex items-center gap-1"><i data-lucide="clock" class="w-4 h-4 text-[var(--color-highlight)]"></i> Hora: <?php echo $appt['time_f']; ?></p>
                        <p class="text-sm text-gray-500 mb-3 flex items-start gap-1.5"><i data-lucide="map-pin" class="w-4 h-4 text-gray-400 mt-0.5"></i> <?php echo htmlspecialchars($appt['street_address']); ?>, <?php echo htmlspecialchars($appt['city']); ?></p>
                        <div class="text-sm bg-[var(--color-light)] p-3 rounded-lg text-gray-600 italic border-l-4 border-gray-300">"<?php echo htmlspecialchars($appt['notes'] ?: 'Sin notas.'); ?>"</div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <button onclick="openServiceQR(<?php echo $appt['id']; ?>)" 
    class="mt-3 w-full bg-[var(--color-primary)] text-white py-2 rounded-lg font-bold text-xs uppercase flex items-center justify-center gap-2 hover:bg-[var(--color-secondary)] transition shadow">
    <i data-lucide="qr-code" class="w-4 h-4"></i> Verificar Servicio
</button>

</section>

            <hr class="border-t border-gray-300">
            
<section id="routes">
                <div class="mb-8 text-center">
                    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
                        <i data-lucide="map" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
                        TUS RUTAS ASIGNADAS
                    </h3>
                    <p class="text-gray-600 text-lg uppercase font-medium">LISTA DE CLIENTES A VISITAR EN ORDEN</p>
                </div>
                <?php if (empty($today_route)): ?>
                    <div class="bg-white p-8 rounded-2xl border-2 border-gray-300 text-center shadow-xl">
                        <i data-lucide="triangle-alert" class="w-20 h-20 text-[var(--color-secondary)] mx-auto mb-3 block"></i>
                        <p class="text-gray-500 font-black uppercase text-lg">No hay ruta asignada para hoy.</p></div>
                <?php else: ?>
                    <div class="space-y-4">
                        <?php foreach ($today_route as $index => $stop): ?>
                            <div class="bg-white p-5 rounded-xl shadow-lg flex flex-col md:flex-row items-start md:items-center gap-4 border-l-8 border-[var(--color-primary)] transition-all hover:border-[var(--color-highlight)] hover:shadow-2xl">
                                <div class="flex-shrink-0 bg-[var(--color-secondary)] text-white font-black w-14 h-14 rounded-full flex items-center justify-center text-xl shadow-lg border-2 border-white"><?php echo $index + 1; ?></div>
                                <div class="flex-1">
                                    <h3 class="text-2xl font-black text-[var(--color-primary)]"><?php echo htmlspecialchars($stop['first_name'] . ' ' . $stop['last_name']); ?></h3>
                                    <p class="text-sm text-gray-500"><span class="font-bold text-[var(--color-secondary)] uppercase text-xs mr-2 border border-[var(--color-secondary)] px-2 py-0.5 rounded-full"><?php echo htmlspecialchars($stop['route_name']); ?></span> <?php echo htmlspecialchars($stop['street_address']); ?></p>
                                </div>
                                <a href="https://maps.google.com/?q=<?php echo urlencode($stop['street_address'] . ' ' . $stop['city']); ?>" target="_blank" class="p-3 bg-[var(--color-highlight)] rounded-full hover:bg-[var(--color-primary)] hover:text-white text-[var(--color-primary)] transition shadow-md flex-shrink-0" title="Navegar">
                                    <i data-lucide="navigation" class="w-5 h-5"></i>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

<section id="complaints" class="fade-in">
                <?php if (!empty($my_complaints)): ?>
                <div class="mb-8 text-center">
                    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
                        <i data-lucide="alert-circle" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
                        ASUNTOS PENDIENTES
                    </h3>
                    <p class="text-gray-600 text-lg uppercase font-medium">QUEJAS DE CLIENTES ASIGNADOS A TI</p>
                </div>
                <div class="bg-white p-6 rounded-2xl shadow-xl border-l-8 border-red-600">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <?php foreach ($my_complaints as $queja): ?>
                            <div class="p-5 rounded-xl shadow-sm border border-red-200 relative bg-red-50/50">
                                <div class="flex justify-between items-start">
                                    <h4 class="font-black text-xl text-[var(--color-primary)] uppercase"><?php echo htmlspecialchars($queja['first_name'] . ' ' . $queja['last_name']); ?></h4>
                                    <span class="text-xs font-bold bg-red-200 text-red-700 px-3 py-1 rounded-full uppercase flex items-center gap-1.5"><i data-lucide="calendar" class="w-4 h-4"></i> <?php echo $queja['fecha']; ?></span>
                                </div>
                                <p class="font-bold text-sm mt-3 text-[var(--color-secondary)] uppercase border-b border-red-200 pb-2"><?php echo htmlspecialchars($queja['title']); ?></p>
                                <p class="text-sm text-gray-700 mt-2 italic">"<?php echo htmlspecialchars($queja['description']); ?>"</p>
                                <div class="mt-4 text-xs text-gray-500 font-bold uppercase flex justify-between items-center">
                                    <span>Estado: <?php echo $queja['status']; ?></span>
                                     <a href="#" class="text-[var(--color-primary)] hover:text-[var(--color-secondary)] underline font-black">Ver Detalles</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
            <?php else: ?>
            
            
            <section id="complaints" class="fade-in">
                <div class="mb-8 text-center">
                    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
                        <i data-lucide="award" class="w-8 h-8 md:w-10 md:h-10 text-green-500"></i>
                        EXCELENTE DESEMPEÑO
                    </h3>
                    <p class="text-gray-600 text-lg uppercase font-medium">SIN REPORTES NEGATIVOS</p>
                </div>
                <div class="bg-white p-10 rounded-2xl border-2 border-green-400 text-center shadow-xl">
                    <i data-lucide="handshake" class="w-16 h-16 text-green-600 mx-auto mb-4 block"></i>
                    <p class="font-black text-3xl text-[var(--color-primary)]">¡FELICITACIONES, <?php echo strtoupper($staffName); ?>!</p>
                    <p class="text-gray-700 font-medium mt-2">No tienes reportes de quejas o asuntos pendientes.</p>
                    <p class="text-gray-500 text-sm mt-1">Sigue brindando un servicio de excelencia.</p>
                </div>
                <?php endif; ?>
            </section>
            
<section id="documents" class="fade-in mt-12">
    <div class="mb-10 text-center border-b border-gray-100 pb-6">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="folder-open" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            DOCUMENTOS EMPRESARIALES
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">MANUALES, POLÍTICAS Y DOCUMENTOS PRIVADOS</p>
    </div>

    
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <?php if(empty($docs_global)): ?>
            <p class="text-gray-500 text-sm italic py-4 col-span-full text-center">No hay documentos globales disponibles.</p>
        <?php endif; ?>
        <?php foreach($docs_global as $doc): ?>
            <a href="<?php echo $doc['file_path']; ?>" target="_blank" class="flex items-center p-4 border border-gray-200 rounded-xl hover:border-[var(--color-highlight)] transition-all group hover:shadow-md bg-white">
                <div class="bg-white p-3 rounded-lg text-[var(--color-primary)] group-hover:bg-[var(--color-highlight)] group-hover:text-white border-2 border-gray-100"><i data-lucide="file-text" class="w-5 h-5"></i></div>
                <div class="ml-3 overflow-hidden">
                    <h4 class="font-black text-[var(--color-primary)] text-lg truncate"><?php echo $doc['file_name']; ?></h4>
                    <p class="text-xs font-bold text-gray-500 uppercase mt-1">Global / Descargar</p>
                </div>
                <i data-lucide="download" class="w-5 h-5 ml-auto text-gray-400 group-hover:text-[var(--color-primary)]"></i>
            </a>
        <?php endforeach; ?>
    </div>
    
    <div class="md:col-span-full pt-8 mt-8 border-t border-gray-200">
        <div class="mb-8 text-center">
            <h3 class="text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
                <i data-lucide="lock" class="w-7 h-7 text-[var(--color-secondary)]"></i> 
                DOCUMENTOS EXCLUSIVOS
            </h3>
            <p class="text-gray-600 text-base uppercase font-medium">Información específica y confidencial</p>
        </div>
    </div>
    
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <?php if(empty($docs_personal)): ?>
            <div class="col-span-full flex flex-col items-center justify-center py-8 text-center">
                <i data-lucide="folder-x" class="w-20 h-20 text-[var(--color-secondary)] mb-3"></i>
                <p class="text-gray-500 text-sm italic uppercase">No tienes documentos privados asignados.</p>
            </div>
        <?php endif; ?>

        <?php foreach($docs_personal as $doc): ?>
            <a href="<?php echo $doc['file_path']; ?>" target="_blank" class="flex items-center p-4 border-l-4 border-[var(--color-secondary)] bg-white rounded-r-xl hover:shadow-md transition-all">
                <div class="bg-white p-3 rounded-lg text-[var(--color-secondary)] border border-gray-200"><i data-lucide="user-cog" class="w-5 h-5"></i></div>
                <div class="ml-3 overflow-hidden">
                    <h4 class="font-black text-[var(--color-primary)] text-lg truncate"><?php echo $doc['file_name']; ?></h4>
                    <p class="text-xs font-bold text-red-500 uppercase mt-1">Privado / Confidencial</p>
                </div>
                <i data-lucide="eye" class="w-5 h-5 ml-auto text-red-500"></i>
            </a>
        <?php endforeach; ?>
    </div>
</section>

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

<section id="academy" class="bg-black text-white p-6 lg:p-10 shadow-2xl relative overflow-hidden">
    <div class="absolute inset-0 z-0 opacity-10"><div class="absolute bottom-0 left-0 translate-x-1/4 translate-y-1/4 w-[42rem] h-[42rem] rounded-md blur-3xl" style="background: radial-gradient(closest-side, var(--color-highlight), transparent 70%);"></div></div>
    <div class="relative z-10 max-w-7xl mx-auto">
        <div class="mb-8 text-center">
            <h3 class="text-3xl md:text-4xl font-black uppercase text-white mb-2 flex items-center justify-center gap-2">
                <i data-lucide="graduation-cap" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-highlight)]"></i>
                ENTRENAMIENTO <?php echo htmlspecialchars($company_name); ?>
            </h3>
            <p class="text-white/80 text-lg uppercase font-medium">VIDEOS Y GUÍAS DE MEJORES PRÁCTICAS</p>
        </div>
        <div id="videos-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div class="col-span-full text-center py-8 text-white/40"><i data-lucide="loader" class="animate-spin w-8 h-8 mx-auto mb-2"></i> Cargando Videos...</div>
        </div>
    </div>
</section>
            
   <?php @include '../files/page-footer.php'; ?>

<div id="clockConfirmModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
     onclick="if(event.target === this) closeClockModal()">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center relative overflow-hidden">
        <div class="modal-header-container bg-[var(--color-primary)] rounded-t-xl pt-6 pb-4 border-b-4 border-[var(--color-highlight)]">
            <h3 id="clock-modal-title" class="modal-primary-title text-3xl font-black text-white uppercase leading-none">CONFIRMACIÓN</h3>
        </div>
        <div class="p-8">
            <div id="clock-modal-icon-container" class="flex justify-center mb-4">
                </div>
            
            <p class="text-[var(--color-primary)] mb-2 uppercase text-xl font-black leading-tight">
                ¿ESTÁS SEGURO?
            </p>
            
            <p id="clock-modal-message" class="text-gray-500 font-medium text-sm mb-6 uppercase leading-relaxed">
                </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" onclick="closeClockModal()" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-black py-3 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 transition-colors">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button type="button" id="clock-confirm-btn" class="text-white font-black py-3 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-lg hover:opacity-90 transition-all">
                    </button>
            </div>
        </div>
    </div>
</div>

<div id="serviceQRModal" class="fixed inset-0 bg-gray-900/95 hidden z-[70] flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm text-center overflow-hidden">
        <div class="bg-[var(--color-secondary)] p-4">
            <h3 class="text-white font-black uppercase tracking-widest text-lg">Pase de Cliente</h3>
        </div>
        <div class="p-8">
            <p class="text-gray-500 text-sm font-bold uppercase mb-4">Pide al cliente que escanee este código para firmar.</p>
            
            <div id="service-qr-display" class="bg-white p-2 rounded-lg shadow-inner border border-gray-200 mx-auto w-fit mb-4"></div>
            
            <div class="animate-pulse text-[var(--color-secondary)] font-black text-xs uppercase flex items-center justify-center gap-2">
                <i data-lucide="smartphone" class="w-4 h-4"></i> Esperando firma...
            </div>
        </div>
        <button onclick="document.getElementById('serviceQRModal').classList.add('hidden')" class="w-full bg-gray-100 text-gray-600 py-4 font-bold uppercase text-xs hover:bg-gray-200">Cerrar</button>
    </div>
</div>

<script>
    // Función para abrir el QR del servicio
    async function openServiceQR(apptId) {
        const modal = document.getElementById('serviceQRModal');
        const qrContainer = document.getElementById('service-qr-display');
        qrContainer.innerHTML = '<p class="text-xs">Generando...</p>';
        modal.classList.remove('hidden');

        try {
            const res = await fetch('db/service-verification-handler.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ action: 'generate_token', appointment_id: apptId })
            });
            const data = await res.json();
            
            if (data.success) {
                qrContainer.innerHTML = '';
                new QRCode(qrContainer, {
                    text: data.url,
                    width: 200,
                    height: 200,
                    colorDark : "#07162d",
                    colorLight : "#ffffff",
                    correctLevel : QRCode.CorrectLevel.H
                });
            } else {
                alert("Error al generar QR: " + data.message);
                modal.classList.add('hidden');
            }
        } catch (e) {
            alert("Error de conexión");
            modal.classList.add('hidden');
        }
    }
</script>

<input type="hidden" id="staff-id" value="<?php echo $staff_id; ?>">

<script>
    const staffId = document.getElementById('staff-id').value;
    const clientsPanel = document.getElementById('clients-panel');
    const mobileNavPanel = document.getElementById('mobile-nav-panel'); 
    const overlay = document.getElementById('overlay');
    const clockDisplay = document.getElementById('clock-display');
    
    const menuToggleBtn = document.getElementById('menu-toggle-btn');
    const menuCloseBtn = document.getElementById('menu-close-btn');
    const clientsToggleBtnMobile = document.getElementById('clients-toggle-btn-mobile');
    const clientsToggleBtnDesktop = document.getElementById('clients-toggle-btn-desktop');
    const clientsCloseBtn = document.getElementById('clients-close-btn');

    // PANEL UTILS
    function openClientsPanel() { clientsPanel.classList.remove('translate-x-full'); overlay.classList.remove('hidden'); }
    function closeClientsPanel() { clientsPanel.classList.add('translate-x-full'); overlay.classList.add('hidden'); }
    function openMobileMenu() { mobileNavPanel?.classList.remove('translate-x-full'); overlay.classList.remove('hidden'); }
    function closeMobileMenu() { mobileNavPanel?.classList.add('translate-x-full'); overlay.classList.add('hidden'); }
    
    // RELOJ DISPLAY
    function updateClockDisplay() {
        if (clockDisplay && clockDisplay.textContent.toUpperCase() === 'EN TURNO') {
            const now = new Date();
            clockDisplay.textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        }
    }
    
    // NAV ACTIVA
    function updateActiveNavLink() {
        const sections = document.querySelectorAll('main section, main header');
        const navLinks = document.querySelectorAll('.nav-link-staff, .mobile-nav-link-staff');
        let currentSection = '';
        sections.forEach(section => {
            const rect = section.getBoundingClientRect();
            if (rect.top <= 150 && rect.bottom >= 150) currentSection = section.id.replace('-content-area', '');
        });
        navLinks.forEach(link => {
            const dataTarget = link.getAttribute('data-target');
            link.classList.remove('bg-[var(--color-highlight)]', 'text-[var(--color-primary)]', 'border-t-white');
            if (dataTarget === currentSection) {
                if (link.classList.contains('nav-link-staff')) link.classList.add('bg-[var(--color-highlight)]', 'text-[var(--color-primary)]', 'border-t-white');
                if (link.classList.contains('mobile-nav-link-staff')) link.classList.add('bg-[var(--color-highlight)]', 'text-[var(--color-primary)]');
            }
        });
    }

    // CLOCK LOGIC
    async function cancelClock() {
        const formData = new FormData(); formData.append('action', 'clock_cancel');
        try {
            const response = await fetch('dashboard.php', { method: 'POST', body: formData });
            const data = await response.json();
            if (data.success) location.reload();
        } catch (error) { console.error(error); }
    }

    function openClockModal() {
        const clockBtn = document.getElementById('clock-btn');
        const modal = document.getElementById('clockConfirmModal');
        const modalBox = modal.querySelector('div:first-of-type');
        const confirmBtn = document.getElementById('clock-confirm-btn');
        const modalTitle = document.getElementById('clock-modal-title');
        const modalMessage = document.getElementById('clock-modal-message');
        const iconContainer = document.getElementById('clock-modal-icon-container');
        const isWorking = clockBtn.innerText.includes('TERMINAR');

        if (isWorking) {
            modalTitle.innerText = "FINALIZAR JORNADA";
            modalMessage.innerHTML = "Se registrará tu hora de salida.<br><span class='font-bold text-red-600'>¿Deseas terminar tu turno ahora?</span>";
            iconContainer.innerHTML = '<i data-lucide="log-out" class="w-16 h-16 text-red-600"></i>';
            confirmBtn.className = "bg-red-600 hover:bg-red-700 text-white font-black py-3 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-lg transition-colors";
            confirmBtn.innerHTML = '<i data-lucide="stop-circle" class="w-5 h-5"></i> SÍ, SALIR';
        } else {
            modalTitle.innerText = "INICIAR JORNADA";
            modalMessage.innerHTML = "Se registrará tu hora de entrada.<br><span class='font-bold text-green-600'>¡Que tengas un excelente día!</span>";
            iconContainer.innerHTML = '<i data-lucide="alarm-clock-check" class="w-16 h-16 text-green-600"></i>';
            confirmBtn.className = "bg-green-600 hover:bg-green-700 text-white font-black py-3 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-lg transition-colors";
            confirmBtn.innerHTML = '<i data-lucide="play-circle" class="w-5 h-5"></i> SÍ, INICIAR';
        }
        modal.classList.remove('hidden');
        setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
        if(typeof lucide !== 'undefined') lucide.createIcons();
    }

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

    async function executeClockToggle() {
        closeClockModal();
        const clockBtn = document.getElementById('clock-btn');
        clockBtn.disabled = true;
        clockBtn.innerHTML = '<i data-lucide="loader" class="w-6 h-6 inline-block mr-2 animate-spin"></i> PROCESANDO...';
        if(typeof lucide !== 'undefined') lucide.createIcons();

        const formData = new FormData(); formData.append('action', 'clock_toggle');
        try {
            const response = await fetch('dashboard.php', { method: 'POST', body: formData });
            const data = await response.json();
            if (data.success) {
                setTimeout(() => location.reload(), 1500);
            } else {
                alert(data.message + " " + (data.subtext || ''));
                location.reload();
            }
        } catch (error) { location.reload(); }
    }

    // ACADEMIA & WIDGETS
     function loadAcademyVideos() {
        const vidC = document.getElementById('videos-container');
        fetch(`staff-read.php?id=${staffId}&academy=true`)
        .then(r => r.json())
        .then(d => {
            if(!d.videos || d.videos.length === 0) {
                vidC.innerHTML = '<p class="text-white/50 col-span-full text-center italic text-lg font-medium py-10">Sin videos de entrenamiento asignados.</p>';
            } else {
                vidC.innerHTML = d.videos.map(v => `
                    <div class="bg-white/10 rounded-xl overflow-hidden border border-white/20 hover:border-[var(--color-highlight)] transition-all group shadow-xl">
                        <div class="aspect-video relative bg-black">
                            <iframe class="w-full h-full" src="https://www.youtube.com/embed/${v.youtube_id}" frameborder="0" allowfullscreen></iframe>
                        </div>
                        <div class="p-4"><h4 class="font-bold text-lg text-white leading-tight group-hover:text-[var(--color-highlight)] transition-colors">${v.title}</h4></div>
                    </div>
                `).join('');
            } 
            lucide.createIcons(); 
        })
        .catch(e => { console.error(e) });
    }

    const toggleWidgetVisibility = (widgetId, isHidden) => {
        const widget = document.getElementById(widgetId);
        const showContainer = document.querySelector('header .show-widget-container'); 
        const videoPlayer = widget ? widget.querySelector('video') : null;
        if (!widget || !showContainer) return;

        if (isHidden) {
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }
        localStorage.setItem(`hide_${widgetId}_${staffId}`, isHidden ? 'true' : 'false');
    };

    // INIT
    document.addEventListener('DOMContentLoaded', () => {
        if (clientsToggleBtnDesktop) clientsToggleBtnDesktop.addEventListener('click', openClientsPanel);
        if (clientsToggleBtnMobile) clientsToggleBtnMobile.addEventListener('click', openClientsPanel);
        if (clientsCloseBtn) clientsCloseBtn.addEventListener('click', closeClientsPanel);
        if (menuToggleBtn) menuToggleBtn.addEventListener('click', openMobileMenu);
        if (menuCloseBtn) menuCloseBtn.addEventListener('click', closeMobileMenu);
        if (overlay) overlay.addEventListener('click', () => { closeClientsPanel(); closeMobileMenu(); });

        loadAcademyVideos();

        const videoWidgetId = 'videotutorial';
        const hideState = localStorage.getItem(`hide_${videoWidgetId}_${staffId}`);
        toggleWidgetVisibility(videoWidgetId, hideState === 'true');

        document.querySelectorAll('.hide-widget-btn').forEach(btn => btn.addEventListener('click', (e) => { e.preventDefault(); toggleWidgetVisibility(videoWidgetId, true); }));
        document.querySelectorAll('.show-widget-btn').forEach(btn => btn.addEventListener('click', (e) => { e.preventDefault(); toggleWidgetVisibility(videoWidgetId, false); }));

        const playOverlayStaff = document.getElementById('playOverlayStaff');
        const videoPlayerStaff = document.getElementById('videoPlayerStaff');
        if (playOverlayStaff && videoPlayerStaff) {
             playOverlayStaff.addEventListener('click', function() { this.style.display = 'none'; videoPlayerStaff.play(); });
        }

        const clockBtn = document.getElementById('clock-btn');
        if (clockBtn) {
            if (clockBtn.innerText.includes('TERMINAR')) { updateClockDisplay(); setInterval(updateClockDisplay, 1000); }
            clockBtn.addEventListener('click', (e) => { e.preventDefault(); openClockModal(); });
        }
        
        const confirmClockBtn = document.getElementById('clock-confirm-btn');
        if (confirmClockBtn) confirmClockBtn.addEventListener('click', executeClockToggle);

        window.addEventListener('scroll', updateActiveNavLink);
        updateActiveNavLink();
        lucide.createIcons();
    });
</script>
<script src="../files/toast.js"></script>
</body>
</html>