<?php
session_start();

// Función para obtener las películas desde la API
function getMoviesFromEndpoint($api_key, $pages = 10) {
    $cache_file = 'movies_cache.json';
    $cache_time = 3600; // 1 hora

    if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_time)) {
        return json_decode(file_get_contents($cache_file), true);
    }

    $movies = [];
    for ($page = 1; $page <= $pages; $page++) {
        $url = "https://api.themoviedb.org/3/movie/now_playing?api_key={$api_key}&language=es-ES&page={$page}";
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        if (isset($data['results']) && is_array($data['results'])) {
            $movies = array_merge($movies, $data['results']);
        }
    }

    $movies = array_filter($movies, function($movie) {
        return isset($movie['poster_path']) && $movie['poster_path'] !== null;
    });

    file_put_contents($cache_file, json_encode($movies));
    return $movies;
}

$api_key = '54a47dfd36406757c9a6b7a0e3fd9cdc';
$movies = getMoviesFromEndpoint($api_key);

// Proceso de autenticación del usuario
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["url"])) {
    $url = rtrim($_POST["url"], '/'); // Elimina la barra final si existe
    $username = $_POST["username"];
    $password = $_POST["password"];

    $authUrl = "{$url}/player_api.php?username={$username}&password={$password}";
    $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36';
    $opts = [
        'http' => [
            'header' => "User-Agent: $userAgent\r\n"
        ]
    ];
    $context = stream_context_create($opts);

    $response = file_get_contents($authUrl, false, $context);
    $api = json_decode($response, true);

    if (isset($api['user_info']['auth']) && $api['user_info']['auth'] == 1 && $api['user_info']['status'] === "Active") {
        // Guardar datos de sesión
        $_SESSION["username"] = $username;
        $_SESSION["password"] = $password;
        $_SESSION["server_url"] = $url;

        // Redirigir a página principal
        echo json_encode(['success' => true, 'redirect' => 'homex']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Credenciales incorrectas o cuenta inactiva']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Login - Carrusel de Películas</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            background-color: #181828;
            color: #fff;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }

        .carousel-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: 1;
        }

        .carousel-content {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            padding: 20px 0;
            height: 100%;
        }

        .poster {
            width: calc(20% - 20px);
            margin: 10px;
            position: relative;
            overflow: hidden;
            aspect-ratio: 2/3;
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .poster:hover {
            transform: scale(1.1);
            z-index: 10;
        }

        .poster img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .poster-title {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px;
            text-align: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .poster:hover .poster-title {
            opacity: 1;
        }

        .content {
            position: relative;
            z-index: 2;
            text-align: center;
            color: #fff;
            padding-top: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            flex-direction: column;
        }

        .login-box {
            background-color: rgba(0, 0, 0, 0.7);
            padding: 20px;
            border-radius: 10px;
            display: inline-block;
            width: 300px;
        }

        .login-box h1 {
            font-size: 30px;
            margin-bottom: 20px;
        }

        .login-box input, .login-box button {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
        }

        .login-box button {
            background-color: #00509b;
            color: #fff;
            cursor: pointer;
        }

        .footer {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            color: #fff;
            text-align: center;
            padding: 10px;
            z-index: 2;
        }

        .footer a {
            color: #ffcc00;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <!-- Carrusel de Posters (Fondo) -->
    <div class="carousel-container">
        <div class="carousel-content" id="carousel-content">
            <?php 
            foreach ($movies as $movie) {
                echo '<div class="poster">';
                echo '<a href="https://www.themoviedb.org/movie/' . $movie['id'] . '" target="_blank">';
                echo '<img src="https://image.tmdb.org/t/p/w500' . $movie['poster_path'] . '" alt="' . $movie['title'] . '" loading="lazy">';
                echo '<div class="poster-title">' . $movie['title'] . '</div>';
                echo '</a>';
                echo '</div>';
            }
            ?>
        </div>
    </div>

    <!-- Contenido Principal (login y footer) -->
    <div class="content">
        <div class="login-box">
            <h1>Bienvenido</h1>
            <form id="login-form" method="POST">
                <input type="text" placeholder="URL del Servidor" name="url" required>
                <input type="text" placeholder="Usuario" name="username" required>
                <input type="password" placeholder="Contraseña" name="password" required>
                <button type="submit">Login</button>
            </form>
        </div>
    </div>

    <div class="footer">
        <p>© 2024 <a href="https://t.me/rebrandmx" target="_blank">Developed by RebrandsMX</a></p>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('login-form').addEventListener('submit', function(event) {
            event.preventDefault();

            const formData = new FormData(this);

            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = data.redirect;
                } else {
                    alert(data.message);
                }
            })
            .catch(error => console.error('Error:', error));
        });

        const content = document.querySelector('.carousel-content');
        let scrollPosition = 0;
        const scrollSpeed = 0.5;

        function scrollPosters() {
            scrollPosition += scrollSpeed;
            if (scrollPosition >= content.scrollHeight / 2) {
                scrollPosition = 0;
            }
            content.style.transform = `translateY(-${scrollPosition}px)`;
            requestAnimationFrame(scrollPosters);
        }

        scrollPosters();
    });
    </script>
</body>
</html>
