<?php
// ------------------------------------------
// 1) Funções de codificação/decodificação
// ------------------------------------------
function codificarURL($url)
{
    return base64_encode($url);
}

function decodificarURL($urlCodificado)
{
    return base64_decode($urlCodificado);
}

// Redirecionamento caso acesse ?img=...
if (isset($_GET['img'])) {
    $url = decodificarURL($_GET['img']);
    header("Location: $url");
    exit;
}

$imagens = [];
$contadorImg = 0;

function ocultarLinksDeImagensNoHTML($html)
{
    global $imagens, $contadorImg;
    return preg_replace_callback(
        '/src=["\'](https:\/\/.*?)["\']/i',
        function ($matches) use (&$imagens, &$contadorImg) {
            $urlCodificado = codificarURL($matches[1]);
            $idImagem = 'img' . $contadorImg++;
            $imagens[$idImagem] = $urlCodificado;
            return 'id="' . $idImagem . '" src="#"';
        },
        $html
    );
}

// ------------------------------------------
// 2) Iniciar Buffer e Config. Timezone
// ------------------------------------------
ob_start();
date_default_timezone_set('America/Sao_Paulo');

// ------------------------------------------
// 3) Mapeamento de Dias e Meses
// ------------------------------------------
$diaSemanaMap = array(
    'Sunday'    => 'Domingo',
    'Monday'    => 'Segunda',
    'Tuesday'   => 'Terça',
    'Wednesday' => 'Quarta',
    'Thursday'  => 'Quinta',
    'Friday'    => 'Sexta',
    'Saturday'  => 'Sábado'
);

$meses = array(
    'January'   => 'Janeiro',
    'February'  => 'Fevereiro',
    'March'     => 'Março',
    'April'     => 'Abril',
    'May'       => 'Maio',
    'June'      => 'Junho',
    'July'      => 'Julho',
    'August'    => 'Agosto',
    'September' => 'Setembro',
    'October'   => 'Outubro',
    'November'  => 'Novembro',
    'December'  => 'Dezembro'
);

// ------------------------------------------
// 4) Obter Data Atual em Português
// ------------------------------------------
$dataAtual = $diaSemanaMap[date('l')] . ', ' . date('d') . ' de ' . $meses[date('F')] . ' de ' . date('Y');

// ------------------------------------------
// 5) URL do JSON com os Jogos
// ------------------------------------------
$api_url = 'https://xsender.painelmaster.lol/retorno.json';

// Tenta obter o conteúdo do JSON
$api_json_content = @file_get_contents($api_url);

if ($api_json_content === false) {
    $jogos = []; 
} else {
    // Tenta decodificar o JSON
    $jogos = json_decode($api_json_content, true);

    // Verifica se houve erro na decodificação
    if (json_last_error() !== JSON_ERROR_NONE) {
        $jogos = [];
    }
}

// ------------------------------------------
// 6) Configurações (cores)
// ------------------------------------------
session_start();

// Valores padrão
$color1 = '#1a1a2e';
$color2 = '#16213e';
$scrollTime = 3;

// Se o formulário foi enviado, salva as configurações na sessão
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['color1'] = $_POST['color1'] ?? $color1;
    $_SESSION['color2'] = $_POST['color2'] ?? $color2;
    
    // Recarrega a página para aplicar as alterações
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// Usa os valores da sessão se existirem
if (isset($_SESSION['color1'])) {
    $color1 = $_SESSION['color1'];
}
if (isset($_SESSION['color2'])) {
    $color2 = $_SESSION['color2'];
}

if (!isset($_SERVER['HTTP_USER_AGENT'])) {
    die("Acesso negado. O código-fonte desta página está protegido.");
}
?>
<!doctype html>
<html lang=pt-BR>
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Jogos do Dia</title>
<script>
        // Executa silenciosamente o salvar_jogos.php em segundo plano
        window.addEventListener('DOMContentLoaded', function() {
            fetch('salvar_jogos.php')
                .catch(error => {}); // Ignora completamente qualquer erro
        });
    </script>
