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

$total_staff = 0;
$active_now = 0;
$total_docs_global = 0;
$company_name = "EMPRESARIAL";

try {
    if (isset($pdo)) {
        $stmt_staff = $pdo->prepare("SELECT COUNT(*) FROM staff WHERE status='activo'");
        $stmt_staff->execute();
        $total_staff = $stmt_staff->fetchColumn();

        $stmt_active = $pdo->prepare("SELECT COUNT(DISTINCT staff_id) FROM work_logs WHERE clock_out IS NULL AND clock_in >= CURDATE() AND clock_in < CURDATE() + INTERVAL 1 DAY");
        $stmt_active->execute();
        $active_now = $stmt_active->fetchColumn();

        $stmt_docs = $pdo->prepare("SELECT COUNT(*) FROM staff_documents WHERE staff_id IS NULL");
        $stmt_docs->execute();
        $total_docs_global = $stmt_docs->fetchColumn();

        $stmtInfo = $pdo->prepare("SELECT company_name FROM business_info LIMIT 1");
        $stmtInfo->execute();
        $info = $stmtInfo->fetch(PDO::FETCH_ASSOC);
        if ($info && !empty($info['company_name'])) {
            $company_name = strtoupper($info['company_name']);
        }
    }
} catch (PDOException $e) { error_log("Error Dashboard: " . $e->getMessage()); }

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Miembros Del Equipo Empresarial <?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>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>

    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
  
  <style>
      .modal-dialog { transition: transform 0.3s ease-out, opacity 0.3s ease-out; }
      #staffPanel { z-index: 5000; } 
      .toast-container { z-index: 9999; position: fixed; top: 20px; right: 20px; }
      /* Estilo QR */
      #qr-code-display img { margin: 0 auto; border: 4px solid white; border-radius: 8px; }
  </style>
</head>

