<?php

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

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

$errors = [];
$form = [
    'key' => '',
    'description' => '',
    'active' => 1,
    'is_system' => 0,
];

if (isset($_POST['key'])) {
    $result = permissionGateway()->createFromAdmin($_POST);
    $form = $result['form'] ?? $form;
    $errors = $result['errors'] ?? [];

    if ($result['ok'] ?? false) {
        $action = (string) ($_POST['action'] ?? 'create');
        if ($action === 'create_close') {
            Flash::success('Permission created', 'admin/permissions', 'permission_created');
            Router::redirect('admin/permissions');
        } else {
            $id = (int) ($result['id'] ?? 0);
            if ($id > 0) {
                $target = "admin/permissions/edit/{$id}";
                Flash::success('Permission created', $target, 'permission_created');
                Router::redirect($target);
            } else {
                Flash::success('Permission created', 'admin/permissions', 'permission_created');
                Router::redirect('admin/permissions');
            }
        }
    }
}

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