<?php
require_once __DIR__ . '/../../../../../function/connect.php';
require_once __DIR__ . '/../../../../../play/game/functions.php';
require_once __DIR__ . '/../../../../../play/game/config.php';

if (!isset($koneksi)) {
    exit('DB NOT CONNECTED');
}

/***********************
 * USER
 ***********************/
$user      = $_SESSION['username'] ?? '';
$extplayer = '';

if ($user !== '') {
    $safeUser = mysqli_real_escape_string($koneksi, $user);
    $qUser    = mysqli_query(
        $koneksi,
        "SELECT extplayer FROM tb_user WHERE username='$safeUser' LIMIT 1"
    );
    if ($qUser && mysqli_num_rows($qUser) > 0) {
        $infouser  = mysqli_fetch_assoc($qUser);
        $extplayer = $infouser['extplayer'] ?? '';
    }
}

/***********************
 * GET GAME FROM CACHE
 ***********************/
$cacheDir  = __DIR__ . '/cache/casino';
$cacheFile = $cacheDir . '/game_' . $id_provider . '.json';

if (!is_dir($cacheDir)) {
    mkdir($cacheDir, 0755, true);
}

$response = [];

if (CACHE_ENABLE && file_exists($cacheFile)) {
    $response = json_decode(file_get_contents($cacheFile), true);
}

$allowRefresh =
    CACHE_ENABLE &&
    CACHE_ALLOW_REFRESH &&
    (
        !file_exists($cacheFile) ||
        (time() - filemtime($cacheFile)) > CACHE_TIME
    );

if ($allowRefresh) {
    $response = nexusGetGameList($id_provider);
    file_put_contents($cacheFile, json_encode($response));
}

/***********************
 * VALIDASI GAME
 ***********************/
$games = [];

if (
    isset($response['status']) &&
    $response['status'] == 1 &&
    !empty($response['games']) &&
    is_array($response['games'])
) {
    $games = $response['games'];
}

/***********************
 * PLAYER COUNT
 ***********************/
function getActivePlayersFast(string $gameName, array $playersSetting): int
{
    $name = strtolower($gameName);
    foreach ($playersSetting as $key => $range) {
        if (strpos($name, $key) !== false) {
            return rand($range[0], $range[1]);
        }
    }
    return rand(0, 20);
}

$playerCount = [];
foreach ($games as $g) {
    $playerCount[$g['game_code']] =
        getActivePlayersFast($g['game_name'], $playersSetting);
}

/***********************
 * SORT PRIORITY
 ***********************/
foreach ($games as &$g) {
    $score = 999;
    $name  = strtolower($g['game_name']);

    foreach ($priorityGames as $i => $keyword) {
        if (strpos($name, $keyword) !== false) {
            $score = $i;
            break;
        }
    }
    $g['priority_score'] = $score;
}
unset($g);

usort($games, fn($a, $b) => $a['priority_score'] <=> $b['priority_score']);
?>

<!-- ================= GAME LIST ================= -->
<?php foreach ($games as $game): ?>

<?php
$link_url = ($user === '')
    ? 'index.php?pesan=28'
    : "?page=playgame"
        . "&provider=" . strtoupper($id_provider)
        . "&game_code=" . urlencode($game['game_code'])
        . "&p=" . urlencode($extplayer)
        . "&ln=id";
?>

<div class="sgx-game-card" data-name="<?= strtolower($game['game_name']); ?>">

    <div class="sgx-player-badge">
        <i class="fa fa-user"></i>
        <?= $playerCount[$game['game_code']] ?? 0; ?>
    </div>
    
    <div class="sgx-game-thumb">
        <img
            src="<?= htmlspecialchars($game['banner']); ?>"
            loading="lazy"
            alt="<?= htmlspecialchars($game['game_name']); ?>">
    </div>

    <!--   <div class="sgx-game-provider">
   <?= strtoupper(htmlspecialchars($game['game_name'])); ?> 
    </div> -->

    <a href="<?= $link_url; ?>" class="sgx-game-hover">
        <div class="game-thumb"></div>
        <div class="game-hover-overlay">
            <div class="play-content">
                <i class="fa fa-play"></i>
            </div>
        </div>
    </a>

</div>
<?php endforeach; ?>