<body data-page-title="Gestión De Miembros Del Equipo"
data-page-subtitle="Panel De Control De Empleados Y Documentos"
data-page-icon="users">
    
    <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-sm 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="content-area" class="p-4 md:p-8 space-y-8">
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                    <i data-lucide="users" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                    <div><h3 class="text-lg font-black text-gray-500 mb-1">TOTAL EMPLEADOS</h3><p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_staff; ?></p></div>
                </div>
                <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                    <i data-lucide="clock" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                    <div><h3 class="text-lg font-black text-gray-500 mb-1">ACTIVOS AHORA</h3><p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $active_now; ?></p></div>
                </div>
                <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                    <i data-lucide="folder" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                    <div><h3 class="text-lg font-black text-gray-500 mb-1">DOCUMENTOS</h3><p id="total-docs-global" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_docs_global; ?></p></div>
                </div>
            </div>

            <section id="directorio" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-end mb-6 gap-4">
                        <div>
                            <h3 class="text-3xl font-black uppercase text-[var(--color-primary)] flex items-center gap-2 leading-none mb-2">
                                <i data-lucide="id-card" class="w-8 h-8 text-[var(--color-secondary)]"></i> EQUIPO COMERCIAL
                            </h3>
                            <p class="text-gray-500 text-sm uppercase font-bold tracking-wide">ADMINISTRA PERFILES, ROLES Y ASIGNACIONES.</p>
                        </div>
                        <div class="flex gap-2 w-full md:w-auto">
                            <input type="text" id="staff-search" placeholder="Buscar..." class="pl-4 p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] outline-none w-full md:w-auto focus:border-transparent">
                            <button class="bg-[var(--color-primary)] text-white font-bold py-2 px-4 rounded-lg flex items-center uppercase text-sm shadow-md hover:opacity-90 transition whitespace-nowrap" onclick="openCreatePanel()">
                                <i data-lucide="plus" class="w-4 h-4 mr-2"></i> NUEVO MIEMBRO
                            </button>
                        </div>
                    </div>
                    <div id="staff-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"></div>
                </div>
            </section>
            
            <div class="bg-orange-50 border-l-4 border-orange-500 p-6 rounded-r shadow-sm flex flex-col md:flex-row justify-between items-center gap-6">
                <div class="flex items-start gap-4 w-full md:w-auto">
                    <div class="bg-orange-100 p-3 rounded-full mt-1"><i data-lucide="megaphone" class="w-8 h-8 text-orange-600"></i></div>
                    <div class="flex-1">
                        <h4 class="font-black text-[var(--color-primary)] text-2xl uppercase mb-1">Notificaciones Importantes</h4>
                        <p class="text-orange-800 text-lg font-medium" id="current-global-msg">Cargando...</p>
                    </div>
                </div>
                <div class="flex gap-2 w-full md:w-auto items-center">
                    <input type="text" id="global-notification-input" placeholder="Nuevo Mensaje..." class="text-sm p-3 border border-orange-200 rounded w-full md:w-80 shadow-sm outline-none focus:ring-2 focus:ring-orange-500">
                    <button onclick="updateGlobalNotification()" class="bg-orange-600 text-white px-5 py-3 rounded text-sm font-bold hover:bg-orange-700 uppercase shadow-md transition-colors">Publicar</button>
                </div>
            </div>

            <section id="documentos-globales" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-secondary)]">
                    <div class="mb-6">
                        <h3 class="text-3xl font-black uppercase text-[var(--color-primary)] flex items-center gap-2">
                            <i data-lucide="folder-open" class="w-7 h-7 text-[var(--color-secondary)]"></i> DOCUMENTOS EMPRESARIALES (SOP)
                        </h3>
                        <p class="text-gray-500 text-sm mt-2 uppercase font-bold tracking-wide mb-6">REPOSITORIO CENTRALIZADO DE PROCEDIMIENTOS.</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200 mb-6">
                           <div class="grid grid-cols-1 md:grid-cols-12 gap-4 items-end">
                                <div class="md:col-span-5">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Nombre del Documento</label>
                                    <input type="text" id="global-doc-name" class="w-full p-2 border rounded text-sm focus:ring-2 focus:ring-[var(--color-secondary)] outline-none border-gray-300">
                                </div>
                                <div class="md:col-span-5">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Archivo PDF</label>
                                    <input type="file" id="global-doc-file" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-[var(--color-primary)] file:text-white hover:file:bg-[var(--color-secondary)]">
                                </div>
                                <div class="md:col-span-2">
                                    <button onclick="uploadGlobalDoc()" class="w-full bg-[var(--color-primary)] text-white font-bold py-2 px-4 rounded text-sm uppercase shadow-md hover:opacity-90 transition">SUBIR</button>
                                </div>
                           </div>
                    </div>
                    <ul id="global-docs-list" class="space-y-2 grid grid-cols-1 md:grid-cols-2 gap-4"></ul>
                </div>
            </section>

            <section id="academia-global" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-primary)]">
                    <div class="mb-6">
                        <h3 class="text-3xl font-black uppercase text-[var(--color-primary)] flex items-center gap-2">
                            <i data-lucide="monitor-play" class="w-7 h-7 text-[var(--color-secondary)]"></i> ACADEMIA <?php echo htmlspecialchars($company_name); ?>
                        </h3>
                        <p class="text-gray-500 text-sm mt-2 uppercase font-bold tracking-wide mb-6">CENTRO DE CAPACITACIÓN.</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200 mb-6">
                           <div class="grid grid-cols-1 md:grid-cols-12 gap-4 items-end">
                                <div class="md:col-span-5">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Título del Video</label>
                                    <input type="text" id="global-video-title" class="w-full p-2 border rounded text-sm focus:ring-2 focus:ring-[var(--color-secondary)] outline-none border-gray-300">
                                </div>
                                <div class="md:col-span-5">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">YouTube URL</label>
                                    <input type="text" id="global-video-url" class="w-full p-2 border rounded text-sm focus:ring-2 focus:ring-[var(--color-secondary)] outline-none border-gray-300">
                                </div>
                                <div class="md:col-span-2">
                                    <button onclick="uploadGlobalVideo()" class="w-full bg-[var(--color-secondary)] text-white font-bold py-2 px-4 rounded text-sm uppercase shadow-md hover:opacity-90 transition">PUBLICAR</button>
                                </div>
                           </div>
                    </div>
                    <div id="global-videos-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="staffPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex flex-col h-full">
        <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
            <h3 class="text-2xl md:text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase gap-2">
                <i data-lucide="user-cog" class="w-8 h-8 text-[var(--color-highlight)]"></i> 
                <span id="panel-title">DETALLES</span>
            </h3>
            <button onclick="closePanel()" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                <i data-lucide="x" class="w-8 h-8"></i>
            </button>
        </div>
        
        <div class="flex border-b border-gray-200 bg-white flex-shrink-0 shadow-sm z-10">
            <button onclick="switchTab('tab-general')" class="flex-1 py-3 text-xs font-black text-center uppercase transition-colors border-b-4 border-[var(--color-primary)] text-[var(--color-primary)] bg-gray-50" id="btn-tab-general">
                PERFIL & ROLES
            </button>
            <button onclick="switchTab('tab-assign')" class="flex-1 py-3 text-xs font-black text-center uppercase transition-colors text-gray-500 hover:text-gray-700 border-b-4 border-transparent hover:bg-gray-50" id="btn-tab-assign">
                ASIGNACIONES
            </button>
            <button onclick="switchTab('tab-academy-indiv')" class="flex-1 py-3 text-xs font-black text-center uppercase transition-colors text-gray-500 hover:text-gray-700 border-b-4 border-transparent hover:bg-gray-50" id="btn-tab-academy-indiv">
                ACADEMIA
            </button>
        </div>
        
        <div class="flex-grow overflow-y-auto p-6 bg-gray-50 relative">
            <input type="hidden" id="current-staff-id">
            <input type="hidden" id="current-public-uid"> 
            
            <div id="tab-general" class="space-y-6">
                <div class="bg-white p-5 rounded-xl shadow-md border border-gray-100">
                    
                    <div class="flex flex-col items-center justify-center mb-6 border-b border-gray-100 pb-6">
                        <div class="relative group cursor-pointer" onclick="document.getElementById('staff-photo-input').click()">
                            <div class="w-24 h-24 rounded-full border-4 border-[var(--color-primary)] overflow-hidden bg-gray-100 shadow-md">
                                <img id="staff-photo-preview" src="img/default-avatar.png" class="w-full h-full object-cover">
                            </div>
                            <div class="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                <i data-lucide="camera" class="w-8 h-8 text-white"></i>
                            </div>
                        </div>
                        <p class="text-[10px] text-gray-400 mt-2 uppercase font-bold">Click para cambiar foto</p>
                        <input type="file" id="staff-photo-input" class="hidden" accept="image/*" onchange="uploadProfilePhoto(this)">
                    </div>

                    <form id="staff-form" class="space-y-5">
                        
                        <div class="bg-indigo-50 border border-indigo-100 p-4 rounded-lg flex flex-col md:flex-row items-center justify-between gap-4">
                            <div><label class="block text-md font-black text-indigo-900 uppercase">Rol Y Permisos</label></div>
                            <select id="staff-role" class="p-2 border border-indigo-200 rounded-lg text-sm font-bold text-indigo-900 bg-white w-full md:w-auto outline-none">
                                <option value="employee">EMPLEADO</option>
                                <option value="manager">MANAGER</option>
                            </select>
                        </div>

                        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                            <label for="is-employee-month" class="flex items-center gap-2 cursor-pointer w-full select-none">
                                <input type="checkbox" id="is-employee-month" class="w-5 h-5 text-yellow-500 rounded focus:ring-yellow-500 border-gray-300">
                                <span class="text-sm font-black text-yellow-800 uppercase flex items-center"><i data-lucide="crown" class="w-4 h-4 inline mr-2"></i> Empleado del Mes</span>
                            </label>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div><label class="block text-xs font-bold text-gray-600 uppercase mb-1">Nombre</label><input type="text" id="staff-firstname" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] outline-none" required></div>
                            <div><label class="block text-xs font-bold text-gray-600 uppercase mb-1">Apellido</label><input type="text" id="staff-lastname" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] outline-none" required></div>
                        </div>
                        
                        <div><label class="block text-xs font-bold text-gray-600 uppercase mb-1">Email</label><input type="email" id="staff-email" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] outline-none" required></div>
                        <div><label class="block text-xs font-bold text-gray-600 uppercase mb-1">Teléfono</label><input type="tel" id="staff-phone" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] outline-none"></div>
                        
                        <div class="grid grid-cols-2 gap-4">
                             <div class="bg-blue-50 p-3 rounded-lg border border-blue-200">
                                <label class="block text-[10px] font-black text-blue-800 uppercase mb-1">Antigüedad</label>
                                <input type="text" id="staff-tenure" class="w-full bg-transparent border-none text-sm font-bold text-blue-900 p-0 focus:ring-0" readonly placeholder="N/A">
                            </div>
                            <div class="bg-green-50 p-3 rounded-lg border border-green-200">
                                <label class="block text-sm font-black text-green-800 uppercase mb-1">Tarifa / Hr</label>
                                <div class="relative">
                                    <span class="absolute inset-y-0 left-0 pl-1 flex items-center text-green-700 font-bold text-sm">$</span>
                                    <input type="number" id="staff-rate" step="0.01" class="w-full pl-4 p-1 bg-transparent border-none font-bold text-green-800 text-sm focus:ring-0 outline-none" placeholder="0.00">
                                </div>
                            </div>
                        </div>

                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <label class="block text-sm font-black text-gray-600 uppercase mb-3 flex items-center"><i data-lucide="calendar-days" class="w-4 h-4 mr-2"></i> Horario Semanal</label>
                            <div id="schedule-container" class="space-y-2"></div>
                        </div>

                        <div class="bg-gray-100 p-4 rounded-lg border border-gray-300">
                            <label class="block text-sm font-black text-gray-600 uppercase mb-3 flex items-center"><i data-lucide="calendar-off" class="w-4 h-4 mr-2"></i> Días Bloqueados</label>
                            <div class="flex gap-2 mb-2">
                                <input type="date" id="block-date" class="border border-gray-300 rounded p-2 text-xs flex-1 outline-none">
                                <input type="text" id="block-reason" placeholder="Razón" class="border border-gray-300 rounded p-2 text-xs flex-1 outline-none">
                                <button type="button" onclick="addBlockedDay()" class="bg-[var(--color-secondary)] text-white px-3 rounded font-bold hover:opacity-90 transition">+</button>
                            </div>
                            <ul id="blocked-days-list" class="space-y-1 max-h-32 overflow-y-auto bg-white p-2 rounded border border-gray-200"></ul>
                        </div>
                        
                        <div class="bg-gray-800 p-4 rounded-lg border border-gray-700 flex flex-col gap-3 shadow-inner">
                            <div class="flex items-center justify-between">
                                <div>
                                    <label class="block text-xs font-black text-gray-400 uppercase mb-1">Código Acceso</label>
                                    <input type="password" id="staff-code" class="bg-transparent border-none font-mono tracking-widest text-lg w-32 text-white focus:ring-0 p-0" readonly>
                                </div>
                                <div class="flex gap-2">
                                    <button type="button" onclick="copyAccessCode()" class="bg-gray-700 text-white p-2 hover:bg-gray-600 rounded transition" title="Copiar"><i data-lucide="copy" class="w-4 h-4"></i></button>
                                    <button type="button" onclick="toggleCodeVisibility()" class="bg-gray-700 text-white p-2 hover:bg-gray-600 rounded transition" title="Ver"><i data-lucide="eye" class="w-4 h-4"></i></button>
                                    <button type="button" onclick="askRegenerate()" class="bg-gray-700 text-white p-2 hover:bg-gray-600 rounded transition" title="Regenerar"><i data-lucide="refresh-cw" class="w-4 h-4"></i></button>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-2 mt-2">
                                <button type="button" onclick="openQRModal()" class="bg-[var(--color-highlight)] hover:bg-white text-[var(--color-primary)] font-black py-2 rounded uppercase text-xs tracking-wider shadow transition-colors flex items-center justify-center gap-2">
                                    <i data-lucide="qr-code" class="w-4 h-4"></i> Ver QR
                                </button>
                                <button type="button" onclick="copyPublicLink()" class="bg-green-600 hover:bg-green-700 text-white font-black py-2 rounded uppercase text-xs tracking-wider shadow transition-colors flex items-center justify-center gap-2">
                                    <i data-lucide="share-2" class="w-4 h-4"></i> Copiar Link
                                </button>
                            </div>
                        </div>
                        
                        <div id="delete-staff-link-container" class="pt-2 text-right hidden">
                            <button type="button" onclick="askDeleteStaff()" class="text-xs font-bold text-red-600 hover:text-red-800 uppercase flex items-center gap-1 ml-auto transition-colors">
                                <i data-lucide="trash-2" class="w-4 h-4"></i> Eliminar Staff
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <div id="tab-assign" class="hidden space-y-6">
                <div class="bg-white p-5 rounded-xl shadow-md border border-gray-100">
                    <div class="flex justify-between items-center mb-4 border-b pb-2">
                        <h4 class="font-black text-gray-700 text-sm uppercase flex items-center gap-2"><i data-lucide="briefcase" class="w-4 h-4 text-[var(--color-primary)]"></i> Clientes (<span id="count-clients">0</span>)</h4>
                    </div>
                    <div class="flex gap-2 mb-4 bg-gray-50 p-2 rounded-lg border border-gray-200">
                        <select id="assign-client-select" class="flex-1 p-2 bg-white border border-gray-300 rounded text-sm focus:ring-1 focus:ring-[var(--color-highlight)] outline-none"><option value="">Cargando lista...</option></select>
                        <button onclick="assignItem('client')" class="bg-[var(--color-primary)] text-white px-4 rounded font-bold hover:opacity-90 transition shadow-sm"><i data-lucide="plus" class="w-4 h-4"></i></button>
                    </div>
                    <div id="list-assigned-clients" class="space-y-2 max-h-60 overflow-y-auto custom-scrollbar"></div>
                </div>

                <div class="bg-white p-5 rounded-xl shadow-md border border-gray-100">
                    <div class="flex justify-between items-center mb-4 border-b pb-2">
                        <h4 class="font-black text-gray-700 text-sm uppercase flex items-center gap-2"><i data-lucide="map" class="w-4 h-4 text-emerald-600"></i> Rutas Asignadas</h4>
                    </div>
                    <div class="flex gap-2 mb-4 bg-gray-50 p-2 rounded-lg border border-gray-200">
                        <select id="assign-route-select" class="flex-1 p-2 bg-white border border-gray-300 rounded text-sm focus:ring-1 focus:ring-emerald-500 outline-none"><option value="">Cargando lista...</option></select>
                        <button onclick="assignItem('route')" class="bg-emerald-600 text-white px-4 rounded font-bold hover:bg-emerald-700 transition shadow-sm"><i data-lucide="plus" class="w-4 h-4"></i></button>
                    </div>
                    <div id="list-assigned-routes" class="space-y-2 max-h-60 overflow-y-auto custom-scrollbar"></div>
                </div>
            </div>

            <div id="tab-academy-indiv" class="hidden space-y-6">
                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-3 rounded-r-lg text-xs text-yellow-800 mb-4 font-bold flex gap-2 uppercase items-center shadow-sm">
                    <i data-lucide="lock" class="w-4 h-4"></i> Recurso Privado (Solo este empleado).
                </div>
                
                <div class="bg-white p-4 rounded-xl shadow-md">
                    <div class="flex justify-between items-center mb-3 border-b pb-2">
                        <h4 class="font-black text-gray-700 uppercase text-sm flex items-center gap-2"><i data-lucide="video" class="w-4 h-4"></i> Videos</h4>
                        <button onclick="document.getElementById('form-vid').classList.toggle('hidden')" class="text-xs bg-[var(--color-primary)] text-white px-2 py-1 rounded font-bold hover:opacity-90">+ AGREGAR</button>
                    </div>
                    <div id="form-vid" class="hidden bg-gray-50 p-3 rounded-lg mb-3 border border-gray-200">
                        <input type="text" id="indiv-video-title" placeholder="Título del Video" class="w-full mb-2 p-2 border border-gray-300 rounded text-xs focus:ring-1 focus:ring-[var(--color-highlight)] outline-none">
                        <div class="flex gap-2">
                            <input type="text" id="indiv-video-url" placeholder="URL (YouTube/Vimeo)" class="flex-1 p-2 border border-gray-300 rounded text-xs focus:ring-1 focus:ring-[var(--color-highlight)] outline-none">
                            <button onclick="uploadIndividualVideo()" class="bg-[var(--color-secondary)] text-white px-3 font-bold text-xs rounded hover:opacity-90">OK</button>
                        </div>
                    </div>
                    <div id="indiv-videos-list" class="grid grid-cols-1 md:grid-cols-1 gap-4"></div>
                </div>

                <div class="bg-white p-4 rounded-xl shadow-md">
                    <div class="flex justify-between items-center mb-3 border-b pb-2">
                         <h4 class="font-black text-gray-700 uppercase text-sm flex items-center gap-2"><i data-lucide="file-text" class="w-4 h-4"></i> Documentos</h4>
                         <button onclick="document.getElementById('form-doc').classList.toggle('hidden')" class="text-xs bg-[var(--color-primary)] text-white px-2 py-1 rounded font-bold hover:opacity-90">+ AGREGAR</button>
                    </div>
                    <div id="form-doc" class="hidden bg-gray-50 p-3 rounded-lg mb-3 border border-gray-200">
                           <input type="text" id="indiv-doc-name" placeholder="Nombre del Documento" class="w-full mb-2 p-2 border border-gray-300 rounded text-xs focus:ring-1 focus:ring-[var(--color-highlight)] outline-none">
                           <div class="flex gap-2 items-center">
                                 <input type="file" id="indiv-doc-file" class="flex-1 text-xs text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-bold file:bg-[var(--color-primary)] file:text-white hover:file:bg-[var(--color-secondary)]">
                                 <button onclick="uploadIndividualDoc()" class="bg-[var(--color-secondary)] text-white px-3 py-2 font-bold text-xs rounded hover:opacity-90">SUBIR</button>
                           </div>
                    </div>
                    <ul id="indiv-docs-list" class="space-y-2"></ul>
                </div>
            </div>
        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
            <div class="grid grid-cols-2 gap-3">
                <button type="button" onclick="closePanel()" class="w-full btn-cancel uppercase flex items-center justify-center gap-2 bg-[var(--color-primary)] hover:bg-gray-800 text-white font-bold py-2 px-4 rounded-lg shadow-sm transition-all">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button type="submit" form="staff-form" class="w-full btn-confirm uppercase flex items-center justify-center gap-2 bg-[var(--color-secondary)] hover:opacity-90 text-white font-bold py-2 px-4 rounded-lg shadow-md transition-all">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                </button>
            </div>
        </div>
    </div>
