<?php
session_start();

// ==================== CONFIGURACIÓN DE SESIÓN PERSISTENTE ====================
// Aumentar la duración de la sesión a 30 días (en segundos)
ini_set('session.gc_maxlifetime', 2592000); // 30 días
ini_set('session.cookie_lifetime', 2592000); // 30 días
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

// Configurar parámetros de sesión para mayor duración
session_set_cookie_params([
    'lifetime' => 2592000, // 30 días
    'path' => '/',
    'domain' => '', // Dejar vacío para el dominio actual
    'secure' => false, // Cambiar a true si usas HTTPS
    'httponly' => true, // Solo accesible via HTTP
    'samesite' => 'Lax' // Protección CSRF
]);

// Regenerar ID de sesión periódicamente por seguridad
if (!isset($_SESSION['session_regenerated'])) {
    session_regenerate_id(true);
    $_SESSION['session_regenerated'] = time();
}

// Verificar si la sesión necesita regeneración (cada 30 minutos)
if (isset($_SESSION['session_regenerated']) && (time() - $_SESSION['session_regenerated']) > 1800) {
    session_regenerate_id(true);
    $_SESSION['session_regenerated'] = time();
}

// Establecer tiempo de actividad de la sesión
if (!isset($_SESSION['last_activity'])) {
    $_SESSION['last_activity'] = time();
}

// Verificar inactividad (opcional - 7 días máximo)
$max_inactivity = 604800; // 7 días
if ((time() - $_SESSION['last_activity']) > $max_inactivity) {
    // Sesión muy antigua, cerrar por seguridad
    session_destroy();
    session_start();
}
$_SESSION['last_activity'] = time();

// Database setup for codes
$users_db_file = 'data/users.db';
$users_db = null;

try {
    $users_db = new PDO('sqlite:' . $users_db_file);
    $users_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    // Database connection error - will continue without code functionality
}

// Load servers
$servers = [];
if (file_exists('data/servers.json')) {
    $servers = json_decode(file_get_contents('data/servers.json'), true) ?: [];
}

$error = '';
$login_type = $_GET['type'] ?? 'select';

