<?php
include('../../config/koneksi.php');
$providerCode = $_GET['provider'] ?? '';
?>
<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
$sid = session_id();
$sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);

if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../../config/url_helper.php');
}
$urlweb = get_active_base_url();
$urlwebs = $urlweb;
$pengguna = $s0['user'];
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d');

include "../header.php";
?>

<div class="container pt-1 sub-games">
    <div class="row no-gutters filter">
        <div class="col-xs-10 text-center">
            <div class="row">
                <div class="col-xs-3">
                    <button class="btn btn-clear f" data-filter="NEW"
                        <a class="navlink" href="javascript:void(0);"
                        [ngClass]="{ 'active': filterProperty==FilterType.New  }">BARU</button>
                </div>
                <div class="col-xs-3">
                    <button class="btn btn-clear f" data-filter="TOP"
                        [ngClass]="{ 'active': filterProperty==FilterType.TOP }">TOP</button>
                </div>
                <div class="col-xs-3">
                    <button class="btn btn-clear  f" data-filter="ALL"
                        [ngClass]="{ 'active': filterProperty==FilterType.All  }">SEMUA </button>
                </div>
            </div>
        </div>
    </div>
    <div class="mobile-border"></div>
    <div class="mobile-border"></div>
    <br>
    <input type="hidden" value="pgsoft_slot" name="hiddenGameID-001" id="hiddenGameID-001">
    <!-- Daftar game-->
    <div class="row games no-gutters">
        <?php
        // 1. Pengaturan Prioritas Game (Urutan tampil dari kiri ke kanan / atas ke bawah)
        $priorityGames = [
            'PR' => [
                "Gates of Olympus Super Scatter",
                "Gates of Olympus 1000",
                "Mahjong Wins Super Scatter",
                "Sweet Bonanza Super Scatter",
                "Starlight Princess 1000",
                "Sweet Bonanza 1000",
                "Gates of Gatot Kaca Super Scatter",
                "Starlight Princess Super Scatter",
                "Wisdom of Athena 1000 Xmas",
                "Gates of Olympus",
                "Gates of Gatot Kaca 1000",
                "Sugar Rush 1000",
                "Starlight Archer 1000",
                "Mahjong wins 2",
                "Starlight Princess",
                "Mahjong Wins – Gong Xi Fa Cai",
                "Wisdom of Athena 1000",
                "Sweet Rush Bonanza",
                "Gates of Olympus Xmas 1000",
                "Gates of Pyroth",
                "Wild West Gold Blazing Bounty",
                "Wrath of Nezha",
                "Wheel of Happiness",
                "Joker's Jewels Hot",
                "Anaconda Gold",
                "Hammerstorm",
                "Big Bass Splash 1000",
                "Bloody Dawn",
                "Sweet Craze",
                "Zeus vs Typhon"
            ],
            'HB' => [
                "Koi Gate",
                "Hot Hot Fruit",
                "Fa Cai Shen",
                "Fa Cai Shen Deluxe",
                "Wild Trucks",
                "Lucky Lucky",
                "Wealth Inn",
                "Fortune Dogs",
                "5 Lucky Lions",
                "Dragon’s Throne",
                "Four Divine Beasts",
                "Zeus",
                "Laughing Buddha",
                "Mount Mazuma",
                "Pumpkin Patch",
                "JellyFish Flow",
                "Lucky Fortune Cat",
                "Bird of Thunder",
                "Orbs of Atlantis",
                "Colossal Gems"
            ],
            'PG' => [
                "Mahjong Ways",
                "Mahjong Ways 2",
                "Wild Bounty Showdown",
                "Wild Bandito",
                "Lucky Neko",
                "Treasures of Aztec",
                "Ways of the Qilin",
                "Wild Ape #3258",
                "Gemstones Gold",
                "Pinata Wins",
                "Cocktail Nights",
                "Anubis Wrath",
                "Jurassic Kingdom",
                "Geisha's Revenge",
                "Queen of Bounty",
                "Dragon Hatch 2",
                "Majestic Empire",
                "The Great Icescape"
            ],
            'JK' => [
                "Roma",
                "Roma X",
                "Wild Giant Panda",
                "Tai Shang Lao Jun",
                "Golden Dragon",
                "Bagua",
                "Horus Eye",
                "Chilli Hunter",
                "Burning Pearl",
                "Treasures of Cleopatra",
                "Crypto Mania",
                "Lady Hawk",
                "Safari Life",
                "Captains Treasure",
                "Witch’s Brew",
                "Neptune Treasure",
                "Ong Bak",
                "Power Stars",
                "Third Prince’s Journey",
                "She-Nanigans"
            ],
        ];

        $currentPriority = isset($priorityGames[$providerCode]) ? $priorityGames[$providerCode] : [];

        if (!empty($currentPriority)) {
            $quotedGames = "'" . implode("','", array_map(function ($g) use ($conn) {
                return mysqli_real_escape_string($conn, $g);
            }, $currentPriority)) . "'";

            $orderBy = "ORDER BY (CASE WHEN game_name IN ($quotedGames) THEN 0 ELSE 1 END) ASC, 
                             FIELD(game_name, $quotedGames) ASC, 
                             sort_order ASC, 
                             game_name ASC";
        } else {
            $orderBy = "ORDER BY sort_order ASC, game_name ASC";
        }

        $sql_3 = $conn->prepare("SELECT * FROM `tb_gamelist` WHERE game_category = 'slot' AND provider_code = ? AND status = 1 $orderBy");
        mysqli_stmt_bind_param($sql_3, "s", $providerCode);
        mysqli_stmt_execute($sql_3);
        $result_3 = mysqli_stmt_get_result($sql_3);

        while ($s3 = mysqli_fetch_array($result_3)) {
            // Logika URL dan Warna (Tetap sama seperti kode asli) 
            if (isset($_SESSION['user'])) {
                $playUrl = site_url('gameplay/opengame/?gamecode=' . $s3['game_code'] . '&providercode=' . $s3['provider_code']);
            } else {
                $playUrl = site_url('m/?notif=6');
            }
            $random = mt_rand(40, 100);
            $warna = ($random < 50) ? 'red' : (($random < 75) ? 'orange' : 'green');
        ?>

            <a class="col-xs-4 col-md-3 game-box text-center" href="<?php echo $playUrl; ?>"
                data-title="<?php echo $s3['game_name']; ?>" data-filter="ALL,Video Slots,TOP,Buy Bonus Feature"
                [ngClass]="{'flex-grow-2' : game.FlexGrow =='2'}"
                onclick="showGameLinks(event, '<?php echo $s3['game_name']; ?>', '<?php echo $s3['banner']; ?>')">
                <div class="content-wrapper">

                    <img width=120 height=120 class="lazy" data-src="<?php echo $s3['banner']; ?>">
                </div>
                <h5 data-title="<?php echo $s3['game_name']; ?>"><?php echo $s3['game_name']; ?></h5>

            </a>
        <?php } ?>
        <style></style>
        <div class="nifty-modal slide-in-bottom " id="gamelinksModal-1">
            <div class="md-content">
                <div class="md-body">
                    <div class="row mb-4 no-gutters">
                        <div class="col-xs-5">
                            <img src="" class="img-fluid">
                        </div>
                        <div class="col-xs-7">
                            <div class="g-title"></div>
                        </div>
                        <input type="hidden" value="" name="hiddenGameCode001" id="hiddenGameCode001">
                        <input type="hidden" value="" name="hiddenSubGameCode001" id="hiddenSubGameCode001">

                    </div>

                    <div class="row  pt-2">
                        <div class="col-xs-5">
                        </div>
                        <div class="col-xs-7   ">
                            <button class="btn  btn-block btn-primary" onclick="subGameLaunch(event,001)" i18n="@PlayNow">
                                MAIN SEKARANG </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="md-overlay"></div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            function handleSearch() {
                var searchKeyword = $('#searchInput').val().toLowerCase();
                $('#gameList a').hide();
                $('#gameList a').each(function() {
                    var gameName = $(this).find('h5').text().toLowerCase();
                    if (gameName.indexOf(searchKeyword) !== -1) {
                        $(this).show();
                    }
                });
            }
        </script>

        <div class="nifty-modal slide-in-bottom " id="filterModal-2">
            <div class="md-content">
                <div class="md-body">
                    <div>
                        <p id="" i18n>Select a filter : </label>
                    </div>
                    <div>
                        <button class="btn btn-primary" id="btnApplyFilter_01">APPLY</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="md-overlay"></div>

        <script>
            var joinedJpIds = "";
            var gameCode = "pgsoft_slot";

            function showGameLinks(e, name, imgSrc, gameCode, subCode) {

                $('#gamelinksModal-1 .g-title').text(name);
                $('#gamelinksModal-1 img').attr('src', imgSrc);
                $('#hiddenGameCode001').val(gameCode);
                $('#hiddenSubGameCode001').val(subCode);
                $('#gamelinksModal-1').nifty("show");
            }


            $(document).ready(function() {
                var hotGame = '';

                if (hotGame) {
                    $('.game-box').each(function() {
                        var isMatch = hotGame == $(this).data('title');
                        if (isMatch) {
                            $(this).trigger('click');
                            return false;
                        }
                    });
                }

                /*search*/
                $('.search').keyup(function() {

                    var value = $(this).val().toLowerCase();
                    var exp = new RegExp(value);
                    $('.game-box').each(function() {
                        var isMatch = exp.test(((typeof $(this).find('h5').data('title') == 'string') ? $(this).find('h5').data('title').toLowerCase() : $(this).find('h5').data('title')));
                        $(this).toggle(isMatch);
                    });
                });
                $('.srch_button').click(function() {
                    $('.search').val("");
                    $('.search').trigger("keyup");
                });
                /*search end*/


                $('.sub-games .filter .top').addClass('active');

                function filterGameBoxes(self) {

                    $('.sub-games .filter .btn').removeClass('active');
                    $(self).addClass('active');
                    var filterType = $(self).data('filter');

                    $('.sub-games .game-box').hide();
                    $('.sub-games .game-box').filter(function() {
                        return $(this).data("filter").indexOf(filterType) >= 0;
                    }).show();

                }


                //Default to Top Games :
                if (gameCode === 'pgsoft_slot') {
                    filterGameBoxes($('.sub-games .filter .btn[data-filter=TOP]')[0]);
                } else {
                    filterGameBoxes($('.sub-games .filter .btn[data-filter=ALL]')[0]);
                }

                //Add filter btn event listen
                $('.sub-games .filter .btn.f').click(function() {

                    filterGameBoxes(this);
                })

                $('#btnApplyFilter_01').click(function() {

                    var selFilter = $('input[name="rdFilterSubGames"]:checked').val();
                    var e = $('#btnFilters_003')[0];
                    $(e).data('filter', selFilter);
                    filterGameBoxes(e);
                    $('#filterModal-2').nifty('hide');


                })


                if (joinedJpIds) {
                    var url = "https://jpn-ticker-gcp-str.hep200512.com/v1/ticker?currency=" + window.currencyCode + "&jackpotIds=" + joinedJpIds;


                    if ($.ajaxSettings && $.ajaxSettings.headers) {
                        delete $.ajaxSettings.headers["X-CSRF-TOKEN"];
                        // console.log("remove X-CSRF-TOKEN header");
                        // alert("remove X-CSRF-TOKEN header");
                    }
                    $.ajax({
                            url: url,
                            type: 'GET',
                            dataType: 'json',
                            headers: {

                            },
                            beforeSend: function(jqXHR, settings) {

                            }
                        })
                        .done(function(data) {
                            if (data && data.length > 0) {
                                //console.log(data);
                                for (let i = 0; i < data.length; i++) {
                                    var jp = data[i];
                                    if (jp.jackpotId && jp.pools) {
                                        var pool = jp.pools;
                                        for (var key in pool) {
                                            if (pool.hasOwnProperty(key)) {
                                                var amt = pool[key].amount;

                                                if (amt > 0) {
                                                    // console.log(amt);

                                                    amt = amt.toString()
                                                    $('[data-jpid="' + jp.jackpotId + '"]').find('.amount_box').text(window.currencyCode + ' ' + window.formatNumber(amt)).show();

                                                    $('[data-jpid="' + jp.jackpotId + '"]').find('.amount_box').each(function() {
                                                        $(this).prop('Counter', 0).animate({
                                                            Counter: amt
                                                        }, {
                                                            duration: 7000,
                                                            step: function(func) {
                                                                $(this).text(window.currencyCode + ' ' + window.formatNumber(func.toString()));
                                                            }
                                                        });
                                                    });
                                                }
                                            }
                                            break;
                                        }
                                    }

                                }


                            }



                        });
                    if ($.ajaxSettings && $.ajaxSettings.headers) {

                        $.ajaxSettings.headers["X-CSRF-TOKEN"] = $('meta[name="csrf-token"]').attr('content');
                        console.log("add back X-CSRF-TOKEN  header");
                        alert("add back X-CSRF-TOKEN header");
                    }
                }

            });
        </script>
    </div>
    <?php include "../footer.php"; ?>