/**
 * Custom Error Handling with SweetAlert
 */

// Handle AJAX errors
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    if (jqXHR.status === 403) {
        Swal.fire({
            title: 'Access Denied',
            text: 'You do not have permission to perform this action.',
            icon: 'error',
            confirmButtonText: 'Back to Dashboard',
            allowOutsideClick: false
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "/"; // Redirect to dashboard
            }
        });
    }
});

// Function to show permission error
function showPermissionError(message = 'You do not have permission to perform this action.') {
    Swal.fire({
        title: 'Access Denied',
        text: message,
        icon: 'error',
        confirmButtonText: 'OK',
        allowOutsideClick: true
    });
}

// Function to handle unauthorized actions
function handleUnauthorizedAction(redirectUrl = null) {
    Swal.fire({
        title: 'Access Denied',
        text: 'You do not have permission to access this resource.',
        icon: 'error',
        confirmButtonText: 'Back to Dashboard',
        allowOutsideClick: false
    }).then((result) => {
        if (result.isConfirmed) {
            if (redirectUrl) {
                window.location.href = redirectUrl;
            } else {
                window.location.href = "/"; // Default redirect to dashboard
            }
        }
    });
}
