<?php
include "session.php";
include "config.php";
include "header.php"; // Incluir el menú desde header.php

// Definir el User-Agent
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36';

// Función para realizar una solicitud API usando CURL
function getApiData($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        echo 'Error de CURL: ' . curl_error($ch);
        curl_close($ch);
        return [];
    }

    curl_close($ch);

    if ($httpCode !== 200) {
        echo "Error al conectarse a la API. Código HTTP: " . $httpCode;
        return [];
    }

    return json_decode($response, true);
}

// Obtener las categorías de películas desde la API
$categoriesUrl = $get_dns . "/player_api.php?username=" . $username . "&password=" . $password . "&action=get_vod_categories";
$channel_api = getApiData($categoriesUrl);

// Limitar la carga inicial a las primeras 5 secciones
$initial_sections = array_slice($channel_api, 0, 5);
$later_sections = array_slice($channel_api, 5);

// Obtener películas desde la API de Xtream Codes y mezclarlas para las películas destacadas
$moviesUrl = $get_dns . "/player_api.php?username=" . $username . "&password=" . $password . "&action=get_vod_streams";
$channel_api_movies = getApiData($moviesUrl);
shuffle($channel_api_movies); // Mezclar películas para que sean aleatorias

// Preparar datos para las películas destacadas
$random_movies_info = [];
$max_movies = 5; // Número máximo de películas a mostrar
$movie_count = 0; // Contador de películas añadidas

