<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: public, max-age=60');
header('X-Content-Type-Options: nosniff');

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

require_once __DIR__ . '/db.php';

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    echo json_encode(
        [
            'ok' => true,
            'users' => [],
            'warning' => 'db',
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

try {
    $limit = 20;
    $rows = $pdo->query(
        'SELECT id, username, coins FROM users ORDER BY coins DESC, id ASC LIMIT ' . (int) $limit
    )->fetchAll(PDO::FETCH_ASSOC);

    $users = [];
    $rank = 1;
    foreach ($rows as $row) {
        $users[] = [
            'rank' => $rank,
            'username' => (string) $row['username'],
            'coins' => (int) $row['coins'],
        ];
        $rank++;
    }

    echo json_encode(
        [
            'ok' => true,
            'users' => $users,
        ],
        JSON_UNESCAPED_UNICODE
    );
} catch (Throwable $e) {
    echo json_encode(
        [
            'ok' => true,
            'users' => [],
            'warning' => 'query',
        ],
        JSON_UNESCAPED_UNICODE
    );
}
