{% requireEdition CraftPro %}

{% do view.registerTranslations('app', [
    "Select All",
    "Deselect All",
]) %}

{% do view.registerAssetBundle("craft\\web\\assets\\userpermissions\\UserPermissionsAsset") %}

{% macro permissionList(context, permissions, id, disabled) %}
    {% from "_includes/forms" import checkbox %}
    {% from _self import permissionList %}

    <ul{% if id %} id="{{ id|replace(':', '-') }}"{% endif %}>
        {% for permissionName, props in permissions %}
            {% set isInGroupPermissions = (context.groupPermissions is defined and permissionName|lower in context.groupPermissions) %}

            {% if (isInGroupPermissions) %}
                {% set checked = true %}
            {% else %}
                {% if context.userOrGroup is not empty %}
                    {% if context.userOrGroup.hasErrors() %}
                        {% set checked = permissionName in craft.app.request.getBodyParam('permissions', []) %}
                    {% else %}
                        {% set checked = context.userOrGroup.can(permissionName) %}
                    {% endif %}
                {% else %}
                    {% set checked = false %}
                {% endif %}
            {% endif %}

            {% set hasNestedPermissions = props.nested is defined and props.nested is not empty %}
            <li>
                {{ checkbox({
                    label: props.label|e,
                    name: 'permissions[]',
                    value: permissionName,
                    checked: checked,
                    disabled: disabled or isInGroupPermissions,
                }) }}

                {% if hasNestedPermissions %}
                    {{ permissionList(context, props.nested, permissionName~'-nested', not checked) }}
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endmacro %}

{% from _self import permissionList %}

{% set user = userOrGroup and className(userOrGroup) == 'craft\elements\User' ? userOrGroup : null %}
{% for category, catPermissions in craft.app.userPermissions.getAssignablePermissions(user) %}
    <div class="user-permissions">
        <h3>{{ category }}</h3>
        <div class="select-all"></div>

        {{ permissionList(_context, catPermissions) }}
    </div>
{% endfor %}
