<?php    
header('Content-Type: application/json');    
include 'config.php';    
    
$type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : '';    
    
if ($type === 'leaderboard') {    
    
    // Top 100 users (Order remains same: highest total_win first)  
    $sql = "SELECT username, total_play, total_win, profile_pic, verify_badge,  
                   @rownum := @rownum + 1 AS position    
            FROM users, (SELECT @rownum := 0) r    
            ORDER BY total_win DESC    
            LIMIT 100";    
    
    $result = $conn->query($sql);    
    
    $leaderboard = [];    
    while ($row = $result->fetch_assoc()) {    
        $leaderboard[] = [    
            "username" => $row['username'],    
            "total_win" => (int) floatval($row['total_win']),    
            "profile_pic" => $row['profile_pic'],  
            "total_play" => $row['total_play'],    
            "verify_badge" => $row['verify_badge'],   // ← added  
            "position" => (int)$row['position']    
        ];    
    }    
    
    echo !empty($leaderboard)     
        ? json_encode($leaderboard, JSON_UNESCAPED_UNICODE)     
        : json_encode(["message" => "No Users Found"]);    
    mysqli_close($conn);    
    exit;    
}    
    
    
// ======================= USER POSITION =======================    
if ($type === 'position' && isset($_REQUEST['username'])) {    
    $username_param = trim($_REQUEST['username']);    
    if ($username_param === "") {    
        echo json_encode(["message" => "Username required"]);    
        mysqli_close($conn);    
        exit;    
    }    
    
    $sql = "SELECT username, total_play, total_win, profile_pic, verify_badge, position FROM (    
                SELECT username, total_play, total_win, profile_pic, verify_badge,  
                       @rownum2 := @rownum2 + 1 AS position    
                FROM users, (SELECT @rownum2 := 0) r    
                ORDER BY total_win DESC   -- order unchanged  
            ) t    
            WHERE username = ? LIMIT 1";    
    
    $stmt = $conn->prepare($sql);    
    $stmt->bind_param("s", $username_param);    
    $stmt->execute();    
    $res = $stmt->get_result();    
    if ($res->num_rows === 0) {    
        echo json_encode(["message" => "User Not Found"]);    
        $stmt->close();    
        mysqli_close($conn);    
        exit;    
    }    
    
    $row = $res->fetch_assoc();    
    echo json_encode([    
        "username" => $row['username'],    
        "total_win" => (int) floatval($row['total_win']),    
        "profile_pic" => $row['profile_pic'],   
        "total_play" => $row['total_play'],   
        "verify_badge" => $row['verify_badge'],  // ← added  
        "position" => (int)$row['position']    
    ], JSON_UNESCAPED_UNICODE);    
    
    $stmt->close();    
    mysqli_close($conn);    
    exit;    
}    
    
echo json_encode(["message" => "Invalid Request"]);    
mysqli_close($conn);    
exit;    
?>