<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once "koneksi.php";

$nama = "";
if (isset($_SESSION['username'])) {
    $nama = (string)$_SESSION['username'];
}

$score = 0;

if (!empty($nama)) {
    $getScore = "SELECT score FROM users WHERE username = '" . mysqli_real_escape_string($koneksi, $nama) . "'";
    $resultMe = mysqli_query($koneksi, $getScore);
    if ($resultMe && mysqli_num_rows($resultMe) > 0) {
        $row = mysqli_fetch_assoc($resultMe);
        $score = (int)$row['score'];
    }
}

$sql = "SELECT username, score FROM users ORDER BY score DESC LIMIT 10";
$result = mysqli_query($koneksi, $sql);
$leaderboard = [];

if($result && mysqli_num_rows($result) > 0) {
    $leaderboard = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
?>


<!DOCTYPE html>
<html lang="id">
    <style>
        .container {
            padding: 10px;
            justify-items: center;
            justify-self: center;
            border-radius: 7pt;
            width: 540px;
            height: 540px;
            background-image: url("leaderboard/Leaderboard.png");
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
        body {
            height: 568px;
            background-color: rgb(24, 24, 24);
        }
        table {
            margin-top: 20px;
        }
    </style>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaderboard</title>
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="">
</head>
<body>
    <div class=container>
        <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Username</th>
                <th>Score</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $peringkat = 1;
            if (!empty($leaderboard) && is_array($leaderboard)) {
                foreach ($leaderboard as $pemain):
            ?>

            <tr>
                <td><?php echo $peringkat; ?></td>
                <td><?php echo htmlspecialchars($pemain['username']); ?></td>

                <td><?php echo (int)$pemain['score']; ?> PTS</td>
                
            </tr>

        <?php
            $peringkat++;
            endforeach;
        } else {
            echo '<tr><td colspan="3" style="text-align: center;">Belum ada Pemain</td></tr>';
        }
        
        ?>
        </tbody>
        
    </table>
    </div>
</body>
</html>