</div>

<div id="qrModal" class="fixed inset-0 bg-gray-900 bg-opacity-95 flex items-center justify-center hidden z-50 font-barlow" onclick="if(event.target === this) closeModal('qrModal')">
    <div class="modal-dialog relative mx-auto bg-white w-full max-w-sm m-4 rounded-2xl shadow-2xl overflow-hidden transform transition-all duration-300 scale-95 opacity-0">
        <div class="bg-[var(--color-primary)] p-6 text-center border-b-4 border-[var(--color-highlight)]">
            <h3 class="text-2xl font-black uppercase text-white tracking-widest">Credencial Digital</h3>
            <p class="text-[var(--color-highlight)] text-xs font-bold uppercase mt-1">Escanea para Verificar</p>
        </div>
        <div class="p-8 flex flex-col items-center justify-center bg-gray-50">
            <div id="qr-code-display" class="bg-white p-4 rounded-xl shadow-lg border border-gray-200 mb-6"></div>
            <h4 id="qr-staff-name" class="text-xl font-black text-[var(--color-primary)] uppercase text-center mb-1">Nombre Empleado</h4>
            <p class="text-xs font-bold text-gray-500 uppercase">ID: <span id="qr-staff-id">...</span></p>
        </div>
        <div class="p-4 bg-white border-t border-gray-200 grid grid-cols-2 gap-4">
             <button type="button" onclick="closeModal('qrModal')" class="bg-gray-200 text-gray-700 font-black py-3 rounded-lg uppercase text-xs hover:bg-gray-300 transition">Cerrar</button>
            <button type="button" onclick="downloadQR()" class="bg-[var(--color-secondary)] text-white font-black py-3 rounded-lg uppercase text-xs hover:opacity-90 transition flex items-center justify-center gap-2 shadow-lg"><i data-lucide="download" class="w-4 h-4"></i> Descargar</button>
        </div>
    </div>
