<?php
include 'template/header.php';

// Pastikan session_start(); sudah dipanggil di file ini atau di header.php
$is_logged_in = isset($_SESSION['id']); // Sesuaikan dengan key session Anda 

// Daftar game yang ingin diprioritaskan di posisi paling atas
$priority_games = [
    'Wild Bandito',
    'Wild Bounty Showdown', 
    'Mahjong Wins 3 – Black Scatter',
    'Lucky Neko',
    'Mahjong Wins Super Scatter',
    'The Dog House Royal Hunt', 
    'Sweet Bonanza 2500', 
    'Candy Rush', 
    'Launch to Riches', 
    'BigBoy Rush 1000',
    'Zeus vs Typhon',
    'Gates of Olympus X-mas 1000',
    'Gates of Olympus Dice 1000',
    'Gates of Gatot Kaca',
    'Gates of Hades',
    'Games in Olympus',
    'Gates of LeoVegas 1000',
    'Fortune Ace Super Scatter',
    'Mahjong Wins 3 Black Scatter',
    'Gates of Olympus 1000',
    'Starlight Princess',
    'Gates of Gatot Kaca 1000',
    'Gates of Olympus',
    'Starlight Princess 1000',
    'Sweet Bonanza Super Scatter',
    'Mahjong Ways',
    'Mahjong Ways 2',
    'Starlight Princess Super Scatter',
    'Gates of Gatot Kaca Super Scatter',
    'Sweet Bonanza',
    'Gates of Olympus Super Scatter',
    'Mahjong Wins', 
    'Sweet Bonanza 1000', 
    'Mahjong Wins 2'
];

// Menyusun urutan string kebalik untuk klausa FIELD() di MySQL
$escaped_games = array_map(function($g) use ($koneksi) {
    return "'" . mysqli_real_escape_string($koneksi, $g) . "'";
}, $priority_games);

// Balik array agar elemen pertama dalam list ('Wild Bandito') menjadi yang paling atas di prioritaskan
$order_field = implode(',', array_reverse($escaped_games));
?>

<div id="gameLoaderOverlay" class="game-loader-overlay">
    <div class="loader-content">
        <div class="spinner-neon"></div>
        <div class="loader-text">SEDANG MENYIAPKAN PERMAINAN<br>MOHON SABAR MENUNGGU YA...</div>
        <div class="loader-countdown" id="loaderCountdown">10</div>
    </div>
</div>

