{% 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 craft.app.request.isPost %}
                        {% set checked = permissionName in craft.app.request.getBodyParam('permissions', []) %}
                    {% else %}
                        {% set checked = context.userOrGroup.can(permissionName) %}
                    {% endif %}
                {% else %}
                    {% set checked = false %}
                {% endif %}
            {% endif %}

            <li>
                {{ checkbox({
                    label: props.label,
                    name: 'permissions[]',
                    value: permissionName,
                    checked: checked,
                    class: isInGroupPermissions ? 'group-permission',
                    disabled: disabled or isInGroupPermissions,
                }) }}

                {% if props.info ?? false %}
                    <div class="info">{{ props.info }}</div>
                {% endif %}

                {% if props.warning ?? false %}
                    <div class="info warning">{{ props.warning }}</div>
                {% endif %}

                {% if props.nested ?? false %}
                    {{ 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 %}
