<?php
session_start();

if (!isset($_SESSION['user_logged']) || $_SESSION['user_logged'] !== true) {
    header('Location: index.php');
    exit;
}

$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server_url = $_SESSION['server_url'];
$server_name = $_SESSION['server_name'];

function makeApiRequest($action, $params = []) {
    global $username, $password, $server_url;
    
    if (empty($server_url)) {
        return [];
    }
    
    $full_url = rtrim($server_url, '/') . '/player_api.php?' . http_build_query(array_merge([
        'username' => $username,
        'password' => $password,
        'action' => $action
    ], $params));
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $full_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_FOLLOWLOCATION => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response && $httpCode == 200) {
        $data = json_decode($response, true);
        return is_array($data) ? $data : [];
    }
    
    return [];
}

// Obtener datos del servidor (sin caché para asegurar carga)
$all_movies = makeApiRequest('get_vod_streams');
$all_series = makeApiRequest('get_series');

$featured_movies = [];
if (!empty($all_movies) && is_array($all_movies)) {
    shuffle($all_movies);
    $count = 0;
    foreach ($all_movies as $movie) {
        if ($count >= 15) break;
        if (!empty($movie['name']) && !empty($movie['stream_id'])) {
            $featured_movies[] = $movie;
            $count++;
        }
    }
}

$featured_series = [];
if (!empty($all_series) && is_array($all_series)) {
    shuffle($all_series);
    $count = 0;
    foreach ($all_series as $serie) {
        if ($count >= 15) break;
        if (!empty($serie['name']) && !empty($serie['series_id'])) {
            $featured_series[] = $serie;
            $count++;
        }
    }
}