<style>
    .close-btn,.placar,.time p{font-weight:700}
    .canal-box img,.time img,.vs img{object-fit:contain}
    body{font-family:'Segoe UI', Arial, sans-serif;background-color:#0f0f0f;color:#fff;margin:0;padding:0;background-image: linear-gradient(to bottom, #0f0f0f, #1a1a1a);}
    .modal{display:none;position:fixed;z-index:100;left:0;top:0;width:100%;height:100%;background-color:rgba(0,0,0,.9);}
    .canais,.canal-box,.times{display:flex}
    .modal-content{background: linear-gradient(145deg, #1a1a1a, #2a2a2a);margin:5% auto;padding:20px;border-radius:15px;width:320px;text-align:center;color:#fff;box-shadow: 0 0 20px rgba(0,0,0,0.5);}
    .close-btn{color:#aaa;float:right;font-size:28px;margin-top:-20px;}
    .btn-salvar,.close-btn:hover{color:#fff;cursor:pointer}
    .btn-salvar{background: linear-gradient(145deg, #28a745, #1e7e34);border:none;padding:10px 20px;font-size:16px;border-radius:5px;box-shadow: 0 4px 8px rgba(0,0,0,0.3);transition: all 0.3s ease;}
    .btn-salvar:hover{background: linear-gradient(145deg, #218838, #1a7433);transform: translateY(-2px);box-shadow: 0 6px 12px rgba(0,0,0,0.4);}
    .star-button{font-size:24px;cursor:pointer;color:#4cc9f0;border:none;background:0 0;margin-left:10px;transition: all 0.3s ease;}
    .star-button:hover{transform: rotate(15deg);}
    .multiple-container{display:flex;flex-wrap:wrap;justify-content:center;gap:30px;padding:30px;}
    .jogo-card{background: linear-gradient(145deg, <?php echo $color1; ?>, <?php echo $color2; ?>);padding:15px;position:relative;text-align:center;border-radius:10px;width:250px;margin-bottom:30px;box-shadow: 0 5px 15px rgba(0,0,0,0.3);transition: all 0.3s ease;}
    .jogo-card:hover{transform: translateY(-5px);box-shadow: 0 8px 20px rgba(0,0,0,0.4);}
    .times{justify-content:center;align-items:center;gap:15px;position:relative;top:-20px;}
    .time-box{background: rgba(0,0,0,0.3);border-radius:30px;width:120px;color:#fff;box-shadow: 0 3px 10px rgba(0,0,0,0.2);padding:10px;transition: all 0.3s ease;}
    .time-box:hover{transform: scale(1.03);}
    .time img{width:70px;height:70px;display:block;margin:0 auto;transition: all 0.3s ease;}
    .time img:hover{transform: scale(1.1);}
    .time p{margin:5px auto 0;font-size:14px;color:#fff;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;max-width:100px;}
    .placar{font-size:24px;color:#ffd700;margin-top:5px;}
    .campeonato,.hora{color:#fff;font-weight:700;}
    .vs img{width:40px;height:auto;transition: all 0.3s ease;}
    .vs img:hover{transform: rotate(15deg);}
    .hora{font-size:35px;margin:10px 0;color: #fff;}
    .campeonato{font-size:15px;margin-top:-20px;background: rgba(0,0,0,0.3);padding: 5px 10px;border-radius: 20px;display: inline-block;}
    .canais{justify-content:center;gap:10px;margin-top: 10px;}
    .canal-container{position:relative;width:100%;display:flex;justify-content:center;}
    .canal-box{align-items:center;justify-content:center;padding:8px 15px;border-radius:10px;background: rgba(255,255,255,0.9);color:#000;font-weight:700;min-width:100px;height:25px;display:flex;box-shadow: 0 2px 5px rgba(0,0,0,0.1);transition: all 0.3s ease;}
    .canal-box:hover{transform: translateY(-3px);box-shadow: 0 4px 8px rgba(0,0,0,0.2);background: rgba(255,255,255,1);}
    .canal-box img{width:25px;height:25px;margin-right:8px;object-fit:contain;}
    .canal-box p{margin:0;font-size:14px;color:#000;font-weight: bold;}
    .status-fim{background: linear-gradient(145deg, #d00000, #9d0208);margin-top:15px;padding:8px 15px;border-radius:20px;color:#fff;font-weight:700;text-align:center;display:inline-block;font-size:14px;text-transform: uppercase;letter-spacing: 1px;}
    h1{text-align:center;color: #fff;margin: 20px 0;font-size: 2em;padding: 15px;border-radius: 10px;}
</style>
</head>
<body>
<h1 style=text-align:center>
<button class=star-button onclick=openModal()>&#9733;</button>
Jogos de Hoje <?php echo $dataAtual; ?>
<button class=star-button onclick=openModal()>&#9733;</button>
</h1>
<div id=modal class=modal>
<div class=modal-content>
<span class=close-btn onclick=closeModal()>&times;</span>
<h2>Configurações</h2>
<form action="" method="POST" id="configForm">
    <label for=color1>Cor 1 (gradiente): </label><br>
    <input type=color id=color1 name=color1 value="<?php echo htmlspecialchars($color1); ?>"><br><br>
    <label for=color2>Cor 2 (gradiente): </label><br>
    <input type=color id=color2 name=color2 value="<?php echo htmlspecialchars($color2); ?>"><br><br>
    <button type=submit class=btn-salvar>Salvar Configurações</button>
</form>
</div>
</div>
<div id=layoutMultiple class=multiple-container style=display:flex>
<?php if (empty($jogos)) : ?>
<h2 style=width:100%;text-align:center>Nenhum jogo para hoje!</h2>
<?php else : ?>
<?php foreach ($jogos as $jogo) : ?>
<div class=jogo-card>
<div class=times>
<div class=time-box>
<div class=time>
<img src="<?= $jogo['img_time1_url']; ?>" alt="<?= $jogo['time1']; ?>">
<p><?= $jogo['time1']; ?></p>
</div>
<div class=placar><?= $jogo['placar_time1']; ?></div>
</div>
<div class=vs>
<img src=https://pic.onlinewebfonts.com/thumbnails/icons_418591.svg alt=Versus>
</div>
<div class=time-box>
<div class=time>
<img src="<?= $jogo['img_time2_url']; ?>" alt="<?= $jogo['time2']; ?>">
<p><?= $jogo['time2']; ?></p>
</div>
<div class=placar><?= $jogo['placar_time2']; ?></div>
</div>
</div>
<div class=campeonato><?= $jogo['competicao']; ?></div>
<div class=hora><?= $jogo['horario']; ?></div>
<div class=canais>
<?php if (!empty($jogo['canais'])) : ?>
    <div class="canal-container" data-canais='<?= json_encode($jogo['canais']); ?>'>
        <div class=canal-box>
            <img src="<?= $jogo['canais'][0]['img_url']; ?>" alt="<?= $jogo['canais'][0]['nome']; ?>">
            <p><?= $jogo['canais'][0]['nome']; ?></p>
        </div>
    </div>
<?php endif; ?>
</div>
<?php
    $status = strtoupper(trim($jogo['status'] ?? ''));
    if (strpos($status, 'FIM DE JOGO') !== false) : ?>
<div class="status-fim">
<?= $jogo['status']; ?>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<script>
    function openModal() {
        document.getElementById("modal").style.display = "block";
    }
    function closeModal() {
        document.getElementById("modal").style.display = "none";
    }
    document.addEventListener("contextmenu", (e => e.preventDefault()));
    window.onclick = function(e) {
        const n = document.getElementById("modal");
        e.target == n && (n.style.display = "none");
    }

    class AutoScroll {
        constructor() {
            this.container = document.documentElement;
            this.direction = 1;
            this.animationFrame = null;
            this.scrollSpeed = 1;
            this.isPaused = false;
            this.setupEvents();
            this.start();
        }
        setupEvents() {
            document.addEventListener('mousedown', () => this.togglePause(true));
            document.addEventListener('mouseup', () => this.togglePause(false));
            document.addEventListener('touchstart', () => this.togglePause(true));
            document.addEventListener('touchend', () => this.togglePause(false));
            let wheelTimeout;
            document.addEventListener('wheel', () => {
                clearTimeout(wheelTimeout);
                this.stop();
                wheelTimeout = setTimeout(() => {
                    if (!this.isPaused) {
                        this.start();
                    }
                }, 2000);
            }, { passive: true });
        }
        togglePause(state) {
            this.isPaused = state;
            if (state) {
                this.stop();
            } else {
                this.start();
            }
        }
        animate() {
            if (this.isPaused) return;
            const maxScroll = this.container.scrollHeight - this.container.clientHeight;
            if (this.container.scrollTop >= maxScroll && this.direction === 1) {
                this.direction = -1;
            } else if (this.container.scrollTop <= 0 && this.direction === -1) {
                this.direction = 1;
            }
            this.container.scrollBy({
                top: this.scrollSpeed * this.direction,
                behavior: 'auto'
            });
            this.animationFrame = requestAnimationFrame(() => this.animate());
        }
        start() {
            if (!this.animationFrame && !this.isPaused) {
                this.animationFrame = requestAnimationFrame(() => this.animate());
            }
        }
        stop() {
            if (this.animationFrame) {
                cancelAnimationFrame(this.animationFrame);
                this.animationFrame = null;
            }
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        const autoScrollInstance = new AutoScroll();
        inicializarSlideCanais();
    });
    
    function inicializarSlideCanais() {
        const containers = document.querySelectorAll('.canal-container');
        
        containers.forEach(container => {
            const canais = JSON.parse(container.getAttribute('data-canais'));
            
            if (canais.length > 1) {
                let indiceAtual = 0;
                
                const atualizarCanal = () => {
                    indiceAtual = (indiceAtual + 1) % canais.length;
                    const canalAtual = canais[indiceAtual];
                    
                    const canalBox = container.querySelector('.canal-box');
                    const img = canalBox.querySelector('img');
                    const p = canalBox.querySelector('p');
                    
                    img.src = canalAtual.img_url;
                    img.alt = canalAtual.nome;
                    p.textContent = canalAtual.nome;
                };
                
                setInterval(atualizarCanal, 3000);
            }
        });
    }
</script>
</body>
</html>