<?php
header('Content-Type: application/json'); // Response berupa JSON
require 'Connection.php';                 // Koneksi database
session_start();                          // Ambil session user login

// Response default
$response = [
    "status" => "error",
    "leaderboard" => [],
    "user_rank" => null
];

// Ambil Top 10 Leaderboard Global
// Urut score terbesar
$query = "
    SELECT username, score 
    FROM leaderboard 
    ORDER BY score DESC, user_id ASC 
    LIMIT 10
";
$result = $conn->query($query);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $response['leaderboard'][] = $row;
    }
}

// Ambil Ranking User yang Sedang Login (your rank)
if (isset($_SESSION['user_id'])) {
    $my_id = $_SESSION['user_id'];

    // Ambil username & score user
    $scoreQuery = $conn->prepare("
        SELECT username, score 
        FROM leaderboard 
        WHERE user_id = ?
    ");
    $scoreQuery->bind_param("i", $my_id);
    $scoreQuery->execute();
    $scoreResult = $scoreQuery->get_result();

    if ($scoreRow = $scoreResult->fetch_assoc()) {
        $myScore = $scoreRow['score'];
        $myUsername = $scoreRow['username'];

        // Hitung jumlah user yang berada di atas
        $rankQuery = $conn->prepare("
            SELECT COUNT(*) AS rank_above
            FROM leaderboard
            WHERE score > ?
               OR (score = ? AND user_id < ?)
        ");
        $rankQuery->bind_param("iii", $myScore, $myScore, $my_id);
        $rankQuery->execute();
        $rankResult = $rankQuery->get_result();
        $rankRow = $rankResult->fetch_assoc();

        // Rank = jumlah di atas + 1
        $response['user_rank'] = [
            "username" => $myUsername,
            "score" => $myScore,
            "rank" => $rankRow['rank_above'] + 1
        ];
    }
}

// Status sukses
$response['status'] = "success";

// Kirim JSON ke client
echo json_encode($response);

// Tutup koneksi database
$conn->close();
?>