<?php

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

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

$errors = [];
$form = [
    'description' => '',
    'code' => '',
    'active' => 1,
];
$accessServicesFactory = new AccessServicesFactory();
$permissionRepository = $accessServicesFactory->createPermissionRepository();
$rolePermissionRepository = $accessServicesFactory->createRolePermissionRepository();
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = [];

if (isset($_POST['description'])) {
    $currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
    $result = directoryServicesFactory()->createRoleService()->createFromAdmin($_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)));
        $createdId = (int) ($result['id'] ?? 0);
        if ($createdId > 0) {
            $rolePermissionRepository->replaceForRole($createdId, $permissionIds);
        }
        $action = (string) ($_POST['action'] ?? 'create');
        if ($action === 'create_close') {
            Flash::success('Role created', 'admin/roles', 'role_created');
            Router::redirect('admin/roles');
        } else {
            $uuid = (string) ($result['uuid'] ?? '');
            if ($uuid !== '') {
                $target = "admin/roles/edit/{$uuid}";
                Flash::success('Role created', $target, 'role_created');
                Router::redirect($target);
            } else {
                Flash::success('Role created', 'admin/roles', 'role_created');
                Router::redirect('admin/roles');
            }
        }
    }
}

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