/**
 * Marks Form Handler Module
 * Handles dynamic AJAX submission, protection flags, and validation bounds.
 */
(function ($) {
    "use strict";

    $(document).ready(function () {

        /*
        |--------------------------------------------------------------------------
        | AJAX SUBMISSION CONTROL PIPELINE
        |--------------------------------------------------------------------------
        */
        $('#marksEntryForm').on('submit', function (e) {
            // 1. Enforce strict restriction on browser default synchronous execution
            e.preventDefault();
            e.stopImmediatePropagation();

            const $form = $(this);
            const $submitBtn = $form.find('button[type="submit"]');
            const formData = $form.serialize();

            $.ajax({
                url: 'process/save-marks-process.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                beforeSend: function () {
                    // Prevent form double submission vectors by freezing the button
                    $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Saving...');

                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            title: 'Saving Marks...',
                            text: 'Processing academic nodes, please wait.',
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                    }
                },
                success: function (response) {
                    // Close the loading modal loader
                    if (typeof Swal !== 'undefined') {
                        Swal.close();
                    }

                    if (response && response.success) {
                        // Professional Interactive Confirmation
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'success',
                                title: 'Saved Successfully!',
                                text: response.message || 'Student records updated into the master database cluster.',
                                confirmButtonColor: '#28a745',
                                confirmButtonText: 'Great!'
                            });
                        } else if (typeof toastr !== 'undefined') {
                            toastr.success(response.message || 'Marks saved successfully!');
                        }
                    } else {
                        // Re-enable click behavior if verification failed
                        $submitBtn.prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Marks');
                        
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'error',
                                title: 'Validation Failed',
                                text: response.message || 'Unknown processing anomaly encountered.',
                                confirmButtonColor: '#dc3545'
                            });
                        } else if (typeof toastr !== 'undefined') {
                            toastr.error(response.message || 'Failed to save academic records.');
                        }
                    }
                },
                error: function (xhr) {
                    if (typeof Swal !== 'undefined') {
                        Swal.close();
                    }
                    
                    // Unfreeze UI interaction on unexpected runtime breaks
                    $submitBtn.prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Save Marks');

                    let errorMessage = 'System configuration failure or processing exception!';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }

                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'error',
                            title: 'Critical Exception',
                            text: errorMessage,
                            confirmButtonColor: '#dc3545'
                        });
                    } else if (typeof toastr !== 'undefined') {
                        toastr.error(errorMessage);
                    }
                }
            });

            return false; // Absolute routing termination vector
        });

        /*
        |--------------------------------------------------------------------------
        | DYNAMIC ATTENDANCE BOUNDARY EVALUATION (ABSENT CONTROL)
        |--------------------------------------------------------------------------
        */
        $(document).on('change', 'select[name^="attendance_status"]', function () {
            const $row = $(this).closest('tr');
            const $marksInput = $row.find('input[name^="marks_obtained"]');

            if ($(this).val() === 'Absent') {
                $marksInput.val(0);
                $marksInput.prop('readonly', true).addClass('bg-light');
            } else {
                $marksInput.prop('readonly', false).removeClass('bg-light');
            }
        });

    });

})(jQuery);