<?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'];

$movie_id = $_GET['id'] ?? null;
if (!$movie_id) {
    header('Location: movies.php');
    exit;
}

define('TMDB_API_KEY', '6b8e3eaa1a03ebb45642e9531d8a76d2');
define('TMDB_API_URL', 'https://api.themoviedb.org/3');
define('TMDB_IMG_URL', 'https://image.tmdb.org/t/p/');

function tmdbRequest($endpoint, $params = []) {
    $params['api_key'] = TMDB_API_KEY;
    $url = TMDB_API_URL . $endpoint . '?' . http_build_query($params);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return $response ? json_decode($response, true) : null;
}

function makeApiRequest($action, $params = []) {
    global $username, $password, $server_url;
    
    $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($ch, CURLOPT_URL, $full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        return json_decode($response, true);
    }
    return false;
}

$movie_info = makeApiRequest('get_vod_info', ['vod_id' => $movie_id]);

if (!$movie_info || !isset($movie_info['info'])) {
    header('Location: movies.php');
    exit;
}

$movie = $movie_info['info'];
$movie_data = $movie_info['movie_data'] ?? null;

// Limpiar título para TMDB
$movie_title = $movie_data['name'] ?? 'Untitled';
$movie_title = preg_replace('/\s*\|\s*.*$/', '', $movie_title);
$movie_title = preg_replace('/\s*\(\d{4}\)\s*/', '', $movie_title);
$movie_title = preg_replace('/\s*\(.*?\)\s*/', '', $movie_title);
$movie_title = trim($movie_title);

$tmdb_data = null;
$tmdb_id = null;
$similar_movies = [];

if (!empty($movie_title)) {
    $search_results = tmdbRequest('/search/movie', ['query' => $movie_title, 'language' => 'es-ES']);
    
    if (empty($search_results['results']) && strpos($movie_data['name'], '|') !== false) {
        $parts = explode('|', $movie_data['name']);
        if (isset($parts[1])) {
            $english_title = trim($parts[1]);
            $english_title = preg_replace('/\s*\(\d{4}\)\s*/', '', $english_title);
            $search_results = tmdbRequest('/search/movie', ['query' => $english_title, 'language' => 'es-ES']);
        }
    }
    
    if (!empty($search_results['results'])) {
        $tmdb_id = $search_results['results'][0]['id'];
        $tmdb_data = tmdbRequest('/movie/' . $tmdb_id, [
            'append_to_response' => 'credits,videos,images',
            'language' => 'es-ES'
        ]);
        
        // Obtener películas similares (NUEVO)
        $similar_data = tmdbRequest('/movie/' . $tmdb_id . '/similar', [
            'language' => 'es-ES',
            'page' => 1
        ]);
        if (!empty($similar_data['results'])) {
            $similar_movies = array_slice($similar_data['results'], 0, 12);
        }
    }
}

