<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/permissions');
$createTarget = requestPathWithReturnTarget('admin/permissions/create', $returnTarget);

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_CREATE, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}

$errorBag = formErrors();
$errors = [];
$form = [
    'key' => '',
    'description' => '',
    'active' => 1,
    'is_system' => 0,
];

if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), $createTarget, 'csrf_expired');
    Router::redirect($createTarget);
    return;
}

if ($request->hasBody('key')) {
    $result = app(\MintyPHP\Service\Access\PermissionService::class)->createFromAdmin($request->bodyAll());
    $form = $result['form'] ?? $form;
    $errorBag->merge($result['errors'] ?? []);

    if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
        $action = (string) $request->body('action', 'create');
        if ($action === 'create_close') {
            Flash::success('Permission created', $closeTarget, 'permission_created');
            Router::redirect($closeTarget);
        } else {
            $id = (int) ($result['id'] ?? 0);
            if ($id > 0) {
                $target = requestPathWithReturnTarget("admin/permissions/edit/{$id}", $returnTarget);
                Flash::success('Permission created', $target, 'permission_created');
                Router::redirect($target);
            } else {
                Flash::success('Permission created', $closeTarget, 'permission_created');
                Router::redirect($closeTarget);
            }
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Create permission'));