// Handle form submissions
if ($_POST) {
    if (isset($_POST['login_type'])) {
        $login_type = $_POST['login_type'];
        
        if ($login_type === 'credentials') {
            $username = trim($_POST['username'] ?? '');
            $password = trim($_POST['password'] ?? '');
            $remember_me = isset($_POST['remember_me']) ? true : false;
            
            if (!$username || !$password) {
                $error = 'Todos los campos son obligatorios';
            } else {
                $authenticated = false;
                $working_server = null;
                
                foreach ($servers as $server) {
                    $url = rtrim($server['url'], '/') . '/player_api.php?' . http_build_query([
                        'username' => $username,
                        'password' => $password,
                        'action' => 'get_account_info'
                    ]);
                    
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    curl_setopt($ch, CURLOPT_USERAGENT, 'XtremePlayer/1.0');
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
                    
                    $response = curl_exec($ch);
                    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    curl_close($ch);
                    
                    if ($response && $httpCode == 200) {
                        $data = json_decode($response, true);
                        if (isset($data['user_info']['auth']) && $data['user_info']['auth'] == 1) {
                            $authenticated = true;
                            $working_server = $server;
                            break;
                        }
                    }
                }
                
                if ($authenticated && $working_server) {
                    // Configurar variables de sesión
                    $_SESSION['user_logged'] = true;
                    $_SESSION['username'] = $username;
                    $_SESSION['password'] = $password;
                    $_SESSION['server_url'] = $working_server['url'];
                    $_SESSION['server_name'] = $working_server['name'];
                    $_SESSION['login_ok'] = true;
                    $_SESSION['login_time'] = time();
                    $_SESSION['last_activity'] = time();
                    
                    // Si seleccionó "Recordarme", guardar en cookie persistente
                    if ($remember_me) {
                        $token = bin2hex(random_bytes(32));
                        $_SESSION['remember_token'] = $token;
                        setcookie('remember_token', $token, time() + 2592000, '/', '', false, true);
                        
                        // Guardar token en base de datos si existe
                        if ($users_db) {
                            try {
                                // Crear tabla si no existe
                                $users_db->exec("CREATE TABLE IF NOT EXISTS user_tokens (
                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                                    username TEXT NOT NULL,
                                    token TEXT NOT NULL,
                                    created_at INTEGER NOT NULL,
                                    expires_at INTEGER NOT NULL
                                )");
                                
                                $expires_at = time() + 2592000; // 30 días
                                $stmt = $users_db->prepare("INSERT INTO user_tokens (username, token, created_at, expires_at) VALUES (?, ?, ?, ?)");
                                $stmt->execute([$username, $token, time(), $expires_at]);
                            } catch (Exception $e) {
                                // Error al guardar token, continuar
                            }
                        }
                    }
                } else {
                    $error = 'Usuario o contraseña incorrectos';
                }
            }
        } 
        elseif ($login_type === 'code') {
            $access_code = trim($_POST['access_code'] ?? '');
            $remember_code = isset($_POST['remember_code']) ? true : false;
            
            if (!$access_code) {
                $error = 'Código de acceso requerido';
            } elseif (!$users_db) {
                $error = 'Sistema de códigos no disponible';
            } else {
                try {
                    $stmt = $users_db->prepare('SELECT * FROM users WHERE code = ? AND active = 1');
                    $stmt->execute([$access_code]);
                    $user = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if (!$user) {
                        $error = 'Código de acceso inválido o inactivo';
                    } else {
                        $server_url = null;
                        $server_name = null;
                        foreach ($servers as $server) {
                            if ($server['id'] == $user['server_id']) {
                                $server_url = $server['url'];
                                $server_name = $server['name'];
                                break;
                            }
                        }
                        
                        if (!$server_url) {
                            $error = 'Servidor no encontrado';
                        } else {
                            $api_url = rtrim($server_url, '/') . '/player_api.php?' . http_build_query([
                                'username' => $user['username'],
                                'password' => $user['password'],
                                'action' => 'get_account_info'
                            ]);
                            
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $api_url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                            curl_setopt($ch, CURLOPT_USERAGENT, 'XtremePlayer/1.0');
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
                            
                            $response = curl_exec($ch);
                            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);
                            
                            if ($response && $httpCode == 200) {
                                $data = json_decode($response, true);
                                if (isset($data['user_info']['auth']) && $data['user_info']['auth'] == 1) {
                                    $_SESSION['user_logged'] = true;
                                    $_SESSION['username'] = $user['username'];
                                    $_SESSION['password'] = $user['password'];
                                    $_SESSION['server_url'] = $server_url;
                                    $_SESSION['server_name'] = $server_name;
                                    $_SESSION['access_code'] = $access_code;
                                    $_SESSION['login_ok'] = true;
                                    $_SESSION['login_time'] = time();
                                    $_SESSION['last_activity'] = time();
                                    
                                    // Si seleccionó "Recordarme"
                                    if ($remember_code) {
                                        $token = bin2hex(random_bytes(32));
                                        $_SESSION['code_token'] = $token;
                                        setcookie('code_token', $token, time() + 2592000, '/', '', false, true);
                                        
                                        // Actualizar código para recordar
                                        $stmt = $users_db->prepare("UPDATE users SET remember_token = ?, token_expires = ? WHERE code = ?");
                                        $stmt->execute([$token, time() + 2592000, $access_code]);
                                    }
                                } else {
                                    $error = 'Usuario expirado o inválido en el servidor';
                                }
                            } else {
                                $error = 'Error de conexión con el servidor IPTV';
                            }
                        }
                    }
                } catch (Exception $e) {
                    $error = 'Error del sistema: ' . $e->getMessage();
                }
            }
        }
    }
}

