<?php
// ===== CONFIGURAÇÃO DO CAMINHO DO BANCO =====
$db_path = __DIR__ . '/db/db_ads.db';

if (!file_exists(__DIR__ . '/db')) {
    mkdir(__DIR__ . '/db', 0755, true);
}

try {
    $pdo = new PDO("sqlite:" . $db_path);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Erro ao conectar ao banco.");
}

// ALTERADO: Removido RANDOM() e adicionado ORDER BY id ASC para seguir a ordem de adição
$stmt = $pdo->query("SELECT * FROM ads ORDER BY id ASC");
$ads = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($ads)) {
    exit('<body style="background:#000;color:#fff;display:flex;justify-content:center;align-items:center;height:100vh;font-family:sans-serif;"><h1>Aguardando Banners...</h1></body>');
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Display Banners 2026</title>
    <style>
        /* Reset total para modo tela cheia */
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-touch-callout: none; user-select: none; }
        html, body { background-color: #000; overflow: hidden; width: 100%; height: 100%; position: fixed; }
        
        .slideshow-container { position: relative; width: 100vw; height: 100vh; }
        
        .slide {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            opacity: 0; transition: opacity 0.8s ease-in-out;
            display: flex; justify-content: center; align-items: center;
        }
        
        .slide.active { opacity: 1; z-index: 10; }
        
        .media-container { width: 100%; height: 100%; }
        
        .media-container img, .media-container video {
            width: 100%; 
            height: 100%; 
            object-fit: fill; 
            pointer-events: none;
        }

        /* --- LOADING PRETO COM PULSAÇÃO FORTE CORRIGIDO PARA TVBOX --- */
        .loading { 
            position: fixed; 
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #000; 
            display: flex; 
            flex-direction: column; 
            justify-content: center; 
            align-items: center; 
            z-index: 9999; 
            transition: opacity 0.6s ease; 
        }

        .pulse-circle {
            width: 70px;
            height: 70px;
            background-color: #000;
            border: 3px solid #444; 
            border-radius: 50%;
            margin-bottom: 20px; 
            animation: pulse-strong 1.2s ease-in-out infinite;
        }

        .loading-text {
            color: #888;
            font-family: sans-serif;
            font-size: 0.9rem;
            letter-spacing: 2px;
            text-transform: uppercase;
            animation: pulse-text 1.2s ease-in-out infinite;
        }

        @keyframes pulse-strong {
            0% { transform: scale(0.8); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
            50% { transform: scale(1.15); box-shadow: 0 0 20px 5px rgba(255, 255, 255, 0.2); }
            100% { transform: scale(0.8); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
        }

        @keyframes pulse-text {
            0%, 100% { opacity: 0.5; }
            50% { opacity: 1; }
        }
    </style>
</head>
<body oncontextmenu="return false;">

    <div class="loading" id="loading">
        <div class="pulse-circle"></div>
        <div class="loading-text">Aguarde carregando...</div>
    </div>
    
    <div class="slideshow-container" id="slideshow">
        <?php foreach ($ads as $index => $ad): ?>
        <div class="slide <?= $index === 0 ? 'active' : ''; ?>">
            <div class="media-container">
                <?php
                $url = $ad['url'];
                $ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION));
                $is_video = in_array($ext, ['mp4', 'webm', 'ogg']);
                
                if ($is_video): ?>
                    <video autoplay muted loop playsinline disablePictureInPicture>
                        <source src="<?= htmlspecialchars($url) ?>" type="video/<?= $ext ?>">
                    </video>
                <?php else: ?>
                    <img src="<?= htmlspecialchars($url) ?>" alt="Banner">
                <?php endif; ?>
            </div>
            </div>
        <?php endforeach; ?>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const slides = document.querySelectorAll('.slide');
            const loading = document.getElementById('loading');
            let current = 0;
            const delay = 5000; 

            window.onload = () => { 
                loading.style.opacity = '0';
                setTimeout(() => {
                    loading.style.display = 'none';
                }, 600);
            };

            function nextSlide() {
                if (slides.length <= 1) return;
                
                slides[current].classList.remove('active');
                current = (current + 1) % slides.length;
                slides[current].classList.add('active');

                const video = slides[current].querySelector('video');
                if (video) { 
                    video.currentTime = 0; 
                    video.play().catch(e => console.log("Autoplay bloqueado")); 
                }
            }

            if (slides.length > 1) { 
                setInterval(nextSlide, delay); 
            }

            const block = (e) => { e.preventDefault(); return false; };
            ['touchstart', 'touchmove', 'click', 'contextmenu'].forEach(ev => {
                document.addEventListener(ev, block, { passive: false });
            });
        });
    </script>
</body>
</html>