<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
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);

$context = actionCreateContext([
    'abilityKey' => PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_CREATE,
    'context' => ['actor_user_id' => $currentUserId],
    'viewAuthFlags' => [],
    'forbiddenStrategy' => 'deny',
]);
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
// Permissions are global; $tenantScope['ids'] is intentionally not consumed here.
// $canManageAllTenants stays as a resilient hook for future policy extensions.
$canManageAllTenants = $tenantScope['scope'] === 'all';

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

if ($request->isMethod('POST') && !actionRequireCsrf($createTarget, $createTarget, 'csrf_expired')) {
    return;
}

if ($request->isMethod('POST')) {
    $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(t('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(t('Permission created'), $target, 'permission_created');
                Router::redirect($target);
            } else {
                Flash::success(t('Permission created'), $closeTarget, 'permission_created');
                Router::redirect($closeTarget);
            }
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Create permission'));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Permissions'), 'path' => 'admin/permissions'],
    ['label' => t('Create permission')],
];
