$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function addCartProduct(id, count) {
    $.ajax({
        url: '/cart/add',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,

            id: id,
            count: count
        },
        success: function (data) {
            if (data.status === 'success') {
				var ecommerce_items=GNS.analytics.mapProductToGAItem(data.product, data.product.count);
				//console.log(data);
				console.log(ecommerce_items);
                dataLayer.push({ ecommerce: null }); 
                dataLayer.push({
                    event: 'add_to_cart',
                    ecommerce: {
                        items: [ecommerce_items],
                    }
                })
                
                GNS.cart.productsCount[data.product.id] = data.product.count;
                GNS.cart.products.push(data.product);
                if (GNS.product && GNS.product.id === id) { // Product page
                    GNS.productCount = data.product.count;
                    GNS.product.count = data.product.count;
                    GNS.cart.product = data.product;
                }

                $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());
                $('[data-cart-product="' + id + '"]:not([data-no-check])').attr('data-check', '');
                $('[data-cart-product="' + id + '"][data-no-check]')
                    .find('span')
                    .html('<i class="flaticon-shopping-bags"></i>' + GNS.trans.inCart);

                $('#cart_modal').modal('show');
            }

            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/add[success]:', data);
            }
        },
        error: function (error) {
            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/add[error]:', error.responseJSON);
            }
        }
    });
}

function decrementCartProductCount(product) {
    $.ajax({
        url: '/cart/decrement',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,

            id: product.id
        },
        success: function (data) {
            if (data.status !== 'success') {
                product.count = GNS.cart.productsCount[product.id];
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            } else {
                GNS.cart.productsCount[product.id] = product.count;
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            }

            $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());

            if (GNS.isDebug) {
                console.log('/cart/decrement[success]:', data);
            }
        },
        error: function (error) {
            if (GNS.isDebug) {
                console.log('/cart/decrement[error]:', error.responseJSON);
            }
        }
    });
}

function incrementCartProductCount(product) {
    $.ajax({
        url: '/cart/increment',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,

            id: product.id
        },
        success: function (data) {
            if (data.status !== 'success') {
                product.count = GNS.cart.productsCount[product.id];
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            } else {
                GNS.cart.productsCount[product.id] = product.count;
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            }

            $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());

            if (GNS.isDebug) {
                console.log('/cart/increment[success]:', data);
            }
        },
        error: function (error) {
            if (GNS.isDebug) {
                console.log('/cart/increment[error]:', error.responseJSON);
            }
        }
    });
}

function updateCartProductCount(product) {
    $.ajax({
        url: '/cart/update',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,

            id: product.id,
            count: product.count
        },
        success: function (data) {
            if (data.status !== 'success') {
                product.count = GNS.cart.productsCount[product.id];
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            } else {
                GNS.cart.productsCount[product.id] = product.count;
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.productCount = product.count;
                    GNS.product.count = product.count;
                }
            }

            $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());

            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/update[success]:', data);
            }
        },
        error: function (error) {
            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/update[error]:', error.responseJSON);
            }
        }
    });
}

function removeCartProduct(product) {
    
    $.ajax({
        url: '/cart/remove',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,

            id: product.id
        },
        success: function (data) {
            if (data.status === 'success') {
				var ecommerce_items=GNS.analytics.mapProductToGAItem(product, product.count);
				console.log(ecommerce_items);
                dataLayer.push({ ecommerce: null }); 
                dataLayer.push({
                    event: 'remove_from_cart',
                    ecommerce: {
                        items: [ecommerce_items],
                    }
                });
                
                GNS.cart.products = GNS.cart.products.filter(function (p) { return p.id !== product.id; });

                if (GNS.cart.products.length === 0) {
                    GNS.cart.productsCount = {};
                    $('#cart_modal').modal('hide');
                } else {
                    delete GNS.cart.productsCount[product.id];
                }
                if (GNS.product && GNS.product.id === product.id) { // Product page
                    GNS.cart.product = undefined;
                }

                $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());
                $('[data-cart-product="' + product.id + '"]:not([data-no-check])').removeAttr('data-check');
                $('[data-cart-product="' + product.id + '"][data-no-check]')
                    .find('span')
                    .html('<i class="flaticon-shopping-bags"></i>' + GNS.trans.addToCart);
            }

            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/remove[success]:', data);
            }
        },
        error: function (error) {
            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/remove[error]:', error.responseJSON);
            }
        }
    });
}

