<?php
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');

$catalog = ugfx_games_catalog();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $publicGames = ugfx_games_for_public();
    $game = trim((string)($_GET['game'] ?? ''));
    if ($game !== '' && isset($publicGames[$game])) {
        echo json_encode([
            'ok' => true,
            'game' => $publicGames[$game],
            'leaderboard' => ugfx_game_leaderboard($game, 10),
            'stats' => ugfx_game_stats()[$game] ?? [],
        ], JSON_UNESCAPED_SLASHES);
        exit;
    }
    $leaderboards = [];
    foreach ($publicGames as $id => $cfg) {
        $leaderboards[$id] = ugfx_game_leaderboard($id, 10);
    }
    echo json_encode([
        'ok' => true,
        'games' => array_values($publicGames),
        'leaderboards' => $leaderboards,
        'stats' => ugfx_game_stats(),
        'meta' => ugfx_game_meta(),
    ], JSON_UNESCAPED_SLASHES);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw ?: '{}', true);
if (!is_array($data)) $data = [];
$action = trim((string)($data['action'] ?? $_POST['action'] ?? 'submit'));
if ($action !== 'submit') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'message' => 'Unsupported action.']);
    exit;
}
$gameId = trim((string)($data['game'] ?? $_POST['game'] ?? ''));
$name = trim((string)($data['name'] ?? $_POST['name'] ?? 'Guest'));
$score = (int)($data['score'] ?? $_POST['score'] ?? 0);
$extra = is_array($data['extra'] ?? null) ? $data['extra'] : [];
$result = ugfx_game_submit_score($gameId, $name, $score, $extra);
if (empty($result['ok'])) http_response_code(422);
echo json_encode($result, JSON_UNESCAPED_SLASHES);
