<?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');

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$permissionRepository = app(\MintyPHP\Repository\Access\PermissionRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$userRoleRepository = app(\MintyPHP\Repository\Access\UserRoleRepository::class);
$userWriteRepository = app(\MintyPHP\Repository\User\UserWriteRepository::class);
$uuid = trim((string) ($id ?? ''));
$editTarget = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);
$role = $uuid !== '' ? app(\MintyPHP\Service\Access\RoleService::class)->findByUuid($uuid) : null;
if (!$role) {
    Flash::error('Role not found', $closeTarget, 'role_not_found');
    Router::redirect($closeTarget);
}

$roleId = (int) ($role['id'] ?? 0);
$contextDecision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_CONTEXT, [
    'actor_user_id' => $currentUserId,
    'target_role_id' => $roleId,
]);
if (!$contextDecision->isAllowed()) {
    Guard::deny();
}
$capabilities = $contextDecision->attribute('capabilities', []);
$canUpdateRole = is_array($capabilities) ? (bool) ($capabilities['can_edit_role'] ?? false) : false;
$canDeleteRole = is_array($capabilities) ? (bool) ($capabilities['can_delete_role'] ?? false) : false;

app(\MintyPHP\Service\Audit\AuditMetadataEnricher::class)->enrich($role);

$errorBag = formErrors();
$errors = [];
$form = $role;
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = $rolePermissionRepository->listPermissionIdsByRoleId($roleId);

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

if ($request->hasBody('description')) {
    $submitDecision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_SUBMIT, [
        'actor_user_id' => $currentUserId,
        'target_role_id' => $roleId,
    ]);
    if (!$submitDecision->isAllowed()) {
        Guard::deny();
    }
    $result = app(\MintyPHP\Service\Access\RoleService::class)->updateFromAdmin($roleId, $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)));
        $syncSucceeded = false;
        $dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
        $dbSession->beginTransaction();
        try {
            $rolePermissionRepository->replaceForRole($roleId, $permissionIds);
            $affectedUserIds = $userRoleRepository->listUserIdsByRoleIds([$roleId]);
            if ($affectedUserIds) {
                $userWriteRepository->bumpAuthzVersionByUserIds($affectedUserIds);
            }
            $dbSession->commitTransaction();
            $syncSucceeded = true;
        } catch (\Throwable) {
            try {
                $dbSession->rollbackTransaction();
            } catch (\Throwable) {
            }
            $errorBag->merge([t('Failed to update role permissions')]);
        }
        if ($syncSucceeded) {
            $action = (string) $request->body('action', 'save');
            if ($action === 'save_close') {
                Flash::success('Role updated', $closeTarget, 'role_updated');
                Router::redirect($closeTarget);
            } else {
                Flash::success('Role updated', $editTarget, 'role_updated');
                Router::redirect($editTarget);
            }
        }
    }
}

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