<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
  header("Location: login.php");
  exit();
}
$config_file = __DIR__ . '/config.json';
$config = file_exists($config_file) ? json_decode(file_get_contents($config_file), true) : [];

// --- Top 5 Filmes e Séries (direto do TMDB, sempre atualizados e confiáveis) ---
$apiKey = '855ee921df930db2f2a9669eda268032';
$language = 'pt-BR';
$region = 'BR';

// Filmes
$url_filmes = "https://api.themoviedb.org/3/movie/popular?api_key=$apiKey&language=$language&region=$region&page=1";
$ch_filmes = curl_init($url_filmes);
curl_setopt($ch_filmes, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_filmes, CURLOPT_TIMEOUT, 10);
$response_filmes = curl_exec($ch_filmes);
curl_close($ch_filmes);
$data_filmes = json_decode($response_filmes, true);
$top5_filmes = array_slice($data_filmes['results'] ?? [], 0, 5);

// Séries
$url_series = "https://api.themoviedb.org/3/tv/popular?api_key=$apiKey&language=$language&region=$region&page=1";
$ch_series = curl_init($url_series);
curl_setopt($ch_series, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_series, CURLOPT_TIMEOUT, 10);
$response_series = curl_exec($ch_series);
curl_close($ch_series);
$data_series = json_decode($response_series, true);
$top5_series = array_slice($data_series['results'] ?? [], 0, 5);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Gerador de Banner 2.1 - Moderno</title>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:700,400&display=swap" rel="stylesheet">
  <style>
    :root {
      --filmes: #e50914;
      --futebol: #04AA6D;
      --sair: #ff4757;
      --bg-dark: #121212;
      --neon: <?= $config['main_border_color'] ?? '#39FF14' ?>;
    }
    body {
      font-family: 'Montserrat', 'Segoe UI', Arial, sans-serif;
      background: linear-gradient(120deg, #181c1f 0%, #222d34 100%);
      background-size: 200% 200%;
      animation: gradientMove 8s ease-in-out infinite;
      min-height: 100vh;
      margin: 0;
    }
    @keyframes gradientMove {
      0% {background-position: 0% 50%;}
      50% {background-position: 100% 50%;}
      100% {background-position: 0% 50%;}
    }
    * { box-sizing: border-box; }
    .nav-container {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background: rgba(18, 18, 18, 0.85);
      padding: 10px 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
      backdrop-filter: blur(8px);
    }
    .nav-links {
      display: flex;
      gap: 16px;
      width: 100%;
      justify-content: center;
    }
    .nav-link {
      color: white;
      text-decoration: none;
      padding: 10px 24px 10px 44px;
      border-radius: 50px;
      display: flex;
      align-items: center;
      position: relative;
      transition: all 0.22s cubic-bezier(.4,0,.2,1);
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0,0,0,0.10);
      font-size: 1rem;
      gap: 10px;
      min-width: 170px;
      background: linear-gradient(90deg, var(--neon) 0%, #fff700 100%);
      color: #111;
      border: none;
      cursor: pointer;
      text-align: center;
      letter-spacing: 0.5px;
    }
    .banners-futebol { background: var(--futebol); color: #fff; }
    .sair { background: var(--sair); color: #fff; }
    .nav-link .icon {
      position: absolute;
      left: 18px;
      top: 50%;
      transform: translateY(-50%);
      width: 22px;
      height: 22px;
      opacity: 0.9;
      pointer-events: none;
      fill: #fff;
    }
    .nav-link:hover {
      transform: translateY(-3px) scale(1.04);
      box-shadow: 0 4px 16px var(--neon)66;
      filter: brightness(1.08);
    }
    @media (max-width: 768px) {
      .nav-container { flex-direction: column; padding: 10px 0 0 0; }
      .nav-links { flex-wrap: wrap; gap: 10px; }
      .nav-link { padding: 10px 12px 10px 44px; font-size: 0.97rem; min-width: 140px; }
    }
    .main-box {
      max-width: 500px;
      margin: 100px auto 28px auto;
      padding: 34px 28px 28px 28px;
      background: rgba(18, 18, 18, 0.55);
      border-radius: 18px;
      text-align: center;
      box-shadow: 0 0 32px var(--neon)77;
      border: 1.5px solid var(--neon);
      backdrop-filter: blur(18px) saturate(140%);
    }
    .main-box h1 {
      color: var(--neon);
      font-family: 'Montserrat', 'Segoe UI', sans-serif;
      letter-spacing: 1px;
      margin-bottom: 18px;
      font-size: 2.1rem;
      text-shadow: 0 2px 8px var(--neon)44;
    }
    .main-box h2 {
      color: var(--neon);
      font-size: 1.2rem;
      margin: 18px 0 10px 0;
      letter-spacing: 0.5px;
      text-shadow: 0 2px 8px var(--neon)22;
    }
    .input-icon-group {
      position: relative;
      width: 100%;
      margin-bottom: 20px;
    }
    .input-icon-group svg {
      position: absolute;
      left: 14px;
      top: 50%;
      transform: translateY(-50%);
      width: 22px;
      height: 22px;
      fill: var(--neon);
      opacity: 0.85;
      pointer-events: none;
    }
    input[name="query"] {
      padding: 13px 12px 13px 48px;
      width: 100%;
      font-size: 16px;
      border: none;
      border-radius: 6px;
      background: #1a3d1a;
      color: #ffffff;
      transition: box-shadow 0.25s;
      box-shadow: 0 1px 4px rgba(0,0,0,0.10);
      outline: none;
    }
    input[name="query"]:focus {
      box-shadow: 0 0 0 2px var(--neon);
    }
    button[type="submit"] {
      padding: 13px 20px 13px 44px;
      font-size: 16px;
      background: linear-gradient(90deg, var(--neon) 60%, #fff700 100%);
      color: #111;
      border: none;
      border-radius: 30px;
      cursor: pointer;
      width: 100%;
      box-shadow: 0 2px 8px var(--neon)33;
      font-weight: bold;
      letter-spacing: 1px;
      transition: filter 0.2s, box-shadow 0.2s;
      position: relative;
      text-align: center;
      display: inline-block;
      margin-top: 4px;
    }
    button[type="submit"] .icon {
      position: absolute;
      left: 18px;
      top: 50%;
      transform: translateY(-50%);
      width: 20px;
      height: 20px;
      fill: #222;
      opacity: 0.85;
      pointer-events: none;
    }
    button[type="submit"]:hover {
      filter: brightness(1.1) drop-shadow(0 0 8px var(--neon));
      box-shadow: 0 4px 16px var(--neon)55;
      transform: scale(1.03);
    }
    #results {
      max-width: 420px;
      margin: 0 auto 50px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .result-card {
      background: rgba(18, 18, 18, 0.65);
      border-radius: 13px;
      padding: 10px 10px 18px 10px;
      margin-bottom: 24px;
      text-align: center;
      width: 100%;
      box-shadow: 0 0 14px var(--neon)44;
      border: 1.5px solid var(--neon);
      transition: transform 0.3s, box-shadow 0.3s;
      position: relative;
      backdrop-filter: blur(6px);
      cursor: pointer;
      min-width: 140px;
      max-width: 220px;
      margin-left: auto;
      margin-right: auto;
    }
    .result-card:hover {
      transform: scale(1.045) rotate(-1deg);
      box-shadow: 0 8px 32px var(--neon)99, 0 2px 8px #0008;
    }
    .result-card img {
      width: 100%;
      max-width: 160px;
      border-radius: 9px;
      margin: 0 auto;
      box-shadow: 0 2px 16px #0007;
      transition: box-shadow 0.2s;
      display: block;
    }
    .result-card p {
      margin-top: 10px;
      font-size: 1.05rem;
      color: var(--neon);
      font-weight: 600;
      letter-spacing: 0.5px;
      text-shadow: 0 2px 8px var(--neon)22;
    }
    .result-card form {
      margin-top: 10px;
    }
    .result-card form button {
      background: linear-gradient(90deg, var(--neon) 60%, #fff700 100%);
      color: #111;
      padding: 10px 22px 10px 38px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: filter 0.2s, box-shadow 0.2s;
      font-weight: bold;
      position: relative;
      text-align: left;
      display: inline-block;
      box-shadow: 0 2px 8px var(--neon)33;
      margin-top: 0;
    }
    .result-card form button .icon {
      position: absolute;
      left: 13px;
      top: 50%;
      transform: translateY(-50%);
      width: 18px;
      height: 18px;
      fill: #222;
      opacity: 0.85;
      pointer-events: none;
    }
    .result-card form button:hover {
      filter: brightness(1.13) drop-shadow(0 0 8px var(--neon));
      box-shadow: 0 4px 16px var(--neon)55;
    }
    #loading {
      text-align:center;
      padding: 20px;
      color: var(--neon);
      display:none;
    }
    .loader {
      margin: 0 auto 12px auto;
      border: 4px solid #2a2a2a;
      border-top: 4px solid var(--neon);
      border-radius: 50%;
      width: 36px;
      height: 36px;
      animation: spin 1s linear infinite;
      display: inline-block;
    }
    @keyframes spin { 100% { transform: rotate(360deg); } }
    .error-message {
      animation: fadeIn 0.6s;
      color: #ffdddd;
      text-align: center;
      margin-top: 20px;
    }
    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    footer {
      color: #aaa;
      text-align: center;
      margin: 40px 0 10px 0;
      font-size: 0.95rem;
      letter-spacing: 0.5px;
    }
    /* Modal */
    #modal-bg {
      display: none;
      position: fixed;
      top: 0; left: 0; width: 100vw; height: 100vh;
      background: #000a;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }
    #modal {
      background: rgba(32,32,32,0.98);
      padding: 32px 24px;
      border-radius: 18px;
      max-width: 95vw;
      max-height: 95vh;
      overflow: auto;
      position: relative;
      box-shadow: 0 6px 44px var(--neon)77;
      border: 2px solid var(--neon);
      display: flex;
      flex-direction: column;
      align-items: center;
      animation: fadeIn 0.3s;
    }
    #modal img {
      max-width: 320px;
      border-radius: 12px;
      margin-bottom: 18px;
      box-shadow: 0 2px 16px #0008;
    }
    #modal-close {
      position: absolute;
      top: 10px;
      right: 20px;
      font-size: 2.3rem;
      color: var(--neon);
      cursor: pointer;
      background: none;
      border: none;
      z-index: 2;
      transition: color 0.2s;
    }
    #modal-close:hover { color: #fff700; }
    .top5-list {
      display: flex;
      flex-wrap: wrap;
      gap: 18px;
      justify-content: center;
      margin-bottom: 10px;
    }
    .top5-list .result-card {
      width: 160px;
      min-width: 140px;
      max-width: 180px;
      margin-bottom: 0;
      margin-left: 0;
      margin-right: 0;
    }
    @media (max-width: 600px) {
      .main-box { padding: 18px 8px; }
      #modal img { max-width: 95vw; }
      .top5-list { flex-direction: column; gap: 10px; }
      .top5-list .result-card { width: 98%; max-width: 95vw; }
    }
  </style>
</head>
<body>
  <nav class="nav-container">
    <div class="nav-links">
      <a href="futebol/admin.php" class="nav-link banners-futebol">
        <svg class="icon" viewBox="0 0 24 24"><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm3.9 3.5c1.2.7 2.2 1.7 2.9 2.9l-2.3.9-1.2-2.1 0-1.7zm-7.8 0l.6 1.7-1.2 2.1-2.3-.9c.7-1.2 1.7-2.2 2.9-2.9zm-3.5 7.8c0-1.1.2-2.1.5-3.1l2.4 1 0 2.5-2.9-.4zm3.5 7.8c-1.2-.7-2.2-1.7-2.9-2.9l2.3-.9 1.2 2.1 0 1.7zm7.8 0l-.6-1.7 1.2-2.1 2.3.9c-.7 1.2-1.7 2.2-2.9 2.9zm3.5-7.8c0 1.1-.2 2.1-.5 3.1l-2.4-1 0-2.5 2.9.4zm-7.8-7.8c1.1-.3 2.1-.5 3.1-.5s2.1.2 3.1.5l-1 2.4-2.5 0 .4-2.9zm0 15.6c-1.1.3-2.1.5-3.1.5s-2.1-.2-3.1-.5l1-2.4 2.5 0-.4 2.9zm7.8-7.8c-1.1.3-2.1.5-3.1.5s-2.1-.2-3.1-.5l-1-2.4-2.5 0 .4 2.9zm-7.8 7.8c1.1.3 2.1.5 3.1.5s2.1-.2 3.1-.5l-1-2.4-2.5 0 .4 2.9z"/></svg>
        Banners Futebol
      </a>
      <a href="logout.php" class="nav-link sair">
        <svg class="icon" viewBox="0 0 24 24"><path d="M16 13v-2H7V8l-5 4 5 4v-3zM20 3h-8v2h8v14h-8v2h8c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/></svg>
        <a href="trocar_usuario.php" class="nav-link">
    <svg class="icon" viewBox="0 0 24 24"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>
    Trocar Usuário e Senha
</a>
        Sair
      </a>
    </div>
  </nav>
  <div class="main-box">
    <h1>Buscar Filme ou Série</h1>
    <form method="GET" id="busca-form">
      <div class="input-icon-group">
        <svg viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C8.01 14 6 11.99 6 9.5S8.01 5 10.5 5 15 7.01 15 9.5 12.99 14 10.5 14z"/></svg>
        <input type="text" name="query" placeholder="Digite o nome do filme ou série" value="<?= isset($_GET['query']) ? htmlspecialchars($_GET['query']) : '' ?>" required maxlength="60" autocomplete="off">
      </div>
      <button type="submit">
        <svg class="icon" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C8.01 14 6 11.99 6 9.5S8.01 5 10.5 5 15 7.01 15 9.5 12.99 14 10.5 14z"/></svg>
        Buscar
      </button>
    </form>
  </div>

  <!-- RESULTADOS DA BUSCA ANTES DOS TOP 5 -->
  <div id="loading">
    <div class="loader"></div>
    <span>Carregando...</span>
  </div>
  <div id="results">
    <?php
    if (isset($_GET['query'])) {
      $query = trim($_GET['query']);
      if (mb_strlen($query) > 60) {
        echo "<p class='error-message'>Busca muito longa. Tente um termo mais curto.</p>";
        exit;
      }
      $query = urlencode($query);
      $url = "https://api.themoviedb.org/3/search/multi?api_key=$apiKey&language=$language&query=$query";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 10);
      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      $curlError = curl_error($ch);
      curl_close($ch);
      echo "<script>document.getElementById('loading').style.display='none';</script>";
      if ($response === false || !empty($curlError)) {
        echo "<p class='error-message'>Erro ao acessar a API: $curlError</p>";
        exit;
      }
      if ($httpCode !== 200) {
        $errorData = json_decode($response, true);
        $errorMessage = $errorData['status_message'] ?? 'Erro desconhecido na API (código HTTP: ' . $httpCode . ')';
        echo "<p class='error-message'>Erro na API: $errorMessage</p>";
        exit;
      }
      $data = json_decode($response, true);
      if (json_last_error() !== JSON_ERROR_NONE) {
        echo "<p class='error-message'>Erro ao processar a resposta da API: " . json_last_error_msg() . "</p>";
        exit;
      }
      if (!empty($data['results'])) {
        foreach ($data['results'] as $item) {
          if (!empty($item['poster_path'])) {
            $posterUrl = "https://image.tmdb.org/t/p/w342" . $item['poster_path'];
            $titulo = htmlspecialchars($item['title'] ?? $item['name']);
            $id = intval($item['id']);
            $mediaType = $item['media_type'];
            $tipo = 'filme';
            if ($mediaType === 'tv') {
              $nome = strtolower($item['name']);
              if (strpos($nome, 'naruto') !== false || strpos($nome, 'bleach') !== false || strpos($nome, 'one piece') !== false || strpos($nome, 'attack on titan') !== false) {
                $tipo = 'anime';
              } elseif (strpos($nome, 'novela') !== false || strpos($nome, 'amor') !== false || strpos($nome, 'família') !== false) {
                $tipo = 'novela';
              } else {
                $tipo = 'serie';
              }
            } elseif ($mediaType === 'movie') {
              $tipo = 'filme';
            }
            echo "<div class='result-card' data-titulo=\"$titulo\" data-poster=\"$posterUrl\">
                          <img src='$posterUrl' alt='$titulo'>
                          <p>$titulo</p>
                          <form action='gerar_banner.php' method='GET'>
                              <input type='hidden' name='id' value='$id'>
                              <input type='hidden' name='tipo' value='$tipo'>
                              <input type='hidden' name='layout' value='vertical'>
                              <button type='submit'>
                                <svg class='icon' viewBox='0 0 24 24'><path d='M5 13l4 4L19 7'/></svg>
                                Usar esta capa
                              </button>
                          </form>
                        </div>";
          }
        }
      } else {
        echo "<p class='error-message'>Nenhum resultado encontrado.</p>";
      }
    }
    ?>
  </div>

  <!-- TOP 5 FILMES E SÉRIES -->
  <div class="main-box" style="margin-top: 20px;">
    <h2>Top 5 Filmes no Brasil</h2>
    <div class="top5-list">
      <?php foreach ($top5_filmes as $filme): ?>
        <?php
          $poster = $filme['poster_path'] ? "https://image.tmdb.org/t/p/w185".$filme['poster_path'] : '';
          $titulo = htmlspecialchars($filme['title']);
          $id = intval($filme['id']);
        ?>
        <div class="result-card" data-titulo="<?= $titulo ?>" data-poster="<?= $poster ?>">
          <?php if ($poster): ?><img src="<?= $poster ?>" alt="<?= $titulo ?>"><?php endif; ?>
          <p><?= $titulo ?></p>
          <form action="gerar_banner.php" method="GET">
            <input type="hidden" name="id" value="<?= $id ?>">
            <input type="hidden" name="tipo" value="filme">
            <input type="hidden" name="layout" value="vertical">
            <button type="submit">
              <svg class="icon" viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>
              Usar esta capa
            </button>
          </form>
        </div>
      <?php endforeach; ?>
    </div>
    <h2 style="margin-top:30px;">Top 5 Séries no Brasil</h2>
    <div class="top5-list">
      <?php foreach ($top5_series as $serie): ?>
        <?php
          $poster = $serie['poster_path'] ? "https://image.tmdb.org/t/p/w185".$serie['poster_path'] : '';
          $titulo = htmlspecialchars($serie['name']);
          $id = intval($serie['id']);
        ?>
        <div class="result-card" data-titulo="<?= $titulo ?>" data-poster="<?= $poster ?>">
          <?php if ($poster): ?><img src="<?= $poster ?>" alt="<?= $titulo ?>"><?php endif; ?>
          <p><?= $titulo ?></p>
          <form action="gerar_banner.php" method="GET">
            <input type="hidden" name="id" value="<?= $id ?>">
            <input type="hidden" name="tipo" value="serie">
            <input type="hidden" name="layout" value="vertical">
            <button type="submit">
              <svg class="icon" viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>
              Usar esta capa
            </button>
          </form>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Modal para preview da capa -->
  <div id="modal-bg">
    <div id="modal">
      <button id="modal-close" title="Fechar">&times;</button>
      <div id="modal-content"></div>
    </div>
  </div>
  <footer>
    © <?=date('Y')?> Gerador de Banner 2.1. Todos os direitos reservados.
  </footer>
  <script>
    document.getElementById('busca-form').addEventListener('submit', function() {
      document.getElementById('loading').style.display = 'block';
    });
    function closeModal() {
      document.getElementById('modal-bg').style.display = 'none';
      document.getElementById('modal-content').innerHTML = '';
    }
    document.getElementById('modal-close').onclick = closeModal;
    document.getElementById('modal-bg').onclick = function(e) {
      if (e.target === this) closeModal();
    };
    document.addEventListener('click', function(e) {
      let card = e.target.closest('.result-card');
      if (card && e.target.tagName === 'IMG') {
        let titulo = card.getAttribute('data-titulo');
        let poster = card.getAttribute('data-poster');
        document.getElementById('modal-content').innerHTML =
          `<img src="${poster}" alt="${titulo}"><h2 style="color:var(--neon); margin:10px 0 0 0; font-size:1.2rem;">${titulo}</h2>`;
        document.getElementById('modal-bg').style.display = 'flex';
      }
    });
  </script>
</body>
</html>
