<?php
declare(strict_types=1);

function mocker_wheel_config_path(): string
{
    return dirname(__DIR__) . '/data/wheel.json';
}

function mocker_wheel_default_prizes(): array
{
    return [10, 25, 50, 75, 100, 0];
}

function mocker_wheel_normalize_prizes(array $prizes): array
{
    $defaults = mocker_wheel_default_prizes();
    if (count($prizes) !== 6) {
        return $defaults;
    }
    $out = [];
    foreach ($prizes as $p) {
        $n = (int) $p;
        if ($n < 0 || $n > 99999999) {
            return $defaults;
        }
        $out[] = $n;
    }

    return $out;
}

function mocker_wheel_load_config(): array
{
    $defaults = [
        'cooldown_hours' => 24,
        'prizes' => mocker_wheel_default_prizes(),
        'enabled' => true,
    ];
    $path = mocker_wheel_config_path();
    if (!is_readable($path)) {
        return $defaults + ['cooldown_seconds' => $defaults['cooldown_hours'] * 3600];
    }
    $raw = @file_get_contents($path);
    $j = json_decode((string) $raw, true);
    if (!is_array($j)) {
        return $defaults + ['cooldown_seconds' => $defaults['cooldown_hours'] * 3600];
    }
    $h = (int) ($j['cooldown_hours'] ?? 24);
    if ($h < 1 || $h > 168) {
        $h = 24;
    }
    $prizes = isset($j['prizes']) && is_array($j['prizes'])
        ? mocker_wheel_normalize_prizes($j['prizes'])
        : $defaults['prizes'];
    $enabled = array_key_exists('enabled', $j) ? (bool) $j['enabled'] : true;

    return [
        'cooldown_hours' => $h,
        'prizes' => $prizes,
        'cooldown_seconds' => $h * 3600,
        'enabled' => $enabled,
    ];
}

function mocker_wheel_save_config(int $cooldownHours, array $prizes, ?bool $enabled = null): bool
{
    $h = max(1, min(168, $cooldownHours));
    $prizes = mocker_wheel_normalize_prizes($prizes);
    $cfgBefore = mocker_wheel_load_config();
    $en = $enabled !== null ? $enabled : ($cfgBefore['enabled'] ?? true);
    $path = mocker_wheel_config_path();
    $dir = dirname($path);
    if (!is_dir($dir)) {
        if (!@mkdir($dir, 0755, true) && !is_dir($dir)) {
            return false;
        }
    }
    $data = [
        'cooldown_hours' => $h,
        'prizes' => $prizes,
        'enabled' => $en,
    ];
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    if ($json === false) {
        return false;
    }

    return file_put_contents($path, $json) !== false;
}
