jQuery(document).ready(function($) {
    $('.custom-buy-now-button').on('click', function(e) {
        e.preventDefault();

        var productId = $(this).data('product-id');

        // Loading popup
        $('#bwdcv-loading-popup').fadeIn();

        // AJAX call
        $.ajax({
            url: bwdcv_popup_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'bwdcv_add_to_cart_and_checkout',
                product_id: productId
            },
            beforeSend: function() {
                // Loading popup
                $('#bwdcv-loading-popup').fadeIn();
            },
            success: function(response) {
                $.ajax({
                    url: bwdcv_popup_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'bwdcv_load_checkout',
                        product_id: productId
                    },
                    success: function(response) {
                        $.ajax({
                            url: bwdcv_popup_ajax.ajax_url,
                            type: 'POST',
                            data: {
                                action: 'bwdcv_process_checkout',
                                product_id: productId
                            },
                            success: function(response) {
                                $('#bwdcv-loading-popup').fadeOut();
                            },
                            error: function(xhr, status, error) {
                                $('#bwdcv-loading-popup').fadeOut();
                            }
                        });
                    },
                    error: function(xhr, status, error) {
                        $('#bwdcv-loading-popup').fadeOut();
                    }
                });
            },
            error: function(xhr, status, error) {
                $('#bwdcv-loading-popup').fadeOut();
            }
        });
    });
});