$backdrop_url = null;
if (!empty($movie['backdrop_path'][0])) {
    $backdrop_url = $movie['backdrop_path'][0];
} elseif ($tmdb_data && !empty($tmdb_data['backdrop_path'])) {
    $backdrop_url = TMDB_IMG_URL . 'original' . $tmdb_data['backdrop_path'];
}
?>
<!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><?= htmlspecialchars($movie_title) ?> - JTECH TV</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',sans-serif;background:#0f171e;color:#fff;overflow-x:hidden}
        
        .hero{position:relative;height:100vh;min-height:600px;width:100%;overflow:hidden;display:flex;align-items:center;margin-top:-65px}
        .hero-bg{position:absolute;top:0;left:0;width:100%;height:100%;background-image:url('<?= htmlspecialchars($backdrop_url) ?>');background-size:cover;background-position:center;filter:brightness(0.35);z-index:1}
        .hero-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:linear-gradient(90deg,#0f171e 0%,rgba(15,23,30,0.7) 40%,rgba(15,23,30,0.4) 70%,transparent 100%);z-index:2}
        .hero-content{position:relative;z-index:10;padding:0 60px;max-width:55%;animation:fadeInUp .8s ease}
        
        @keyframes fadeInUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}
        
        .movie-title{font-size:clamp(2rem,4vw,3.5rem);font-weight:700;margin-bottom:15px;text-shadow:2px 2px 8px rgba(0,0,0,0.8)}
        .metadata{display:flex;align-items:center;gap:15px;flex-wrap:wrap;margin-bottom:20px}
        .match-score{color:#46d369;font-weight:600}
        .year,.duration,.quality{background:rgba(0,0,0,0.7);padding:6px 12px;border-radius:6px;font-size:13px;font-weight:600;border:1px solid rgba(255,255,255,0.2)}
        .rating{background:#ffa500;color:#000;padding:6px 12px;border-radius:6px;font-size:13px;font-weight:600}
        .synopsis{font-size:16px;line-height:1.5;margin-bottom:25px;color:rgba(255,255,255,0.9)}
        .genres{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:25px}
        .genre{color:rgba(255,255,255,0.8);font-size:14px}
        .play-button{background:#fff;border:none;border-radius:8px;color:#000;display:inline-flex;align-items:center;gap:12px;padding:14px 32px;font-size:16px;font-weight:600;cursor:pointer;transition:all .2s;margin-bottom:30px;text-decoration:none}
        .play-button:hover{background:rgba(255,255,255,0.9);transform:translateY(-2px)}
        
        .cast-section{max-height:180px;overflow:hidden}
        .cast-title{font-size:18px;font-weight:600;margin-bottom:15px}
        .cast-grid{display:flex;gap:15px;overflow-x:auto;padding-bottom:8px;scrollbar-width:thin}
        .cast-grid::-webkit-scrollbar{height:4px}
        .cast-grid::-webkit-scrollbar-track{background:rgba(255,255,255,0.1);border-radius:2px}
        .cast-grid::-webkit-scrollbar-thumb{background:rgba(255,255,255,0.3);border-radius:2px}
        .cast-member{flex-shrink:0;width:80px;text-align:center}
        .cast-photo{width:80px;height:100px;border-radius:8px;object-fit:cover;background:rgba(255,255,255,0.1);margin-bottom:8px;border:2px solid rgba(255,255,255,0.2)}
        .cast-name{font-size:12px;font-weight:600;margin-bottom:4px}
        .cast-character{font-size:10px;color:rgba(255,255,255,0.7)}
        
        /* SECCIÓN DE PELÍCULAS SIMILARES - NUEVA */
        .similar-section{margin:60px 40px 40px 40px}
        .similar-title{font-size:22px;font-weight:700;margin-bottom:20px;display:flex;align-items:center;gap:10px}
        .similar-title i{color:#E50914}
        .similar-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:20px}
        .similar-card{position:relative;border-radius:8px;overflow:hidden;cursor:pointer;aspect-ratio:2/3;background:#1a1a1a;transition:transform .3s ease}
        .similar-card:hover{transform:scale(1.05);z-index:10;box-shadow:0 10px 30px rgba(0,0,0,0.5)}
        .similar-card-bg{position:absolute;top:0;left:0;width:100%;height:100%;background-size:cover;background-position:center;transition:transform .3s}
        .similar-card:hover .similar-card-bg{transform:scale(1.1)}
        .similar-card-overlay{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,0.95));padding:15px 10px 10px}
        .similar-card-title{font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .similar-card-year{font-size:11px;color:#b3b3b3;margin-top:4px}
        .similar-rating{position:absolute;top:8px;right:8px;background:rgba(0,0,0,0.7);padding:3px 6px;border-radius:4px;font-size:10px;color:#ffc107;z-index:2}
        
        @media (max-width:768px){
            .hero-content{padding:0 25px;max-width:85%}
            .movie-title{font-size:clamp(1.5rem,3vw,2rem)}
            .synopsis{font-size:14px;-webkit-line-clamp:3;display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden}
            .play-button{padding:12px 24px}
            .cast-section{max-height:150px}
            .cast-member{width:70px}
            .cast-photo{width:70px;height:90px}
            .similar-section{margin:40px 20px}
            .similar-grid{grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:12px}
        }
        
        @media (max-width:480px){
            .hero-content{max-width:95%}
            .metadata{gap:8px}
            .year,.duration,.quality,.rating{padding:4px 8px;font-size:11px}
            .similar-grid{grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px}
            .similar-card-title{font-size:11px}
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>
    
    <div class="hero">
        <div class="hero-bg"></div>
        <div class="hero-overlay"></div>
        <div class="hero-content">
            <h1 class="movie-title"><?= htmlspecialchars($movie_title) ?></h1>
            
            <div class="metadata">
                <?php if($tmdb_data && !empty($tmdb_data['vote_average'])): ?>
                    <span class="match-score"><?= round($tmdb_data['vote_average'] * 10) ?>% match</span>
                    <span class="rating">★ <?= number_format($tmdb_data['vote_average'], 1) ?></span>
                <?php endif; ?>
                <?php if(!empty($movie['year'])): ?>
                    <span class="year"><?= htmlspecialchars($movie['year']) ?></span>
                <?php endif; ?>
                <?php if(!empty($movie['duration'])): ?>
                    <span class="duration"><?= htmlspecialchars($movie['duration']) ?></span>
                <?php endif; ?>
                <span class="quality">HD</span>
            </div>
            
            <div class="synopsis">
                <?= htmlspecialchars($tmdb_data['overview'] ?? $movie['plot'] ?? 'Disfruta de esta increíble película con la mejor calidad.') ?>
            </div>
            
            <?php if($tmdb_data && !empty($tmdb_data['genres'])): ?>
            <div class="genres">
                <?php foreach($tmdb_data['genres'] as $i => $genre): ?>
                    <span class="genre"><?= htmlspecialchars($genre['name']) ?><?= $i < count($tmdb_data['genres']) - 1 ? ' • ' : '' ?></span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <a href="player.php?id=<?= urlencode($movie_id) ?>&slug=movie&ext=<?= htmlspecialchars($movie_data['container_extension'] ?? 'mp4') ?>" class="play-button">
                <i class="fas fa-play"></i> Reproducir
            </a>
            
            <?php if($tmdb_data && !empty($tmdb_data['credits']['cast'])): ?>
            <div class="cast-section">
                <h3 class="cast-title">Reparto principal</h3>
                <div class="cast-grid">
                    <?php foreach(array_slice($tmdb_data['credits']['cast'], 0, 10) as $actor): ?>
                        <?php if(!empty($actor['profile_path'])): ?>
                        <div class="cast-member">
                            <img class="cast-photo" src="<?= TMDB_IMG_URL ?>w185<?= $actor['profile_path'] ?>" alt="<?= htmlspecialchars($actor['name']) ?>" loading="lazy" onerror="this.style.display='none'">
                            <div class="cast-name"><?= htmlspecialchars($actor['name']) ?></div>
                            <div class="cast-character"><?= htmlspecialchars($actor['character']) ?></div>
                        </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- SECCIÓN DE PELÍCULAS SIMILARES (SOLO AÑADIDO ESTO) -->
    <?php if(!empty($similar_movies)): ?>
    <div class="similar-section">
        <h2 class="similar-title">
            <i class="fas fa-film"></i> Películas similares
        </h2>
        <div class="similar-grid">
            <?php foreach($similar_movies as $similar): ?>
                <?php 
                $similar_title = $similar['title'];
                $similar_year = !empty($similar['release_date']) ? substr($similar['release_date'], 0, 4) : '';
                $similar_poster = !empty($similar['poster_path']) ? TMDB_IMG_URL . 'w500' . $similar['poster_path'] : 'https://via.placeholder.com/300x450/1a252f/E50914?text=' . urlencode(substr($similar_title, 0, 15));
                $similar_rating = $similar['vote_average'] ?? 0;
                ?>
                <div class="similar-card" onclick="window.location.href='https://www.google.com/search?q=<?= urlencode($similar_title) ?>+pelicula+completa'">
                    <div class="similar-card-bg" style="background-image: url('<?= htmlspecialchars($similar_poster) ?>');"></div>
                    <?php if($similar_rating > 0): ?>
                    <div class="similar-rating">★ <?= number_format($similar_rating, 1) ?></div>
                    <?php endif; ?>
                    <div class="similar-card-overlay">
                        <div class="similar-card-title"><?= htmlspecialchars($similar_title) ?></div>
                        <div class="similar-card-year"><?= $similar_year ?: 'Próximamente' ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <script>
        // Animación de entrada para las cards similares
        window.addEventListener('load', function() {
            const cards = document.querySelectorAll('.similar-card');
            cards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(20px)';
                setTimeout(() => {
                    card.style.transition = 'all 0.4s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 50);
            });
        });
    </script>
</body>
</html>