</div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50 font-barlow" onclick="if(event.target === this) closeModal('confirmDeleteModal')"><div class="modal-dialog relative mx-auto p-0 border-0 shadow-2xl rounded-xl bg-white w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center overflow-hidden"><div class="modal-header-container bg-[var(--color-primary)] p-6"><h3 class="modal-primary-title text-3xl font-black uppercase text-[var(--color-highlight)] leading-none">ADVERTENCIA</h3></div><div class="p-8"><div class="flex justify-center mb-6"><i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i></div><p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">¿ESTÁS SEGURO DE ELIMINAR:<span id="delete-item-name" class="font-black text-[var(--color-secondary)] text-xl block mt-2 uppercase"></span><span id="delete-context-text" class="text-sm font-bold text-gray-500 block mt-1"></span></p><div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4 mt-4"><button type="button" onclick="closeModal('confirmDeleteModal')" class="btn-modal-cancel font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-sm"><i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR</button><button type="button" class="btn-modal-confirm font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md" id="confirm-delete-button"><i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR</button></div></div></div></div>
<div id="confirmRegenerateModal" class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50 font-barlow" onclick="if(event.target === this) closeModal('confirmRegenerateModal')"><div class="modal-dialog relative mx-auto p-0 border-0 shadow-2xl rounded-xl bg-white w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center overflow-hidden"><div class="modal-header-container bg-[var(--color-primary)] p-6"><h3 class="modal-primary-title text-3xl font-black uppercase text-[var(--color-highlight)] leading-none">CÓDIGO DE ACCESO</h3></div><div class="p-8"><div class="flex justify-center mb-6"><i data-lucide="refresh-cw" class="w-16 h-16 text-[var(--color-primary)]"></i></div><p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">¿REGENERAR CÓDIGO?<span class="font-bold text-base text-gray-500 block mt-2">EL ANTERIOR DEJARÁ DE FUNCIONAR</span></p><div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4 mt-4"><button type="button" onclick="closeModal('confirmRegenerateModal')" class="btn-modal-cancel font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-sm"><i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR</button><button type="button" onclick="regenerateCode()" class="btn-modal-confirm font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md"><i data-lucide="refresh-cw" class="w-5 h-5"></i> REGENERAR</button></div></div></div></div>

