jQuery(document).ready(function($) {
    const button = $('#confirm-cod-order');
    const checkbox = $('#cod_agreement');

    // Enable the button when the checkbox is checked
    checkbox.on('change', function() {
        button.prop('disabled', !this.checked);
    });

    button.on('click', function() {

        const formData = {
            action: 'formipay_cod_confirmation',
            form_id: $('#form_id').val(),
            order_id: $('#order_id').val(),
            formipay_nonce: $('#formipay_nonce').val(),
        };

        Swal.fire({
            icon: 'info',
            text: "Are you sure to confirm the COD package is arrived and you have paid the bill to courier?",
            showCancelButton: true,
            confirmButtonText: "Yes!",
            cancelButtonText: `No, I haven't paid the bill yet`,
            reverseButtons: true,
            customClass: {
                confirmButton: 'formipay-submit-button'
            }
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    url: formipay_thankyou.ajax_url,
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        // Handle success
                        let timerInterval;
                        Swal.fire({
                            html: response.data.message,
                            icon: response.data.icon,
                            timer: 2500,
                            timerProgressBar: true,
                            didOpen: () => {
                                Swal.showLoading();
                                const timer = Swal.getPopup().querySelector("b");
                                timerInterval = setInterval(() => {
                                timer.textContent = `${Swal.getTimerLeft()}`;
                                }, 100);
                            },
                            willClose: () => {
                                clearInterval(timerInterval);
                            },
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            showCloseButton: false,
                        }).then((result) => {
                            if (result.dismiss === Swal.DismissReason.timer) {
                                window.location.reload();
                            }
                        });
                    },
                    error: function(xhr, status, error) {
                        // Handle error
                        console.error('AJAX Error:', error);
                    }
                });
            }
        });

       

    });
});