<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
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/roles');
$createTarget = requestPathWithReturnTarget('admin/roles/create', $returnTarget);

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

$errorBag = formErrors();
$errors = [];
$form = [
    'description' => '',
    'code' => '',
    'active' => 1,
];
$permissionRepository = app(\MintyPHP\Repository\Access\PermissionRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = [];

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

if ($request->hasBody('description')) {
    $dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
    $transactionStarted = false;

    try {
        $dbSession->beginTransaction();
        $transactionStarted = true;

        $result = app(\MintyPHP\Service\Access\RoleService::class)->createFromAdmin($request->bodyAll(), $currentUserId);
        $form = $result['form'] ?? $form;
        $errorBag->merge($result['errors'] ?? []);
        $selectedPermissionIds = $request->body('permission_ids', $selectedPermissionIds);
        if (!is_array($selectedPermissionIds)) {
            $selectedPermissionIds = [$selectedPermissionIds];
        }
        $selectedPermissionIds = array_values(array_unique(array_map('intval', $selectedPermissionIds)));

        if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
            $permissionIds = $request->body('permission_ids', []);
            if (!is_array($permissionIds)) {
                $permissionIds = [$permissionIds];
            }
            $permissionIds = array_values(array_unique(array_map('intval', $permissionIds)));
            $createdId = (int) ($result['id'] ?? 0);
            if ($createdId <= 0) {
                throw new \RuntimeException('role_create_missing_id');
            }
            $rolePermissionRepository->replaceForRole($createdId, $permissionIds);
            $dbSession->commitTransaction();
            $transactionStarted = false;

            $action = (string) $request->body('action', 'create');
            if ($action === 'create_close') {
                Flash::success('Role created', $closeTarget, 'role_created');
                Router::redirect($closeTarget);
            } else {
                $uuid = (string) ($result['uuid'] ?? '');
                if ($uuid !== '') {
                    $target = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);
                    Flash::success('Role created', $target, 'role_created');
                    Router::redirect($target);
                } else {
                    Flash::success('Role created', $closeTarget, 'role_created');
                    Router::redirect($closeTarget);
                }
            }
        }
    } catch (\Throwable) {
        if ($transactionStarted) {
            try {
                $dbSession->rollbackTransaction();
            } catch (\Throwable) {
            }
        }
        if (!$errorBag->hasAny()) {
            $errorBag->merge([t('Failed to update role permissions')]);
        }
    }
}

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