<?php
session_start();
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}
ob_start();
ini_set('display_errors', 0);

include('includes/header.php');

// Variáveis para feedback
$saved = '';
$error = '';

// SALVAR A IMAGEM NO SERVIDOR
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_backdrop'])) {
    $url = $_POST['backdrop_url'] ?? '';
    $filename = basename($_POST['filename'] ?? '');

    if (!empty($url) && !empty($filename)) {
        $savePath = __DIR__ . "/img/" . $filename . ".jpg";
        $imageData = @file_get_contents($url);
        if ($imageData !== false) {
            file_put_contents($savePath, $imageData);
            file_put_contents(__DIR__ . "/img/bg_config.txt", $filename . ".jpg");
            $saved = $filename;
        } else {
            $error = "Erro ao baixar a imagem da URL.";
        }
    } else {
        $error = "URL ou nome de arquivo inválido.";
    }
}
?>

<style>
/* ======== NAV TABS ======== */
.nav-tabs {
    display: flex;
    border-bottom: 3px solid #007bff;
    margin-bottom: 25px;
    background: #f8f9fa;
    border-radius: 8px 8px 0 0;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
.nav-tabs button {
    flex: 1;
    padding: 14px;
    border: none;
    background: transparent;
    font-weight: 600;
    cursor: pointer;
    transition: all .3s ease;
    color: #555;
    font-size: 1rem;
}
.nav-tabs button:hover {
    background: #e9ecef;
}
.nav-tabs button.active {
    background: #007bff;
    color: #fff;
    border-radius: 6px 6px 0 0;
}
.tab-content {
    display: none;
    animation: fadeIn .4s ease;
}
.tab-content.active {
    display: block;
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* ======== GRID DE CARDS ======== */
.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 25px;
    margin-top: 20px;
}

/* ======== MOVIE CARD ======== */
.movie-card {
    background: #fff;
    border-radius: 14px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    box-shadow: 0 6px 15px rgba(0,0,0,0.15);
    transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.movie-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 25px rgba(0,0,0,0.25);
}
.movie-card img {
    width: 100%;
    height: 180px;
    object-fit: cover;
}
.movie-card h4 {
    padding: 12px;
    font-size: 1rem;
    font-weight: 600;
    color: #333;
    flex-grow: 1;
}

/* ======== BOTÕES ======== */
.buttons-container {
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.generate-btn,
.custom-button {
    padding: 10px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: .9rem;
    font-weight: 600;
    transition: all 0.3s ease;
    color: #fff;
}
.custom-button {
    background: #007bff;
}
.btn-horizontal { background: #17a2b8; }   /* Azul piscina */
.btn-vertical { background: #28a745; }     /* Verde */
.btn-logo { background: #e74a3b; }         /* Vermelho */
.generate-btn:hover,
.custom-button:hover {
    opacity: 0.9;
    transform: scale(1.05);
}
/* ======== LOADING ======== */
#loading-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.6);
    z-index: 9999;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #fff;
    font-size: 1.2rem;
    font-weight: bold;
}

.spinner {
    border: 6px solid rgba(255,255,255,0.3);
    border-top: 6px solid #fff;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}


</style>

<div class="container-fluid">
    <!-- Abas -->
    <div class="nav-tabs">
        <button class="tab-link active" data-tab="backdrops">🎬 Fundo do App</button>
        <button class="tab-link" data-tab="banners">🖼️ Gerar Banners</button>
      <button class="tab-link" onclick="window.location.href='banner.php'">
    🎮 Jogos do Dia
</button>


    </div>



<!-- TAB BACKDROPS -->
<div id="backdrops" class="tab-content active">
    <div class="card">
        <div class="card-header bg-primary text-white">
            <h2>Fundo do App inicial</h2>
        </div>
        <br>
         <!-- Botões de Navegação -->
<div class="button-group text-center mb-4">
    <a href="layouts.php" class="btn btn-primary mx-2 btn-lg">
        <i class="fas fa-image"></i> Trocar tema
    </a>
    <a href="logo.php" class="btn btn-success mx-2 btn-lg">
        <i class="fas fa-film"></i> Trocar logo
    </a>
    <a href="Image.php" class="btn btn-warning mx-2 btn-lg">
        <i class="fas fa-cog"></i> Trocar fundo
    </a>
</div>
        <div class="card-body">
            <?php if ($saved): ?>
                <div class='alert alert-success'>
                    Imagem salva como <strong><?= htmlspecialchars($saved) ?>.jpg</strong> ✅
                </div>
            <?php elseif ($error): ?>
                <div class='alert alert-danger'><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="POST" id="form-backdrop" class="form-wrapper mb-3">
                <label for="searchTerm">Buscar filme ou série:</label>
                <input type="text" name="searchTerm" id="searchTerm" placeholder="Ex: Barbie, Stranger Things..." class="form-control mb-2">
                <input type="submit" value="Buscar" class="btn btn-primary">
            </form>
            <div class="grid-container" id="results-grid"></div>
        </div>
    </div>
</div>

<!-- Estilo Customizado -->
<style>
.button-group .btn {
    transition: transform 0.2s, box-shadow 0.2s;
}
.button-group .btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
</style>

<!-- Font Awesome (ícones) -->
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>


    <!-- TAB BANNERS -->
    <div id="banners" class="tab-content">
        <div class="card">
            <div class="card-header bg-success text-white"><h2>Gerar Banners</h2></div>
            <div class="card-body">
                <form method="POST" id="form-banner" class="form-wrapper">
                    <label for="searchBanner">Buscar filme ou série:</label>
                    <input type="text" name="searchBanner" id="searchBanner" placeholder="Ex: Avatar, The Boys...">
                    <input type="submit" value="Buscar" class="custom-button">
                </form>
                <div class="grid-container" id="banner-grid"></div>
            </div>
        </div>
    </div>
</div>
<div id="games" class="tab-content">
  <div class="card">
    <div class="card-header bg-warning text-dark"><h2>Jogos do Dia</h2></div>
    <div class="card-body">
        <div class="mb-3">
            <a href="?dia=hoje" class="btn btn-primary">Hoje</a>
            <a href="?dia=amanha" class="btn btn-secondary">Amanhã</a>
        </div>
        <div class="grid-container">
            <?php if (!empty($jogos)): ?>
                <?php foreach ($jogos as $jogo): ?>
                    <div class="movie-card">
                        <img src="<?= !empty($jogo['logo']) ? $jogo['logo'] : 'https://via.placeholder.com/400x200?text=Jogo' ?>" alt="<?= htmlspecialchars($jogo['time1'].' x '.$jogo['time2']) ?>">
                        <h4><?= htmlspecialchars($jogo['time1'].' x '.$jogo['time2']) ?></h4>
                        <p><strong>Campeonato:</strong> <?= htmlspecialchars($jogo['campeonato']) ?></p>
                        <p><strong>Hora:</strong> <?= htmlspecialchars($jogo['hora']) ?></p>
                        <div class="buttons-container">
                            <form method="GET" action="?banner=1">
                                <input type="hidden" name="dia" value="<?= $dia ?>">
                                <button type="submit" class="generate-btn btn-horizontal">Banner Horizontal</button>
                            </form>
                            <form method="GET" action="?banner=2">
                                <input type="hidden" name="dia" value="<?= $dia ?>">
                                <button type="submit" class="generate-btn btn-vertical">Banner Vertical</button>
                            </form>
                            <form method="POST" action="">
                                <input type="hidden" name="dia" value="<?= $dia ?>">
                                <input type="hidden" name="generate_with_my_logo" value="1">
                                <button type="submit" class="generate-btn btn-logo">Com Minha Logo</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p>Nenhum jogo encontrado.</p>
            <?php endif; ?>
        </div>
    </div>
  </div>
</div>

<!-- Form oculto -->
<form method="POST" id="hidden-form" style="display:none;">
    <input type="hidden" name="save_backdrop" value="1">
    <input type="hidden" name="backdrop_url" id="form_backdrop_url">
    <input type="hidden" name="filename" id="form_filename">
</form>
<div id="loading-overlay">
    <div class="spinner"></div>
    Processando...
</div>

<script>
const apiKey = "1ab6ba39765d76b62c53391fa840744c";
const gridBackdrop = document.getElementById("results-grid");
const gridBanner = document.getElementById("banner-grid");

// -------- Funções de loading --------
function showLoading() {
    document.getElementById("loading-overlay").style.display = "flex";
}
function hideLoading() {
    document.getElementById("loading-overlay").style.display = "none";
}

// -------- Backdrops --------
async function fetchBackdrops(query = "") {
    try {
        showLoading();
        const endpoint = query
            ? `https://api.themoviedb.org/3/search/multi?api_key=${apiKey}&language=pt-BR&query=${encodeURIComponent(query)}`
            : `https://api.themoviedb.org/3/trending/all/week?api_key=${apiKey}&language=pt-BR`;
        const res = await fetch(endpoint);
        const data = await res.json();
        gridBackdrop.innerHTML = "";

        if (data.results) {
            data.results.forEach(item => {
                const title = item.title || item.name || "Sem título";
                const backdrop = item.backdrop_path ? `https://image.tmdb.org/t/p/original${item.backdrop_path}` : null;
                if (!backdrop) return;
                const card = document.createElement("div");
                card.className = "movie-card";
                card.innerHTML = `
                    <img src="${backdrop}" alt="${title}">
                    <h4>${title}</h4>
                    <button class="custom-button" onclick="saveImage('${backdrop}','${title}')">Salvar</button>`;
                gridBackdrop.appendChild(card);
            });
        }
    } catch (err) {
        console.error("Erro ao buscar backdrops:", err);
    } finally {
        hideLoading();
    }
}
document.getElementById("form-backdrop").addEventListener("submit", e => {
    e.preventDefault();
    fetchBackdrops(document.getElementById("searchTerm").value);
});

// -------- Banners --------
async function fetchBanners(query = "") {
    try {
        showLoading();
        const endpoint = query
            ? `https://api.themoviedb.org/3/search/multi?api_key=${apiKey}&language=pt-BR&query=${encodeURIComponent(query)}`
            : `https://api.themoviedb.org/3/trending/all/week?api_key=${apiKey}&language=pt-BR`;
        const res = await fetch(endpoint);
        const data = await res.json();
        gridBanner.innerHTML = "";

        if (data.results) {
            data.results.forEach(item => {
                const title = item.title || item.name || "Sem título";
                const year = (item.release_date || item.first_air_date || "").slice(0,4);
                const poster = item.poster_path ? `https://image.tmdb.org/t/p/w500${item.poster_path}` : null;
                if (!poster) return;
                const card = document.createElement("div");
                card.className = "movie-card";
                card.innerHTML = `
                    <img src="${poster}" alt="${title}">
                    <h4>${title} (${year})</h4>
                    <div class="buttons-container">
                        <form method="GET" action="gerar_banner.php">
                            <input type="hidden" name="name" value="${title}">
                            <input type="hidden" name="type" value="${item.media_type}">
                            <input type="hidden" name="year" value="${year}">
                            <button type="submit" class="generate-btn btn-horizontal">Banner Horizontal</button>
                        </form>
                       
                    </div>`;
                gridBanner.appendChild(card);
            });
        }
    } catch (err) {
        console.error("Erro ao buscar banners:", err);
    } finally {
        hideLoading();
    }
}
document.getElementById("form-banner").addEventListener("submit", e => {
    e.preventDefault();
    fetchBanners(document.getElementById("searchBanner").value);
});

// -------- Salvar imagem (backdrops) --------
function saveImage(url,title){
    const safe = title.replace(/[^a-zA-Z0-9-_]/g,"_");
    document.getElementById("form_backdrop_url").value = url;
    document.getElementById("form_filename").value = safe;
    showLoading();
    document.getElementById("hidden-form").submit();

    // Esconde loading depois de alguns segundos para evitar loop
    setTimeout(hideLoading, 5000);
}

// Abas
document.querySelectorAll(".tab-link").forEach(btn=>{
    btn.addEventListener("click",()=>{
        document.querySelectorAll(".tab-link").forEach(b=>b.classList.remove("active"));
        document.querySelectorAll(".tab-content").forEach(t=>t.classList.remove("active"));
        btn.classList.add("active");
        document.getElementById(btn.dataset.tab).classList.add("active");
    });
});

// Adicionar loading nos forms de gerar banners
document.addEventListener("submit", function(e){
    if (
        e.target.closest("form[action*='gerar_banner']")
    ) {
        showLoading();
        // também adiciona timeout de segurança
        setTimeout(hideLoading, 5000);
    }
});

// Inicial
fetchBackdrops();
fetchBanners();
</script>

<?php include('includes/footer.php'); ?>