<?php if ($mobile): ?>
    <div style="margin-top: 50px;">
        <div>
            <img src="https://rajabotak.dataklmsad902.site/asset/images/banner-game-2.jpg?s=6ad8d77b69c3661f8ca7458816992e23"
                style="width: 100%;">
        </div>
        <?php include "template/menu-outer.php" ?>

        <?php if (!isset($_GET['s'])): ?>
            <div style="width: 95%; margin: 0 auto 20px auto;">
                <div
                    style="font-family: Teko-SemiBold; text-align: center; font-size: 24px; color: transparent !important; -webkit-background-clip: text; background-image: radial-gradient(ellipse farthest-corner at right bottom, #FEDB37 0%, #FDB931 8%, #9f7928 30%, #8A6E2F 40%, transparent 80%), radial-gradient(ellipse farthest-corner at left top, #e99c05 0%, #f4ae00 8%, #f8bf33 25%, #f8ce19 62.5%, #ffdc02 100%); padding: 10px 0;">
                    Pilih Game
                    <hr
                        style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box; border-top: 2px solid transparent; margin: 0 auto; width: 70px;">
                </div>

                <ul style="list-style-type: none; padding: 0; margin-bottom: 0; display: flex; flex-wrap: wrap;">
                    <?php
                    $q = mysqli_query($koneksi, "SELECT * FROM tb_provider WHERE provider_type = 'SL'");

                    while ($data = mysqli_fetch_assoc($q)):
                        $providerName = htmlspecialchars($data['provider_name']);
                        $providerImg = htmlspecialchars($data['provider_image']);
                        $slug = htmlspecialchars($data['slug']);
                        $status = $data['status'];
                        ?>
                        <li <?php if ($status == 1): ?> onclick="window.location='?s=<?= $slug ?>'" <?php else: ?>
                                onclick="alert('Provider ini sedang Maintenance!');" <?php endif; ?>
                            style="display: inline-block; width: 50%; padding: 0 5px; cursor: pointer;">
                            <img src="<?= $providerImg ?>" alt="<?= $providerName ?>"
                                onerror="this.src='https://via.placeholder.com/300x150/667eea/ffffff?text=<?= urlencode($providerName) ?>'"
                                style="width: 100%; margin-bottom: 6px;">
                        </li>
                    <?php endwhile; ?>
                </ul>
            </div>
        <?php else:
            $slug = $_GET['s'];
            $provider = mysqli_query($koneksi, "SELECT * FROM tb_provider where UPPER(slug) = UPPER('$slug')");
            $data_pr = mysqli_fetch_assoc($provider) ?>
            <div style="background-color:var(--secondary-color);">
                <div style="width: 90%; margin: 0 auto; padding: 10px 0;">
                    <div style="display: flex; padding: 4px 0 4px 10px;">
                        <div style="color: var(--primary-color); font-family: Teko-SemiBold; font-size: 20px; margin: auto auto auto 0;">
                            <?= htmlspecialchars(strtoupper($data_pr['provider_name'])); ?>
                        </div>

                        <div style="margin: auto 0 auto auto; position: relative; width: 45%;">
                            <i class="fa fa-search" aria-hidden="true"
                                style="position: absolute; top: 10px; left: 15px; height: 18px; width: 18px; margin: 0; color: var(--primary-color);"></i>
                            <input type="text" name="search" class="search" placeholder="Cari Permainan"
                                style="font-family: Poppins-Regular; font-size: 12px; width: 100%; background-color: transparent; color: #fff; border: 1px solid var(--primary-color); border-radius: 25px; padding: 6px 15px 6px 35px;">
                        </div>
                    </div>

                    <div>
                        <ul id="game_list"
                            style="list-style-type: none; padding: 20px 0 0 0; margin-bottom: 0; display: flex; flex-wrap: wrap;">
                            <?php
                            $data_game = mysqli_query($koneksi, "SELECT * FROM tb_game WHERE UPPER(provider_name) = UPPER('$data_pr[provider_name]') ORDER BY FIELD(game_name, $order_field) DESC, (seq = 0), seq ASC");
                            if (mysqli_num_rows($data_game) > 0) {
                                while ($game = mysqli_fetch_assoc($data_game)) {
                                    $game_name = htmlspecialchars($game['game_name']);
                                    $game_code = htmlspecialchars($game['game_code']);
                                    $provider_code = htmlspecialchars($game['game_provider']);
                                    $image = htmlspecialchars($game['game_image']);
                                    $slug = htmlspecialchars($game['provider_name']);
                                    ?>
                                    <li onclick="mulaiMembukaGame('play.php?game=<?= $game_code ?>&provider=<?= $provider_code ?>')"
                                        style="display: inline-block; padding: 0 8px; width: 33.3%; margin-bottom: 15px; cursor: pointer;">
                                        <div style="background-color: var(--primary-color); padding: 5px; border-radius: 4px;">
                                            <div style="width: 100%; height: 90px; position: relative; overflow: hidden;">
                                                <img src="<?= $image ?>" alt="<?= $game_name ?>"
                                                    style="position: absolute; box-sizing: border-box; border: medium; margin: auto; display: block; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%; object-fit: cover;">
                                            </div>
                                            <div
                                                style="margin-top: 6px; font-size: 10px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                                <?= $game_name ?>
                                            </div>
                                        </div>
                                    </li>
                                    <?php
                                }
                            } ?>
                        </ul>
                    </div>
                </div>
            </div>
        <?php endif; ?>

    </div>
