<?php
include "session.php";
include "config.php";

// Carpeta para caché
define('CACHE_DIR', __DIR__ . '/cache/');
if (!file_exists(CACHE_DIR)) mkdir(CACHE_DIR, 0777, true);

// Genera una clave de caché basada SOLO en el DNS y una etiqueta
function getCacheFile($key, $server) {
    $filename = md5($server . '_' . $key) . '.json';
    return CACHE_DIR . $filename;
}

// Función para obtener datos desde API con caché en archivo JSON
function getApiDataWithCache($apiUrl, $key, $expiration = 86400) {
    global $get_dns;

    $cacheFile = getCacheFile($key, $get_dns);
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $expiration)) {
        $json = file_get_contents($cacheFile);
        $data = json_decode($json, true);
        if (is_array($data)) return $data;
    }

    $ch = curl_init($apiUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0',
        CURLOPT_TIMEOUT => 30,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200 || !$response) {
        error_log("Error al conectarse a la API: $apiUrl - HTTP: $httpCode");
        return [];
    }

    $data = json_decode($response, true);
    if (!is_array($data)) return [];

    file_put_contents($cacheFile, json_encode($data));
    return $data;
}

// Validación
if (!isset($get_dns, $username, $password)) {
    die("Error: Faltan datos de conexión.");
}

// Generar URL API
function buildApiUrl($action) {
    global $get_dns, $username, $password;
    return "$get_dns/player_api.php?username=$username&password=$password&action=$action";
}

// Función para obtener imagen con prioridad
function getImagePriority($info, $fallback) {
    return !empty($info['backdrop_path'][0]) ? $info['backdrop_path'][0]
         : (!empty($info['cover_big']) ? $info['cover_big']
         : (!empty($info['movie_image']) ? $info['movie_image']
         : $fallback));
}

// Función para imagen top
function getTopImage($info, $fallback) {
    return $info['movie_image'] ?? $info['cover_big'] ?? $fallback;
}

// Obtener datos de API con caché (solo usando DNS como base de clave)
$movie_categories = getApiDataWithCache(buildApiUrl('get_vod_categories'), 'movie_categories');
$channel_api = getApiDataWithCache(buildApiUrl('get_vod_streams'), 'vod_streams');
$channel_api1 = getApiDataWithCache(buildApiUrl('get_series'), 'series');

// Ordenar por fecha de adición
usort($channel_api, function($a, $b) {
    return ($b['added'] ?? 0) - ($a['added'] ?? 0);
});

// Construir array de elementos destacados
$items = [];
$i = 0;
foreach ($channel_api as $value) {
    if ($i >= 10) break;

    $stream_id = $value['stream_id'];
    $info_url = "$get_dns/player_api.php?username=$username&password=$password&action=get_vod_info&vod_id=$stream_id";
    $movie_info = getApiDataWithCache($info_url, "vod_info_$stream_id");
    $info = $movie_info['info'] ?? [];
    $year = $movie_info['movie_data']['year'] ?? '';

    $poster = getImagePriority($info, $value['stream_icon'] ?: "https://i.imgur.com/Mn7aXQD.jpg");
    $topPoster = getTopImage($info, "https://i.imgur.com/Mn7aXQD.jpg");

    $items[] = [
        'stream_id' => $stream_id,
        'title' => htmlspecialchars($info['name'] ?? $value['name']),
        'description' => htmlspecialchars($info['description'] ?? "Sin descripción disponible."),
        'poster' => $poster,
        'topPoster' => $topPoster,
        'rating' => floatval($info['rating'] ?? 0),
        'genres' => htmlspecialchars($info['genre'] ?? "Acción"),
        'duration' => $info['duration'] ?? "01:30:00",
        'medialink' => "movidet?id=$stream_id",
        'year' => $year,
        'youtube_trailer' => $info['youtube_trailer'] ?? ''
    ];

    $i++;
}

