64 lines
2.0 KiB
PHP
64 lines
2.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
require_once __DIR__ . '/../lib/tetris_store.php';
|
|
|
|
function respond(int $status, array $payload): void
|
|
{
|
|
http_response_code($status);
|
|
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
|
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 12;
|
|
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
|
|
|
|
if ($id > 0) {
|
|
$score = tetrisFetchScore($id);
|
|
if (!$score) {
|
|
respond(404, ['success' => false, 'message' => 'Score not found.']);
|
|
}
|
|
|
|
respond(200, [
|
|
'success' => true,
|
|
'score' => $score,
|
|
'rank' => tetrisFetchScoreRank($id),
|
|
]);
|
|
}
|
|
|
|
respond(200, [
|
|
'success' => true,
|
|
'scores' => tetrisFetchTopScores($limit),
|
|
'recent' => tetrisFetchRecentScores(6),
|
|
]);
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
respond(405, ['success' => false, 'message' => 'Method not allowed.']);
|
|
}
|
|
|
|
$raw = file_get_contents('php://input');
|
|
$data = json_decode($raw ?: '{}', true);
|
|
if (!is_array($data)) {
|
|
respond(400, ['success' => false, 'message' => 'Invalid JSON payload.']);
|
|
}
|
|
|
|
$result = tetrisInsertScore($data);
|
|
respond(201, [
|
|
'success' => true,
|
|
'message' => 'Score submitted to the online leaderboard.',
|
|
'score' => $result['score'],
|
|
'rank' => $result['rank'],
|
|
'scores' => tetrisFetchTopScores(12),
|
|
]);
|
|
} catch (InvalidArgumentException $exception) {
|
|
respond(422, ['success' => false, 'message' => $exception->getMessage()]);
|
|
} catch (Throwable $exception) {
|
|
error_log('Tetris score API error: ' . $exception->getMessage());
|
|
respond(500, ['success' => false, 'message' => 'Leaderboard service is temporarily unavailable.']);
|
|
}
|