<script>
    let staffData = [];
    let currentBlockedDays = [];
    const DAYS_MAP = { 'Mon': 'Lunes', 'Tue': 'Martes', 'Wed': 'Miércoles', 'Thu': 'Jueves', 'Fri': 'Viernes', 'Sat': 'Sábado', 'Sun': 'Domingo' };

    document.addEventListener('DOMContentLoaded', () => { 
        loadStaff(); 
        loadGlobalResources(); 
        const phoneInput = document.getElementById('staff-phone');
        if(phoneInput && typeof IMask !== 'undefined') IMask(phoneInput, {mask: '(000) 000-0000'}); 
        document.getElementById('staff-search').addEventListener('keyup', renderGrid);
        
        // Cierres de panel
        const panelOverlay = document.getElementById('panel-overlay');
        panelOverlay.addEventListener('click', () => {
             const modalOpen = document.querySelector('.fixed.z-50:not(.hidden)');
             if (!modalOpen) closePanel();
        });
    });

    // --- FUNCIONES NUEVAS (Foto, QR, Antiguedad) ---
    function calculateTenure(dateString) {
        if (!dateString) return "Nuevo Ingreso";
        const start = new Date(dateString);
        const now = new Date();
        let years = now.getFullYear() - start.getFullYear();
        let months = now.getMonth() - start.getMonth();
        if (months < 0 || (months === 0 && now.getDate() < start.getDate())) { years--; months += 12; }
        if (years > 0) return `${years} Año${years > 1 ? 's' : ''}, ${months} Mes${months > 1 ? 'es' : ''}`;
        if (months > 0) return `${months} Mes${months > 1 ? 'es' : ''}`;
        return "Nuevo Ingreso";
    }

    async function uploadProfilePhoto(input) {
        const file = input.files[0];
        const staffId = document.getElementById('current-staff-id').value;
        if (!file || !staffId) return showToast('Guarde el perfil antes de subir foto.', 'info');
        const formData = new FormData();
        formData.append('staff_id', staffId);
        formData.append('photo', file);
        formData.append('action', 'update_photo'); 
        const reader = new FileReader();
        reader.onload = function(e) { document.getElementById('staff-photo-preview').src = e.target.result; }
        reader.readAsDataURL(file);
        try {
            const res = await fetch('db/staff-upload-photo.php', { method: 'POST', body: formData }); 
            const data = await res.json();
            if (data.success) { showToast('Foto actualizada', 'success'); loadStaff(); } 
            else { showToast('Error al subir foto', 'error'); }
        } catch (e) { showToast('Error de conexión', 'error'); }
    }

    function openQRModal() {
        const publicUid = document.getElementById('current-public-uid').value;
        const name = document.getElementById('staff-firstname').value + ' ' + document.getElementById('staff-lastname').value;
        if (!publicUid) return showToast('Error: UID Público no encontrado', 'error');
        document.getElementById('qr-staff-name').textContent = name;
        document.getElementById('qr-staff-id').textContent = publicUid;
        const qrContainer = document.getElementById('qr-code-display');
        qrContainer.innerHTML = '';
        const verificationUrl = `${window.location.origin}/verify-staff.php?id=${publicUid}`;
        new QRCode(qrContainer, { text: verificationUrl, width: 180, height: 180, colorDark : "#07162d", colorLight : "#ffffff", correctLevel : QRCode.CorrectLevel.H });
        window.openModal('qrModal');
    }

    function downloadQR() {
        const qrImg = document.querySelector('#qr-code-display img'); 
        if(qrImg && qrImg.src) {
            const a = document.createElement('a'); a.href = qrImg.src; a.download = `QR-${document.getElementById('current-public-uid').value}.png`;
            document.body.appendChild(a); a.click(); document.body.removeChild(a);
        }
    }
    
    function copyPublicLink() {
        const uid = document.getElementById('current-public-uid').value;
        if(!uid) return showToast('Error: Guarde el empleado primero', 'error');
        const url = `${window.location.origin}/verify-staff.php?id=${uid}`;
        navigator.clipboard.writeText(url).then(() => { showToast('Link copiado al portapapeles', 'success'); });
    }

    // --- FUNCIONES ORIGINALES RESTAURADAS ---
    window.showToast = function(message, type = 'success') {
       const c = document.getElementById('toast-container'); const t = document.createElement('div');
       const s = { success: 'bg-emerald-600', error: 'bg-[var(--color-secondary)]', info: 'bg-slate-800' };
       t.className = `${s[type]} text-white p-4 rounded shadow-lg flex items-center gap-3 min-w-[300px] transform translate-x-full transition-all duration-300 opacity-0 pointer-events-auto`;
       t.innerHTML = `<i data-lucide="${type==='success'?'check-circle':'info'}" class="w-5 h-5"></i> <span class="font-bold text-sm">${message}</span>`;
       c.appendChild(t); if(typeof lucide !== 'undefined') lucide.createIcons({container:t}); requestAnimationFrame(() => t.classList.remove('translate-x-full', 'opacity-0')); setTimeout(() => { t.classList.add('translate-x-full', 'opacity-0'); setTimeout(() => t.remove(), 500); }, 3000);
    }
    window.openModal = (id) => { const m=document.getElementById(id); if(m){m.classList.remove('hidden'); setTimeout(()=>m.querySelector('.modal-dialog').classList.remove('scale-95','opacity-0'),50);} }
    window.closeModal = (id) => { const m=document.getElementById(id); if(m){m.querySelector('.modal-dialog').classList.add('scale-95','opacity-0'); setTimeout(()=>m.classList.add('hidden'),300);} }

    // Modales logica
    function askRegenerate() {
        const staffId = document.getElementById('current-staff-id').value;
        if (!staffId) return showToast('Error: ID no encontrado.', 'error');
        window.openModal('confirmRegenerateModal');
    }
    function askDeleteStaff() {
        const staffId = document.getElementById('current-staff-id').value;
        const staffName = document.getElementById('panel-title').innerText.replace('DETALLES', '').trim();
        if (!staffId) return showToast('Error: ID no encontrado.', 'error');
        const deleteButton = document.getElementById('confirm-delete-button');
        deleteButton.onclick = deleteStaffMember;
        deleteButton.dataset.itemId = staffId;
        document.getElementById('delete-item-name').textContent = staffName.toUpperCase();
        document.getElementById('delete-context-text').textContent = 'Se eliminará al miembro y todas sus asignaciones.';
        window.openModal('confirmDeleteModal');
    }
    function openDeleteModal(type, id, context) {
        const deleteButton = document.getElementById('confirm-delete-button');
        deleteButton.onclick = () => {
            fetch('db/staff-actions.php', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ action: 'delete_academy', type: type, id: id }) })
            .then(res => res.json()).then(d => {
                if(d.success) { showToast('Eliminado'); context === 'global' ? loadGlobalResources() : loadIndividualAcademy(document.getElementById('current-staff-id').value); window.closeModal('confirmDeleteModal'); } 
                else { showToast('Error al eliminar', 'error'); }
            }).catch(e => showToast('Error', 'error'));
        };
        document.getElementById('delete-item-name').textContent = (type === 'video' ? 'VIDEO' : 'DOCUMENTO');
        document.getElementById('delete-context-text').textContent = 'Se eliminará este recurso.';
        window.openModal('confirmDeleteModal');
    }
    async function regenerateCode() {
        const id = document.getElementById('current-staff-id').value;
        window.closeModal('confirmRegenerateModal');
        try {
            const res = await fetch('db/staff-update.php', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({action: 'regenerate_code', id: id}) });
            const d = await res.json();
            if(d.success) { document.getElementById('staff-code').value = d.new_code; showToast('Nuevo código generado', 'success'); loadStaff(); }
        } catch(e) { showToast('Error', 'error'); }
    }
    async function deleteStaffMember() {
        const id = document.getElementById('confirm-delete-button').dataset.itemId;
        window.closeModal('confirmDeleteModal');
        try {
            const res = await fetch('db/staff-actions.php', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({action: 'delete_staff', id: id}) });
            const d = await res.json();
            if(d.success) { showToast('Eliminado', 'success'); loadStaff(); closePanel(); }
        } catch(e) { showToast('Error', 'error'); }
    }

    // Cargas de Datos
    async function loadStaff() {
        try { const res = await fetch('db/staff-read.php'); const data = await res.json(); if(data.success) { staffData = data.data; document.getElementById('total-docs-global').innerText = data.total_docs || 0; document.getElementById('current-global-msg').innerText = data.global_notification || '...'; renderGrid(); } } catch (e) { console.error(e); }
    }
    function renderGrid() {
        const grid = document.getElementById('staff-grid'); const term = document.getElementById('staff-search').value.toLowerCase();
        grid.innerHTML = staffData.filter(s => s.name.toLowerCase().includes(term)).map(s => {
            const isManager = s.role === 'manager';
            const cardClass = isManager ? 'bg-[var(--color-primary)] text-white shadow-xl ring-2 ring-[var(--color-secondary)]' : (s.is_employee_of_month ? 'border-2 border-[var(--color-highlight)] bg-gradient-to-br from-white to-yellow-50' : 'bg-white border border-gray-200');
            const textPrimary = isManager ? 'text-white' : 'text-gray-900';
            const textSecondary = isManager ? 'text-gray-300' : 'text-gray-500';
            const bgIcon = isManager ? 'bg-[var(--color-secondary)] text-white' : 'bg-[var(--color-primary)] text-white';
            
            let timeStatus = `<span class="text-sm text-red-600 font-bold flex items-center gap-1"><div class="w-2 h-2 bg-red-500 rounded-full"></div> OFFLINE</span>`;
            if(s.today_entry) {
                if(s.is_working) timeStatus = `<span class="text-sm text-green-600 font-bold flex items-center gap-1"><div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div> ACTIVO (Desde ${s.today_entry})</span>`;
                else if (s.today_exit) timeStatus = `<span class="text-sm text-gray-500 font-bold"><i data-lucide="clock" class="w-3 h-3 inline mr-1"></i> OFFLINE (Turno: ${s.today_entry} - ${s.today_exit})</span>`;
            }
            
            let avatarHTML = '';
            if (s.profile_photo_url && s.profile_photo_url !== "") {
                avatarHTML = `<img src="${s.profile_photo_url}" alt="${s.first_name}" class="w-full h-full object-cover rounded-full">`;
            } else {
                avatarHTML = s.first_name.charAt(0);
            }

            return `<div class="${cardClass} p-5 rounded-xl shadow-sm relative group hover:shadow-md transition-all hover:-translate-y-1">
                ${s.is_employee_of_month ? '<div class="absolute top-0 right-0 bg-gradient-to-r from-yellow-600 to-yellow-500 text-white text-[10px] font-black px-3 py-1 rounded-bl-lg uppercase tracking-wider shadow-sm z-10"><i data-lucide="crown" class="w-3 h-3 inline mr-1"></i> DESTACADO</div>' : ''}
                ${isManager ? '<div class="absolute top-0 right-0 bg-[var(--color-secondary)] text-white text-[10px] font-black px-3 py-1 rounded-bl-lg uppercase tracking-wider">MANAGER</div>' : ''}
                <div class="flex items-center gap-4 mb-4 mt-2">
                    <div class="w-14 h-14 rounded-full ${bgIcon} flex items-center justify-center font-bold text-2xl border-4 border-white/20 shadow-sm overflow-hidden">
                        ${avatarHTML}
                    </div>
                    <div>
                        <h4 class="font-black ${textPrimary} text-xl leading-tight uppercase">${s.name}</h4>
                        <p class="text-xs ${textSecondary} font-semibold">${s.email}</p>
                    </div>
                </div>
                <div class="mb-4 px-3 py-2 rounded border ${isManager ? 'border-gray-600 bg-white/10' : 'border-gray-100 bg-gray-50'}">${timeStatus}</div>
                <div class="flex justify-between text-xs ${textSecondary} font-bold mb-4 px-1 uppercase tracking-wide">
                    <span><i data-lucide="user" class="w-3 h-3 inline mr-1"></i> ${s.total_clients || 0} Clientes</span>
                    <span><i data-lucide="dollar-sign" class="w-3 h-3 inline mr-1"></i> ${s.hourly_rate || '0.00'}/hr</span>
                </div>
                <button onclick="openEditPanel(${s.id})" class="w-full bg-white text-[var(--color-primary)] border border-gray-300 hover:bg-gray-50 py-2.5 rounded-lg font-black text-sm uppercase flex items-center justify-center gap-2 transition-colors shadow-sm"><i data-lucide="settings" class="w-4 h-4"></i> Gestionar</button>
            </div>`;
        }).join('');
        if(typeof lucide !== 'undefined') lucide.createIcons();
    }

    // Renderizado de Recursos (Original)
    function renderNetflixCard(v, context) {
        return `<div class="relative group bg-black rounded-lg overflow-hidden shadow-lg transition-all duration-300 hover:scale-[1.02] border border-gray-800">
            <div class="relative w-full aspect-video bg-gray-900"><iframe class="w-full h-full" src="https://www.youtube.com/embed/${v.youtube_id}" title="${v.title}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
            <div class="p-3 bg-gradient-to-b from-gray-900 to-black flex justify-between items-start gap-2"><h4 class="text-white font-bold text-xs leading-snug line-clamp-2 uppercase tracking-wide">${v.title}</h4><button onclick="openDeleteModal('video',${v.id},'${context}')" class="text-gray-500 hover:text-[var(--color-secondary)] transition-colors p-1"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>
        </div>`;
    }
    function renderProDocCard(doc, context) {
        return `<li class="flex items-center p-3 border border-gray-200 rounded-lg bg-white hover:border-[var(--color-primary)] hover:shadow-sm transition group">
            <div class="bg-[var(--color-primary)] p-2 rounded mr-3 group-hover:scale-110 transition-transform"><i data-lucide="file-text" class="w-5 h-5 text-white"></i></div>
            <div class="flex-1 min-w-0"><a href="${doc.file_path}" target="_blank" class="block group-hover:text-[var(--color-primary)] transition-colors"><p class="text-sm font-bold text-gray-800 truncate uppercase">${doc.file_name}</p><p class="text-[10px] text-gray-400 uppercase font-semibold">PDF Document</p></a></div>
            <button onclick="openDeleteModal('doc',${doc.id},'${context}')" class="text-gray-300 hover:text-[var(--color-secondary)] p-2 transition-colors"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
        </li>`;
    }
    async function loadGlobalResources() { 
        try { const res = await fetch('db/staff-read.php?global_academy=true'); const d = await res.json(); if(d.success) { const vList=document.getElementById('global-videos-list'); if(vList) vList.innerHTML = d.videos.map(v => renderNetflixCard(v, 'global')).join(''); const dList=document.getElementById('global-docs-list'); if(dList) dList.innerHTML = d.documents.map(doc => renderProDocCard(doc, 'global')).join(''); if(typeof lucide !== 'undefined') lucide.createIcons(); } } catch(e) {} 
    }
    async function loadIndividualAcademy(id){
        const res=await fetch(`db/staff-read.php?id=${id}&academy=true`); const d=await res.json();
        if(d.success){
            const iv=d.videos.filter(x=>!x.is_global); const idoc=d.documents.filter(x=>!x.is_global);
            document.getElementById('indiv-videos-list').innerHTML = iv.map(v => renderNetflixCard(v, 'indiv')).join('');
            document.getElementById('indiv-docs-list').innerHTML = idoc.map(f => renderProDocCard(f, 'indiv')).join('');
            if(typeof lucide !== 'undefined') lucide.createIcons();
        }
    }

    // Funciones de Subida (Original)
    async function uploadGlobalDoc(){ const n=document.getElementById('global-doc-name').value; const f=document.getElementById('global-doc-file').files[0]; if(!n||!f)return showToast('Faltan datos','error'); const fd=new FormData(); fd.append('type','document'); fd.append('staff_id','global'); fd.append('name',n); fd.append('file',f); await fetch('db/staff-training-upload.php',{method:'POST',body:fd}); showToast('Subido'); loadGlobalResources(); document.getElementById('global-doc-name').value=''; document.getElementById('global-doc-file').value='';}
    async function uploadGlobalVideo(){ const t=document.getElementById('global-video-title').value; const u=document.getElementById('global-video-url').value; if(!t||!u)return showToast('Faltan datos','error'); await fetch('db/staff-training-upload.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({type:'video',staff_id:'global',title:t,url:u})}); showToast('Publicado'); loadGlobalResources(); document.getElementById('global-video-title').value=''; document.getElementById('global-video-url').value='';}
    async function uploadIndividualVideo(){const id=document.getElementById('current-staff-id').value, t=document.getElementById('indiv-video-title').value, u=document.getElementById('indiv-video-url').value; if(!t||!u)return showToast('Faltan datos','error'); await fetch('db/staff-training-upload.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({type:'video',staff_id:id,title:t,url:u})}); showToast('Subido'); loadIndividualAcademy(id); document.getElementById('indiv-video-title').value=''; document.getElementById('indiv-video-url').value='';}
    async function uploadIndividualDoc(){const id=document.getElementById('current-staff-id').value, n=document.getElementById('indiv-doc-name').value, f=document.getElementById('indiv-doc-file').files[0]; if(!n||!f)return showToast('Faltan datos','error'); const fd=new FormData(); fd.append('type','document'); fd.append('staff_id',id); fd.append('name',n); fd.append('file',f); await fetch('db/staff-training-upload.php',{method:'POST',body:fd}); showToast('Subido'); loadIndividualAcademy(id); document.getElementById('indiv-doc-name').value=''; document.getElementById('indiv-doc-file').value='';}
    
    // Funciones Asignacion (Original)
    async function assignItem(t){const s=document.getElementById('current-staff-id').value, i=document.getElementById(`assign-${t}-select`).value; if(i) { await fetch('db/staff-actions.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'assign',type:t,staff_id:s,item_id:i})}); showToast('Asignado'); loadAssignments(s); }}
    async function removeAssign(t,i){const s=document.getElementById('current-staff-id').value; await fetch('db/staff-actions.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'unassign',type:t,item_id:i})}); showToast('Removido'); loadAssignments(s); }
    async function loadAssignments(id){ const listC = document.getElementById('list-assigned-clients'); listC.innerHTML = '<p class="text-center text-xs text-gray-400 py-2">Cargando...</p>'; try { const res = await fetch(`db/staff-read.php?id=${id}&details=true`); const d = await res.json(); if(d.success){ document.getElementById('assign-client-select').innerHTML = '<option value="">Seleccionar Cliente...</option>' + d.all_clients.map(i=>`<option value="${i.id}">${i.name}</option>`).join(''); document.getElementById('assign-route-select').innerHTML = '<option value="">Seleccionar Ruta...</option>' + d.all_routes.map(i=>`<option value="${i.id}">${i.name}</option>`).join(''); if(d.assigned_clients.length === 0) listC.innerHTML = '<div class="text-center p-3 border border-dashed rounded bg-gray-50 text-xs text-gray-400 italic">Sin asignaciones</div>'; else { listC.innerHTML = d.assigned_clients.map(i => `<div class="bg-white border-l-4 border-[var(--color-secondary)] p-3 rounded shadow-sm flex justify-between items-center mb-2"><div><p class="font-bold text-gray-800 text-sm uppercase">${i.name}</p><p class="text-xs text-gray-500"><i data-lucide="map-pin" class="w-3 h-3 inline"></i> ${i.street_address || 'N/A'}</p></div><button onclick="removeAssign('client',${i.id})" class="text-gray-300 hover:text-[var(--color-secondary)] transition"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>`).join(''); } document.getElementById('count-clients').innerText = d.assigned_clients.length; document.getElementById('list-assigned-routes').innerHTML = d.assigned_routes.map(i => `<div class="bg-white border p-3 rounded shadow-sm flex justify-between text-xs mb-2 uppercase font-bold text-gray-700"><span>${i.name} <span class="text-[var(--color-primary)]">(${i.route_day||'Fijo'})</span></span><button onclick="removeAssign('route',${i.id})" class="text-gray-300 hover:text-[var(--color-secondary)]"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>`).join(''); if(typeof lucide !== 'undefined') lucide.createIcons(); } } catch(e) { console.error(e); listC.innerHTML = '<p class="text-[var(--color-secondary)] text-xs">Error de carga</p>'; } }

    // Apertura y Cierre Panel
    function openCreatePanel(){ 
        document.getElementById('staff-form').reset(); 
        document.getElementById('current-staff-id').value=''; 
        document.getElementById('staff-photo-preview').src='img/default-avatar.png'; // Reset foto
        document.getElementById('staff-tenure').value='N/A'; // Reset antiguedad
        document.getElementById('panel-title').innerText = "NUEVO EMPLEADO"; 
        document.getElementById('delete-staff-link-container').classList.add('hidden'); 
        renderScheduleInputs(null); currentBlockedDays=[]; renderBlockedDays(); 
        document.getElementById('staffPanel').classList.remove('translate-x-full'); document.getElementById('panel-overlay').classList.remove('hidden'); switchTab('tab-general');
    }
    
    async function openEditPanel(id){ 
        const s = staffData.find(x => x.id === id); if(!s) return; 
        document.getElementById('panel-title').innerText = s.name; 
        document.getElementById('current-staff-id').value = s.id; 
        document.getElementById('current-public-uid').value = s.public_uid || s.access_code || id; // Set UID para QR
        
        // Carga Campos Originales
        document.getElementById('staff-firstname').value = s.first_name; 
        document.getElementById('staff-lastname').value = s.last_name; 
        document.getElementById('staff-email').value = s.email; 
        document.getElementById('staff-phone').value = s.phone; 
        document.getElementById('staff-code').value = s.access_code; 
        document.getElementById('staff-rate').value = s.hourly_rate; 
        document.getElementById('staff-role').value = s.role || 'employee'; 
        document.getElementById('is-employee-month').checked = s.is_employee_of_month == 1; 
        renderScheduleInputs(typeof s.schedule_config === 'string' ? JSON.parse(s.schedule_config) : s.schedule_config); 
        currentBlockedDays = s.blocked_days || []; renderBlockedDays(); 
        
        // Carga Campos Nuevos
        document.getElementById('staff-photo-preview').src = s.profile_photo_url || 'img/default-avatar.png';
        document.getElementById('staff-tenure').value = calculateTenure(s.created_at || s.hired_date);
        
        document.getElementById('staffPanel').classList.remove('translate-x-full'); document.getElementById('panel-overlay').classList.remove('hidden'); switchTab('tab-general'); 
        loadAssignments(id); loadIndividualAcademy(id); document.getElementById('delete-staff-link-container').classList.remove('hidden'); 
        if(typeof IMask !== 'undefined') document.getElementById('staff-phone').dispatchEvent(new Event('input'));
    }
    
    function closePanel(){ document.getElementById('staffPanel').classList.add('translate-x-full'); document.getElementById('panel-overlay').classList.add('hidden'); }
    function switchTab(id){ ['tab-general','tab-assign','tab-academy-indiv'].forEach(t=>document.getElementById(t).classList.add('hidden')); document.getElementById(id).classList.remove('hidden'); document.querySelectorAll('[id^="btn-tab-"]').forEach(btn => { btn.classList.remove('border-[var(--color-primary)]', 'text-[var(--color-primary)]', 'bg-gray-50'); btn.classList.add('border-transparent', 'text-gray-500'); }); const activeBtn = document.getElementById(`btn-${id}`); activeBtn.classList.add('border-[var(--color-primary)]', 'text-[var(--color-primary)]', 'bg-gray-50'); activeBtn.classList.remove('border-transparent', 'text-gray-500'); }

    // Helpers Formulario (Original)
    function renderScheduleInputs(scheduleData) { const c = document.getElementById('schedule-container'); c.innerHTML = ''; Object.keys(DAYS_MAP).forEach(k => { const d = scheduleData && scheduleData[k] ? scheduleData[k] : {active:false, start:'09:00', end:'17:00'}; c.insertAdjacentHTML('beforeend', `<div class="flex items-center gap-2 py-1 border-b border-gray-100 last:border-0"><div class="w-24"><label class="flex items-center gap-2 cursor-pointer"><input type="checkbox" class="day-check text-[var(--color-primary)] focus:ring-[var(--color-highlight)] rounded" data-day="${k}" ${d.active?'checked':''} onchange="toggleTimeInputs(this)"><span class="text-xs font-bold uppercase text-gray-700">${DAYS_MAP[k]}</span></label></div><div class="flex gap-1 ${d.active?'':'opacity-30 pointer-events-none'}" id="times-${k}"><input type="time" class="border border-gray-300 rounded text-xs p-1 bg-white" id="start-${k}" value="${d.start}"><span class="text-gray-400">-</span><input type="time" class="border border-gray-300 rounded text-xs p-1 bg-white" id="end-${k}" value="${d.end}"></div></div>`); }); }
    function toggleTimeInputs(cb){ document.getElementById(`times-${cb.dataset.day}`).classList.toggle('opacity-30', !cb.checked); document.getElementById(`times-${cb.dataset.day}`).classList.toggle('pointer-events-none', !cb.checked); }
    function renderBlockedDays() { document.getElementById('blocked-days-list').innerHTML = currentBlockedDays.map((d,i)=>`<li class="flex justify-between items-center text-xs bg-white p-2 border border-gray-200 rounded shadow-sm mb-1"><span><strong>${d.date}</strong>: ${d.reason}</span><button type="button" onclick="currentBlockedDays.splice(${i},1);renderBlockedDays()" class="text-red-500 hover:text-red-700"><i data-lucide="x" class="w-3 h-3"></i></button></li>`).join(''); if(typeof lucide !== 'undefined') lucide.createIcons(); }
    function addBlockedDay() { const d=document.getElementById('block-date').value, r=document.getElementById('block-reason').value; if(d){currentBlockedDays.push({date:d,reason:r}); renderBlockedDays(); document.getElementById('block-date').value=''; document.getElementById('block-reason').value='';} }
    function toggleCodeVisibility(){ const i=document.getElementById('staff-code'); i.type=i.type==='password'?'text':'password'; }
    function copyAccessCode() { const i = document.getElementById('staff-code'); if(!i.value)return; navigator.clipboard.writeText(i.value); showToast('Copiado'); }
    async function updateGlobalNotification(){ const m=document.getElementById('global-notification-input').value; if(m) { await fetch('db/staff-update.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'update_notification',message:m})}); showToast('Publicado'); loadStaff(); } }

    // SUBMIT FINAL
    document.getElementById('staff-form').addEventListener('submit', async (e) => { 
        e.preventDefault(); const id = document.getElementById('current-staff-id').value; 
        let scheduleConfig = {}; document.querySelectorAll('.day-check').forEach(cb => { if(cb.checked) { const day=cb.dataset.day; scheduleConfig[day]={active:true, start:document.getElementById(`start-${day}`).value, end:document.getElementById(`end-${day}`).value}; }}); 
        const fd = { id: id, first_name: document.getElementById('staff-firstname').value, last_name: document.getElementById('staff-lastname').value, email: document.getElementById('staff-email').value, phone: document.getElementById('staff-phone').value, role: document.getElementById('staff-role').value, hourly_rate: document.getElementById('staff-rate').value || "0.00", schedule: scheduleConfig, blocked_days: currentBlockedDays, is_employee_month: document.getElementById('is-employee-month').checked ? 1 : 0 }; 
        const res = await fetch(id ? 'db/staff-update.php' : 'db/staff-create.php', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(fd) }); 
        if((await res.json()).success) { showToast('Guardado'); loadStaff(); if(!id) closePanel(); } else { showToast('Error','error'); } 
    });
</script>
</body>
</html>