/**
 * Marks Entry Script
 * Handles Select2 initialization, filters form submission via AJAX,
 * and dynamic rendering of DataTables.
 */
(function ($) {
    "use strict";

    $(document).ready(function () {

        /*
        |--------------------------------------------------------------------------
        | INITIALIZE SELECT2 COMPONENTS (AdminLTE 3 Theme)
        |--------------------------------------------------------------------------
        */
        if ($.fn.select2) {
            $('.select2').select2({
                theme: 'bootstrap4',
                width: '100%',
                placeholder: '-- Select --',
                allowClear: true
            });
        }

        /*
        |--------------------------------------------------------------------------
        | AJAX STUDENT FILTER & LISTING HANDLER
        |--------------------------------------------------------------------------
        */
        $('#marksEntryFilterForm').on('submit', function (e) {
            e.preventDefault();

            const $form = $(this);
            const formData = $form.serialize();
            const $container = $('#studentsContainer');
            const $table = $('#studentsTable');

            $.ajax({
                // Puraani galti khatam: Hum usi same page par request bhejenge jahan aapka logic hai
                url: 'ajax/get-students.php', 
                type: 'POST',
                data: formData,
                dataType: 'json',
                beforeSend: function () {
                    // AdminLTE standard loader show karna
                    $('#filterCardLoader').removeClass('d-none');
                    $('#btnLoadStudents').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Loading...');
                },
                success: function (response) {
                    // Agar response sahi aata hai
                    if (response && response.success) {
                        
                        // Aapke purane backend ke mutabik agar HTML string aa rahi hai, toh use body me daalna
                        const htmlContent = (response.data && response.data.html) ? response.data.html : (response.html || '');
                        const responseMsg = response.message || 'Students loaded successfully!';

                        // Container dikhana aur data HTML render karna
                        $container.removeClass('d-none').show();
                        $('#studentsTableBody').html(htmlContent);

                        /*
                        |--------------------------------------------------------------------------
                        | DATATABLE INITIALIZATION
                        |--------------------------------------------------------------------------
                        */
                        if ($.fn.DataTable) {
                            if ($.fn.DataTable.isDataTable($table)) {
                                $table.DataTable().clear().destroy();
                            }

                            $table.DataTable({
                                responsive: true,
                                autoWidth: false,
                                pageLength: 25,
                                ordering: true,
                                language: {
                                    emptyTable: "No students available for selection"
                                }
                            });
                        }

                        if (typeof toastr !== 'undefined') {
                            toastr.success(responseMsg);
                        }

                    } else {
                        // Agar backend mana kare ya data na ho
                        const errorMsg = response.message || 'Failed to load students data.';
                        $container.addClass('d-none').hide();
                        
                        if (typeof toastr !== 'undefined') {
                            toastr.error(errorMsg);
                        }
                    }
                },
                error: function (xhr, status, error) {
                    $container.addClass('d-none').hide();
                    
                    let errorMessage = 'Something went wrong while fetching data!';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }

                    if (typeof toastr !== 'undefined') {
                        toastr.error(errorMessage);
                    }
                },
                complete: function () {
                    // Loader band karna aur button normal karna
                    $('#filterCardLoader').addClass('d-none');
                    $('#btnLoadStudents').prop('disabled', false).html('<i class="fas fa-search mr-1"></i> Load Students');
                }
            });
        });
    });

})(jQuery);