<?php

use MintyPHP\Buffer;
use MintyPHP\Repository\Access\RoleRepository;
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::PERMISSIONS_VIEW);

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($currentUserId > 0) {
    permissionGateway()->getUserPermissions($currentUserId);
}

$id = (int) ($id ?? 0);
$permission = $id > 0 ? permissionGateway()->find($id) : null;
if (!$permission) {
    Flash::error('Permission not found', 'admin/permissions', 'permission_not_found');
    Router::redirect('admin/permissions');
}

$errors = [];
$form = $permission;
$roles = (new RoleRepository())->listActive();
$rolePermissionRepository = (new AccessServicesFactory())->createRolePermissionRepository();
$selectedRoleIds = $rolePermissionRepository->listRoleIdsByPermissionId($id);

if (isset($_POST['key'])) {
    if (!permissionGateway()->userHas($currentUserId, PermissionService::PERMISSIONS_UPDATE)) {
        Flash::error('Permission denied', "admin/permissions/edit/{$id}", 'permission_denied');
        Router::redirect("admin/permissions/edit/{$id}");
        return;
    }
    $result = permissionGateway()->updateFromAdmin($id, $_POST);
    $form = $result['form'] ?? $form;
    $errors = $result['errors'] ?? [];
    $selectedRoleIds = $_POST['role_ids'] ?? $selectedRoleIds;
    if (!is_array($selectedRoleIds)) {
        $selectedRoleIds = [$selectedRoleIds];
    }
    $selectedRoleIds = array_values(array_unique(array_map('intval', $selectedRoleIds)));

    if ($result['ok'] ?? false) {
        $roleIds = $_POST['role_ids'] ?? [];
        if (!is_array($roleIds)) {
            $roleIds = [$roleIds];
        }
        $roleIds = array_values(array_unique(array_map('intval', $roleIds)));
        $rolePermissionRepository->replaceForPermission($id, $roleIds);
        $action = (string) ($_POST['action'] ?? 'save');
        if ($action === 'save_close') {
            Flash::success('Permission updated', 'admin/permissions', 'permission_updated');
            Router::redirect('admin/permissions');
        } else {
            Flash::success('Permission updated', "admin/permissions/edit/{$id}", 'permission_updated');
            Router::redirect("admin/permissions/edit/{$id}");
        }
    }
}

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