/**
 * Finance Module — Client-side utilities
 */
(function() {
    'use strict';

    // Auto-reload datatables on successful form submission within modals
    document.addEventListener('DOMContentLoaded', function() {
        // Close modals and reload tables on AJAX form success inside modals
        var originalSubmit = FormHelper.submit.bind(FormHelper);
        var _origSuccess = null;

        document.querySelectorAll('.modal form[data-ajax="true"]').forEach(function(form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();

                var modal = form.closest('.modal');
                FormHelper.clearErrors(form);
                var submitBtn = form.querySelector('[type="submit"]');
                var originalText = submitBtn ? submitBtn.innerHTML : '';

                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>...';
                }

                var formData = new FormData(form);

                $.ajax({
                    url: form.action,
                    type: form.method || 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            FormHelper.showToast('success', response.message || 'Success');
                            if (modal) {
                                bootstrap.Modal.getInstance(modal).hide();
                            }
                            // Reload all visible DataTables
                            Object.keys(DataTableHelper.instances).forEach(function(key) {
                                DataTableHelper.reload(key);
                            });
                            if (response.redirect) {
                                setTimeout(function() { window.location.href = response.redirect; }, 500);
                            }
                        } else if (response.errors) {
                            FormHelper.showErrors(form, response.errors);
                        } else {
                            FormHelper.showToast('error', response.message || 'Operation failed');
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
                            FormHelper.showErrors(form, xhr.responseJSON.errors);
                        }
                    },
                    complete: function() {
                        if (submitBtn) {
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = originalText;
                        }
                    }
                });
            });
        });
    });
})();