<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php");
    exit();
}
ini_set('display_errors', 1);
error_reporting(E_ALL);

// TMDB API KEY
$tmdb_api_key = '76730f01e24238f420442c266ef2fee9';

// Funções TMDB AJAX
function buscar_tmdb($query, $tipo, $api_key) {
    $url = "https://api.themoviedb.org/3/search/$tipo?api_key=$api_key&language=pt-BR&query=" . urlencode($query);
    $res = file_get_contents($url);
    return json_decode($res, true);
}
function detalhes_tmdb($id, $tipo, $api_key) {
    $url = "https://api.themoviedb.org/3/$tipo/$id?api_key=$api_key&language=pt-BR";
    $res = file_get_contents($url);
    return json_decode($res, true);
}
if (isset($_GET['tmdb_search'])) {
    $tipo = $_GET['tipo'] ?? 'movie';
    $query = $_GET['tmdb_search'] ?? '';
    $resultados = buscar_tmdb($query, $tipo, $tmdb_api_key);
    header('Content-Type: application/json');
    echo json_encode($resultados['results'] ?? []);
    exit;
}
if (isset($_GET['tmdb_id'])) {
    $tipo = $_GET['tipo'] ?? 'movie';
    $id = $_GET['tmdb_id'];
    $detalhes = detalhes_tmdb($id, $tipo, $tmdb_api_key);
    header('Content-Type: application/json');
    echo json_encode($detalhes);
    exit;
}