function removeAllCartProducts() {

    const products = GNS.cart.products

    $.ajax({
        url: '/cart/remove-all',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress
        },
        success: function (data) {
            if (data.status === 'success') {
                dataLayer.push({ ecommerce: null }); 
                dataLayer.push({
                    event: 'remove_from_cart',
                    ecommerce: {
                        items: products.map(product => GNS.analytics.mapProductToGAItem(product, product.count)),
                    }
                })
                
                GNS.cart.products = [];
                GNS.cart.productsCount = {};
                if (GNS.product && GNS.cart.product) { // Product page
                    GNS.cart.product = undefined;
                }

                $('#cart_modal').modal('hide');
                $('[data-cart-products-count]').attr('data-count', 0);
                $('[data-cart-product]').removeAttr('data-check');
                $('[data-cart-product][data-no-check]')
                    .find('span')
                    .html('<i class="flaticon-shopping-bags"></i>' + GNS.trans.addToCart);
            }

            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/remove-all[success]:', data);
            }
        },
        error: function (error) {
            GNS.cart.isSubmit = false;

            if (GNS.isDebug) {
                console.log('/cart/remove-all[error]:', error.responseJSON);
            }
        }
    });
}

GNS.cart = {
    productsCount: {},
    products: [],
    product: undefined,
    isLoaded: false,
    isSubmit: false,
    addProduct: addCartProduct,
    decrementProductCount: decrementCartProductCount,
    incrementProductCount: incrementCartProductCount,
    updateProductCount: updateCartProductCount,
    removeProduct: removeCartProduct,
    removeAllProducts: removeAllCartProducts,
    showMaxCountToBuyNotification: function (maxCount, isKg) {
        GNS.notification.show(
            GNS.trans.maxCountToBuy + ' - <b>' +
            parseFloat(+maxCount).toFixed(isKg ? 1 : 0) +
            '</b> ' + (isKg ? 'кг.' : 'шт.'));
    },
    calcProductsCount: function () {
        var self = this,
            count = self.products.reduce(function (a, b) {
                return a + +b.count;
            }, 0);

        if (count !== parseInt(count)) {
            return count.toFixed(1);
        }
        return count.toFixed(0);
    },
    calcProductSum: function (product) {
        return (Math.round((+product.price * (+product.count || 1)) * 100) / 100).toFixed(2);
    },
    calcProductsSum: function () {
        var self = this;

        return self.products.reduce(function (a, b) {
            return a + +self.calcProductSum(b);
        }, 0).toFixed(2);
    }
};

function loadCart() {
    $.ajax({
        url: '/cart/get',
        type: 'POST',
        data: {
            language: GNS.language,
            user_location_id: GNS.userLocationId,
            user_shop_id: GNS.userShopId,
            user_delivery_address: GNS.userDeliveryAddress,
            
            is_order_page: GNS.isOrderPage
        },
        success: function (data) {
            if (data.status === 'success') {
                GNS.cart.products = data.products;

                $('[data-cart-products-count]').attr('data-count', GNS.cart.calcProductsCount());
                $.each(GNS.cart.products, function (i, product) {
                    GNS.cart.productsCount[product.id] = product.count;
                    if (GNS.product && GNS.product.id === product.id) {
                        GNS.productCount = product.count;
                        GNS.product.count = product.count;
                        GNS.cart.product = product;
                    }

                    $('[data-cart-product="' + product.id + '"]:not([data-no-check])').attr('data-check', '');
                    $('[data-cart-product="' + product.id + '"][data-no-check]')
                        .find('span')
                        .html('<i class="flaticon-shopping-bags"></i>' + GNS.trans.inCart);
                });

                if (data.hasOwnProperty('changedProductsCountByApi') && data.changedProductsCountByApi.length > 0) {
                    var message = GNS.trans.changed_products_count_by_api + ':<br/><br/>';
                    $.each(data.changedProductsCountByApi, function (i, product) {
                        message += product.name + ' - ' + product.count + ' ' + (product.is_kg ? 'кг.' : 'шт.') + '<br/>';
                    });
                    GNS.notification.show(message);
                }

                GNS.cart.isLoaded = true;
            }

            if (GNS.isDebug) {
                console.log('/cart/get[success]:', data);
            }
        },
        error: function (error) {
            if (GNS.isDebug) {
                console.log('/cart/get[error]:', error.responseJSON);
            }
        }
    });
}

