$(document).ready(function () {

    /*
    |--------------------------------------------------------------------------
    | INIT DATATABLE
    |--------------------------------------------------------------------------
    */

    if ($('#resultTable').length) {

        $('#resultTable').DataTable({

            responsive: true,

            autoWidth: false,

            pageLength: 25,

            ordering: true
        });
    }

    /*
    |--------------------------------------------------------------------------
    | DELETE RESULT
    |--------------------------------------------------------------------------
    */

    $(document).on(
        'submit',
        '.deleteResultForm',
        function (e) {

            e.preventDefault();

            const form = $(this);

            Swal.fire({

                title: 'Delete Result?',

                text: 'This action cannot be undone.',

                icon: 'warning',

                showCancelButton: true,

                confirmButtonText: 'Yes, Delete',

                cancelButtonText: 'Cancel'

            }).then((result) => {

                if (!result.isConfirmed) {

                    return;
                }

                $.ajax({

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

                    type: 'POST',

                    data: form.serialize(),

                    dataType: 'json',

                    beforeSend: function () {

                        Swal.fire({

                            title: 'Deleting Result...',

                            text: 'Please wait',

                            allowOutsideClick: false,

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

                    success: function (response) {

                        Swal.close();

                        if (response.success) {

                            toastr.success(
                                response.message
                            );

                            form.closest('tr').remove();

                        } 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);
                    }
                });
            });
        }
    );
});