<?php

namespace apexl\Io\modules\userDisplay\forms;

use apexl\Io\modules\formbuilder\Components\FormKitField\CheckboxFormKitField;
use apexl\Io\modules\formbuilder\Components\FormKitField\EntityForm;
use apexl\Io\modules\formbuilder\Components\FormKitField\Form;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\services\Permissions;

class rolesForm
{
    public static function rolesForm($args, Permissions $permissions): Form
    {
        $roleEntity = new roleEntity();
        $form = new EntityForm($roleEntity, $args, ['permissions']);
        //->deleteField("permissions");
        $form->setSubmitText('Submit');

        $permissions = $permissions->permissions;

        if (isset($args[$roleEntity->primaryKey])) {
            $roleEntity->load($args[$roleEntity->primaryKey]);
        }

        foreach ($permissions as $macName => $data) {
            $form->setFieldsetSetting($data->group, 'fieldset_legend', $data->group);

            $permissionBox = (new CheckboxFormKitField($macName))->setLabel($data->name);
            if (isset($args[$roleEntity->primaryKey])) {
                if ($roleEntity->can(constant($macName))) {
                    $permissionBox->setValue(true);
                } else {
                    $permissionBox->setValue(false);
                }
            }
            $form->addField($permissionBox, $data->group);
        }

        return $form;
    }
}
