<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/level_lib.php';

mocker_admin_require_permission('site');

header('Content-Type: application/json; charset=utf-8');

try {
    $pdo = mocker_db();
    mocker_level_migrate($pdo);
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    $settings = mocker_level_get_settings($pdo);
    $top = [];
    try {
        $st = $pdo->query(
            'SELECT s.user_id, u.username, s.level_no, s.xp_total
             FROM user_level_state s
             JOIN users u ON u.id = s.user_id
             ORDER BY s.level_no DESC, s.xp_total DESC
             LIMIT 20'
        );
        while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
            $top[] = [
                'userId' => (int) ($r['user_id'] ?? 0),
                'username' => (string) ($r['username'] ?? ''),
                'level' => (int) ($r['level_no'] ?? 0),
                'xp' => (int) ($r['xp_total'] ?? 0),
            ];
        }
    } catch (Throwable $e) {
        $top = [];
    }
    echo json_encode(
        [
            'ok' => true,
            'settings' => $settings,
            'topUsers' => $top,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

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

mocker_require_csrf_post();

$raw = json_decode((string) file_get_contents('php://input'), true);
$payload = is_array($raw) ? $raw : [];

try {
    $pdo->beginTransaction();
    $settings = mocker_level_upsert_settings($pdo, $payload);
    $pdo->commit();
    echo json_encode(['ok' => true, 'settings' => $settings], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'save_failed'], JSON_UNESCAPED_UNICODE);
}
