function saveForm(elem)
{
    $('.butn').attr('disabled','disabled');
    event.preventDefault();
    var action = $(elem).attr('action');
    $('.is-invalid').removeClass('is-invalid');
    let dataform = new FormData( $(elem)[0]);

    // Check if form has file inputs for enhanced loader
    const hasFiles = elem.querySelector('input[type="file"]');
    const fileInputs = elem.querySelectorAll('input[type="file"]');
    let totalFiles = 0;
    let uploadedFiles = 0;

    // Count files if any
    if (hasFiles) {
        fileInputs.forEach(input => {
            if (input.files.length > 0) {
                totalFiles += input.files.length;
            }
        });
    }

    let langs = ['ar', 'en'];
    let fields = ['description','reply'];
    for (let field of fields) {
        let textareaId = `${field}`;

        if ($(`#${textareaId}`).hasClass('my-editor') || $(`#${textareaId}`).hasClass('tinymce')) {
            let tinymceContent = tinymce.get(textareaId).getContent();
            dataform.append(textareaId, tinymceContent);
        }

        for (let lang of langs) {
            let textareaId = `${field}_${lang}`;

            if ($(`#${textareaId}`).hasClass('my-editor') || $(`#${textareaId}`).hasClass('tinymce')) {
                let tinymceContent = tinymce.get(textareaId).getContent();
                dataform.append(textareaId, tinymceContent);
            }
        }
    }

    // Show appropriate loader
    if (hasFiles && totalFiles > 0) {
        if (window.adminLoader) {
            const uploadingFilesText = window.loaderTranslations?.uploading_files || 'Uploading files';
            window.adminLoader.show({
                title: window.loaderTranslations?.uploading || 'Uploading...',
                message: `${uploadingFilesText} (0/${totalFiles})`,
                type: 'file-upload',
                showProgress: true,
                progress: 0
            });
        }
    } else {
        if (window.adminLoader) {
            window.adminLoader.show({
                title: window.loaderTranslations?.processing || 'Processing...',
                message: window.loaderTranslations?.please_wait || 'Please wait...',
                type: 'default'
            });
        }
    }

    $.ajax
    ({
        url : action,
        type: 'POST',
        data: dataform,
        dataType : 'json',
        contentType: false,
        processData: false,
        xhr: function() {
            var xhr = new window.XMLHttpRequest();

            // Track upload progress for file uploads
            if (hasFiles && totalFiles > 0) {
                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round((evt.loaded / evt.total) * 100);

                        if (window.adminLoader) {
                            window.adminLoader.setProgress(percentComplete);
                            const uploadingFilesText = window.loaderTranslations?.uploading_files || 'Uploading files';
                            window.adminLoader.message.textContent =
                                `${uploadingFilesText} (${Math.round(percentComplete)}%)`;
                        }
                    }
                }, false);
            }

            return xhr;
        },
        success:function(data)
        {
            // Hide loader immediately to prevent hanging
            if (window.adminLoader) {
                window.adminLoader.hide();
            }

            $('#errors').html('');
            $('#errors').css("display", "none");
            if(data.hasOwnProperty('errors'))
            {
                 $('#errors').css("display", "block");
                let html = '<div class="alert alert-danger">';
                $.each(data.errors, function(key,value)
                {
                    html += '<li>'+value+'</li>';
                    if (key.indexOf('.') == 0)
                    {
                        $('input[name='+key+']').addClass('is-invalid');
                        $('select[name='+key+']').addClass('is-invalid');
                        $('textarea[name='+key+']').addClass('is-invalid');
                    }
                    else
                    {
                        var keys = key.replaceAll(".","_");

                        $('#'+keys).addClass('is-invalid');
                    }
                });
                html += "</div>";
                $('#errors').html(html);
                $('.butn').removeAttr('disabled','disabled');

                // Show error loader with proper cleanup
                if (window.adminLoader) {
                    window.adminLoader.showError(window.loaderTranslations?.validation_errors || 'Validation errors', 3000);
                }
            }
            else
            {
                // Show success loader with proper cleanup
                if (window.adminLoader) {
                    window.adminLoader.showSuccess(window.loaderTranslations?.saved_successfully || 'Data saved successfully', 1500);
                }

                // Ensure loader is hidden before redirect
                setTimeout(
                    function()
                    {
                        if (window.adminLoader) {
                            window.adminLoader.hide();
                        }
                        window.location.href = data.data
                    }, 1500);
            }
        }
        ,error:function(data)
        {
            // Hide loader immediately to prevent hanging
            if (window.adminLoader) {
                window.adminLoader.hide();
            }

            $('#errors').css("display", "block");
            let html = '<div class="alert alert-danger">';

            if (data.responseJSON && data.responseJSON.errors) {
                $.each(data.responseJSON.errors, function(key,value)
                {
                    html += '<li>'+value+'</li>';
                    if (key.indexOf('.') > -1)
                    {
                        var keys = key.replaceAll(".","_");

                        $('#'+keys).addClass('is-invalid');
                    }
                    else
                    {
                        $('input[name='+key+']').addClass('is-invalid');
                        $('select[name='+key+']').addClass('is-invalid');
                        $('textarea[name='+key+']').addClass('is-invalid');
                    }
                });
            } else {
                const requestFailedText = window.loaderTranslations?.request_failed || 'Request failed';
                html += `<li>${requestFailedText}</li>`;
            }

            $('.butn').removeAttr('disabled','disabled');
            html += "</div>";
            $('#errors').html(html);

            // Show error loader with proper cleanup
            if (window.adminLoader) {
                window.adminLoader.showError(window.loaderTranslations?.request_failed || 'Request failed', 3000);
            }
        }
    })
}
