<?php
// === CORRECCIÓN: INICIO DE SESIÓN EXPLÍCITO ===
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
    require_once(__DIR__ . '/db/db_connection.php');
    require_once(__DIR__ . '/core/business-information.php');
    include_once(__DIR__ . '/core/branding.php');
    include_once(__DIR__ . '/files/timezone.php');

// 1. Inicializar sesión y mensaje de error
$user_id = $_SESSION['user_id'] ?? null;
// === SOLUCIÓN A LA ADVERTENCIA ===
$error_message = '';

// Si el usuario ya está autenticado, redirigir al dashboard.
if ($user_id) {
    header("Location: app-dashboard.php");
    exit();
}
// 2. Lógica de Autenticación por Código (Si NO hay sesión y se envió el formulario)
if (!$user_id && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['access_code'])) {
    
    $input_code = trim($_POST['access_code']);

    if (!preg_match('/^\d{5,7}$/', $input_code)) {
        $error_message = "El código debe ser de 5 a 7 dígitos numéricos.";
    } else {
        try {
            // Buscamos a TODOS los usuarios (dueño principal) que tienen un código de acceso configurado.
            $stmt = $pdo->prepare("SELECT user_id, access_code_hash FROM users WHERE access_code_hash IS NOT NULL");
            $stmt->execute();
            $potential_users = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $authenticated = false;
            foreach ($potential_users as $user) {
                
                $stored_code_hash = $user['access_code_hash'];
                $match_found = false;

                // --- 1. INTENTO DE HASH BCRYPT ---
                if (strpos($stored_code_hash, '$2y$') === 0 || strpos($stored_code_hash, '$2a$') === 0) {
                    if (password_verify($input_code, $stored_code_hash)) {
                        $match_found = true;
                    }
                } 
                
                // --- 2. INTENTO DE TEXTO PLANO ---
                if (!$match_found && $stored_code_hash === $input_code) {
                    $match_found = true;
                }

                if ($match_found) {
                    
                    $_SESSION['user_id'] = $user['user_id'];
                    $user_id = $user['user_id'];
                    $authenticated = true;
                    
                    header("Location: app-dashboard.php");
                    exit();
                }
            }
            
            if (!$authenticated) {
                $error_message = "Código de acceso incorrecto.";
            }

        } catch (PDOException $e) {
            error_log("Error de autenticación: " . $e->getMessage());
            $error_message = "Error interno del sistema.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="csrf-token" content="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
    
    <title>Live Ops Center <?php echo htmlspecialchars($client_info['business_name'] ?? 'FlowCRM'); ?> <?php echo htmlspecialchars($branding['full_title'] ?? ''); ?></title>
    <meta name="robots" content="noindex, nofollow">
    <link rel="manifest" href="manifest.php">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    
    <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">

    <link rel="manifest" href="manifest.php">
    <meta name="theme-color" content="#ef4444">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <style>
        /* Touch improvements */
        * { -webkit-tap-highlight-color: transparent; }
        body { touch-action: manipulation; }

        .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;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .5; }
        }
        
        @keyframes slide-in {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-slide-in { animation: slide-in 0.3s ease-out; }
    </style>
</head>
<body class="flex flex-col bg-gray-50">

<div class="hidden lg:flex fixed inset-0 z-[100] bg-[var(--color-primary)]/95 backdrop-blur-sm flex-col items-center justify-center p-8">
    
    <div class="bg-white max-w-5xl w-full rounded-3xl shadow-2xl overflow-hidden animate-slide-in flex h-[550px] border-4 border-[var(--color-highlight)]">
        
                <div class="w-1/2 bg-gray-900 flex items-center justify-center relative bg-cover bg-center" 
             style="background-image: url('https://www.free-mockup.com/wp-content/uploads/edd/2024/08/floating-iphone-app-screens-mockup.jpg?q=80&w=1974&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');">
            
                        <div class="absolute inset-0 bg-black/30 flex items-center justify-center">
            </div>
        </div>

        <div class="w-1/2 p-10 flex flex-col items-center justify-center text-center">
            
            <h2 class="text-4xl font-black text-[var(--color-primary)] mb-2 uppercase tracking-tight">
                Acceso Exclusivo Móvil
            </h2>
            <p class="text-lg text-gray-600 mb-8 font-semibold">
                Esta es la experiencia de uso definitiva. Escanea y accede al Live Ops Center desde tu dispositivo móvil
            </p>
            
            <div class="bg-gray-50 p-6 rounded-2xl shadow-inner border border-gray-200 inline-block mb-6 relative">
                <img id="desktop-qr-code" src="" alt="QR Acceso Móvil" class="w-56 h-56 object-contain">
                <div class="absolute -bottom-3 -right-3 bg-[var(--color-secondary)] text-white p-2 rounded-full shadow-lg border-4 border-white">
                    <i data-lucide="scan-line" class="w-6 h-6"></i>
                </div>
            </div>
            
            <p class="text-md text-gray-400 font-mono break-all opacity-70" id="page-url-display"></p>
            
        </div>
        
    </div>
</div>

<div class="bg-[var(--color-background)] flex items-center justify-center p-4 mt-7 mb-7">
    <div class="w-full max-w-sm">

        <?php if(!empty($client_info['logo_url'])): ?>
            <div class="text-center mb-8 pt-10">
                <img src="<?php echo htmlspecialchars($client_info['logo_url']); ?>" class="h-20 mx-auto object-contain drop-shadow-md">
            </div>
        <?php endif; ?>

        <div class="p-8 bg-white rounded-3xl shadow-2xl border-t-8 border-[var(--color-highlight)] relative">
            
            <h2 class="text-center text-4xl font-black text-[var(--color-primary)] uppercase mb-1 tracking-tighter">
                Acceso Live OPS
            </h2>
             <div class="flex items-center justify-center text-md md:text-xs font-black text-[var(--color-secondary)] uppercase tracking-wider">
                    <div class="live-indicator"></div> <span class="sm:inline ml-2">Conexión </span>En Vivo
                </div>
            <p class="text-center text-gray-500 mb-6 uppercase font-semibold">
                Ingresa tu código de acceso
            </p>
            
            <?php if ($error_message): ?>
                <div class="bg-red-50 border border-red-400 text-black uppercase px-4 py-3 rounded-xl mb-6 text-sm font-bold" role="alert">
                    <i data-lucide="alert-triangle" class="w-4 h-4 inline mr-1"></i>
                    <span><?php echo htmlspecialchars($error_message); ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" action="app.php" class="space-y-6 input-code-form">
                <div>
                    <input type="password" 
                           name="access_code" 
                           required 
                           minlength="5" 
                           maxlength="7"
                           inputmode="numeric"
                           pattern="\d{5,7}"
                           class="w-full border-4 border-gray-200 rounded-xl p-4 text-3xl font-black text-center focus:border-[var(--color-secondary)] outline-none transition uppercase"
                           placeholder="CÓDIGO"
                           autocomplete="off"
                           autofocus>
                </div>
                
                <button type="submit" 
                        class="w-full bg-[var(--color-primary)] text-white font-black uppercase py-4 rounded-xl shadow-lg shadow-indigo-200 hover:bg-black active:scale-[0.98] transition-all flex justify-center items-center gap-2">
                    <i data-lucide="log-in" class="w-5 h-5"></i> Acceder al Sistema
                </button>
            </form>

        </div>
    </div>
</div>
    
<?php @include 'core/page-footer.php'; ?>
    

</body>
<script>
    lucide.createIcons();
    document.addEventListener('DOMContentLoaded', () => {
        const qrImg = document.getElementById('desktop-qr-code');
        const urlDisplay = document.getElementById('page-url-display');
        const currentUrl = window.location.href;
        
        if(qrImg) {
            qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(currentUrl)}`;
        }
        if(urlDisplay) {
            urlDisplay.innerText = currentUrl;
        }
    });
</script>
<script src="files/toast.js"></script>
</html>