<?php
require_once __DIR__ . '/../../../../function/connect.php';
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['extplayer'])) {
    echo json_encode([]);
    exit;
}

$id_user = $_SESSION['extplayer'];

/* ===== TOTAL WIN USER ===== */
$qTotal = mysqli_query($koneksi, "
    SELECT 
        COALESCE(SUM(nominal),0) AS total_win
    FROM tb_bonus
    WHERE id_user = '$id_user'
    AND id_bonus = '7'
");

$totalWin = (int) mysqli_fetch_assoc($qTotal)['total_win'];

/* ===== RANK USER ===== */
$qRank = mysqli_query($koneksi, "
    SELECT id_user, SUM(nominal) total
    FROM tb_bonus
    WHERE id_bonus = '7'
    GROUP BY id_user
    ORDER BY total DESC
");

$rank = 0;
$posisi = '50+';
$i = 1;

while ($r = mysqli_fetch_assoc($qRank)) {
    if ($r['id_user'] == $id_user) {
        $rank = $i;
        $posisi = $rank;
        break;
    }
    $i++;
}

/* ===== DATA USER ===== */
$qUser = mysqli_query($koneksi, "
    SELECT username, avatar
    FROM tb_user
    WHERE extplayer = '$id_user'
    LIMIT 1
");

$user = mysqli_fetch_assoc($qUser);

$username = $user['username'];
$masked   = substr($username,0,2).'****'.substr($username,-1);

/* ===== BONUS BASED ON RANK ===== */
$bonusMap = [
    1 => 100000,
    2 => 75000,
    3 => 65000,
    4 => 57500,
    5 => 52500
];

$bonus = $bonusMap[$rank] ?? 0;

echo json_encode([
    'username'   => $masked,
    'avatar'    => $user['avatar'] ?: 'default.png',
    'posisi'    => $posisi,
    'total_win' => $totalWin,
    'bonus'     => $bonus
]);