// Verificar token de "Recordarme" si no hay sesión activa
if (!isset($_SESSION['user_logged']) && isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];
    
    if ($users_db) {
        try {
            $stmt = $users_db->prepare("SELECT * FROM user_tokens WHERE token = ? AND expires_at > ?");
            $stmt->execute([$token, time()]);
            $token_data = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($token_data) {
                // Restaurar sesión
                $_SESSION['user_logged'] = true;
                $_SESSION['username'] = $token_data['username'];
                $_SESSION['login_ok'] = true;
                $_SESSION['login_time'] = time();
                $_SESSION['last_activity'] = time();
                
                // Buscar servidor del usuario
                // Nota: Necesitarías guardar esta información en otra tabla
                // Por simplicidad, redirigir al login
                header('Location: index.php');
                exit();
            }
        } catch (Exception $e) {
            // Error al verificar token
        }
    }
}

// Redirigir si ya está logueado
if (isset($_SESSION['user_logged']) && $_SESSION['user_logged'] === true) {
    header('Location: dashboard.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>JTECH TV - Acceso Seguro</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            overflow-x: hidden;
            background: #141414;
        }

        .main-container {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        /* Login Section - Netflix Style Dark */
        .login-section {
            flex: 1;
            background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            position: relative;
            z-index: 2;
        }

        .login-container {
            width: 100%;
            max-width: 450px;
            background: rgba(20, 20, 20, 0.95);
            border-radius: 12px;
            padding: 40px 35px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }

        .logo-section {
            text-align: center;
            margin-bottom: 40px;
        }

        .logo-text {
            font-size: 32px;
            font-weight: 800;
            color: #E50914;
            letter-spacing: -0.5px;
        }

        .welcome-text {
            text-align: center;
            margin-bottom: 35px;
        }

        .welcome-title {
            font-size: 28px;
            font-weight: 700;
            color: white;
            margin-bottom: 10px;
        }

        .welcome-subtitle {
            font-size: 14px;
            color: #b3b3b3;
            letter-spacing: 2px;
        }

        /* Login Options - Netflix Cards */
        .login-options {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .login-option {
            background: #2a2a2a;
            border: 1px solid #404040;
            border-radius: 8px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .login-option:hover {
            background: #333333;
            transform: translateX(5px);
            border-color: #E50914;
        }

        .option-content {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .option-icon {
            width: 50px;
            height: 50px;
            background: #E50914;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }

        .option-text {
            flex: 1;
        }

        .option-title {
            font-size: 16px;
            font-weight: 600;
            color: white;
            margin-bottom: 5px;
        }

        .option-description {
            font-size: 12px;
            color: #b3b3b3;
        }

        .option-arrow {
            color: #E50914;
            font-size: 20px;
        }

        /* Login Screen */
        .login-screen {
            display: none;
        }

        .back-button {
            background: #2a2a2a;
            border: none;
            color: white;
            padding: 10px 18px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            margin-bottom: 25px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .back-button:hover {
            background: #E50914;
            transform: translateX(-3px);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-input {
            width: 100%;
            padding: 15px 18px;
            background: #333333;
            border: 1px solid #404040;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: #E50914;
            background: #3a3a3a;
        }

        .form-input::placeholder {
            color: #808080;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 15px 0;
            cursor: pointer;
        }

        .checkbox-group input {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #E50914;
        }

        .checkbox-group label {
            color: #b3b3b3;
            font-size: 14px;
            cursor: pointer;
        }

        .checkbox-group label:hover {
            color: white;
        }

        .submit-button {
            width: 100%;
            padding: 15px;
            background: #E50914;
            border: none;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
        }

        .submit-button:hover {
            background: #ff0a16;
            transform: translateY(-2px);
        }

        .error-message {
            background: rgba(229, 9, 20, 0.2);
            border: 1px solid #E50914;
            border-radius: 8px;
            padding: 12px;
            color: #ff6b6b;
            font-size: 14px;
            text-align: center;
            margin-top: 20px;
        }

        .info-message {
            background: rgba(229, 9, 20, 0.1);
            border: 1px solid rgba(229, 9, 20, 0.3);
            border-radius: 8px;
            padding: 12px;
            color: #b3b3b3;
            font-size: 12px;
            text-align: center;
            margin-top: 20px;
        }

        /* Hero Section - Netflix Style */
        .hero-section {
            flex: 1.2;
            position: relative;
            overflow: hidden;
        }

        .hero-background {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            transition: background-image 1s ease-in-out;
        }

        .hero-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 100%);
        }

        .hero-content {
            position: relative;
            z-index: 1;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding: 50px;
        }

        .hero-main {
            text-align: center;
            margin-top: auto;
            margin-bottom: auto;
        }

        .hero-title {
            font-size: 48px;
            font-weight: 800;
            color: white;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            animation: fadeInUp 0.8s ease;
        }

        .hero-subtitle {
            font-size: 18px;
            color: rgba(255, 255, 255, 0.9);
            max-width: 500px;
            margin: 0 auto;
            line-height: 1.6;
            animation: fadeInUp 0.8s ease 0.1s both;
        }

        .trending-section {
            margin-top: 30px;
        }

        .trending-header {
            margin-bottom: 15px;
        }

        .trending-title {
            color: white;
            font-size: 20px;
            font-weight: 600;
        }

        .movies-slider {
            overflow-x: auto;
            scrollbar-width: thin;
            scrollbar-color: #E50914 #2a2a2a;
        }

        .movies-slider::-webkit-scrollbar {
            height: 6px;
        }

        .movies-slider::-webkit-scrollbar-track {
            background: #2a2a2a;
            border-radius: 10px;
        }

        .movies-slider::-webkit-scrollbar-thumb {
            background: #E50914;
            border-radius: 10px;
        }

        .movies-track {
            display: flex;
            gap: 15px;
            animation: scrollMovies 40s linear infinite;
        }

        .movies-track:hover {
            animation-play-state: paused;
        }

        .movie-card {
            flex: 0 0 120px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }

        .movie-card:hover {
            transform: scale(1.05);
        }

        .movie-poster {
            width: 120px;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
        }

        .movie-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
            padding: 10px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .movie-card:hover .movie-overlay {
            opacity: 1;
        }

        .movie-title {
            font-size: 11px;
            color: white;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .movie-rating {
            font-size: 10px;
            color: #ffd700;
            margin-top: 3px;
        }

        /* Animations */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes scrollMovies {
            0% {
                transform: translateX(0);
            }
            100% {
                transform: translateX(-50%);
            }
        }

        /* Loading Spinner - Netflix Style */
        #loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.95);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .spinner {
            border: 4px solid rgba(255, 255, 255, 0.1);
            border-top: 4px solid #E50914;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 15px auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Responsive */
        @media (max-width: 968px) {
            .main-container {
                flex-direction: column;
            }
            
            .hero-section {
                min-height: 400px;
            }
            
            .hero-content {
                padding: 30px;
            }
            
            .hero-title {
                font-size: 32px;
            }
            
            .login-container {
                margin: 20px;
                padding: 30px 25px;
            }
        }

        @media (max-width: 480px) {
            .login-container {
                padding: 25px 20px;
            }
            
            .option-content {
                gap: 12px;
            }
            
            .option-icon {
                width: 40px;
                height: 40px;
                font-size: 18px;
            }
            
            .hero-title {
                font-size: 24px;
            }
            
            .hero-subtitle {
                font-size: 14px;
            }
        }

        .code-input-group {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .code-input-group .form-input {
            flex: 1;
            text-align: center;
            font-size: 24px;
            letter-spacing: 4px;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- Login Section - Left -->
        <div class="login-section">
            <div class="login-container">
                <div class="logo-section">
                    <div class="logo-text">JTECH TV</div>
                </div>

                <!-- Selector Screen -->
                <div class="selector-screen" id="selectorScreen" <?= $login_type !== 'select' ? 'style="display: none;"' : '' ?>>
                    <div class="welcome-text">
                        <h2 class="welcome-title">BIENVENIDO</h2>
                        <p class="welcome-subtitle">INGRESA TUS DATOS DE ACCESO</p>
                    </div>

                    <div class="login-options">
                        <div class="login-option" onclick="showLoginForm('credentials')">
                            <div class="option-content">
                                <div class="option-icon">
                                    <i class="fas fa-user-lock"></i>
                                </div>
                                <div class="option-text">
                                    <div class="option-title">USUARIO Y CONTRASEÑA</div>
                                    <div class="option-description">ACCEDE CON TUS CREDENCIALES</div>
                                </div>
                                <div class="option-arrow">
                                    <i class="fas fa-chevron-right"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="login-option" onclick="showLoginForm('code')">
                            <div class="option-content">
                                <div class="option-icon">
                                    <i class="fas fa-qrcode"></i>
                                </div>
                                <div class="option-text">
                                    <div class="option-title">CÓDIGO DE ACCESO</div>
                                    <div class="option-description">INGRESA TU CÓDIGO DE 6 DÍGITOS</div>
                                </div>
                                <div class="option-arrow">
                                    <i class="fas fa-chevron-right"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="info-message">
                        <i class="fas fa-info-circle"></i> La sesión permanecerá activa por 30 días
                    </div>
                </div>

                <!-- Credentials Login -->
                <div class="login-screen" id="credentialsScreen" <?= $login_type === 'credentials' ? 'style="display: block;"' : '' ?>>
                    <button class="back-button" onclick="showSelector()">
                        <i class="fas fa-arrow-left"></i> Atrás
                    </button>
                    
                    <div class="welcome-text">
                        <h2 class="welcome-title">INICIAR SESIÓN</h2>
                        <p class="welcome-subtitle">INGRESA TUS CREDENCIALES</p>
                    </div>

                    <form method="POST" id="credentialsForm">
                        <input type="hidden" name="login_type" value="credentials">
                        
                        <div class="form-group">
                            <input type="text" name="username" class="form-input" placeholder="Nombre de usuario" required 
                                   value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                        </div>
                        
                        <div class="form-group">
                            <input type="password" name="password" class="form-input" placeholder="Contraseña" required>
                        </div>
                        
                        <div class="checkbox-group">
                            <input type="checkbox" name="remember_me" id="remember_me">
                            <label for="remember_me">Recordarme por 30 días</label>
                        </div>
                        
                        <button type="submit" class="submit-button">Ingresar</button>
                    </form>

                    <?php if ($error && $login_type === 'credentials'): ?>
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Code Login -->
                <div class="login-screen" id="codeScreen" <?= $login_type === 'code' ? 'style="display: block;"' : '' ?>>
                    <button class="back-button" onclick="showSelector()">
                        <i class="fas fa-arrow-left"></i> Atrás
                    </button>
                    
                    <div class="welcome-text">
                        <h2 class="welcome-title">CÓDIGO DE ACCESO</h2>
                        <p class="welcome-subtitle">INGRESA TU CÓDIGO DE 6 DÍGITOS</p>
                    </div>

                    <form method="POST" id="codeForm">
                        <input type="hidden" name="login_type" value="code">
                        
                        <div class="form-group">
                            <div class="code-input-group">
                                <input type="text" name="access_code" class="form-input" placeholder="000000" maxlength="6" 
                                       pattern="[0-9]{6}" inputmode="numeric" required autocomplete="off">
                            </div>
                        </div>
                        
                        <div class="checkbox-group">
                            <input type="checkbox" name="remember_code" id="remember_code">
                            <label for="remember_code">Recordarme por 30 días</label>
                        </div>
                        
                        <button type="submit" class="submit-button">Validar Código</button>
                    </form>

                    <?php if ($error && $login_type === 'code'): ?>
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Hero Section - Right -->
        <div class="hero-section">
            <div class="hero-background" id="heroBackground"></div>
            <div class="hero-overlay"></div>
            
            <div class="hero-content">
                <div class="hero-main">
                    <h1 class="hero-title" id="heroTitle">Cargando Contenido...</h1>
                    <p class="hero-subtitle" id="heroSubtitle">Descubre entretenimiento ilimitado en calidad 4K</p>
                </div>
                
                <div class="trending-section">
                    <div class="trending-header">
                        <h3 class="trending-title">🎬 Tendencias de la semana</h3>
                    </div>
                    <div class="movies-slider">
                        <div class="movies-track" id="moviesTrack"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if (isset($_SESSION['login_ok']) && $_SESSION['login_ok'] === true): ?>
    <div id="loading">
        <div style="text-align: center;">
            <div class="logo-text" style="font-size: 48px; margin-bottom: 20px;">JTECH TV</div>
            <div class="spinner"></div>
            <p style="color: white; margin-top: 20px; font-size: 16px;">Cargando contenido...</p>
        </div>
    </div>

    <script>
        setTimeout(function() {
            window.location.href = "dashboard.php";
        }, 2000);
    </script>
    <?php unset($_SESSION['login_ok']); ?>
    <?php endif; ?>

    <script>
        const TMDB_API_KEY = '6b8e3eaa1a03ebb45642e9531d8a76d2';
        const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
        const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/w500';
        const BACKDROP_BASE_URL = 'https://image.tmdb.org/t/p/original';
        
        let currentMovieIndex = 0;
        let movies = [];
        let rotationInterval;
        
        async function loadTrendingMovies() {
            try {
                const response = await fetch(`${TMDB_BASE_URL}/trending/movie/week?api_key=${TMDB_API_KEY}&language=es-ES`);
                if (!response.ok) throw new Error('Network response was not ok');
                const data = await response.json();
                movies = data.results.slice(0, 12);
                displayMovies();
                startHeroRotation();
            } catch (error) {
                console.error('Error loading TMDB data:', error);
                loadFallbackData();
            }
        }
        
        function loadFallbackData() {
            movies = [
                { title: "Avatar: The Way of Water", backdrop_path: "/s16H6tpK2utvwDtzZ8Qy4qm5Emw.jpg", poster_path: "/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg", vote_average: 8.2, overview: "Una nueva aventura épica en Pandora que llevará a la familia Sully a explorar nuevas regiones del planeta." },
                { title: "Top Gun: Maverick", backdrop_path: "/odJ4hx6g6vBt4lBWKFD1tI8WS4x.jpg", poster_path: "/62HCnUTziyWcpDaBO2i1DX17ljH.jpg", vote_average: 8.7, overview: "Pete 'Maverick' Mitchell regresa después de más de treinta años de servicio como aviador de élite." },
                { title: "Black Panther: Wakanda Forever", backdrop_path: "/yYrvN5WFeGYjJnRzhY0QXuo4Isw.jpg", poster_path: "/sv1xJUazXeYqALzczSZ3O6nkH75.jpg", vote_average: 7.5, overview: "Wakanda lucha por proteger su nación tras la muerte del Rey T'Challa." },
                { title: "The Batman", backdrop_path: "/b0PlSFdDwbyK0cf5RxwDpaOJQvQ.jpg", poster_path: "/74xTEgt7R36Fpooo50r9T25onhq.jpg", vote_average: 8.1, overview: "Cuando un asesino en serie comienza a asesinar figuras políticas clave en Gotham, Batman se ve obligado a investigar la corrupción oculta de la ciudad." }
            ];
            displayMovies();
            startHeroRotation();
        }
        
        function displayMovies() {
            const track = document.getElementById('moviesTrack');
            if (!track) return;
            
            track.innerHTML = '';
            const allMovies = [...movies, ...movies];
            
            allMovies.forEach((movie, index) => {
                const movieCard = document.createElement('div');
                movieCard.className = 'movie-card';
                const posterUrl = movie.poster_path ? `${IMAGE_BASE_URL}${movie.poster_path}` : 'https://via.placeholder.com/300x450/2a2a2a/E50914?text=No+Image';
                movieCard.innerHTML = `
                    <img class="movie-poster" src="${posterUrl}" alt="${movie.title}" onerror="this.src='https://via.placeholder.com/300x450/2a2a2a/E50914?text=No+Image'">
                    <div class="movie-overlay">
                        <div class="movie-title">${movie.title}</div>
                        <div class="movie-rating">⭐ ${movie.vote_average?.toFixed(1) || 'N/A'}</div>
                    </div>
                `;
                
                if (index < movies.length) {
                    movieCard.addEventListener('click', () => {
                        currentMovieIndex = index;
                        updateHeroContent();
                    });
                }
                
                track.appendChild(movieCard);
            });
            
            updateHeroContent();
        }
        
        function updateHeroContent() {
            if (movies.length === 0) return;
            
            const movie = movies[currentMovieIndex];
            const heroBackground = document.getElementById('heroBackground');
            const heroTitle = document.getElementById('heroTitle');
            const heroSubtitle = document.getElementById('heroSubtitle');
            
            if (heroBackground && movie.backdrop_path) {
                heroBackground.style.backgroundImage = `url(${BACKDROP_BASE_URL}${movie.backdrop_path})`;
            }
            if (heroTitle) heroTitle.textContent = movie.title;
            if (heroSubtitle) heroSubtitle.textContent = movie.overview || 'Descubre entretenimiento ilimitado en calidad 4K';
        }
        
        function startHeroRotation() {
            if (rotationInterval) clearInterval(rotationInterval);
            rotationInterval = setInterval(() => {
                currentMovieIndex = (currentMovieIndex + 1) % movies.length;
                updateHeroContent();
            }, 8000);
        }
        
        function showLoginForm(type) {
            const selectorScreen = document.getElementById('selectorScreen');
            const credentialsScreen = document.getElementById('credentialsScreen');
            const codeScreen = document.getElementById('codeScreen');
            
            if (selectorScreen) selectorScreen.style.display = 'none';
            if (credentialsScreen) credentialsScreen.style.display = 'none';
            if (codeScreen) codeScreen.style.display = 'none';
            
            if (type === 'credentials' && credentialsScreen) {
                credentialsScreen.style.display = 'block';
                setTimeout(() => {
                    const usernameInput = document.querySelector('input[name="username"]');
                    if (usernameInput) usernameInput.focus();
                }, 100);
            } else if (type === 'code' && codeScreen) {
                codeScreen.style.display = 'block';
                setTimeout(() => {
                    const codeInput = document.querySelector('input[name="access_code"]');
                    if (codeInput) codeInput.focus();
                }, 100);
            }
            
            const url = new URL(window.location);
            url.searchParams.set('type', type);
            window.history.pushState({}, '', url);
        }
        
        function showSelector() {
            const selectorScreen = document.getElementById('selectorScreen');
            const credentialsScreen = document.getElementById('credentialsScreen');
            const codeScreen = document.getElementById('codeScreen');
            
            if (selectorScreen) selectorScreen.style.display = 'block';
            if (credentialsScreen) credentialsScreen.style.display = 'none';
            if (codeScreen) codeScreen.style.display = 'none';
            
            const url = new URL(window.location);
            url.searchParams.delete('type');
            window.history.pushState({}, '', url);
        }
        
        // Inicialización
        document.addEventListener('DOMContentLoaded', function() {
            const codeInput = document.querySelector('input[name="access_code"]');
            if (codeInput) {
                codeInput.addEventListener('input', function(e) {
                    e.target.value = e.target.value.replace(/\D/g, '');
                    if (e.target.value.length > 6) {
                        e.target.value = e.target.value.slice(0, 6);
                    }
                });
            }
             
            loadTrendingMovies();
        });
    </script>
</body>
</html>