<?php declare(strict_types=1);

namespace Diamond\Modules\AdminUserGroups;

use ActiveTable\ColumnTable;
use Core\Form\NiftyControlBuilder;
use Core\ModuleController;
use Core\Security\Access;
use Diamond\Domain\UserGroup\Contracts\UserGroupEntityInterface;
use Diamond\Infrastructure\Models\UserGroup\UserGroup;
use Diamond\Repositories\UserGroup\UserGroupCriteria;
use Diamond\Repositories\UserGroup\UserGroupRepository;
use DiamondTable\CommandFactory;
use DiamondTable\TableFactory;

/**
 * Description of AdminUsers
 *
 * @author Dmitriy
 */
class AdminUserGroups extends ModuleController
{

    public function __construct(private UserGroupRepository $groupRepo,
                                private NiftyControlBuilder $controlBuilder,
                                private Access              $access,
                                private TableFactory        $tableFactory)
    {
    }

    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable($this->groupRepo, UserGroupCriteria::create(), 'Создать роль');
        $table->getCommandFactory()->addCommand(CommandFactory::FORM_SAVE, new GroupSaveCommand($table, $this->access));
        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('name', 'Наименование'))
            )
            ->addColumn(
                (new ColumnTable('grpCode', 'Идентификатор'))
            )
            ->addColumn(
                (new ColumnTable('actions', ''))->setWidth(120)->setFormat($this, 'formatActions')
            );

        $optRules = [];
        $isRoot = false;

        if (input_get('id')) {
            /**
             * @var UserGroup $group
             */
            $group = $this->groupRepo->findById((int)input_get('id'));

            if ($group->getGrpCode() === 'root') {
                $isRoot = true;
            }

            $permissionsActive = $this->access->getRulePermissionsForRole($group->getGrpCode());
        }

        $control = $this->controlBuilder->buildInput('grpCode');
        if ($isRoot === true) {
            $control->addAttr('disabled', 'disabled');
        }
        $table
            ->startTab('Роль')
            ->addField($this->controlBuilder->buildInput('name'), true)
            ->addField($control, $isRoot !== true, null, $isRoot === true ? 'root изменить нельзя' : '')
            ->endTab();

        $rules = $this->access->getRulePermissions();

        foreach ($rules as $rule => $data) {
            $control = $this->controlBuilder->buildNiftySimpleSwitchery('rule[' . $rule . ']', '1', '0');

            if ($isRoot === true || isset($permissionsActive[$rule])) {
                $control->setChecked(true);
            }

            $optRules[$data['tab']][$rule] = [
                'control' => $control->render(),
                'label' => $data['label']
            ];
        }

        $table->startTab('Разрешения');

        $table->addField($this->controlBuilder->buildRow('rules', $this->render('rules_group', [
            'permissions' => $optRules
        ])));

        $table->endTab();

        return $table->render();
    }

    /**
     * @param UserGroupEntityInterface $userEntity
     * @return string
     */
    public function formatActions(UserGroupEntityInterface $userEntity): string
    {
        return $this->controlBuilder->buildActionMenuAdmin([], (int)$userEntity->getId())->render();
    }
}