// Banner content (para el carrusel principal)
$banner_content = array_merge(
    array_slice($featured_movies, 0, 5),
    array_slice($featured_series, 0, 5)
);
shuffle($banner_content);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>JTECH TV - Inicio</title>
    <link rel="preconnect" href="https://cdnjs.cloudflare.com">
    <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;background:#141414;color:#fff;overflow-x:hidden}
        
        /* Loading */
        .loading-spinner{position:fixed;top:0;left:0;right:0;bottom:0;background:#141414;display:flex;align-items:center;justify-content:center;z-index:9999;transition:opacity .3s}
        .spinner{width:50px;height:50px;border:3px solid rgba(229,9,20,0.3);border-top-color:#E50914;border-radius:50%;animation:spin .6s linear infinite}
        @keyframes spin{to{transform:rotate(360deg)}}
        
        /* Banner Principal tipo Netflix */
        .main-banner{position:relative;height:85vh;min-height:500px;max-height:800px;overflow:hidden;margin-top:-70px;margin-bottom:40px}
        .banner-slide{position:absolute;top:0;left:0;width:100%;height:100%;opacity:0;transition:opacity .8s ease}
        .banner-slide.active{opacity:1}
        .banner-bg{position:absolute;top:0;left:0;width:100%;height:100%;background-size:cover;background-position:center 20%}
        .banner-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:linear-gradient(0deg,#141414 0%,transparent 30%,transparent 70%,#141414 100%)}
        .banner-content{position:absolute;bottom:25%;left:60px;max-width:550px;animation:fadeInUp .8s ease}
        @keyframes fadeInUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}
        .banner-title{font-size:52px;font-weight:800;margin-bottom:15px;text-shadow:2px 2px 4px rgba(0,0,0,0.5)}
        .banner-meta{display:flex;gap:12px;margin-bottom:15px;flex-wrap:wrap}
        .meta-item{padding:4px 12px;background:rgba(255,255,255,0.2);border-radius:4px;font-size:12px;backdrop-filter:blur(5px)}
        .meta-item.type{background:#E50914}
        .meta-item.rating{color:#ffc107}
        .banner-description{font-size:16px;line-height:1.5;color:rgba(255,255,255,0.9);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
        .banner-buttons{display:flex;gap:15px;margin-top:20px}
        .btn-play,.btn-info{padding:10px 25px;border-radius:4px;font-size:16px;font-weight:600;cursor:pointer;border:none;transition:all .2s}
        .btn-play{background:#fff;color:#000}
        .btn-play:hover{background:rgba(255,255,255,0.8)}
        .btn-info{background:rgba(109,109,110,0.7);color:#fff}
        .btn-info:hover{background:rgba(109,109,110,0.9)}
        .banner-dots{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);display:flex;gap:10px;z-index:10}
        .dot{width:10px;height:10px;border-radius:50%;background:rgba(255,255,255,0.5);cursor:pointer;transition:all .3s}
        .dot.active{width:30px;border-radius:5px;background:#E50914}
        
        /* Contenido principal */
        .main-content{margin-top:0;padding:20px 4% 80px}
        .section{margin-bottom:50px}
        .section-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}
        .section-title{font-size:24px;font-weight:700}
        .section-icon{color:#E50914;margin-right:10px}
        .view-all{color:#b3b3b3;text-decoration:none;font-size:14px;transition:color .2s}
        .view-all:hover{color:#fff}
        
        /* Grid de contenido */
        .content-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:20px}
        .content-card{position:relative;border-radius:8px;overflow:hidden;cursor:pointer;aspect-ratio:2/3;background:#1a1a1a;transition:transform .3s ease}
        .content-card:hover{transform:scale(1.05);z-index:10;box-shadow:0 10px 30px rgba(0,0,0,0.5)}
        .card-background{position:absolute;top:0;left:0;width:100%;height:100%;background-size:cover;background-position:center;transition:transform .3s}
        .content-card:hover .card-background{transform:scale(1.1)}
        .type-badge{position:absolute;top:10px;left:10px;padding:4px 10px;border-radius:4px;font-size:10px;font-weight:600;background:#E50914;z-index:2}
        .type-badge.series{background:#f59e0b}
        .play-button{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:50px;height:50px;background:rgba(0,0,0,0.8);border-radius:50%;display:flex;align-items:center;justify-content:center;opacity:0;transition:all .3s;z-index:3;cursor:pointer}
        .content-card:hover .play-button{opacity:1;transform:translate(-50%,-50%) scale(1.1)}
        .play-button i{font-size:20px;color:#fff;margin-left:3px}
        .card-overlay{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,0.95));padding:20px 12px 12px}
        .card-title{font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .card-meta{display:flex;gap:10px;font-size:11px;color:#b3b3b3;margin-top:5px}
        .card-year{color:#E50914}
        .card-rating{color:#ffc107}
        .card-genre{font-size:10px;color:#b3b3b3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        
        @media (max-width:968px){
            .banner-title{font-size:32px}
            .banner-content{left:30px;bottom:20%}
            .main-banner{height:60vh;min-height:400px}
            .content-row{grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:15px}
            .section-title{font-size:20px}
        }
        @media (max-width:768px){
            .main-content{padding:15px}
            .content-row{grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px}
            .banner-title{font-size:24px}
            .btn-play,.btn-info{padding:8px 16px;font-size:14px}
        }
        @media (max-width:480px){
            .content-row{grid-template-columns:repeat(auto-fill,minmax(100px,1fr))}
            .card-title{font-size:11px}
            .banner-description{font-size:12px;-webkit-line-clamp:3}
        }
    </style>
</head>
<body>
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner"></div>
    </div>

    <?php include 'header.php'; ?>
    
    <!-- BANNER PRINCIPAL ESTILO NETFLIX -->
    <?php if (!empty($banner_content)): ?>
    <div class="main-banner">
        <?php foreach ($banner_content as $index => $item): ?>
        <div class="banner-slide <?= $index === 0 ? 'active' : '' ?>">
            <div class="banner-bg" style="background-image: url('<?= htmlspecialchars($item['stream_icon'] ?? $item['cover'] ?? 'https://via.placeholder.com/1920x1080/1a252f/E50914?text=' . urlencode(substr($item['name'], 0, 20))) ?>');"></div>
            <div class="banner-overlay"></div>
            <div class="banner-content">
                <h1 class="banner-title"><?= htmlspecialchars($item['name']) ?></h1>
                <div class="banner-meta">
                    <span class="meta-item type"><?= isset($item['stream_id']) ? 'Película' : 'Serie' ?></span>
                    <?php if (!empty($item['year'])): ?>
                    <span class="meta-item"><?= htmlspecialchars($item['year']) ?></span>
                    <?php endif; ?>
                    <?php if (!empty($item['rating']) && $item['rating'] != '0'): ?>
                    <span class="meta-item rating">★ <?= number_format(floatval($item['rating']), 1) ?></span>
                    <?php endif; ?>
                </div>
                <p class="banner-description"><?= htmlspecialchars($item['plot'] ?? 'Disfruta de este increíble contenido en JTECH TV.') ?></p>
                <div class="banner-buttons">
                    <?php if (isset($item['stream_id'])): ?>
                    <button class="btn-play" onclick="playMovie(<?= $item['stream_id'] ?>, '<?= $item['container_extension'] ?? 'mp4' ?>')"><i class="fas fa-play"></i> Reproducir</button>
                    <button class="btn-info" onclick="openMovie(<?= $item['stream_id'] ?>)"><i class="fas fa-info-circle"></i> Más información</button>
                    <?php else: ?>
                    <button class="btn-play" onclick="openSeries(<?= $item['series_id'] ?>)"><i class="fas fa-play"></i> Ver serie</button>
                    <button class="btn-info" onclick="openSeries(<?= $item['series_id'] ?>)"><i class="fas fa-info-circle"></i> Más información</button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php if (count($banner_content) > 1): ?>
        <div class="banner-dots">
            <?php for($i = 0; $i < count($banner_content); $i++): ?>
            <div class="dot <?= $i === 0 ? 'active' : '' ?>" onclick="goToSlide(<?= $i ?>)"></div>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="main-content" id="mainContent" style="opacity:0">
        <!-- SECCIÓN DE PELÍCULAS -->
        <?php if (!empty($featured_movies)): ?>
        <div class="section">
            <div class="section-header">
                <h2 class="section-title"><i class="fas fa-film section-icon"></i> Películas Destacadas</h2>
                <a href="movies.php" class="view-all">Ver todas <i class="fas fa-arrow-right"></i></a>
            </div>
            <div class="content-row">
                <?php foreach ($featured_movies as $movie): ?>
                <div class="content-card" onclick="openMovie(<?= $movie['stream_id'] ?>)">
                    <div class="card-background" style="background-image: url('<?= htmlspecialchars(!empty($movie['stream_icon']) ? $movie['stream_icon'] : 'https://via.placeholder.com/300x450/1a252f/E50914?text=' . urlencode(substr($movie['name'], 0, 15))) ?>');"></div>
                    <div class="type-badge">Película</div>
                    <div class="play-button" onclick="event.stopPropagation(); playMovie(<?= $movie['stream_id'] ?>, '<?= $movie['container_extension'] ?? 'mp4' ?>')">
                        <i class="fas fa-play"></i>
                    </div>
                    <div class="card-overlay">
                        <div class="card-title"><?= htmlspecialchars($movie['name']) ?></div>
                        <div class="card-meta">
                            <span class="card-year"><?= !empty($movie['year']) ? htmlspecialchars($movie['year']) : 'N/A' ?></span>
                            <?php if (!empty($movie['rating']) && $movie['rating'] != '0'): ?>
                            <span class="card-rating">★ <?= number_format(floatval($movie['rating']), 1) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($movie['genre'])): ?>
                        <div class="card-genre"><?= htmlspecialchars($movie['genre']) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- SECCIÓN DE SERIES -->
        <?php if (!empty($featured_series)): ?>
        <div class="section">
            <div class="section-header">
                <h2 class="section-title"><i class="fas fa-tv section-icon"></i> Series Destacadas</h2>
                <a href="series.php" class="view-all">Ver todas <i class="fas fa-arrow-right"></i></a>
            </div>
            <div class="content-row">
                <?php foreach ($featured_series as $serie): ?>
                <div class="content-card" onclick="openSeries(<?= $serie['series_id'] ?>)">
                    <div class="card-background" style="background-image: url('<?= htmlspecialchars(!empty($serie['cover']) ? $serie['cover'] : 'https://via.placeholder.com/300x450/1a252f/f59e0b?text=' . urlencode(substr($serie['name'], 0, 15))) ?>');"></div>
                    <div class="type-badge series">Serie</div>
                    <div class="play-button" onclick="event.stopPropagation(); openSeries(<?= $serie['series_id'] ?>)">
                        <i class="fas fa-play"></i>
                    </div>
                    <div class="card-overlay">
                        <div class="card-title"><?= htmlspecialchars($serie['name']) ?></div>
                        <div class="card-meta">
                            <span class="card-year"><?= !empty($serie['year']) ? htmlspecialchars($serie['year']) : 'N/A' ?></span>
                            <?php if (!empty($serie['rating']) && $serie['rating'] != '0'): ?>
                            <span class="card-rating">★ <?= number_format(floatval($serie['rating']), 1) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($serie['genre'])): ?>
                        <div class="card-genre"><?= htmlspecialchars($serie['genre']) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if (empty($featured_movies) && empty($featured_series)): ?>
        <div style="text-align:center;padding:50px;background:#1a1a1a;border-radius:12px;margin:20px">
            <i class="fas fa-exclamation-triangle" style="font-size:48px;color:#E50914;margin-bottom:15px"></i>
            <h3>No se encontraron contenidos</h3>
            <p style="color:#b3b3b3;margin-top:10px">Verifica tu conexión o contacta al soporte.</p>
            <p style="font-size:12px;color:#666;margin-top:15px">Servidor: <?= htmlspecialchars($server_name) ?></p>
        </div>
        <?php endif; ?>
    </div>

    <script>
        // Ocultar loading
        setTimeout(function() {
            var spinner = document.getElementById('loadingSpinner');
            if(spinner) {
                spinner.style.opacity = '0';
                setTimeout(function() { spinner.style.display = 'none'; }, 300);
            }
            document.getElementById('mainContent').style.opacity = '1';
        }, 500);

        // Banner slides
        let currentSlide = 0;
        const slides = document.querySelectorAll('.banner-slide');
        const dots = document.querySelectorAll('.dot');
        const totalSlides = slides.length;

        function goToSlide(index) {
            if(slides[currentSlide]) slides[currentSlide].classList.remove('active');
            if(dots[currentSlide]) dots[currentSlide].classList.remove('active');
            currentSlide = index;
            if(slides[currentSlide]) slides[currentSlide].classList.add('active');
            if(dots[currentSlide]) dots[currentSlide].classList.add('active');
        }

        // Auto slide
        if(totalSlides > 1) {
            setInterval(function() {
                goToSlide((currentSlide + 1) % totalSlides);
            }, 7000);
        }

        // Funciones de navegación
        function openMovie(movieId) {
            window.location.href = 'movie-detail.php?id=' + movieId;
        }

        function playMovie(movieId, extension) {
            window.location.href = 'player.php?id=' + movieId + '&slug=movie&ext=' + extension;
        }

        function openSeries(seriesId) {
            window.location.href = 'series-detail.php?id=' + seriesId;
        }

        // Animación de entrada para las cards
        window.addEventListener('load', function() {
            const cards = document.querySelectorAll('.content-card');
            cards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(30px)';
                setTimeout(() => {
                    card.style.transition = 'all 0.5s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 50);
            });
        });
    </script>
</body>
</html>