function initCart() {
    var $body = $('body');

    // Add/Remove cart product
    $body.on('click', '[data-cart-product]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (GNS.cart.isSubmit) {
            return false;
        }
        GNS.cart.isSubmit = true;

        var id = +$(this).attr('data-cart-product'),
            isAdd = !GNS.cart.productsCount.hasOwnProperty(id);
        if (id === -1) {
            return false;
        } else if (isAdd) { // Add cart product
            if (GNS.product && GNS.product.id === id) { // Product page
                GNS.cart.addProduct(id, GNS.product.count);
            } else {
                GNS.cart.addProduct(id, 1);
            }
        } else { // Open cart modal
            $('#cart_modal').modal('show');

            GNS.cart.isSubmit = false;
        }

        return false;
    });
}

function initCartViews() {
    // Modal cart view
    new Vue({
        el: '[data-cart]',
        data: {
            cart: GNS.cart,
            orderUrl: GNS.orderUrl,
            isOrderPage: typeof GNS.order !== 'undefined'
        },
        computed: {
            orderSum: function () {
                var sum = this.cart.calcProductsSum();

                if (GNS.order) { // Order page
                    GNS.order.sum = sum;
                }

                return sum;
            },
            isMinOrderSum: function () {
                return this.orderSum > GNS.minOrderSum;
            }
        },
        methods: {
            setPrevProductCount: function (value, product) {
                if (product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }

                this.cart.productsCount[product.id] = parseFloat(value).toFixed(product.is_kg ? 1 : 0);
            },
            setProductCount: function (value, product) {
                if (this.cart.isSubmit) {
                    product.count = this.cart.productsCount[product.id];

                    return false;
                }

                if (product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }

                product.count = value;
            },
            decrementProductCount: function (product) {
                var i = product.is_kg ? 0.1 : 1;

                if (this.cart.isSubmit) {
                    return false;
                } else if (+product.count - i <= 0) {
                    return false;
                }

                this.cart.productsCount[product.id] = product.count;

                product.count = parseFloat(+product.count - i).toFixed(product.is_kg ? 1 : 0);

                this.cart.decrementProductCount(product);
            },
            incrementProductCount: function (product) {
                var i = product.is_kg ? 0.1 : 1;

                if (this.cart.isSubmit) {
                    return false;
                } else if (+product.count + i > +product.max_count) {
                    this.updateProductCount((+product.count + i).toString(), product);
                } else {
                    this.cart.productsCount[product.id] = product.count;

                    product.count = parseFloat(+product.count + i).toFixed(product.is_kg ? 1 : 0);

                    this.cart.incrementProductCount(product);
                }
            },
            updateProductCount: function (value, product) {
                if (this.cart.isSubmit) {
                    product.count = this.cart.productsCount[product.id];

                    return false;
                }

                if (product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }
                if (!value) {
                    value = 1;
                } else if (+value > +product.max_count) {
                    value = product.max_count;
                    GNS.cart.showMaxCountToBuyNotification(product.max_count, product.is_kg);
                }

                product.count = parseFloat(value).toFixed(product.is_kg ? 1 : 0);

                if (product.count !== this.cart.productsCount[product.id]) {
                    GNS.cart.isSubmit = true;

                    this.cart.updateProductCount(product);
                }
            },
            removeProduct: function (product) {
                if (this.cart.isSubmit) {
                    return false;
                }
                this.cart.isSubmit = true;

                this.cart.removeProduct(product);
            },
            removeAllProducts: function () {
                if (this.cart.isSubmit) {
                    return false;
                }
                this.cart.isSubmit = true;

                this.cart.removeAllProducts();
            }
        }
    });

    // Min cart view
    new Vue({
        el: '[data-cart-min]',
        data: {
            cart: GNS.cart,
            orderUrl: GNS.orderUrl,
            isOrderPage: typeof GNS.order !== 'undefined'
        },
        computed: {
            orderSum: function () {
                return this.cart.calcProductsSum();
            },
            isMinOrderSum: function () {
                return this.orderSum >= GNS.minOrderSum;
            }
        },
        methods: {
            removeProduct: function (product) {
                if (this.cart.isSubmit) {
                    return false;
                }
                this.cart.isSubmit = true;

                this.cart.removeProduct(product);
            }
        }
    });
}