// Carrega logos e escudos para futebol
$logo_padrao = 'logo/logo.png';
$escudos = [];
foreach (glob('escudos/*.{png,jpg,jpeg}', GLOB_BRACE) as $arq) { $escudos[] = $arq; }
$logos = [];
foreach (glob('logo/*.{png,jpg,jpeg}', GLOB_BRACE) as $arq) { $logos[] = $arq; }
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Painel Unificado - Gerador de Banner</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Roboto', Arial, sans-serif; margin: 0; padding: 0; background: linear-gradient(135deg, #1a1a2e, #16213e, #0f3460); color: #e0e0e0; }
        .container { max-width: 980px; margin: 32px auto; background: rgba(255,255,255,0.09); padding: 32px 24px; border-radius: 14px; box-shadow: 0 0 24px rgba(0,255,242,0.13);}
        h1 { text-align: center; color: #00e5ff; text-shadow: 0 0 12px rgba(0,229,255,0.5); margin-bottom: 10px; font-size: 2.2rem; }
        h2 { color: #00e5ff; text-shadow: 0 0 8px rgba(0,229,255,0.3); margin-top: 38px; margin-bottom: 16px; font-size: 1.2rem; }
        label { display: block; margin: 18px 0 8px; font-weight: bold; color: #b0eaff; font-size: 1rem; }
        input[type="text"], select, input[type="file"], input[type="color"], input[type="number"], textarea {
            width: 100%; padding: 12px 10px; margin-bottom: 8px; border: 1px solid rgba(0,229,255,0.20); border-radius: 5px;
            background: rgba(255,255,255,0.07); color: #fff; font-size: 16px; box-sizing: border-box; transition: border 0.2s, box-shadow 0.2s;
        }
        select, input[type="color"] { background: rgba(255,255,255,0.12); }
        input:focus, select:focus, textarea:focus { outline: none; border-color: #00e5ff; box-shadow: 0 0 10px rgba(0,229,255,0.32);}
        textarea { min-height: 60px; }
        .preview-container { margin: 10px 0 18px 0; display: flex; align-items: center; gap: 16px; }
        .escudo-preview, .logo-preview { max-height: 92px; max-width: 120px; border: 1px solid rgba(0,229,255,0.25); border-radius: 7px; background: rgba(255,255,255,0.11); padding: 6px; box-shadow: 0 2px 8px rgba(0,229,255,0.07);}
        .logo-preview { max-height: 110px; max-width: 200px; }
        .banner-preview { display: block; margin: 0 auto 16px auto; max-width: 320px; border-radius: 10px; box-shadow: 0 0 18px rgba(0,229,255,0.11);}
        button {
            background: linear-gradient(90deg, #00e5ff, #00b09b);
            color: white; padding: 13px 28px; border: none; border-radius: 6px;
            cursor: pointer; font-size: 17px; font-weight: bold; margin-top: 10px;
            box-shadow: 0 2px 10px rgba(0,229,255,0.10); transition: background 0.2s;
        }
        button:hover { background: linear-gradient(90deg, #00b09b, #00e5ff);}
        .section { background: #232949; border-radius: 12px; margin-bottom: 32px; padding: 24px 18px; box-shadow: 0 2px 8px rgba(0,229,255,0.07);}
        .tmdb-search-results { background: #222a44; border-radius: 6px; margin-bottom: 14px; max-height: 220px; overflow-y: auto; }
        .tmdb-item { display: flex; align-items: center; gap: 10px; padding: 8px; border-bottom: 1px solid #333c5c; cursor: pointer;}
        .tmdb-item:last-child { border-bottom: none; }
        .tmdb-item:hover { background: #1a2238; }
        .tmdb-poster { width: 54px; height: 80px; object-fit: cover; border-radius: 4px; background: #111; }
        .preview-img { max-width: 120px; border-radius: 5px; margin: 8px 0;}
        @media (max-width: 700px) {
            .container { padding: 8px; }
            .section { padding: 12px 4px; }
            .preview-container { flex-direction: column; }
        }
    </style>
    <script>
        function buscarTMDB() {
            var termo = document.getElementById('tmdb_query').value;
            var tipo = document.getElementById('tmdb_tipo').value;
            if (termo.length < 2) {
                document.getElementById('tmdb_results').innerHTML = '';
                return;
            }
            fetch(`?tmdb_search=${encodeURIComponent(termo)}&tipo=${tipo}`)
                .then(r=>r.json())
                .then(res=>{
                    var html = '';
                    res.forEach(item=>{
                        var titulo = tipo=='movie' ? item.title : item.name;
                        var data = (tipo=='movie' ? item.release_date : item.first_air_date) || '';
                        var poster = item.poster_path ? 'https://image.tmdb.org/t/p/w92'+item.poster_path : '';
                        html += `<div class="tmdb-item" onclick="selecionarTMDB('${item.id}','${tipo}')">
                            ${poster?`<img src="${poster}" class="tmdb-poster">`:''}
                            <div>
                                <b>${titulo}</b> <small style="color:#ccc;">${data}</small><br>
                                <span style="font-size:13px;color:#aaf;">${item.original_title||item.original_name||''}</span>
                            </div>
                        </div>`;
                    });
                    document.getElementById('tmdb_results').innerHTML = html || '<div style="padding:8px;color:#aaa;">Nenhum resultado...</div>';
                });
        }
        function selecionarTMDB(id, tipo) {
            fetch(`?tmdb_id=${id}&tipo=${tipo}`)
                .then(r=>r.json())
                .then(item=>{
                    document.getElementById('titulo_filme').value = tipo=='movie' ? item.title : item.name;
                    document.getElementById('sinopse').value = item.overview || '';
                    document.getElementById('ano').value = (tipo=='movie' ? item.release_date : item.first_air_date || '').slice(0,4);
                    document.getElementById('genero').value = item.genres && item.genres.length ? item.genres.map(g=>g.name).join(', ') : '';
                    document.getElementById('poster_url').value = item.poster_path ? 'https://image.tmdb.org/t/p/w500'+item.poster_path : '';
                    document.getElementById('backdrop_url').value = item.backdrop_path ? 'https://image.tmdb.org/t/p/w780'+item.backdrop_path : '';
                    document.getElementById('tmdb_id').value = item.id;
                    document.getElementById('tipo').value = tipo;
                    if(item.poster_path){
                        document.getElementById('poster_preview').src = 'https://image.tmdb.org/t/p/w185'+item.poster_path;
                        document.getElementById('poster_preview').style.display = 'block';
                    } else {
                        document.getElementById('poster_preview').style.display = 'none';
                    }
                    document.getElementById('tmdb_results').innerHTML = '';
                });
        }
        function previewUpload(inputId, imgId) {
            var input = document.getElementById(inputId);
            var img = document.getElementById(imgId);
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) { img.src = e.target.result; img.style.display = 'inline'; };
                reader.readAsDataURL(input.files[0]);
            }
        }
        function trocarLogo() {
            var sel = document.getElementById('logo_existente');
            var img = document.getElementById('img_logo_topo');
            if(sel.value) img.src = sel.value + '?t=' + Date.now();
        }
        function previewEscudo(selectId, imgId) {
            var select = document.getElementById(selectId);
            var img = document.getElementById(imgId);
            if (select.value) { img.src = select.value; img.style.display = 'inline'; } else { img.src = ''; img.style.display = 'none'; }
        }
        function filterEscudos(inputId, selectId, timeInputId) {
            var input = document.getElementById(inputId);
            var select = document.getElementById(selectId);
            var timeInput = document.getElementById(timeInputId);
            var filter = input.value.toLowerCase();
            var options = select.getElementsByTagName('option');
            var firstMatch = null;
            for (var i = 0; i < options.length; i++) {
                var txtValue = options[i].textContent.toLowerCase();
                if (txtValue.includes(filter) || options[i].value === '') {
                    options[i].style.display = '';
                    if (options[i].value !== '' && firstMatch === null && txtValue.includes(filter)) { firstMatch = options[i]; }
                } else { options[i].style.display = 'none'; }
            }
            if (firstMatch) {
                select.value = firstMatch.value;
                timeInput.value = firstMatch.textContent.split('.')[0].toUpperCase();
                previewEscudo(selectId, 'img_' + selectId.split('_')[1]);
            }
        }
        function clearSearch(inputId, selectId, timeInputId, defaultTime) {
            var input = document.getElementById(inputId);
            var select = document.getElementById(selectId);
            var timeInput = document.getElementById(timeInputId);
            input.value = '';
            select.value = '';
            timeInput.value = defaultTime;
            previewEscudo(selectId, 'img_' + selectId.split('_')[1]);
            var options = select.getElementsByTagName('option');
            for (var i = 0; i < options.length; i++) { options[i].style.display = ''; }
        }
    </script>
</head>
<body>
    <div class="container">
        <h1>Painel Unificado - Gerador de Banner</h1>

        <!-- GERADOR DE BANNER DE FUTEBOL -->
        <div class="section">
            <h2><i class="fas fa-futbol"></i> Gerador de Banner de Futebol</h2>
            <form action="gerar_banner.php" method="POST" enctype="multipart/form-data">
                <label>Selecionar Logo Existente</label>
                <select name="logo_existente" id="logo_existente" onchange="trocarLogo()">
                    <?php foreach ($logos as $logo) { ?>
                        <option value="<?= htmlspecialchars($logo) ?>"<?= $logo == $logo_padrao ? ' selected' : '' ?>><?= basename($logo) ?></option>
                    <?php } ?>
                </select>
                <div class="preview-container">
                    <img id="img_logo_topo" class="logo-preview" src="<?= $logo_padrao ?>?t=<?= time() ?>" alt="Prévia da logo" style="display:inline;">
                </div>
                <label>Alterar Logo (PNG, JPG, JPEG)</label>
                <input type="file" id="upload_logo_input" name="upload_logo" accept="image/png, image/jpeg, image/jpg" onchange="previewUpload('upload_logo_input', 'img_logo_topo')">
                <label>Imagem de Fundo do Banner (opcional)</label>
                <input type="file" name="fundo_personalizado" accept="image/png, image/jpeg, image/jpg">
                <label>Fonte do Título</label>
                <select name="fonte_titulo">
                    <option value="BebasNeue-Regular.ttf">Bebas Neue</option>
                    <option value="Oswald-Regular.ttf">Oswald</option>
                    <option value="Roboto-Bold.ttf">Roboto Bold</option>
                    <option value="Montserrat-Bold.ttf">Montserrat Bold</option>
                </select>
                <label>Fonte dos Times</label>
                <select name="fonte_times">
                    <option value="BebasNeue-Regular.ttf">Bebas Neue</option>
                    <option value="Oswald-Regular.ttf">Oswald</option>
                    <option value="Roboto-Bold.ttf">Roboto Bold</option>
                    <option value="Montserrat-Bold.ttf">Montserrat Bold</option>
                </select>
                <label>Fonte das Infos</label>
                <select name="fonte_info">
                    <option value="Roboto-Regular.ttf">Roboto</option>
                    <option value="Montserrat-Regular.ttf">Montserrat</option>
                    <option value="Oswald-Regular.ttf">Oswald</option>
                </select>
                <label>Data do Jogo</label>
                <input type="text" name="data" value="01 JAN 2025" required>
                <label>Horário</label>
                <input type="text" name="horario" value="19:00" required>
                <label>Título do Evento</label>
                <input type="text" name="titulo" value="SUPER JOGO 2025" required>
                <label>Subtítulo (opcional)</label>
                <input type="text" name="subtitulo" value="">
                <label>Competição ou Liga</label>
                <input type="text" name="liga" value="CAMPEONATO BRASILEIRO" required>
                <label>Time 1</label>
                <input type="text" name="time1" id="time1" value="TIME CASA" required>
                <label>Pesquisar Escudo Time 1</label>
                <div style="display:flex;gap:8px;">
                    <input type="text" id="search_time1" style="flex:1;" placeholder="Digite o nome do time..." onkeyup="filterEscudos('search_time1', 'escudo_time1', 'time1')">
                    <button type="button" onclick="clearSearch('search_time1', 'escudo_time1', 'time1', 'TIME CASA')">Limpar</button>
                </div>
                <label>Escudo Time 1</label>
                <select name="escudo_time1" id="escudo_time1" onchange="previewEscudo('escudo_time1','img_escudo1')">
                    <option value="">Sem escudo</option>
                    <?php foreach ($escudos as $esc) { ?>
                        <option value="<?= htmlspecialchars($esc) ?>"><?= basename($esc) ?></option>
                    <?php } ?>
                </select>
                <div class="preview-container">
                    <img id="img_escudo1" class="escudo-preview" src="" alt="" style="display: none;">
                </div>
                <label>Time 2</label>
                <input type="text" name="time2" id="time2" value="TIME VISITANTE" required>
                <label>Pesquisar Escudo Time 2</label>
                <div style="display:flex;gap:8px;">
                    <input type="text" id="search_time2" style="flex:1;" placeholder="Digite o nome do time..." onkeyup="filterEscudos('search_time2', 'escudo_time2', 'time2')">
                    <button type="button" onclick="clearSearch('search_time2', 'escudo_time2', 'time2', 'TIME VISITANTE')">Limpar</button>
                </div>
                <label>Escudo Time 2</label>
                <select name="escudo_time2" id="escudo_time2" onchange="previewEscudo('escudo_time2','img_escudo2')">
                    <option value="">Sem escudo</option>
                    <?php foreach ($escudos as $esc) { ?>
                        <option value="<?= htmlspecialchars($esc) ?>"><?= basename($esc) ?></option>
                    <?php } ?>
                </select>
                <div class="preview-container">
                    <img id="img_escudo2" class="escudo-preview" src="" alt="" style="display: none;">
                </div>
                <label>Texto de Confronto (ex.: VS, X)</label>
                <input type="text" name="confronto" value="VS" required>
                <label>Canal/Streaming</label>
                <input type="text" name="canal" value="TV ESPORTE 2025" required>
                <label>Qualidade do Streaming</label>
                <input type="text" name="qualidade" value="4K ULTRA HD" required>
                <label>Plano de Assinatura</label>
                <input type="text" name="plano" value="PLANO PREMIUM IPTV" required>
                <label>Mensagem Extra (opcional)</label>
                <input type="text" name="mensagem_extra" value="">
                <button type="submit" style="margin-top:20px;">Gerar Banner Futebol</button>
            </form>
            <div class="banners">
                <h2>Prévia do Banner de Futebol</h2>
                <img src="img/banner_futebol.png?t=<?= time() ?>" alt="Prévia do Banner" class="banner-preview" id="banner_preview">
                <div style="margin-top:24px;">
                    <?php
                    $banner_file = 'img/banner_futebol.png';
                    if (file_exists($banner_file)) {
                        echo '<a href="' . $banner_file . '" download="banner_futebol.png" class="download-btn">Baixar Banner</a>';
                    } else {
                        echo '<span style="color:#b0eaff;">Nenhum banner gerado ainda.</span>';
                    }
                    ?>
                </div>
            </div>
        </div>

        <!-- GERADOR DE BANNER DE FILME/SÉRIE -->
        <div class="section">
            <h2><i class="fas fa-film"></i> Gerador de Banner de Filme/Série (Busca TMDB)</h2>
            <form action="gerar_banner.php" method="POST" enctype="multipart/form-data">
                <label>Pesquisar no TMDB:</label>
                <div style="display:flex;gap:8px;">
                    <select id="tmdb_tipo" onchange="buscarTMDB()">
                        <option value="movie">Filme</option>
                        <option value="tv">Série</option>
                    </select>
                    <input type="text" id="tmdb_query" oninput="buscarTMDB()" placeholder="Digite o nome do filme ou série...">
                </div>
                <div id="tmdb_results" class="tmdb-search-results"></div>
                <input type="hidden" name="tmdb_id" id="tmdb_id">
                <input type="hidden" name="tipo" id="tipo" value="movie">
                <label>Título</label>
                <input type="text" name="titulo" id="titulo_filme" required>
                <label>Sinopse</label>
                <textarea name="sinopse" id="sinopse"></textarea>
                <label>Ano</label>
                <input type="text" name="ano" id="ano">
                <label>Gênero</label>
                <input type="text" name="genero" id="genero">
                <label>Poster URL</label>
                <input type="text" name="poster_url" id="poster_url">
                <img id="poster_preview" class="preview-img" style="display:none;">
                <label>Backdrop URL</label>
                <input type="text" name="backdrop_url" id="backdrop_url">
                <label>Upload de Poster (opcional)</label>
                <input type="file" name="poster_upload" accept="image/png,image/jpeg">
                <button type="submit" style="margin-top:20px;">Gerar Banner Filme/Série</button>
            </form>
            <div class="banners">
                <h2>Prévia do Banner de Filme/Série</h2>
                <img src="img/banner_filme.png?t=<?= time() ?>" alt="Prévia do Banner" class="banner-preview" id="banner_preview_filme">
                <div style="margin-top:24px;">
                    <?php
                    $banner_file = 'img/banner_filme.png';
                    if (file_exists($banner_file)) {
                        echo '<a href="' . $banner_file . '" download="banner_filme.png" class="download-btn">Baixar Banner</a>';
                    } else {
                        echo '<span style="color:#b0eaff;">Nenhum banner gerado ainda.</span>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