// Para compartir enlaces desde esta misma ubicación
$sharedlink = "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['REQUEST_URI']), '/') . '/';
?>


<!doctype html>
<html lang="en" data-bs-theme="dark">

  <?php include("./head.php"); ?>

<body class=" custom-header-relative ">
  <span class="screen-darken"></span>
  <!-- loader Start -->
   <!-- loader Start -->
  <div class="loader simple-loader">
     <div class="loader-body">
        <img src="./assets/img/logo.png" alt="loader" class="logoloader"   width="300">
      </div>
  </div>
  <!-- loader END -->  <!-- loader END -->
  <main class="main-content">
      <!--Nav Start-->
  <?php include("./navbar.php"); ?>

      <!--bread-crumb-->
<section class="banner-container">
  <div class="movie-banner">
    <div class="swiper swiper-banner-container" data-swiper="banner-detail-slider">
      <div class="swiper-wrapper">
        <?php foreach ($items as $item): ?>
          <?php if (empty($item['youtube_trailer'])) continue; // Saltar ítems sin tráiler ?>

        <div class="swiper-slide movie-banner p-0">
          <div class="movie-banner-image">
            <img  rel="preload" src="<?= $item['poster'] ?>"   alt="movie-banner-image">
          </div>
          <div class="shows-content h-100">
            <div class="row align-items-center h-100">
              <div class="col-lg-7 col-md-12">
                <h1 class="texture-text big-font letter-spacing-1 line-count-1 text-uppercase RightAnimate-two"
                    data-animation-in="fadeInLeft" data-delay-in="0.6">
                  <?= htmlspecialchars($item['title']) ?>
                </h1>
                <div class="flex-wrap align-items-center fadeInLeft animated" data-animation-in="fadeInLeft" style="opacity: 1;">
                  <div class="slider-ratting d-flex align-items-center gap-3">
                    <ul class="ratting-start p-0 m-0 list-inline text-primary d-flex align-items-center justify-content-left">
                      <?php 
                      // Calificación de estrellas
                      $fullStars = floor($item['rating']); 
                      $halfStar = ($item['rating'] - $fullStars) >= 0.5 ? true : false;
                      $emptyStars = 5 - ($fullStars + ($halfStar ? 1 : 0));
                      
                      // Estrellas completas
                      for ($s = 0; $s < $fullStars; $s++): ?>
                        <li><i class="fas fa-star" aria-hidden="true"></i></li>
                      <?php endfor; ?>
                      
                      <!-- Estrella media si corresponde -->
                      <?php if ($halfStar): ?>
                        <li><i class="fa fa-star-half" aria-hidden="true"></i></li>
                      <?php endif; ?>
                      
                      <!-- Estrellas vacías -->
                      <?php for ($s = 0; $s < $emptyStars; $s++): ?>
                        <li><i class="fa fa-star-o" aria-hidden="true"></i></li>
                      <?php endfor; ?>
                    </ul>
                    <span class="text-white"><?= $item['rating'] ?>/10</span>
                  </div>
                  <div class="d-flex flex-wrap align-items-center gap-3 movie-banner-time">
                    <span class="badge bg-secondary p-2">
                      <i class="fa fa-eye"></i>
                      <?= htmlspecialchars($item['rating']) ?>
                    </span>
                    <span class="font-size-6">
                      <i class="fa-solid fa-circle"></i>
                    </span>
                    <span class="trending-time font-normal"><?= htmlspecialchars($item['duration']) ?></span>
                    <span class="font-size-6">
                      <i class="fa-solid fa-circle"></i>
                     
                   <span class="trending-time font-normal"><?= htmlspecialchars($item['year']) ?></span>

                    </span>
                  </div>
                  <p class="movie-banner-text line-count-3" data-animation-in="fadeInUp" data-delay-in="1.2">
                    <?= htmlspecialchars($item['description']) ?>
                  </p>
                </div>
                <div class="iq-button" data-animation-in="fadeInUp" data-delay-in="1.2">
                  <a href="<?= $item['medialink'] ?>" class="btn text-uppercase position-relative">
                    <span class="button-text">Play Now</span>
                    <i class="fa-solid fa-play"></i>
                  </a>
                </div>
              </div>
              <div class="col-lg-5 col-md-12 trailor-video iq-slider d-none d-lg-block position-relative">
