$(function () {
    loadMatrix();
});

function loadMatrix() {
    $.getJSON('api/permissions.php?action=matrix', function (res) {
        if (res.status === 'error') {
            alert('Failed to load permission matrix: ' + (res.message || 'Unknown error'));
            return;
        }
        const roles = res.roles;
        const permissions = res.permissions;
        const assigned = res.assigned;

        if (!Array.isArray(roles) || !Array.isArray(permissions)) {
            alert('Invalid permission matrix response');
            return;
        }

        // HEADER
        let head = '<tr><th>Permission</th>';
        roles.forEach(r => {
            head += '<th>' + escapeHtml(r.name) + '</th>';
        });
        head += '</tr>';
        $('#permHead').html(head);

        // BODY
        let body = '';

        permissions.forEach(p => {
            body += '<tr><td>' + escapeHtml(p.code) + '</td>';

            roles.forEach(r => {
                const key = r.id + '_' + p.id;
                const checked = assigned.includes(key) ? 'checked' : '';

                body += '<td class="text-center">' +
                    '<input type="checkbox" class="perm-checkbox" data-role="' + r.id + '" data-perm="' + p.id + '" ' + checked + '>' +
                    '</td>';
            });

            body += '</tr>';
        });

        $('#permBody').html(body);
    }).fail(function (jqXHR) {
        alert('Failed to load permission matrix: ' + (jqXHR.responseJSON?.message || jqXHR.statusText));
    });
}

$(document).on('change', '.perm-checkbox', function () {
    const $cb = $(this);
    const role_id = $cb.data('role');
    const permission_id = $cb.data('perm');
    const checked = $cb.is(':checked') ? 1 : 0;
    const action = checked ? 'grant' : 'revoke';

    if (!confirm('Are you sure you want to ' + action + ' this permission?')) {
        $cb.prop('checked', !$cb.is(':checked'));
        return;
    }

    $cb.prop('disabled', true);

    $.post('api/permissions.php?action=toggle', {
        role_id: role_id,
        permission_id: permission_id,
        checked: checked
    }, function (res) {
        if (res.status !== 'success') {
            alert('Failed to update: ' + (res.message || 'Unknown error'));
            $cb.prop('checked', !$cb.is(':checked'));
        }
    }, 'json').fail(function (jqXHR) {
        alert('Network error: ' + (jqXHR.responseJSON?.message || jqXHR.statusText));
        $cb.prop('checked', !$cb.is(':checked'));
    }).always(function () {
        $cb.prop('disabled', false);
    });
});

function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}
