

jQuery(function($) {

    $('body').append('<div class="wrap-remote-item" style="display: none;">' +
        '<div class="remote-item-alert"><div class="close">&times;</div>' +
        '<div class="remote-item-text">'+bundle_loc.info_remote+'</div> ' +
        '<div class="remote-item-action"><button class="btnNo">'+bundle_loc.cancel+'</button><button class="btnYes">'+bundle_loc.remove+'</button></div>' +
        '</div>' +
        '</div>');

    function dialog(yesCallback, noCallback) {

        noCallback = noCallback || function(){}

        $('.wrap-remote-item').show();

        $('.btnYes').click(function() {
            $('.wrap-remote-item').hide();
            yesCallback();
        });
        $('.btnNo').click(function() {
            $('.wrap-remote-item').hide();
            noCallback();
        });
        $('.close').click(function() {
            $('.wrap-remote-item').hide();
            noCallback();
        });
        $('.wrap-remote-item').click(function() {
            $('.wrap-remote-item').hide();
            noCallback();
        });
    }

    $('body').on('click', '.product-remove a:not(.remote-bundle)', function () {
        var self = this;

        if($(this).closest('.cart_item').find('.isBundle').length){
            dialog(function(){
                $(self).addClass('remote-bundle').click();
            });

            return false;
        }
    })

    $('body').on('click', '.order-item-remove:not(.remote-bundle)', function () {
        var self = this;

        if($(this).closest('.order-item').find('.isBundle').length){
            dialog(function(){
                $(self).addClass('remote-bundle').click();
            });

            return false;
        }
    })
});

jQuery(function($) {
    var bundle = (function() {
        var $this;

        var ajaxurl = '';

        if(typeof alidAjax !== 'undefined'){
            ajaxurl = alidAjax.ajaxurl;
        }

        if(typeof woocommerce_params !== 'undefined'){
            ajaxurl = woocommerce_params.ajax_url;
        }

        return {
            init: function() {
                if ($this) {
                    return ;
                }

                $this = this;
                $this.initAddButton();

                $('select[name="adsbundle_products[]"]').on('change', function () {
                    let price_html = $(this).children("option:selected").attr('date-price_html');
                    if(price_html){
                        $(this).closest('.adsbundleProduct').find('.bundle-product-price > strong').html(price_html);
                    }
                });

                $('select[name="adsbundle_products[]"]').each(function () {
                    let price_html = $(this).children("option:selected").attr('date-price_html');
                    if(price_html){
                        $(this).closest('.adsbundleProduct').find('.bundle-product-price > strong').html(price_html);
                    }
                })
            },
            initAddButton: function() {
                $('.adsbundle-btn').on('click', function(e) {

                    var products = [];
                    var productIds = [];

                    var shipping = $('[name="shipping"]').length ? $('[name="shipping"]').val() : '';

                    $('select[name="adsbundle_products[]"]').each(function(index, value) {
                        products.push({
                            product_id : $(value).data('post_id'),
                            variation_id : $(value).val(),
                            quantity : 1,
                            shipping : shipping,
                            variation : 'quantity-attribute'
                        });
                    });

                    if (products.length > 0) {
                        for (var index in products) {
                            productIds.push(products[index].product_id);
                        }
                    }

                    $('.bundle-product-title').each(function(index, value) {
                        if (!productIds.includes($(value).data('post_id'))) {
                            products.push({
                                product_id : $(value).data('post_id'),
                                quantity : 1,
                                shipping : shipping,
                                variation : 'quantity-attribute'
                            });
                        }
                    });

                    var id = $(this).closest('.adsbundle-col-centered').attr('data-id');
                    var post_id = $(this).closest('.adsbundle-col-centered').attr('data-post-id');

                    var data = {
                        action : 'adsbundle_add_to_cart',
                        products : products,
                        id : id,
                        post_id : post_id,
                    };

                    $.ajax({
                        url : ajaxurl,
                        data : data,
                        type : "POST",
                        dataType : 'json',
                        success : function(response) {

                            if(response.productInCart){

                                    if(confirm(response.__productInCart)){
                                        $.ajax({
                                            url : ajaxurl,
                                            data : {
                                                action : 'adsbundle_key_remove_cart_item',
                                                key : response.productInCart,
                                            },
                                            type : "POST",
                                            dataType : 'json',
                                            success : function() {
                                                if (!document.body.classList.contains('adslandingpage')) {
                                                    $(location).attr('href', response.redirect_url);
                                                }
                                            }
                                        });

                                        return;
                                    }
                            }

                            if (response.result === true && !document.body.classList.contains('adslandingpage')) {
                                $(location).attr('href', response.redirect_url);
                            }


                        }
                    });
                });
            },
            serialize: function(obj, str = []) {
                for (var p in obj) {
                    if (obj.hasOwnProperty(p)) {
                        if (typeof obj[p] == 'object') {
                            $this.serialize(obj[p], str);
                        } else {
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        }
                    }
                }

                return str.join("&");
            }
        };
    })();

    bundle.init();
});
