$(function () {
    'use strict';

    // CSRF setup
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    const form = $('#systemCoreSettingsForm');

    // Form submission
    form.on('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);

        // Fix checkbox values - convert to boolean
        const checkboxFields = ['include_date_in_order_number', 'enable_sync_logging'];
        checkboxFields.forEach(field => {
            const checkbox = $(`#${field}`);
            const isChecked = checkbox.is(':checked');
            formData.delete(field);
            formData.append(field, isChecked ? '1' : '0');
        });

        // Show loading state
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> ' + (pageData.labels.saving || 'Saving...'));

        $.ajax({
            url: pageData.urls.update,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: pageData.labels.success,
                        text: response.message || pageData.labels.settingsUpdated,
                        timer: 2000,
                        showConfirmButton: false,
                        customClass: {
                            confirmButton: 'btn btn-success'
                        },
                        buttonsStyling: false
                    });
                }
            },
            error: function (xhr) {
                let errorMessage = pageData.labels.errorOccurred;

                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    errorMessage = Object.values(errors).flat().join('\n');
                } else if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }

                Swal.fire({
                    icon: 'error',
                    title: pageData.labels.error,
                    text: errorMessage,
                    confirmButtonText: pageData.labels.ok || 'OK',
                    customClass: { confirmButton: 'btn btn-danger' },
                    buttonsStyling: false
                });
            },
            complete: function () {
                // Restore button state
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Reset button
    form.find('button[type="reset"]').on('click', function (e) {
        e.preventDefault();

        Swal.fire({
            title: pageData.labels.resetSettings || 'Reset Settings?',
            text: pageData.labels.resetConfirmText || 'This will reset the form to last saved values',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: pageData.labels.yesReset || 'Yes, reset',
            cancelButtonText: pageData.labels.cancel || 'Cancel',
            customClass: {
                confirmButton: 'btn btn-warning me-3',
                cancelButton: 'btn btn-label-secondary'
            },
            buttonsStyling: false
        }).then((result) => {
            if (result.isConfirmed) {
                form[0].reset();
                // Reload page to get fresh values
                location.reload();
            }
        });
    });
});
