<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/games_helpers.php';
require_once __DIR__ . '/games_settings_helpers.php';

mocker_admin_require_permission('site');

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

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    $covers = mocker_games_covers_load();
    $settings = mocker_games_settings_load();
    echo json_encode(
        [
            'ok' => true,
            'covers' => $covers,
            'defaults' => mocker_games_covers_default(),
            'settings' => $settings,
            'settingsDefaults' => mocker_games_settings_default(),
        ],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    exit;
}

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

mocker_require_csrf_post();

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

try {
    $covers = null;
    $settings = null;

    if (isset($input['covers']) && is_array($input['covers'])) {
        $covers = mocker_games_covers_save($input['covers']);
    }
    if (isset($input['settings']) && is_array($input['settings'])) {
        $settings = mocker_games_settings_save($input['settings']);
    } elseif (isset($input['winChancePercent']) && is_array($input['winChancePercent'])) {
        $settings = mocker_games_settings_save(['winChancePercent' => $input['winChancePercent']]);
    }

    if ($covers === null && $settings === null) {
        throw new InvalidArgumentException('Kaydedilecek veri yok');
    }

    echo json_encode(
        [
            'ok' => true,
            'covers' => $covers ?? mocker_games_covers_load(),
            'settings' => $settings ?? mocker_games_settings_load(),
        ],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
} catch (InvalidArgumentException $e) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'validation', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'write'], JSON_UNESCAPED_UNICODE);
}
