2025-12-20 15:34:12 +07:00

52 lines
1.4 KiB
PHP

<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../database/db_connect.php';
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
// Get Top 10 Scores
// Join with users table to get username
$sql = "SELECT users.username, scores.score, scores.level
FROM scores
JOIN users ON scores.user_id = users.id
ORDER BY scores.score DESC
LIMIT 10";
$stmt = $pdo->query($sql);
$data = [];
$rank = 1;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['rank'] = $rank++;
$data[] = $row;
}
echo json_encode(['success' => true, 'data' => $data]);
} elseif ($method === 'POST') {
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => 'Not logged in']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$score = intval($input['score'] ?? 0);
$level = intval($input['level'] ?? 1);
if ($score <= 0) {
echo json_encode(['ok' => true]);
exit;
}
$stmt = $pdo->prepare("INSERT INTO scores (user_id, score, level) VALUES (?, ?, ?)");
if ($stmt->execute([$_SESSION['user_id'], $score, $level])) {
echo json_encode(['ok' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Failed to save score']);
}
}
?>