<?php else: ?>
    <div style="margin-top: 170px;">
        <div class="background-top" style="padding: 30px 0 50px 0;">

            <?php if (!isset($_GET['s'])): ?>

                <div style="width: 95%; margin: 0 auto; max-width: 1280px; padding-top: 20px;">
                    <div
                        style="margin-bottom: 20px; color: var(--primary-color); font-family: Teko-SemiBold; font-size: 24px; text-align: center;">
                        SLOT
                    </div>

                    <ul style="list-style-type: none; padding: 20px 0 0 0; margin: 0; display: flex; flex-wrap: wrap;">

                        <?php
                        $providers = mysqli_query($koneksi, "SELECT * FROM tb_provider WHERE provider_type = 'SL'");

                        while ($data = mysqli_fetch_assoc($providers)):
                            $providerName = htmlspecialchars($data['provider_name']);
                            $providerImg = htmlspecialchars($data['provider_image']);
                            $slug = htmlspecialchars($data['slug']);
                            ?>
                            <li onclick="window.location='?s=<?= $slug ?>'"
                                style="display: inline-block; padding: 0 10px; width: 20%; margin-bottom: 20px; cursor: pointer;">
                                <img src="<?= $providerImg ?>" alt="<?= $providerName ?>" style="width: 100%; border-radius: 6px;">
                            </li>
                        <?php endwhile; ?>

                    </ul>
                </div>

            <?php else: ?>

                <?php
                $slug = mysqli_real_escape_string($koneksi, $_GET['s']);

                $provider = mysqli_query(
                    $koneksi,
                    "SELECT * FROM tb_provider WHERE UPPER(slug) = UPPER('$slug')"
                );

                $data_pr = mysqli_fetch_assoc($provider);

                if (!$data_pr) {
                    echo "<div style='text-align:center; color:#fff; padding:40px;'>Provider tidak ditemukan.</div>";
                    include 'template/footer.php';
                    exit;
                }

                $providerName = mysqli_real_escape_string($koneksi, $data_pr['provider_name']);
                ?>

                <div style="background-color:var(--secondary-color);">
                    <div style="width: 90%; margin: 0 auto; padding: 10px 0;">

                        <div style="display: flex; padding: 4px 0;">
                            <div style="color: var(--primary-color); font-family: Teko-SemiBold; font-size: 20px;">
                                <?= htmlspecialchars(strtoupper($data_pr['provider_name'])) ?>
                            </div>

                            <div style="margin: auto 0 auto auto; position: relative; width: 20%;">
                                <i class="fa fa-search" aria-hidden="true"
                                    style="position: absolute; top: 10px; left: 15px; color: var(--primary-color);"></i>
                                <input type="text" class="search" placeholder="Cari Permainan"
                                    style="font-family: Poppins-Regular; font-size: 14px; width: 100%; background-color: transparent; color: #fff; border: 1px solid var(--primary-color); border-radius: 25px; padding: 6px 15px 6px 35px;">
                            </div>
                        </div>

                        <ul id="game_list"
                            style="list-style-type: none; padding: 20px 0 0 0; margin-bottom: 0; display: flex; flex-wrap: wrap;">
                            
                            <?php
                            $games = mysqli_query(
                                $koneksi,
                                "SELECT * FROM tb_game 
                             WHERE UPPER(provider_name) = UPPER('$providerName')
                             ORDER BY FIELD(game_name, $order_field) DESC, (seq = 0), seq ASC"
                            );

                            while ($game = mysqli_fetch_assoc($games)):
                                $game_name = htmlspecialchars($game['game_name']);
                                $game_code = htmlspecialchars($game['game_code']);
                                $provider_code = htmlspecialchars($game['game_provider']);
                                $image = htmlspecialchars($game['game_image']);
                                ?>
                                <li onclick="mulaiMembukaGame('play.php?game=<?= $game_code ?>&provider=<?= $provider_code ?>')"
                                    style="display: inline-block; padding: 0 8px; width: 14.2%; margin-bottom: 15px; cursor: pointer;">
                                    <div style="background-color: var(--primary-color); padding: 5px; border-radius: 4px;">
                                        <div style="width: 100%; height: 160px; position: relative; overflow: hidden;">
                                            <img src="<?= $image ?>" alt="<?= $game_name ?>"
                                                style="position: absolute; box-sizing: border-box; border: medium; margin: auto; display: block; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%; object-fit: cover;">
                                        </div>
                                        <div
                                            style="margin-top: 6px; font-size: 12px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                            <?= $game_name ?>
                                        </div>
                                    </div>
                                </li>
                            <?php endwhile; ?>

                        </ul>

                    </div>
                </div>

            <?php endif; ?>

        </div>
    </div>
