{% extends 'base.html.twig' %}
{% import "macros/datatables.html.twig" as tables %}
{% import "macros/widgets.html.twig" as widgets %}
{% import "macros/toolbar.html.twig" as toolbar %}
{% import "permission/actions.html.twig" as actions %}

{% set columns = {
    'label.name': 'alwaysVisible',
} %}
{% set canEditPermissions = is_granted('role_permissions') %}
{% for role in roles %}
    {% set options = {'class': 'alwaysVisible text-center'} %}
    {% if canEditPermissions and role.name not in system_roles|keys %}
        {% set widget %}
        &nbsp;<a href="{{ path('admin_user_role_delete', {'id': role.id, 'csrfToken': token}) }}" class="confirmation-link" data-question="confirm.delete">{{ widgets.icon('trash') }}</a>
        {% endset %}
        {% set options = options|merge({'html_after': widget}) %}
    {% endif %}
    {% set columns = columns|merge({
        (role.name|trans): options,
    }) %}
{% endfor %}

{% set tableName = 'user_admin_permissions' %}

{% block page_title %}{{ 'profile.roles'|trans }}{% endblock %}
{% block page_actions %}{{ actions.user_permissions('index') }}{% endblock %}

{% block main %}
    {{ tables.datatable_header(tableName, columns, null, {'translationPrefix': ''}) }}
    
    {% set colspan = 1 + (roles|length) %}

    {% for title, perms in sorted %}
        {% if perms|length > 0 %}
            <tr class="summary info">
                <td colspan="{{ colspan }}">{{ title }}</td>
            </tr>
            {% for permission in perms|sort %}
                <tr>
                    <td>{{ permission }}</td>
                    {% for role in roles %}
                        {% set value = manager.permission(role.name, permission) %}
                        <td class="text-center">
                            {# see RolePermissionManager for this special case #}
                            {% if role.name == 'ROLE_SUPER_ADMIN' and permission in always_apply_superadmin %}
                                {% if value %}
                                    {{ widgets.label('yes'|trans, 'warning') }}
                                {% else %}
                                    <a class="togglePerm permOff" href="#" data-href="{{ path('admin_user_permission_save', {'id': role.id, 'name': permission, 'value': '1', 'csrfToken': '__TOKEN__'}) }}">{{ widgets.label('no'|trans, 'danger') }}</a>
                                {% endif %}
                            {% else %}
                                <a class="togglePerm {{ value ? 'permOn' : 'permOff' }}" href="#" data-href="{{ path('admin_user_permission_save', {'id': role.id, 'name': permission, 'value': '__VALUE__', 'csrfToken': '__TOKEN__'}) }}">{{ widgets.label_boolean(value) }}</a>
                            {% endif %}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
        {% endif %}
    {% endfor %}

    {{ tables.data_table_footer() }}

{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript">
        let PERM_TOKEN = '{{ token }}';
        document.addEventListener('kimai.initialized', function() {
            jQuery('a.togglePerm').on('click', function(event) {
                event.stopPropagation();
                event.preventDefault();

                let target = event.target;
                if (!target.matches('a')) {
                    target = target.parentNode;
                }

                let linkElement = jQuery(target);
                linkElement.html('<i class="fas fa-spinner fa-pulse"></i>');

                let isActive = linkElement.hasClass('permOn');
                let url = linkElement.data('href').replace(/__VALUE__/, isActive ? '0' : '1').replace(/__TOKEN__/, PERM_TOKEN);

                jQuery.ajax({
                    url: url,
                    headers: {'Content-Type':'application/json'},
                    method: 'POST',
                    data: [], {# data doesn't matter, everything is in the URL #}
                    dataType: 'json',
                    success: function(result) {
                        kimai.getPlugin('alert').success('action.update.success');
                        linkElement.toggleClass('permOn').toggleClass('permOff');
                        toggleLabel(linkElement, !isActive);
                        PERM_TOKEN = result.token;
                    },
                    error: function(xhr, err) {
                        kimai.getPlugin('alert').error('action.update.error');
                        toggleLabel(linkElement, isActive);
                    }
                });
            });

            KimaiReloadPageWidget.create('kimai.userRoleUpdate');
        });

        function toggleLabel(element, showTrue) {
            if (showTrue) {
                element.html('{{ widgets.label_boolean(true)|e('js') }}');
            } else {
                element.html('{{ widgets.label_boolean(false)|e('js') }}');
            }
        }
    </script>
{% endblock %}
