/**
 * Academic Result Generator Logic Pipelines Controller
 * Handles async validation, state masking, and confirmation prompts.
 */
jQuery(document).ready(function ($) {
    "use strict";

    /*
    |--------------------------------------------------------------------------
    | GENERATE RESULT SUBMISSION ASYNC BINDING
    |--------------------------------------------------------------------------
    */
    $('#generateResultForm').on('submit', function (e) {
        // Enforce strong preventive action on sync document route
        e.preventDefault();

        const $form = $(this);
        const $submitBtn = $form.find('#btnGenerateResults, button[type="submit"]');
        const $cardLoader = $('#generationLoaderWrapper'); // AdminLTE layout integration hook
        const formData = $form.serialize();

        // Safe client validation fallback checking
        const examId = $('#exam_type_id').val();
        const classId = $('#class_id').val();

        if (!examId || !classId) {
            if (typeof toastr !== 'undefined') {
                toastr.warning('Validation Error: Please select valid configuration options first.');
            } else {
                alert('Please filter valid configuration options first.');
            }
            return false;
        }

        // Professional Prompt Warning confirmation mechanism
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Are you sure?',
                text: "This will run deep batch processing routines to recalculate ranks, metrics, and grade configurations across all students in this class.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#3085d6',
                confirmButtonText: '<i class="fas fa-check mr-1"></i> Yes, Compile Now!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    executeCompilationPipeline($form, formData, $submitBtn, $cardLoader);
                }
            });
        } else {
            // Fallback native browser confirmation mechanism if SweetAlert fails to bind
            if (confirm("Are you sure? This will run deep batch processing routines to recalculate ranks.")) {
                executeCompilationPipeline($form, formData, $submitBtn, $cardLoader);
            }
        }

        return false;
    });

    /**
     * Processing Logic Module Execution Block
     */
    function executeCompilationPipeline($form, formData, $submitBtn, $cardLoader) {
        $.ajax({
            url: 'process/generate-result-process.php', // Strictly preserved actual destination file path mapping
            type: 'POST',
            data: formData,
            dataType: 'json',
            beforeSend: function () {
                // Freeze interactions to protect batch transactions integrity
                $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i> Compiling...');
                
                // Show AdminLTE native background container card shadow overlay layer mask
                if ($cardLoader.length) {
                    $cardLoader.removeClass('d-none');
                }

                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Processing Node Matrix...',
                        text: 'Calculating grades, evaluating percentage metrics, and assigning group ranks. Please do not close or refresh this view.',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                }
            },
            success: function (response) {
                if (typeof Swal !== 'undefined') {
                    Swal.close();
                }

                if (response && response.success) {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Pipeline Compiled!',
                            text: response.message || 'Academic result ledger updated successfully.',
                            confirmButtonColor: '#28a745'
                        });
                    } else if (typeof toastr !== 'undefined') {
                        toastr.success(response.message || 'Academic result ledger updated successfully.');
                    }
                } else {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'error',
                            title: 'Compilation Aborted',
                            text: response.message || 'Error occurred while saving analytics context.',
                            confirmButtonColor: '#dc3545'
                        });
                    } else if (typeof toastr !== 'undefined') {
                        toastr.error(response.message || 'Error occurred while saving analytics context.');
                    }
                }
            },
            error: function (xhr, status, error) {
                if (typeof Swal !== 'undefined') {
                    Swal.close();
                }

                console.error("Pipeline Exception Failure Trace:", error, xhr.responseText);
                
                let errLog = 'Internal compilation engine break or missing runtime script context.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errLog = xhr.responseJSON.message;
                }

                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Fatal Pipeline Break',
                        text: errLog,
                        confirmButtonColor: '#dc3545'
                    });
                } else if (typeof toastr !== 'undefined') {
                    toastr.error(errLog);
                }
            },
            complete: function () {
                // Remove state locks and fully restore native action control elements
                $submitBtn.prop('disabled', false).html('<i class="fas fa-calculator mr-2"></i> Compile & Generate');
                
                if ($cardLoader.length) {
                    $cardLoader.addClass('d-none');
                }
            }
        });
    }
});