<?php
clearstatcache();
// Menangkap nilai parameter dari URL
$providerCode = isset($_GET['provider']) ? $_GET['provider'] : 'PRAGMATICLIVE';

ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../../config/koneksi.php');
$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;

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

<?php
error_reporting(E_ALL);

$validNotifications = [1];

$sql_m = "SELECT status FROM maintenance WHERE id = 1";
$result_m = $conn->query($sql_m);
if ($result_m && $result_m->num_rows > 0) {
    $row = $result_m->fetch_assoc();
    $status = isset($row["status"]) ? $row["status"] : 0;

    if ($status == 1) {
        // Mengarahkan pengguna kembali ke halaman sebelumnya
        echo "<script>window.history.back();</script>";
        // Menampilkan notifikasi dengan JavaScript
        echo "<script>alert('Halaman sedang dalam pemeliharaan. Kembali ke halaman sebelumnya.');</script>";
        exit();
    }
}
?>
<div class="container pt-1 sub-games">
    <div>
        <h3 class="title" i18n>LIVE </h3>
        <div class="row">
        </div>

       <div class="scroll-wrapper row" style="height:100%;">
    <div class="left">
        <button class="prev-btn btn" id="left-button"><i class="icon-keyboard_arrow_left"></i></button>
    </div>
    
    <div style="overflow:hidden;width:100%;" class="scroller">
        <?php
        // Fetch data from the tb_wprovider table dengan type='live' dan status=1
        $navbarQuery = "SELECT * FROM tb_wprovider 
                       WHERE type = 'live' AND status = 1 
                       ORDER BY COALESCE(sort_order, 0) ASC, cuid ASC";
        $navbarResult = mysqli_query($conn, $navbarQuery);
        
        if ($navbarResult && mysqli_num_rows($navbarResult) > 0) {
            echo '<div class="row no-gutters text-center slider-content">';
            
            while ($navbarRow = mysqli_fetch_assoc($navbarResult)) {
                // Cek apakah provider punya game
                $gameCheckQuery = "SELECT COUNT(*) as count FROM tb_gamelist 
                                  WHERE provider_code = '" . mysqli_real_escape_string($conn, $navbarRow['code']) . "' 
                                  AND (game_category = 'live' OR game_category = 'lc') AND status = 1";
                $gameCheckResult = mysqli_query($conn, $gameCheckQuery);
                $hasGames = false;
                if ($gameCheckResult) {
                    $gameCheckRow = mysqli_fetch_assoc($gameCheckResult);
                    $hasGames = (int)$gameCheckRow['count'] > 0;
                }
                
                // Hanya tampilkan jika punya game
                if ($hasGames) {
                    $isActive = (isset($_GET['provider']) && $_GET['provider'] == $navbarRow['code']) ? 'active' : '';
                    echo '<div class="col">';
                    echo '<a class="btn-box ' . $isActive . '" href="/m/casino/game/?provider=' . urlencode($navbarRow['code']) . '" rel="opener">';
                    
                    // Gunakan image dari database jika ada, jika tidak gunakan fallback
                    if (!empty($navbarRow['image'])) {
                        echo '<img alt="' . htmlspecialchars($navbarRow['name']) . '" src="' . htmlspecialchars($navbarRow['image']) . '" data-src="' . htmlspecialchars($navbarRow['image']) . '" height="60%" width="70%"/>';
                    } else {
                        // Fallback ke uploads/provider jika tidak ada image di database
                        $provider_image = strtolower(str_replace(' ', '-', $navbarRow['name'])) . '.png';
                        echo '<img alt="' . htmlspecialchars($navbarRow['name']) . '" src="'.site_url('uploads/provider/'.$provider_image).'" data-src="'.site_url('uploads/provider/'.$provider_image).'" height="60%" width="70%"/>';
                    }
                    echo '<div class="text-center fs-sm game-title">' . htmlspecialchars($navbarRow['name']) . '</div>';
                    echo '</a>';
                    echo '</div>';
                }
            }
            
            echo '</div>';
        } else {
            echo '<div class="row no-gutters text-center slider-content">';
            echo '<div class="col"><p class="text-muted">Tidak ada provider tersedia</p></div>';
            echo '</div>';
        }
        ?>
    </div>

    <div class="right">
        <button class="next-btn btn" id="right-button"><i class="icon-keyboard_arrow_right"></i></button>
    </div>
