<?php
// Variable de control para que init.php no ejecute guardiankey.php
$skip_auth_check = true; 

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

if (isset($_SESSION['staff_id'])) {
    // Redirección inmediata al dashboard, que consumirá el mensaje flash (toast) si existe.
    header('Location: dashboard.php'); 
    exit();
}

$logo_url = $client_info['logo_url'] ?? $branding['flow-logo'];

$error_message = '';
$access_code = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Fase V: Verificación de Token CSRF (Seguridad CSRF)
    $csrf_ok = isset($_POST['csrf_token']) && ($_POST['csrf_token'] === ($_SESSION['csrf_token'] ?? ''));

    if (!$csrf_ok) {
        error_log("CSRF Attack Detected on login.php. IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'));
        $error_message = 'Error de seguridad. Recarga la página e intenta de nuevo.';
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); 
    } else {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); 

        $access_code = filter_input(INPUT_POST, 'access_code', FILTER_UNSAFE_RAW) ?? '';
        $access_code = substr(trim($access_code), 0, 10);

        if (empty($access_code)) {
            $error_message = 'Ingresa tu código de acceso.';
        } else {
            try {
                if (!isset($pdo)) {
                    $error_message = 'Error interno: Conexión a la base de datos no disponible.';
                    error_log("PDO object not set in login.php");
                } else {
                    $stmt = $pdo->prepare("SELECT id, first_name, last_name, status FROM staff WHERE access_code = ?");
                    $stmt->execute([$access_code]);
                    $staff = $stmt->fetch();

                    if ($staff) {
                        if ($staff['status'] === 'activo') {
                            $_SESSION['staff_id'] = $staff['id'];
                            $_SESSION['staff_first_name'] = $staff['first_name'];
                            $_SESSION['staff_full_name'] = $staff['first_name'] . ' ' . $staff['last_name'];
                            
                            // Corrección Funcional: Agregar un mensaje flash para el 'Toast'
                            $_SESSION['flash_message'] = [
                                'type' => 'success',
                                'title' => '¡Bienvenido(a), ' . htmlspecialchars($staff['first_name']) . '!',
                                'message' => 'Has accedido al Portal de Miembros de forma segura.'
                            ];
                            
                            header('Location: dashboard.php');
                            exit();
                        } else {
                            $error_message = 'Cuenta inactiva. Contacta al administrador.';
                        }
                    } else {
                        // Corrección Funcional: Mensaje de error más específico para código/ID incorrecto.
                        $error_message = 'El código de acceso no es válido o tu cuenta no existe.';
                    }
                }
            } catch (PDOException $e) {
                error_log("Database Error in login.php: " . $e->getMessage());
                $error_message = 'Intenta de nuevo más tarde.';
            }
        }
    }
}
?>
<!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($client_info['business_name'] ?? $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">
</head>
<body class="bg-gray-100">
    
     <section class="md:hidden relative w-full h-48">
    <img src="<?php echo htmlspecialchars($branding['staff-bg']); ?>" alt="CRM Background"
         class="absolute inset-0 w-full h-full object-cover">
    <div class="absolute inset-0 bg-gradient-to-tr from-[#07162d]/70 via-[#07162d]/40 to-[#9e1428]/40"></div>
    
    <div class="relative z-10 h-full flex flex-col items-center justify-center p-4"> 
        
        <h1 class="text-4xl font-black text-white leading-tight uppercase text-center mb-4">
            Portal de <span class="text-[var(--color-highlight)]">Equipo</span>
        </h1>
        
        <div class="inline-flex items-center px-3 py-1 text-lg font-black text-black bg-[var(--color-highlight)] rounded-full uppercase">
            <?php echo htmlspecialchars($client_info['business_name'] ?? ''); ?>
        </div>
        
    </div>
</section>
  
    <div class="min-h-screen grid grid-cols-1 lg:grid-cols-2">
        <div class="hidden lg:flex relative flex-col items-center justify-center bg-[var(--brand-primary)] p-12 text-center bg-cover bg-center" style="background-image: url('<?php echo htmlspecialchars($branding['staff-bg'] ?? ''); ?>');">
            <div class="bg-[var(--brand-primary)] opacity-90"></div>
            <div class="relative z-10 flex flex-col items-center mt-20">
                <h1 class="text-5xl font-black text-white leading-tight uppercase">
                    Portal de <span class="text-[var(--color-highlight)]">Equipo</span>
                </h1>
                 <div class="inline-flex items-center px-3 py-1 text-lg font-black text-black bg-[var(--color-highlight)] rounded-full uppercase">
<?php echo htmlspecialchars($client_info['business_name'] ?? ''); ?>
            </div>
                <ul class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-3 text-white/90 max-w-2xl">
                    <li class="flex items-start gap-3"><i data-lucide="clock" class="w-6 h-6 text-[var(--brand-secondary)] mt-1"></i><span class="text-lg text-white/90">Control De Horarios</span></li>
                    <li class="flex items-start gap-3"><i data-lucide="calendar-check" class="w-6 h-6 text-[var(--brand-secondary)] mt-1"></i><span class="text-lg text-white/90">Agenda y Rutas Asignadas</span></li>
                    <li class="flex items-start gap-3"><i data-lucide="graduation-cap" class="w-6 h-6 text-[var(--brand-secondary)] mt-1"></i><span class="text-lg text-white/90">Academia y Capacitación</span></li>
                    <li class="flex items-start gap-3"><i data-lucide="users" class="w-6 h-6 text-[var(--brand-secondary)] mt-1"></i><span class="text-lg text-white/90">Clientes Asignados</span></li>
                </ul>
            </div>
        </div>

        <div class="flex flex-col items-center justify-center p-6 sm:p-12">
            <div class="w-full max-w-md">
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="w-40 mx-auto mb-6">
                <div class="text-center mb-10">
                            <h2 class="text-4xl md:text-5xl font-black leading-none uppercase">
          <span class="text-[var(--color-primary)]">INICIAR</span>
          <span class="text-[var(--color-secondary)]">SESIÓN</span>
        </h2>
                <p class="mt-3 text-xs font-semibold tracking-widest text-gray-500 uppercase">
          Accede a tu porta de miembros
        </p>
                </div>

                <?php if (!empty($error_message)): ?>
                    <div class="bg-[var(--color-secondary)] text-white px-4 py-3 rounded-xl relative mb-6 uppercase" role="alert">
                        <span class="font-bold"></span> <span class="block sm:inline"><?php echo htmlspecialchars($error_message); ?></span>
                    </div>
                <?php endif; ?>

                <form class="space-y-6" method="POST">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
                    
                    <div>
                        <div class="relative mt-2">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-4 pointer-events-none"><i data-lucide="key-round" class="w-5 h-5 text-gray-400"></i></span>
                            <input id="access_code" name="access_code" type="password" required class="block w-full h-14 pl-14 pr-12 rounded-xl border-gray-300 shadow-sm focus:border-[var(--brand-secondary)] focus:ring-[var(--brand-secondary)] tracking-[0.2em] text-lg font-bold" placeholder="•••••" maxlength="5" value="<?php echo htmlspecialchars($access_code); ?>">
                            <button type="button" id="toggle-btn" class="absolute inset-y-0 right-0 flex items-center pr-4 text-gray-500 hover:text-[var(--brand-primary)]"><i data-lucide="eye" class="w-5 h-5"></i></button>
                        </div>
                    </div>
                    <button type="submit" class="btn-primary w-full inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3.5 font-bold uppercase tracking-wide">
                        <i data-lucide="log-in" class="w-5 h-5"></i> INGRESAR
                    </button>
                </form>
                
        <div class="mt-12 text-center">
   <div class="max-w-7xl mx-auto px-6 lg:px-10 text-center">
        <p class="text-base font-semibold text-black">
            © <?php echo date('Y'); ?> <?php echo htmlspecialchars($client_info['business_name'] ?? ''); ?> <br /><span class="text-base font-thin text-black">All Rights Reserved</span>
        </p>
        
        <div class="mt-4 pt-2 mx-auto max-w-sm">
            <p class="font-thin text-sm text-black flex items-center justify-center gap-1.5">
                Powered by <i data-lucide="shield-check" class="w-4 h-4 text-green-700"></i>
                <span class="font-black text-[var(--color-secondary)] tracking-wide">
                    <?php echo htmlspecialchars($branding['name'] ?? ''); ?><span class="font-black text-black tracking-wide"><?php echo htmlspecialchars($branding['crm'] ?? ''); ?></span>™
                </span>
            </p>
        </div>
    </div>
       </div>
                
            </div>
        </div>
    </div>
    <script>
        const btn = document.getElementById('toggle-btn');
        const inp = document.getElementById('access_code');
        if(btn) btn.addEventListener('click', () => { 
            inp.type = inp.type==='password' ? 'text' : 'password'; 
            lucide.createIcons(); 
        });
        lucide.createIcons();
    </script>
</body>
</html>