function initCartAnalyticsListeners() {
    const $body = $('body');

    $body.on('click', '[data-go-to-order]', function () {
        var ecommerce_items=GNS.cart.products.map(product => GNS.analytics.mapProductToGAItem(product, product.count));
		console.log(ecommerce_items);
		dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: 'begin_checkout',
            ecommerce: {
                items: ecommerce_items,
            }
        });
    });
    $body.on('click', '.header_cart-list_btn', function () {
		var ecommerce_items=GNS.cart.products.map(product => GNS.analytics.mapProductToGAItem(product, product.count));
		console.log(ecommerce_items);
        dataLayer.push({ ecommerce: null });
        dataLayer.push({
            event: 'view_cart',
            ecommerce: {
                items: ecommerce_items,
            }
        });
    });
}

// Single cart view
if (GNS.product) { // Product page
    new Vue({
        el: '[data-cart-single]',
        data: {
            cart: GNS.cart,
            productCount: GNS.product.count,
            product: GNS.product
        },
        methods: {
            setPrevProductCount: function (value) {
                if (this.product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }

                this.productCount = parseFloat(value).toFixed(this.product.is_kg ? 1 : 0);
                if (this.cart.product) {
                    this.cart.productsCount[this.cart.product.id] = this.productCount;
                }
            },
            setProductCount: function (value) {
                if (this.cart.isSubmit) {
                    this.product.count = this.productCount;
                    if (this.cart.product) {
                        this.cart.product.count = this.productCount;
                    }

                    return false;
                }

                if (this.product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }

                this.product.count = value;
                if (this.cart.product) {
                    this.cart.product.count = value;
                }
            },
            decrementProductCount: function () {
                var i = this.product.is_kg ? 0.1 : 1;

                if (this.cart.isSubmit) {
                    return false;
                } else if (+this.product.count - i <= 0) {
                    return false;
                }
                this.productCount = this.product.count;

                this.product.count = parseFloat(+this.product.count - i).toFixed(this.product.is_kg ? 1 : 0);

                if (this.cart.product) {
                    this.cart.product.count = this.product.count;

                    this.cart.decrementProductCount(this.product);
                } else {
                    this.productCount = this.product.count;
                }
            },
            incrementProductCount: function () {
                var i = this.product.is_kg ? 0.1 : 1;

                if (this.cart.isSubmit) {
                    return false;
                } else if (+this.product.count + i > +this.product.max_count) {
                    this.updateProductCount((+this.product.count + i).toString());
                } else {
                    this.productCount = this.product.count;

                    this.product.count = parseFloat(+this.product.count + i).toFixed(this.product.is_kg ? 1 : 0);

                    if (this.cart.product) {
                        this.cart.product.count = this.product.count;

                        this.cart.incrementProductCount(this.cart.product);
                    } else {
                        this.productCount = this.product.count;
                    }
                }
            },
            updateProductCount: function (value) {
                if (this.cart.isSubmit) {
                    this.product.count = this.productCount;
                    if (this.cart.product) {
                        this.cart.product.count = this.productCount;
                    }

                    return false;
                }

                if (this.product.is_kg) {
                    value = value.replace(',', '.').replace(/[^\d.]/g, '');
                } else {
                    value = value.replace(/[^\d]/g, '');
                }
                if (!value) {
                    value = 1;
                } else if (+value > +this.product.max_count) {
                    value = this.product.max_count;
                    GNS.cart.showMaxCountToBuyNotification(this.product.max_count, this.product.is_kg);
                }

                this.product.count = parseFloat(value).toFixed(this.product.is_kg ? 1 : 0);
                if (this.cart.product) {
                    this.cart.product.count = this.product.count;
                }

                if (this.product.count !== this.productCount) {
                    if (this.cart.product) {
                        this.cart.isSubmit = true;

                        this.cart.updateProductCount(this.cart.product);
                    } else {
                        this.productCount = this.product.count;
                    }
                }
            }
        }
    });
}

// Order cart view
if (GNS.order) { // Order page
    new Vue({
        el: '[data-cart-order]',
        data: {
            order: GNS.order,
            cart: GNS.cart
        },
        computed: {
            isFreeDeliveryMinOrderSum: function () {
                return +this.order.sum === 0 || +this.order.sum >= +this.order.free_delivery_min_order_sum;
            }
        }
    });
}

loadCart();
initCart();
initCartViews();
initCartAnalyticsListeners()
