$(document).ready(function() {
    
    // Generic AJAX handler for standard forms (Shortcodes & Payments)
    function submitAjaxForm(formId, modalId) {
        $(formId).on('submit', function(e) {
            e.preventDefault();
            let $form = $(this);
            let $submitBtn = $form.find('button[type="submit"]');
            let originalBtnText = $submitBtn.text();

            // Disable button and show loading state
            $submitBtn.prop('disabled', true).text('Saving...');

            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: $form.serialize(),
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    // Hide modal
                    $(modalId).modal('hide');
                    // Reset form
                    $form[0].reset();
                    // Reload page to show fresh data (or dynamically append to table)
                    location.reload();
                },
                error: function(xhr) {
                    let errors = xhr.responseJSON?.errors;
                    let errorMsg = 'Something went wrong. Please check your inputs.';
                    if (errors) {
                        errorMsg = Object.values(errors).flat().join('\n');
                    }
                    alert(errorMsg);
                },
                complete: function() {
                    $submitBtn.prop('disabled', false).text(originalBtnText);
                }
            });
        });
    }

    // AJAX handler for Document Upload (Requires FormData for files)
    function submitFileForm(formId, modalId) {
        $(formId).on('submit', function(e) {
            e.preventDefault();
            let formElement = $(this)[0];
            let formData = new FormData(formElement);
            let $submitBtn = $(this).find('button[type="submit"]');
            let originalBtnText = $submitBtn.text();

            $submitBtn.prop('disabled', true).text('Uploading...');

            $.ajax({
                url: $(this).attr('action'),
                type: 'POST',
                data: formData,
                processData: false, // Essential for file uploads
                contentType: false, // Essential for file uploads
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    $(modalId).modal('hide');
                    formElement.reset();
                    location.reload();
                },
                error: function(xhr) {
                    let errors = xhr.responseJSON?.errors;
                    let errorMsg = 'Failed to upload document. Please check the file size and format.';
                    if (errors) {
                        errorMsg = Object.values(errors).flat().join('\n');
                    }
                    alert(errorMsg);
                },
                complete: function() {
                    $submitBtn.prop('disabled', false).text(originalBtnText);
                }
            });
        });
    }

    // Initialize the handlers
    submitAjaxForm('#shortcodeForm', '#addShortcodeModal');
    submitAjaxForm('#paymentForm', '#addPaymentModal');
    submitFileForm('#documentForm', '#uploadDocumentModal');
});