$(document).ready(function () {

    /*
    |--------------------------------------------------------------------------
    | INIT SELECT2
    |--------------------------------------------------------------------------
    */

    $('.select2').select2({
        width: '100%'
    });

    /*
    |--------------------------------------------------------------------------
    | GENERATE RESULTS
    |--------------------------------------------------------------------------
    */

    $('#generateResultForm').on('submit', function (e) {

        e.preventDefault();

        Swal.fire({

            title: 'Generate Results?',

            text: 'Existing results may be updated.',

            icon: 'warning',

            showCancelButton: true,

            confirmButtonText: 'Yes, Generate',

            cancelButtonText: 'Cancel'

        }).then((result) => {

            if (!result.isConfirmed) {

                return;
            }

            const formData = $(this).serialize();

            $.ajax({

                url: 'process/generate-result-process.php',

                type: 'POST',

                data: formData,

                dataType: 'json',

                beforeSend: function () {

                    Swal.fire({

                        title: 'Generating Results...',

                        text: 'Please wait',

                        allowOutsideClick: false,

                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                },

                success: function (response) {

                    Swal.close();

                    if (response.success) {

                        toastr.success(
                            response.message
                        );

                    } else {

                        toastr.error(
                            response.message
                        );
                    }
                },

                error: function (xhr) {

                    Swal.close();

                    let errorMessage =
                        'Something went wrong!';

                    if (
                        xhr.responseJSON &&
                        xhr.responseJSON.message
                    ) {

                        errorMessage =
                            xhr.responseJSON.message;
                    }

                    toastr.error(errorMessage);
                }
            });
        });
    });
});