<?php
header('Content-Type: text/html; charset=utf-8');

// Leer el estado de la marquesina y el texto desde config.txt
$configFile = 'config.txt';
if (file_exists($configFile)) {
    $configContent = file_get_contents($configFile);
    list($marquesinaStatus, $marquesinaTexto) = explode("\n", $configContent);
    $marquesinaStatus = trim($marquesinaStatus);
    $marquesinaTexto = trim($marquesinaTexto);
} else {
    $marquesinaStatus = 'activo';
    $marquesinaTexto = 'Este es el texto en movimiento dentro de la marquesina.';
}

// ===== CONFIGURAÇÃO DIRETA DA API KEY =====
$api_key = "0776ece87c6c30b33226dd307bc655e1";  

if (empty($api_key)) {
    die("⚠️ API KEY TMDB está vacía. Defina en el código PHP.");
}

// Configuración de la API de TMDB
$base_url = 'https://api.themoviedb.org/3';
$language = 'es-MX';

// Obtener películas populares
$movie_url = $base_url . '/movie/popular?api_key=' . $api_key . '&language=' . $language;
$movie_response = @file_get_contents($movie_url);

if ($movie_response === FALSE) {
    die('Error al conectar con la API de TMDB o clave inválida.');
}

$movies = json_decode($movie_response, true)['results'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Anuncios Dinámicos TMDB</title>
<style>
body {
    margin: 0;
    padding: 0;
    font-family: 'Arial', sans-serif;
    background-color: #000;
    color: white;
    overflow: hidden;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.background {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background-size: cover;
    background-position: center;
    filter: brightness(0.5);
    z-index: -1;
}

.marquee-container {
    position: fixed;
    bottom: 0;
    width: 100%;
    background: rgba(0,0,0,0.7);
    color: #fff;
    font-size: 1.2em;
    padding: 10px 0;
    white-space: nowrap;
    overflow: hidden;
    z-index: 10;
}

.marquee-text {
    display: inline-block;
    padding-left: 100%;
    animation: marquee 15s linear infinite;
}

@keyframes marquee {
    0% { transform: translateX(0%); }
    100% { transform: translateX(-100%); }
}

/* Layout TMDB */
.main-layout {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 30px;
    width: 90%;
    max-width: 1000px;
    transform: translateY(-40px);
}

.cast-side {
    display: flex;
    flex-direction: column;
    gap: 15px;
    align-items: center;
    justify-content: center;
}
.cast-member {
    text-align: center;
}
.cast-member img {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    border: 2px solid white;
    object-fit: cover;
}
.cast-member span {
    display: block;
    margin-top: 5px;
    font-size: 0.75em;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.container {
    width: 60%;
    background-color: rgba(0,0,0,0.6);
    padding: 20px;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.7);
    text-align: center;
}
h1 {
    font-size: 1.6em;
    margin-bottom: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.rating span {
    font-size: 1.2em;
    color: gold;
}
p {
    font-size: 0.9em;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
@media (max-width: 767px) {
    .main-layout {
        flex-direction: row;
        gap: 10px;
    }
    .container {
        width: 70%;
        padding: 15px;
    }
    .cast-member img {
        width: 55px;
        height: 55px;
    }
    h1 { font-size: 1.2em; }
    p { font-size: 0.8em; -webkit-line-clamp: 2; }
}
</style>
</head>
<body>
<div id="background" class="background"></div>

<div class="main-layout">
    <div class="cast-side" id="cast-left"></div>

    <div class="container">
        <h1 id="title">Cargando...</h1>
        <div id="rating" class="rating"></div>
        <p id="overview">Por favor, espera mientras cargamos el anuncio.</p>
    </div>

    <div class="cast-side" id="cast-right"></div>
</div>

<?php if($marquesinaStatus === 'activo'): ?>
<div class="marquee-container">
    <div class="marquee-text"><?= htmlspecialchars($marquesinaTexto) ?></div>
</div>
<?php endif; ?>

<script>
const movies = <?php echo json_encode($movies); ?>;
const apiKey = "<?php echo $api_key; ?>";
const baseUrl = "https://api.themoviedb.org/3";
let currentIndex = 0;

async function fetchCast(movieId) {
    const res = await fetch(`${baseUrl}/movie/${movieId}/credits?api_key=${apiKey}`);
    const data = await res.json();
    return data.cast.slice(0, 4);
}

async function updateAd() {
    const movie = movies[currentIndex];
    const background = document.getElementById('background');
    const title = document.getElementById('title');
    const overview = document.getElementById('overview');
    const rating = document.getElementById('rating');
    const castLeft = document.getElementById('cast-left');
    const castRight = document.getElementById('cast-right');

    const bgImageUrl = `https://image.tmdb.org/t/p/original${movie.backdrop_path}`;
    background.style.backgroundImage = `url('${bgImageUrl}')`;

    title.textContent = movie.title;
    overview.textContent = movie.overview;

    const starRating = Math.round(movie.vote_average / 2);
    rating.innerHTML = '<span>' + '★'.repeat(starRating) + '☆'.repeat(5 - starRating) + '</span>';

    const castData = await fetchCast(movie.id);
    castLeft.innerHTML = '';
    castRight.innerHTML = '';

    castData.forEach((member, i) => {
        const imgUrl = member.profile_path
            ? `https://image.tmdb.org/t/p/w500${member.profile_path}`
            : 'https://via.placeholder.com/70';
        const div = document.createElement('div');
        div.classList.add('cast-member');
        div.innerHTML = `<img src="${imgUrl}" alt="${member.name}"><span>${member.name}</span>`;
        if (i < 2) castLeft.appendChild(div);
        else castRight.appendChild(div);
    });

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

setInterval(updateAd, 10000);
updateAd();
</script>
</body>
</html>