<?php if (isset($item['youtube_trailer']) && !empty($item['youtube_trailer'])) : 
    // Crear la URL completa del video de YouTube
    $youtube_url = "https://www.youtube.com/embed/" . $item['youtube_trailer'];
?>
    <div class="">
        <!-- Botón para abrir el tráiler en una nueva página -->
        <a data-fslightbox="html5-video"  href="<?= $youtube_url ?>" target="_blank" class="video-open playbtn text-decoration-none" tabindex="0">
            <svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="80px" height="80px" viewBox="0 0 213.7 213.7" enable-background="new 0 0 213.7 213.7" xml:space="preserve">
                <polygon class="triangle" fill="none" stroke-width="7" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="73.5,62.5 148.5,105.8 73.5,149.1 "></polygon>
                <circle class="circle" fill="none" stroke-width="7" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" cx="106.8" cy="106.8" r="103.3"></circle>
            </svg>
            <span class="w-trailor text-uppercase"> Watch Trailer </span>
        </a>
    </div>

<?php else: ?>
    <p>No tiene trailer. Jode al dueño IPTV.</p> <!-- O algún otro contenido para cuando no haya tráiler -->
<?php endif; ?>


              </div>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="swiper-banner-button-next">
        <i class="iconly-Arrow-Right-2 icli arrow-icon"></i>
      </div>
      <div class="swiper-banner-button-prev">
        <i class="iconly-Arrow-Left-2 icli arrow-icon"></i>
      </div>
    </div>
  </div>
</section>


