<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';
require_once __DIR__ . '/../../src/RbacAdminRepository.php';

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

Auth::check();

if (!Rbac::canManageRbac()) {
    json_out(['ok' => false, 'error' => 'forbidden'], 403);
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = trim((string) ($_GET['action'] ?? ''));

if ($method === 'GET' && $action === 'panel') {
    $panel = RbacAdminRepository::buildPanel();
    json_out($panel, empty($panel['ok']) ? 403 : 200);
}

if ($method !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

$raw = file_get_contents('php://input') ?: '';
$body = json_decode($raw, true);
if (!is_array($body)) {
    json_out(['ok' => false, 'error' => 'invalid_json'], 400);
}

if ($action === 'set_global_role') {
    $result = RbacAdminRepository::setGlobalRole(
        (int) ($body['user_id'] ?? 0),
        (string) ($body['role'] ?? '')
    );
    json_out($result, empty($result['ok']) ? 400 : 200);
}

if ($action === 'set_company_role') {
    $result = RbacAdminRepository::setCompanyRole(
        (int) ($body['user_id'] ?? 0),
        (int) ($body['company_id'] ?? 0),
        (string) ($body['role'] ?? '')
    );
    json_out($result, empty($result['ok']) ? 400 : 200);
}

if ($action === 'apply_privilege_set') {
    $result = RbacAdminRepository::applyPrivilegeSet(
        (int) ($body['user_id'] ?? 0),
        (int) ($body['company_id'] ?? 0),
        (string) ($body['privilege_set'] ?? '')
    );
    json_out($result, empty($result['ok']) ? 400 : 200);
}

if ($action === 'clear_auth_lockouts') {
    if (!Rbac::isRoot() && !Rbac::isGlobalAdmin()) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $userId = (int) ($body['user_id'] ?? 0);
    if ($userId <= 0) {
        json_out(['ok' => false, 'error' => 'invalid_user'], 400);
    }
    $deleted = AuthAttempts::clearForUser($userId);
    json_out(['ok' => true, 'cleared' => $deleted]);
}

json_out(['ok' => false, 'error' => 'unknown_action'], 400);
