<?php
session_start();
include 'auth.php'; 

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$db_path = __DIR__ . '/api/db/panaci_futebol_premium.db';
if (!file_exists(__DIR__ . '/api/db')) { @mkdir(__DIR__ . '/api/db', 0755, true); }

try {
    $pdo = new PDO("sqlite:" . $db_path);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS game_settings (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        show_games INTEGER DEFAULT 0,
        bg_url TEXT, vs_url TEXT,
        top_text_color TEXT DEFAULT '#ffffff',
        label_watch_color TEXT DEFAULT '#ffaa00',
        canal_text_color TEXT DEFAULT '#ffffff',
        canal_bg_color TEXT DEFAULT '#0f172a',
        game_top TEXT, game_casa TEXT, game_fora TEXT, game_canal TEXT,
        game_hora TEXT, game_data_top TEXT
    )");
} catch(PDOException $e) { die("Erro: " . $e->getMessage()); }

if (isset($_POST['save_game'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php"); exit();
    }
    $id = (!empty($_POST['game_id'])) ? $_POST['game_id'] : null;
    $show = isset($_POST['show_games']) ? 1 : 0;
    
    try {
        if ($id) {
            $sql = "UPDATE game_settings SET show_games=?, bg_url=?, vs_url=?, top_text_color=?, label_watch_color=?, canal_text_color=?, canal_bg_color=?, game_top=?, game_casa=?, game_fora=?, game_canal=?, game_hora=?, game_data_top=? WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$show, $_POST['bg_url'], "https://i.postimg.cc/sgqbRhcd/vs.png", $_POST['top_text_color'], $_POST['label_watch_color'], $_POST['canal_text_color'], $_POST['canal_bg_color'], $_POST['game_top'], $_POST['game_casa'], $_POST['game_fora'], $_POST['game_canal'], $_POST['game_hora'], $_POST['game_data_top'], $id]);
        } else {
            $sql = "INSERT INTO game_settings (show_games, bg_url, vs_url, top_text_color, label_watch_color, canal_text_color, canal_bg_color, game_top, game_casa, game_fora, game_canal, game_hora, game_data_top) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$show, $_POST['bg_url'], "https://i.postimg.cc/sgqbRhcd/vs.png", $_POST['top_text_color'], $_POST['label_watch_color'], $_POST['canal_text_color'], $_POST['canal_bg_color'], $_POST['game_top'], $_POST['game_casa'], $_POST['game_fora'], $_POST['game_canal'], $_POST['game_hora'], $_POST['game_data_top']]);
        }
        $_SESSION['msg_success'] = "Dados salvos!";
        header("Location: panaci_manual_jogos.php"); exit;
    } catch(PDOException $e) { die("Erro ao salvar"); }
}

if (isset($_GET['delete_confirmed'])) {
    $stmt = $pdo->prepare("DELETE FROM game_settings WHERE id = ?");
    $stmt->execute([$_GET['delete_confirmed']]);
    $_SESSION['msg_success'] = "Removido!";
    header("Location: panaci_manual_jogos.php"); exit;
}
$all_games = $pdo->query("SELECT * FROM game_settings ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
include ('includes/header.php');
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    body, .main-panel { background-color: #020617 !important; color: #e2e8f0 !important; }
    .header-top h1 { color: #fff; font-weight: 800; font-size: 1.6rem; text-transform: uppercase; margin-bottom: 20px; }
    
    /* FIX: GRID DE BOTÕES COM TAMANHOS IGUAIS E SEM SOBREPOSIÇÃO */
    .top-nav-grid { 
        display: grid; 
        grid-template-columns: 1fr 1fr; /* Duas colunas iguais */
        gap: 15px; 
        margin-bottom: 25px; 
        width: 100%;
        box-sizing: border-box;
    }
    
    .btn-nav-premium {
        background: #0f172a !important; 
        border: 1px solid #1e293b !important;
        padding: 16px; 
        border-radius: 14px; 
        display: flex; 
        align-items: center; 
        justify-content: center;
        gap: 10px; 
        color: #fff !important; 
        font-weight: 900; 
        cursor: pointer; 
        text-transform: uppercase; 
        font-size: 0.75rem; 
        text-decoration: none;
        width: 100%; /* Ocupa exatamente o espaço da sua coluna no grid */
        box-sizing: border-box;
    }

    .premium-card { background: #0f172a !important; border: 1px solid #1e293b !important; padding: 20px; border-radius: 18px; margin-bottom: 20px; box-sizing: border-box; }
    .section-label { color: #fff !important; font-size: 0.8rem; font-weight: 900; text-transform: uppercase; margin: 30px 0 15px; display: block; border-left: 3px solid #ffaa00; padding-left: 10px; }
    label { font-size: 0.75rem; font-weight: 900; color: #fff !important; text-transform: uppercase; margin-bottom: 8px; display: block; }
    .dg-input { width: 100%; background: #070e1b; border: 1px solid #1e293b; padding: 14px; border-radius: 12px; color: white; margin-bottom: 15px; outline: none; box-sizing: border-box; }
    
    .btn-nav-premium i { color: #ffaa00; animation: wiggle 2s infinite ease-in-out; display: inline-block; }
    @keyframes wiggle { 0%, 100% { transform: rotate(0deg); } 25% { transform: rotate(-10deg); } 50% { transform: rotate(10deg); } 75% { transform: rotate(-10deg); } }

    .rgb-row { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; }
    .rgb-row span { font-weight: 900; color: #fff; width: 15px; font-size: 11px; }
    .rgb-row input[type="range"] { flex: 1; accent-color: #ffaa00; }
    .rgb-row b { font-size: 11px; width: 35px; text-align: right; color: #ffaa00; font-weight: 900; }
    .preview-box { width: 100%; height: 40px; border-radius: 10px; margin-bottom: 15px; border: 2px solid #1e293b; }

    .banner-real-view {
        width: 100%; aspect-ratio: 16/9; border-radius: 15px; 
        background-size: 100% 100%; background-repeat: no-repeat; background-position: center;
        position: relative; overflow: hidden; border: 1px solid #1e293b;
    }
    .banner-content-box {
        position: absolute; inset: 0; display: flex; flex-direction: column; 
        align-items: center; justify-content: space-between; padding: 15px 10px;
    }
    .escudos-container { display: flex; align-items: center; justify-content: center; gap: 35px; width: 100%; }
    .escudos-container img { height: 65px; width: 65px; object-fit: contain; }
    .vs-icon-view { height: 30px !important; width: auto !important; }
    .footer-banner-text { display: flex; flex-direction: column; align-items: center; gap: 3px; }
</style>

<div class="container-fluid">
    <div class="header-top"><h1>GERENCIAMENTO DE JOGOS</h1></div>

    <form method="POST">
        <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
        
        <div class="top-nav-grid">
            <a href="index.php" class="btn-nav-premium"><i class="fas fa-th-large"></i> DASHBOARD</a>
            <button type="submit" name="save_game" class="btn-nav-premium" style="border-bottom: 3px solid #ffaa00;">
                <i class="fas fa-sync-alt"></i> ATUALIZAR
            </button>
        </div>

        <input type="hidden" name="game_id" id="game_id">
        <input type="hidden" name="top_text_color" id="top_text_color" value="#ffffff">
        <input type="hidden" name="label_watch_color" id="label_watch_color" value="#ffaa00">
        <input type="hidden" name="canal_text_color" id="canal_text_color" value="#ffffff">
        <input type="hidden" name="canal_bg_color" id="canal_bg_color" value="#0f172a">

        <div class="premium-card">
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <label style="margin:0;">ATIVAR NO APLICATIVO</label>
                <input type="checkbox" name="show_games" id="show_games" style="width:24px; height:24px; accent-color: #ffaa00;">
            </div>
        </div>

        <span class="section-label">Ajuste de Cores (RGB)</span>
        <div style="display: grid; grid-template-columns: 1fr; gap: 10px;">
            <?php 
            $fields = ['top_text_color' => 'Textos Topo', 'label_watch_color' => 'Hora / Assistir', 'canal_text_color' => 'Nome Canal', 'canal_bg_color' => 'Fundo Canal'];
            foreach($fields as $id => $title): ?>
            <div class="premium-card">
                <label><?= $title ?></label>
                <div class="preview-box" id="prev_<?= $id ?>"></div>
                <div class="rgb-row"><span>R</span><input type="range" min="0" max="255" value="255" class="r-slide" data-id="<?= $id ?>"> <b id="v_r_<?= $id ?>">255</b></div>
                <div class="rgb-row"><span>G</span><input type="range" min="0" max="255" value="255" class="g-slide" data-id="<?= $id ?>"> <b id="v_g_<?= $id ?>">255</b></div>
                <div class="rgb-row"><span>B</span><input type="range" min="0" max="255" value="255" class="b-slide" data-id="<?= $id ?>"> <b id="v_b_<?= $id ?>">255</b></div>
            </div>
            <?php endforeach; ?>
        </div>

        <span class="section-label">Informações da Partida</span>
        <div class="premium-card">
            <label>Data Topo</label>
            <input type="text" name="game_data_top" id="game_data_top" class="dg-input" placeholder="Ex: HOJE 30/01">
            <label>Link Fundo</label>
            <input type="text" name="bg_url" id="bg_url" class="dg-input" placeholder="URL da imagem de fundo">
            <label>Campeonato</label>
            <input type="text" name="game_top" id="game_top" class="dg-input" placeholder="Ex: BRASILEIRÃO">
            <label>Hora</label>
            <input type="text" name="game_hora" id="game_hora" class="dg-input" placeholder="21:30">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div><label>Time Casa</label><input type="text" name="game_casa" id="game_casa" class="dg-input" placeholder="Ex: flamengo"></div>
                <div><label>Time Fora</label><input type="text" name="game_fora" id="game_fora" class="dg-input" placeholder="Ex: vasco"></div>
            </div>
            <label>Onde Assistir</label>
            <input type="text" name="game_canal" id="game_canal" class="dg-input" placeholder="Canais">
        </div>
    </form>

    <span class="section-label">Jogos Ativos</span>
    <?php foreach($all_games as $game): 
        $img_casa = (strpos($game['game_casa'], 'http') === 0) ? $game['game_casa'] : "escudos/" . $game['game_casa'] . ".png";
        $img_fora = (strpos($game['game_fora'], 'http') === 0) ? $game['game_fora'] : "escudos/" . $game['game_fora'] . ".png";
    ?>
    <div class="premium-card" style="padding: 12px;">
        <div class="banner-real-view" style="background-image: url('<?= $game['bg_url'] ?>');">
            <div class="banner-content-box">
                <span style="color: <?= $game['top_text_color'] ?>; font-weight: 900; font-size: 0.8rem;"><?= strtoupper($game['game_data_top']) ?></span>
                <div class="escudos-container">
                    <img src="<?= $img_casa ?>" onerror="this.src='https://placehold.co/100/0f172a/fff?text=?'">
                    <img src="https://i.postimg.cc/sgqbRhcd/vs.png" class="vs-icon-view">
                    <img src="<?= $img_fora ?>" onerror="this.src='https://placehold.co/100/0f172a/fff?text=?'">
                </div>
                <div class="footer-banner-text">
                    <span style="color: <?= $game['top_text_color'] ?>; font-weight: 900; font-size: 0.9rem;"><?= strtoupper($game['game_top']) ?></span>
                    <div style="display:flex; gap:5px;">
                        <span style="background:<?= $game['label_watch_color'] ?>; color:#000; font-size:9px; padding:2px 5px; border-radius:3px; font-weight:900;"><?= $game['game_hora'] ?></span>
                        <span style="background:<?= $game['canal_bg_color'] ?>; color:<?= $game['canal_text_color'] ?>; font-size:9px; padding:2px 5px; border-radius:3px; font-weight:900;"><?= strtoupper($game['game_canal']) ?></span>
                    </div>
                </div>
            </div>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 15px;">
            <button onclick='editGame(<?= json_encode($game) ?>)' class="btn-nav-premium" style="border-left: 3px solid #3b82f6;"><i class="fas fa-edit"></i> EDITAR</button>
            <button onclick="confirmarDelete(<?= $game['id'] ?>)" class="btn-nav-premium" style="border-left: 3px solid #ef4444;"><i class="fas fa-trash-alt"></i> EXCLUIR</button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
    <?php if (isset($_SESSION['msg_success'])): ?>
        Swal.fire({ icon: 'success', title: 'Pronto!', text: '<?= $_SESSION['msg_success'] ?>', background: '#020617', color: '#fff', confirmButtonColor: '#ffaa00' });
        <?php unset($_SESSION['msg_success']); ?>
    <?php endif; ?>

    function confirmarDelete(id) {
        Swal.fire({ title: 'Excluir Jogo?', icon: 'warning', showCancelButton: true, background: '#020617', color: '#fff', confirmButtonColor: '#ef4444', confirmButtonText: 'APAGAR'
        }).then((res) => { if (res.isConfirmed) window.location.href = '?delete_confirmed=' + id; });
    }

    function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (parseInt(r) << 16) + (parseInt(g) << 8) + parseInt(b)).toString(16).slice(1); }
    function hexToRgb(hex) { if(!hex) hex = "#ffffff"; let r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); return {r, g, b}; }
    
    function updateRGB(id) {
        let r = document.querySelector(`.r-slide[data-id="${id}"]`).value, g = document.querySelector(`.g-slide[data-id="${id}"]`).value, b = document.querySelector(`.b-slide[data-id="${id}"]`).value;
        document.getElementById(`v_r_${id}`).innerText = r; document.getElementById(`v_g_${id}`).innerText = g; document.getElementById(`v_b_${id}`).innerText = b;
        let hex = rgbToHex(r, g, b); document.getElementById(`prev_${id}`).style.backgroundColor = hex; document.getElementById(id).value = hex;
    }
    document.querySelectorAll('input[type="range"]').forEach(s => s.addEventListener('input', function() { updateRGB(this.getAttribute('data-id')); }));

    function editGame(data) {
        document.getElementById('game_id').value = data.id;
        document.getElementById('bg_url').value = data.bg_url;
        document.getElementById('game_top').value = data.game_top;
        document.getElementById('game_casa').value = data.game_casa;
        document.getElementById('game_fora').value = data.game_fora;
        document.getElementById('game_canal').value = data.game_canal;
        document.getElementById('game_hora').value = data.game_hora;
        document.getElementById('game_data_top').value = data.game_data_top;
        document.getElementById('show_games').checked = (data.show_games == 1);
        ['top_text_color', 'label_watch_color', 'canal_text_color', 'canal_bg_color'].forEach(cId => {
            let rgb = hexToRgb(data[cId]);
            document.querySelector(`.r-slide[data-id="${cId}"]`).value = rgb.r;
            document.querySelector(`.g-slide[data-id="${cId}"]`).value = rgb.g;
            document.querySelector(`.b-slide[data-id="${cId}"]`).value = rgb.b;
            updateRGB(cId);
        });
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
</script>
<?php include ('includes/footer.php');?>