</div>
</div>
    <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"
                        [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 class="col-xs-1 text-right">
            <button class="btn btn-clear" id="btnFilters_003" data-filter="" data-trigger='nifty'
                data-target='#searchModal'><i class="icon-magnifier"></i></button>
        </div>
        <div class="col-xs-1 text-right">
            <button class="btn btn-clear" id="btnFilters_003" data-filter="" data-trigger='nifty'
                data-target='#filterModal-2'><i class="icon-equalizer2"></i></button>
        </div>
    </div>
    <div class="mobile-border"></div>
    <div class="mobile-border"></div>
    <br />
        <div class="row">
        <div class="col-md-6 offset-md-3">
            <input type="text" id="searchInput" class="form-control" placeholder="Cari game..." onkeyup="handleSearch()">
        </div>
    </div>
    <br/>
    <input type="hidden" value="pp_slots" name="hiddenGameID-001" id="hiddenGameID-001">
    <div class="row games no-gutters">
    <?php
        // Ambil provider code dari URL parameter
        $providerCode = isset($_GET['provider']) ? trim($_GET['provider']) : '';
        
        if (empty($providerCode)) {
            echo '<div class="col-xs-12"><div class="alert alert-warning text-center"><p>Provider tidak ditemukan.</p></div></div>';
        } else {
            // Escape untuk keamanan
            $providerCode = mysqli_real_escape_string($conn, $providerCode);
            
            $sql_3 = mysqli_query($conn, "SELECT * FROM `tb_gamelist` 
                                          WHERE provider_code = '$providerCode' 
                                          AND (game_category = 'live' OR game_category = 'lc') 
                                          AND status = 1 
                                          ORDER BY sort_order ASC, game_name ASC") or die(mysqli_error($conn));
            
            if (mysqli_num_rows($sql_3) == 0) {
                echo '<div class="col-xs-12"><div class="alert alert-info text-center"><p>Tidak ada game live casino tersedia untuk provider ini.</p></div></div>';
            } else {
                while($s3 = mysqli_fetch_array($sql_3)){
                //var_dump($s3);
                if(isset($_SESSION['user'])){
                    $externalPlayerId = $_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);
                $progressBarId = 'progress-bar-' . uniqid();                
                if ($random < 50) {
                    $warna = 'red'; // Merah untuk nilai di bawah 50
                } else if ($random >= 50 && $random < 75) {
                    $warna = 'orange'; // Orange untuk nilai di antara 50 dan 75
                } else {
                    $warna = 'green'; // Hijau untuk nilai di atas 75
                }
                ?>
                <a class="col-xs-4 col-md-3 game-box text-center" href="<?php echo $playUrl; ?>"
                   data-title="<?php echo htmlspecialchars($s3['game_name']); ?>" data-filter="ALL,Video Slots,TOP,Buy Bonus Feature"
                   [ngClass]="{'flex-grow-2' : game.FlexGrow =='2'}"
                   onclick="showGameLinks(event, '<?php echo htmlspecialchars($s3['game_name']); ?>', '<?php echo htmlspecialchars($s3['banner']); ?>')">
                    <div class="content-wrapper" style="width: 100%; aspect-ratio: 1/1; border: 1px solid #333; display: flex; align-items: center; justify-content: center; overflow: hidden; background: #000; border-radius: 8px; position: relative;">
                        <div class="daily-wins-tag"></div>
                        <img width="100%" height="100%" class="lazy" style="border: 1px solid transparent; object-fit: cover; position: absolute; top: 0; left: 0;" data-src="<?php echo htmlspecialchars($s3['banner']); ?>" alt="<?php echo htmlspecialchars($s3['game_name']); ?>">
                    </div>
                    <h5 data-title="<?php echo htmlspecialchars($s3['game_name']); ?>" style="font-size: 11px; margin-top: 5px; height: 25px; overflow: hidden; text-overflow: ellipsis;"><?php echo htmlspecialchars($s3['game_name']); ?></h5>
                </a>
            <?php 
                } // End while loop
            } // End else (mysqli_num_rows check)
        } // End else block (empty providerCode check)
        ?>
    </div>

    <?php include "../footer.php";?>