<?php
declare(strict_types=1);

function mocker_admin_permission_keys(): array
{
    return [
        'dashboard',
        'members',
        'market-requests',
        'complaints',
        'affiliate-requests',
        'ip-clashes',
        'sponsors',
        'bonuses',
        'market',
        'social',
        'site',
        'wheel',
        'telegram-broadcast',
        'telegram-invites',
        'promo-codes',
        'audit',
        'chat',
        'special-odds',
        'tickets',
        'events',
        'news',
        'notifications',
        'sponsor-promo-codes',
        'maintenance',
        'games-covers',
        'member-twofa',
    ];
}

function mocker_admin_require_login(): void
{
    if (!isset($_SESSION['mocker_admin']) || $_SESSION['mocker_admin'] !== true) {
        http_response_code(401);
        echo json_encode(['ok' => false, 'error' => 'unauthorized'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

function mocker_admin_is_super(): bool
{
    if (!isset($_SESSION['mocker_admin']) || $_SESSION['mocker_admin'] !== true) {
        return false;
    }

    return (string) ($_SESSION['mocker_admin_kind'] ?? '') !== 'staff';
}

function mocker_admin_permission_list(): array
{
    if (mocker_admin_is_super()) {
        return mocker_admin_permission_keys();
    }
    $p = $_SESSION['mocker_perms'] ?? [];
    if (!is_array($p)) {
        return [];
    }
    $keys = mocker_admin_permission_keys();

    return array_values(array_unique(array_filter(array_map('strval', $p), static fn ($x) => in_array($x, $keys, true))));
}

function mocker_admin_can(string $perm): bool
{
    if (mocker_admin_is_super()) {
        return true;
    }

    return in_array($perm, mocker_admin_permission_list(), true);
}

function mocker_admin_require_permission(string $perm): void
{
    mocker_admin_require_login();
    if (mocker_admin_can($perm)) {
        return;
    }
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden'], JSON_UNESCAPED_UNICODE);
    exit;
}

function mocker_admin_require_any_permission(array $perms): void
{
    mocker_admin_require_login();
    if (mocker_admin_is_super()) {
        return;
    }
    $mine = mocker_admin_permission_list();
    foreach ($perms as $p) {
        if (in_array($p, $mine, true)) {
            return;
        }
    }
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden'], JSON_UNESCAPED_UNICODE);
    exit;
}

function mocker_admin_require_super(): void
{
    mocker_admin_require_login();
    if (mocker_admin_is_super()) {
        return;
    }
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden'], JSON_UNESCAPED_UNICODE);
    exit;
}