<?php endif; ?>

<script>
// Pastikan variabel is_logged_in dikirim dari PHP ke JS
const IS_LOGGED_IN = <?= json_encode(isset($_SESSION['id'])); ?>;

document.addEventListener("DOMContentLoaded", function () {
    const searchInputs = document.querySelectorAll(".search");
    
    searchInputs.forEach(function(searchInput) {
        searchInput.addEventListener("keyup", function () {
            const keyword = this.value.toLowerCase();
            const gameList = this.closest('.background-top, div[style*="background-color:var(--secondary-color)"]').querySelectorAll("#game_list li");

            gameList.forEach(function (item) {
                const title = item.innerText.toLowerCase();
                item.style.display = title.includes(keyword) ? "inline-block" : "none";
            });
        });
    });
});

var loadingAktif = false;

function mulaiMembukaGame(urlTujuan) {
    // 1. Cek Login Terlebih Dahulu
    if (!IS_LOGGED_IN) {
        window.location.href = 'login.php';
        return; // Hentikan fungsi agar loader tidak jalan
    }

    if (loadingAktif) return;
    loadingAktif = true;

    // 2. Ambil elemen overlay spinner
    var overlay = document.getElementById('gameLoaderOverlay');
    var countdownEl = document.getElementById('loaderCountdown');

    // 3. Tampilkan overlay
    overlay.style.setProperty("display", "flex", "important");
    setTimeout(function() {
        overlay.classList.add('active');
    }, 50);

    // 4. Hitung mundur
    var sisaWaktu = 5;
    countdownEl.textContent = sisaWaktu;

    var intervalWaktu = setInterval(function() {
        sisaWaktu--;
        countdownEl.textContent = sisaWaktu;
        if (sisaWaktu <= 0) {
            clearInterval(intervalWaktu);
        }
    }, 1000);

    // 5. Redirect setelah 5 detik
    setTimeout(function () {
        window.location.href = urlTujuan;
    }, 5000);
}
</script>

<style>
/* CSS LOADING OVERLAY ULTRA PREMIUM */
.game-loader-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
    background: rgba(0, 0, 0, 0.95) !important;
    z-index: 999999 !important;
    display: none; 
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}
.game-loader-overlay.active {
    opacity: 1 !important;
}
.loader-content {
    text-align: center;
}
.spinner-neon {
    width: 80px;
    height: 80px;
    border: 6px solid rgba(0, 255, 0, 0.1);
    border-top: 6px solid #00ff00;
    border-right: 6px solid #ee9601;
    border-radius: 50%;
    margin: 0 auto 25px;
    animation: spinNeon 1s linear infinite;
    filter: drop-shadow(0 0 15px #00ff00);
}
.loader-text {
    color: #fff;
    font-family: 'Courier New', monospace;
    font-size: 15px;
    font-weight: bold;
    letter-spacing: 3px;
    margin-bottom: 10px;
    text-shadow: 0 0 10px #00ff00;
}
.loader-countdown {
    color: #ee9601;
    font-size: 38px;
    font-weight: bold;
    font-family: Arial, sans-serif;
    text-shadow: 0 0 20px #ee9601;
    animation: pulseCustom 1s infinite alternate;
}

@keyframes spinNeon {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
@keyframes pulseCustom {
    0% { transform: scale(0.95); opacity: 0.8; }
    100% { transform: scale(1.1); opacity: 1; }
}
</style>

<?php include 'template/footer.php' ?>