<section class="recommended-block section-top-spacing">
  <div class="container-fluid">
    <div class="overflow-hidden">
      <?php foreach ($movie_categories as $category): ?>
      <!-- Mostrar el nombre de la categoría -->
      <div class="d-flex align-items-center justify-content-between px-3 my-4">
        <h5 class="main-title text-capitalize mb-0"><?= htmlspecialchars($category['category_name']) ?></h5>
        <?php
        // Construir la URL para redirigir a la categoría específica
        $category_url = "vod_cat?id=" . $category['category_id'];
        ?>
        <!-- Actualizar el enlace de View All -->
        <a href="<?= $category_url ?>" class="text-primary iq-view-all text-decoration-none">View All</a>
      </div>

      <!-- Carrusel de películas de esta categoría -->
      <div class="card-style-slider">
        <div class="position-relative swiper swiper-card" data-slide="6" data-laptop="5" data-tab="3" data-mobile="2"
          data-mobile-sm="2" data-autoplay="false" data-loop="true" data-navigation="true" data-pagination="true">
          <ul class="p-0 swiper-wrapper m-0 list-inline">
            <?php
            // Filtrar las películas que pertenecen a esta categoría y mostrar hasta 10
            $i = 0;
            foreach ($channel_api as $movie) {
                if ($movie['category_id'] == $category['category_id'] && $i < 7) {
                    $title = $movie["name"];
                    $stream_id = $movie["stream_id"];
                    $poster = $movie["stream_icon"] ?: "https://i.imgur.com/Mn7aXQD.jpg";
                    $medialink = "movidet?id=" . $stream_id;
            ?>
            <li class="swiper-slide">
                <div class="iq-card card-hover">
                  <div class="block-images position-relative w-100">
                    <div class="img-box w-100">
                      <a href="<?= $medialink ?>" class="position-absolute top-0 bottom-0 start-0 end-0"></a>
                      <img src="<?= $poster ?>" loading="lazy" alt="movie-card" class="img-fluid object-cover w-100 d-block border-0">
                    </div>
                    <div class="card-description with-transition">
                      <div class="cart-content">
                        <div class="content-left">
                          <h5 class="iq-title text-capitalize">
                            <a href="<?= $medialink ?>"><?= htmlspecialchars($title) ?></a>
                          </h5>
                          <div class="movie-time d-flex align-items-center my-2"> 
                            <span class="movie-time-text font-normal"><?= htmlspecialchars($info['duration']) ?></span>
                          </div>
                        </div>
                       </div>
                    </div>
                    <div class="block-social-info align-items-center">
              <ul class="p-0 m-0 d-flex gap-2 music-play-lists" style="content-visibility: hidden;" >
                        <li class="share position-relative d-flex align-items-center text-center mb-0">
                          <span class="w-100 h-100 d-inline-block bg-transparent">
                            <i class="fas fa-share-alt"></i>
                          </span>
                          <div class="share-wrapper">
                            <div class="share-boxs d-inline-block">
                             <div class="overflow-hidden">
   
  
  <!-- WhatsApp -->
  <a href="https://wa.me/+51916967110?text=¡Mira esta película: <?= urlencode($title) ?> en: <?= $sharedlink . $medialink ?> " target="_blank">
    <i class="fab fa-whatsapp"></i>
  </a>
</div>

                            </div>
                          </div>
                        </li>
                       </ul>
                      <div class="iq-button">
                        <a href="<?= $medialink ?>" class="btn text-uppercase position-relative rounded-circle">
                          <i class="fa-solid fa-play ms-0"></i>
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
            </li>
            <?php 
                    $i++; // Incrementamos el contador de películas
                }
            }
            ?>
          </ul>
          <div class="swiper-button swiper-button-next"></div>
          <div class="swiper-button swiper-button-prev"></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

 


  </main>
 
  
  
  <div id="back-to-top" style="display: none;">
     <a class="p-0 btn bg-primary btn-sm position-fixed top border-0 rounded-circle text-white" id="top" href="#top">
        <i class="fa-solid fa-chevron-up"></i>
     </a>
  </div>
  <!-- Wrapper End-->
   



  <!-- Library Bundle Script -->
  <script src="./assets/js/core/libs.min.js"></script>
  <!-- Plugin Scripts -->
  
  
  <!-- SwiperSlider Script -->
  <script src="./assets/vendor/swiperSlider/swiper.min.js"></script>
  
  
  
    <script>
    window.onload = function() {
        // Obtener el loader
        const loader = document.querySelector('.loader');
        
        // Asegurarse de que el loader desaparezca de forma suave
        setTimeout(function() {
            loader.style.opacity = '0';  // Desvanecer el loader
            loader.style.transition = 'opacity 1s ease'; // Transición suave de 1s
        }, 100); // Ajusta el tiempo de espera si es necesario

        // Ocultar el loader después de la transición
        setTimeout(function() {
            loader.style.display = 'none'; // Ocultar el loader
        }, 100); // Tiempo que tarda en desaparecer completamente (1s + un poco de margen)
    };
</script>
  <!-- fslightbox Script -->
  <script src="./assets/js/plugins/fslightbox.js" defer></script>
  <!-- Lodash Utility -->
  <script src="./assets/vendor/lodash/lodash.min.js"></script>
  <!-- External Library Bundle Script -->
  <script src="./assets/js/core/external.min.js"></script>
  <!-- countdown Script -->
  <script src="./assets/js/plugins/countdown.js"></script>
  <!-- utility Script -->
  <script src="./assets/js/utility.js"></script>
  <!-- Setting Script -->
  <script src="./assets/js/setting.js"></script>
  <script src="./assets/js/setting-init.js" defer></script>
  <!-- Streamit Script -->
  <script src="./assets/js/streamit.js" defer></script>
  <script src="./assets/js/swiper.js" defer></script>
</body>

</html>