(function($) {
    "use strict";

    $(document).ready(function () {
        // Sirf hamari custom class ko initialize karein taaki global scripts se conflict na ho
        $('.custom-select2').select2({ 
            width: '100%', 
            placeholder: 'Select an option' 
        });

        // Toastr Config
        toastr.options = { "closeButton": true, "progressBar": true, "positionClass": "toast-top-right", "timeOut": "5000" };

        function performAction(action) {
            const examId = $('#exam_type_id').val();
            const classId = $('#class_id').val();
            const csrfToken = $('input[name="csrf_token"]').val();

            if (!examId || !classId) {
                toastr.warning('Please select Exam and Class first.');
                return;
            }

            Swal.fire({
                title: 'Are you sure?',
                text: `You are about to ${action} the results.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: action === 'publish' ? '#28a745' : '#dc3545',
                confirmButtonText: 'Yes, proceed!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'process/publish-result-process.php',
                        type: 'POST',
                        data: { exam_type_id: examId, class_id: classId, action: action, csrf_token: csrfToken },
                        dataType: 'json',
                        beforeSend: () => Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() }),
                        success: (res) => {
                            Swal.close();
                            res.success ? toastr.success(res.message) : toastr.error(res.message);
                        },
                        error: (xhr) => {
                            Swal.close();
                            toastr.error(xhr.responseJSON?.message || 'A system error occurred.');
                        }
                    });
                }
            });
        }

        $('#publishResultsBtn').on('click', function(e) { e.preventDefault(); performAction('publish'); });
        $('#unpublishResultsBtn').on('click', function(e) { e.preventDefault(); performAction('unpublish'); });
    });
})(jQuery);