<?php
declare(strict_types=1);

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

mocker_admin_require_permission('wheel');

require_once __DIR__ . '/wheel_helpers.php';

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

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

if ($method === 'GET') {
    $cfg = mocker_wheel_load_config();
    echo json_encode(
        [
            'ok' => true,
            'cooldown_hours' => $cfg['cooldown_hours'],
            'prizes' => $cfg['prizes'],
            'cooldown_seconds' => $cfg['cooldown_seconds'],
            'enabled' => $cfg['enabled'],
        ],
        JSON_UNESCAPED_UNICODE
    );
    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) ?: [];
$cfg = mocker_wheel_load_config();
$h = isset($input['cooldown_hours']) ? (int) $input['cooldown_hours'] : $cfg['cooldown_hours'];
$h = max(1, min(168, $h));
if (isset($input['prizes'])) {
    $prizesIn = $input['prizes'];
    if (!is_array($prizesIn) || count($prizesIn) !== 6) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'prizes'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $prizesIn = array_map('intval', $prizesIn);
} else {
    $prizesIn = $cfg['prizes'];
}
$enabledArg = array_key_exists('enabled', $input) ? (bool) $input['enabled'] : null;

if (!mocker_wheel_save_config($h, $prizesIn, $enabledArg)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'write'], JSON_UNESCAPED_UNICODE);
    exit;
}

$cfg = mocker_wheel_load_config();
echo json_encode(
    [
        'ok' => true,
        'cooldown_hours' => $cfg['cooldown_hours'],
        'prizes' => $cfg['prizes'],
        'cooldown_seconds' => $cfg['cooldown_seconds'],
        'enabled' => $cfg['enabled'],
    ],
    JSON_UNESCAPED_UNICODE
);
