<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Access\AccessServicesFactory;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermission(PermissionService::ROLES_VIEW);

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($currentUserId > 0) {
    permissionGateway()->getUserPermissions($currentUserId);
}
$accessServicesFactory = new AccessServicesFactory();
$permissionRepository = $accessServicesFactory->createPermissionRepository();
$rolePermissionRepository = $accessServicesFactory->createRolePermissionRepository();
$userAccountService = (new UserServicesFactory())->createUserAccountService();

$uuid = trim((string) ($id ?? ''));
$role = $uuid !== '' ? directoryServicesFactory()->createRoleService()->findByUuid($uuid) : null;
if (!$role) {
    Flash::error('Role not found', 'admin/roles', 'role_not_found');
    Router::redirect('admin/roles');
}

$roleId = (int) ($role['id'] ?? 0);
$creatorId = (int) ($role['created_by'] ?? 0);
if ($creatorId > 0) {
    $creator = $userAccountService->findById($creatorId);
    if ($creator) {
        $creatorName = trim(($creator['first_name'] ?? '') . ' ' . ($creator['last_name'] ?? ''));
        $role['created_by_label'] = $creatorName !== '' ? $creatorName : ($creator['email'] ?? '');
        $role['created_by_uuid'] = $creator['uuid'] ?? null;
    }
}
$modifierId = (int) ($role['modified_by'] ?? 0);
if ($modifierId > 0) {
    $modifier = $userAccountService->findById($modifierId);
    if ($modifier) {
        $modifierName = trim(($modifier['first_name'] ?? '') . ' ' . ($modifier['last_name'] ?? ''));
        $role['modified_by_label'] = $modifierName !== '' ? $modifierName : ($modifier['email'] ?? '');
        $role['modified_by_uuid'] = $modifier['uuid'] ?? null;
    }
}

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

if (isset($_POST['description'])) {
    if (!permissionGateway()->userHas($currentUserId, PermissionService::ROLES_UPDATE)) {
        Flash::error('Permission denied', "admin/roles/edit/{$uuid}", 'permission_denied');
        Router::redirect("admin/roles/edit/{$uuid}");
        return;
    }
    $result = directoryServicesFactory()->createRoleService()->updateFromAdmin($roleId, $_POST, $currentUserId);
    $form = $result['form'] ?? $form;
    $errors = $result['errors'] ?? [];
    $selectedPermissionIds = $_POST['permission_ids'] ?? $selectedPermissionIds;
    if (!is_array($selectedPermissionIds)) {
        $selectedPermissionIds = [$selectedPermissionIds];
    }
    $selectedPermissionIds = array_values(array_unique(array_map('intval', $selectedPermissionIds)));

    if ($result['ok'] ?? false) {
        $permissionIds = $_POST['permission_ids'] ?? [];
        if (!is_array($permissionIds)) {
            $permissionIds = [$permissionIds];
        }
        $permissionIds = array_values(array_unique(array_map('intval', $permissionIds)));
        $rolePermissionRepository->replaceForRole($roleId, $permissionIds);
        $action = (string) ($_POST['action'] ?? 'save');
        if ($action === 'save_close') {
            Flash::success('Role updated', 'admin/roles', 'role_updated');
            Router::redirect('admin/roles');
        } else {
            Flash::success('Role updated', "admin/roles/edit/{$uuid}", 'role_updated');
            Router::redirect("admin/roles/edit/{$uuid}");
        }
    }
}

Buffer::set('title', t('Edit role'));