foreach ($channel_api_movies as $movie) {
    if ($movie_count >= $max_movies) {
        break; // Detener el bucle cuando se hayan añadido 5 películas
    }

    $id = $movie["stream_id"];
    $movieInfoUrl = $get_dns . "/player_api.php?username=" . $username . "&password=" . $password . "&action=get_vod_info&vod_id=" . $id;
    $channel_api_info = getApiData($movieInfoUrl);
    $channel_api_info2 = $channel_api_info["info"];

    // Verificar si la película tiene un backdrop
    if (isset($channel_api_info2["backdrop_path"][0]) && !empty($channel_api_info2["backdrop_path"][0])) {
        $backdrop = $channel_api_info2["backdrop_path"][0];
        $background_image = $backdrop;
        $play_link = "Movie_description?id=" . $id; // Enlace para el botón de play

        // Guardar la información de la película con backdrop
        $random_movies_info[] = [
            'title' => $channel_api_info2["name"],
            'description' => $channel_api_info2["plot"],
            'rating' => $channel_api_info2["rating"],
            'background_image' => $background_image,
            'play_link' => $play_link
        ];

        // Incrementar el contador de películas añadidas
        $movie_count++;
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home - IPTV Estilo Netflix</title>
    <style>
        body {
            background-color: #0f0f0f;
            color: white;
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
        }

        /* Contenedor principal */
        .container {
            max-width: auto;
            margin: 0 auto;
            padding: 10px;
        }

         /* Contenedor de la película destacada */
        .featured-movie-container {
            position: relative;
            height: 60vh;
            background-size: cover;
            background-position: center;
            display: flex;
            align-items: flex-end;
            padding: 30px;
            color: white;
            box-shadow: inset 0 -100px 100px rgba(0, 0, 0, 0.6);
        }

        .featured-movie-info {
            max-width: 50%;
            padding: 20px;
            background: rgba(0, 0, 0, 0.8);
            border-radius: 10px;
            transition: transform 0.3s ease;
        }

        .featured-movie-info h2 {
            font-size: 36px;
            color: #fff;
            text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.7);
        }

        .featured-movie-info p {
            font-size: 16px;
            color: #bbb;
        }

        .play-button {
            display: inline-block;
            background-color: #e50914;
            color: white;
            padding: 12px 25px;
            font-size: 18px;
            text-decoration: none;
            border-radius: 5px;
            transition: 0.3s;
        }

        .play-button:hover {
            background-color: #f40612;
        }

        /* Carrusel de contenido */
        .poster-carousel {
            display: flex;
            overflow-x: auto;
            padding: 10px 0;
            scroll-behavior: smooth;
        }

        .poster-carousel::-webkit-scrollbar {
            display: none;
        }

        .poster-item {
            flex: 0 0 auto;
            width: 200px;
            margin-right: 15px;
            text-align: center;
        }

        .poster-item img {
            width: 100%;
            height: auto;
            border-radius: 10px;
            transition: transform 0.3s ease;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
        }

        .poster-item img:hover {
            transform: scale(1.05);
        }

        .poster-item p {
            margin-top: 10px;
            font-size: 16px;
            color: #e5e5e5;
        }

        /* Título de las secciones */
        .section-title {
            font-size: 28px;
            margin: 30px 20px;
            color: #e50914;
        }

        .category-section .view-all a {
            color: #e50914;
            text-decoration: none;
        }

        .category-section .view-all a:hover {
            color: #f40612;
        }

        /* Responsivo */
        @media (max-width: 768px) {
            .featured-movie-info h2 {
                font-size: 28px;
            }

            .poster-item {
                width: 150px;
            }
        }
    </style>
</head>
<body>

<div class="container">
    <!-- Contenedor de la película destacada -->
    <div class="featured-movie-container" id="featured-movie-container">
        <div class="featured-movie-info">
            <h2 id="movie-title">Película Destacada</h2>
            <p id="movie-description">Descripción de la película.</p>
            <a id="play-link" class="play-button" href="#">Ver Ahora</a>
        </div>
    </div>

    <!-- Sección de categorías de películas (inicialmente 5) -->
    <h2 class="section-title">Películas</h2>
    <?php
    foreach ($initial_sections as $value) {
        $category_id = $value["category_id"];
        $category_name = $value["category_name"];

        echo "<div class='category-section'>\n";
        echo "<h3 class='section-title'>$category_name</h3>\n";
        echo "<div class='view-all'><a href='movies.php?id=$category_id'>Ver todas</a></div>\n";

        // Obtener los primeros 16 pósters de cada categoría de películas
        $movies_api = json_decode(file_get_contents($get_dns . "/player_api.php?username=" . $username . "&password=" . $password . "&action=get_vod_streams&category_id=" . $category_id . "&limit=16"), true);

        echo "<div class='poster-carousel'>\n";
        foreach ($movies_api as $movie) {
            $title = $movie["name"];
            $stream_id = $movie["stream_id"];
            $poster = $movie["stream_icon"] ?: "https://i.imgur.com/Mn7aXQD.jpg"; // Imagen predeterminada
            $medialink = "Movie_description?id=" . $stream_id;

            echo "<div class='poster-item'>\n";
            echo "<a href='$medialink'><img src='$poster' alt='$title' loading='lazy'></a>\n";
            echo "<p>$title</p>\n";
            echo "</div>\n";
        }
        echo "</div>\n"; // Fin del carrusel
        echo "</div>\n"; // Fin de la sección de categoría
    }
    ?>

    <!-- Secciones adicionales que se cargan bajo demanda -->
    <div id="lazy-sections"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
    const movies = <?php echo json_encode($random_movies_info); ?>;
    let movieIndex = 0;

    // Función para actualizar la película destacada
    function updateFeaturedMovie() {
        const movie = movies[movieIndex];
        document.getElementById('movie-title').innerText = movie.title;
        document.getElementById('movie-description').innerText = movie.description;
        document.getElementById('featured-movie-container').style.backgroundImage = `url('${movie.background_image}')`;
        document.getElementById('play-link').href = movie.play_link;

        movieIndex = (movieIndex + 1) % movies.length;
    }

    setInterval(updateFeaturedMovie, 5000);
    document.addEventListener("DOMContentLoaded", function() {
        updateFeaturedMovie();
    });

    // Función para cargar más secciones al hacer scroll
    document.addEventListener("DOMContentLoaded", function() {
        let laterSections = <?php echo json_encode($later_sections); ?>;
        let lazySectionsContainer = document.getElementById('lazy-sections');
        let currentIndex = 0;

        function loadMoreSections() {
    for (let i = 0; i < 2; i++) { // Cargar 2 secciones adicionales a la vez
        if (currentIndex >= laterSections.length) return;

        let section = laterSections[currentIndex];
        let category_id = section.category_id;
        let category_name = section.category_name;

        let sectionHTML = `
            <div class="category-section">
                <h3 class="section-title">` + category_name + `</h3>
                <div class="view-all"><a href="movies.php?id=` + category_id + `">Ver todas</a></div>
                <div class="poster-carousel" id="carousel_` + category_id + `"></div>
            </div>
        `;
        lazySectionsContainer.insertAdjacentHTML('beforeend', sectionHTML);

        fetch('<?php echo $get_dns; ?>/player_api.php?username=<?php echo $username; ?>&password=<?php echo $password; ?>&action=get_vod_streams&category_id=' + category_id + '&limit=16')
            .then(response => response.json())
            .then(movies_api => {
                let carousel = document.getElementById('carousel_' + category_id);
                movies_api.forEach(movie => {
                    let title = movie.name;
                    let stream_id = movie.stream_id;
                    let poster = movie.stream_icon || "https://i.imgur.com/Mn7aXQD.jpg";
                    let medialink = "Movie_description?id=" + stream_id;

                    let movieHTML = `
                        <div class="poster-item">
                            <a href="` + medialink + `"><img src="` + poster + `" alt="` + title + `" loading="lazy"></a>
                            <p>` + title + `</p>
                        </div>
                    `;
                    carousel.insertAdjacentHTML('beforeend', movieHTML);
                });
            });

        currentIndex++;
    }
}


        loadMoreSections();

        window.addEventListener('scroll', function() {
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
                loadMoreSections();
            }
        });
    });
</script>

</body>
</html>
