<?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 SESSION
 *************************/
$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/slot';
$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);
}

if (CACHE_ENABLE && CACHE_ALLOW_REFRESH && (!file_exists($cacheFile) || (time() - filemtime($cacheFile)) > CACHE_TIME)) {
    $response = nexusGetGameList($id_provider);
    file_put_contents($cacheFile, json_encode($response));
}

$games = (isset($response['status']) && $response['status'] == 1 && !empty($response['games'])) ? $response['games'] : [];
$games = array_slice($games, 0, 700);

/*************************
 * LOGIKA PEMAIN (1.000 - 2.000++)
 *************************/
function getFakePlayersDynamic($gameCode) {
    $base = 1000; // Minimal 1.000
    $seed = hexdec(substr(md5($gameCode), 0, 4));
    $game_variance = $seed % 1500; // Variasi max sampai 2.500
    
    // Efek naik turun tiap menit (Dynamic)
    $minute = (int)date('i');
    $fluctuation = ($minute % 2 == 0) ? rand(30, 150) : rand(-150, -30);
    
    $total = $base + $game_variance + $fluctuation;
    return ($total < 1000) ? 1000 + rand(1, 50) : $total;
}

/*************************
 * SORT & PREPARE DATA
 *************************/
foreach ($games as &$g) {
    $score = 999;
    $name  = strtolower($g['game_name']);
    if (isset($priorityGames)) {
        foreach ($priorityGames as $i => $keyword) {
            if (strpos($name, $keyword) !== false) { $score = $i; break; }
        }
    }
    $g['priority_score'] = $score;
    $g['fake_players'] = getFakePlayersDynamic($g['game_code']);
}
unset($g);

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

<?php foreach ($games as $i => $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 <?= $i >= 60 ? 'hidden' : '' ?>" 
     data-index="<?= $i ?>" 
     data-name="<?= strtolower($game['game_name']); ?>">
    
    <div class="sgx-player-badge">
        <i class="fa fa-user"></i>
        <?= number_format($game['fake_players'], 0, ',', '.'); ?>
    </div>

    <div class="sgx-game-thumb">
        <img src="<?= htmlspecialchars($game['banner']); ?>" loading="lazy" alt="<?= 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; ?>
<div id="loadMoreTrigger"></div>
