$(document).ready(function() {
    // Set up AJAX defaults with CSRF token
    $.ajaxSetup({
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': csrfTokenValue // Using the global variable
        }
    });

    // Load current permissions when accordion opens
    $('.collapse').on('show.bs.collapse', function() {
        const groupId = $(this).attr('id').replace('collapse', '');
        loadCurrentPermissions(groupId);
    });

    // Handle permission checkbox changes
    $('.permissions-grid').on('change', '.perm-checkbox', function() {
        const groupId = $(this).data('group');
        const permId = $(this).data('perm');
        const isChecked = $(this).is(':checked');
        
        $('#confirmMessage').text(`Are you sure you want to ${isChecked ? 'add' : 'remove'} this permission?`);
        $('#confirmModal').modal('show');
        
        $('#confirmAction').off('click').on('click', function() {
            updatePermission(groupId, permId, isChecked ? 'add' : 'remove');
            
            $('#confirmModal').modal('hide');
        });
    });

    function loadCurrentPermissions(groupId) {
        $.get( base_url + 'administrator/settings/show-group-permissions/' + groupId, function(data) {
            let html = '<div class="d-flex flex-wrap">';
            if (data.length > 0) {
                data.forEach(perm => {
                    html += `<span class="badge bg-primary m-1 p-2">
                                ${perm.name} 
                                <small>(${perm.module})</small>
                                <button class="btn btn-xs p-1 btn-danger ml-2 remove-perm" 
                                        data-group="${groupId}" 
                                        data-perm="${perm.id}">
                                    <i class="bi bi-x"></i>
                                </button>
                            </span>`;
                });
            } else {
                html += '<span class="text-muted">No permissions assigned</span>';
            }
            html += '</div>';
            $(`#currentPermissions${groupId}`).html(html);
            
            // Mark checkboxes as checked
            data.forEach(perm => {
                $(`#perm_${groupId}_${perm.id}`).prop('checked', true);
            });
        });
    }

    function updatePermission(groupId, permId, action) {
        const postData = {
            group_id: groupId,
            permission_id: permId,
            action: action,
            csrfTokenp : csrfTokenp
        };
        

        $.ajax({
            url: base_url + 'administrator/settings/update-group-permission',
            type: 'POST',
            data: postData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    loadCurrentPermissions(groupId);
                    toastr.success('Permission updated successfully');
                } else {
                    toastr.error(response.message || 'Operation failed');
                }
            },
            error: function(xhr) {
                toastr.error('Error: ' + (xhr.responseJSON?.message || xhr.statusText));
            }
        });
    }

    // Handle remove permission buttons
    $(document).on('click', '.remove-perm', function() {
        const groupId = $(this).data('group');
        const permId = $(this).data('perm');
        
        $('#confirmMessage').text('Are you sure you want to remove this permission?');
        $('#confirmModal').modal('show');
        
        $('#confirmAction').off('click').on('click', function() {
            updatePermission(groupId, permId, 'remove');
            $('#confirmModal').modal('hide');
        });
    });
});