(function($) {
    "use strict";

    $(document).ready(function () {
        $('.select2').select2({
            width: '100%',
            placeholder: 'Select an option'
        });

        $('#finalResultForm').on('submit', function (e) {
            e.preventDefault();
            const form = $(this);
            const formData = form.serialize();

            Swal.fire({
                title: 'Generate Final Results?',
                text: 'This will compile and update all academic records.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, Proceed'
            }).then((result) => {
                if (result.isConfirmed) {
                    processFinalResult(formData);
                }
            });
        });

        function processFinalResult(data) {
            $.ajax({
                url: 'process/generate-final-result-process.php',
                type: 'POST',
                data: data,
                dataType: 'json',
                beforeSend: function () {
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Calculating...',
                        allowOutsideClick: false,
                        didOpen: () => { Swal.showLoading(); }
                    });
                },
                success: function (response) {
                    Swal.close();
                    if (response.success) {
                        Swal.fire('Success!', response.message, 'success');
                        if (typeof toastr !== 'undefined') toastr.success(response.message);
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                        if (typeof toastr !== 'undefined') toastr.error(response.message);
                    }
                },
                error: function (xhr) {
                    Swal.close();
                    let msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'System Error';
                    Swal.fire('Error!', msg, 'error');
                    if (typeof toastr !== 'undefined') toastr.error(msg);
                }
            });
        }
    });
})(jQuery);