var app = angular.module("myApp", ["ngSanitize", "ui.select"]).filter("safeHtml", function ($sce) {
    return function (val) {
        return $sce.trustAsHtml(val);
    };
});
app.controller("CheckOutController", function ($scope, $http, $q) {
    $scope.loading = false;
    $scope.discount = 0;
    $scope.discountByPromotionCode = 0;
    $scope.discountByProduct = 0;
    $scope.discountByOriginOrder = 0;
    $scope.shipping_fee = 0;
    $scope.otherFee = 0;
    $scope.otherTaxFee = parseFloat(otherTaxFee);
    $scope.tips = 0;
    $scope.customTips = {value: 0};
    $scope.otherFeePercent = stripeFee;
    $scope.payment_type = cardForm == 'stripe' ? 'stripe' : 'paypal_card';
    $scope.deliveryTime = "";
    $scope.shipingLocation = {
        country: customerCountry,
        province: null,
        state_name: "",
        city_name: "",
        optional_address: "",
    };
    $scope.items = [];
    $scope.calculateShippingByType = [];
    $scope.shipping_type = "standard";
    $scope.sameShippingType = true;
    $scope.isFocusStateName = false;
    $scope.locale = localeCheckout;
    $scope.ignoreOptionIds = ignoreOptionIds;
    $scope.expressAuDescription = expressAuDescription;
    $scope.expressDescription = expressDescription;
    $scope.shippingTypeAdvantages = shippingTypeAdvantages;
    $scope.monthNames = monthNames;
    $scope.errorCard = "";

    $scope.promotionCode = "";
    $scope.errorPromotionCode = "";
    $scope.successPromotionCode = "";
    $scope.validPromotionCode = "";

    $scope.currentCartItem = {};
    $scope.currentVariant = {};
    $scope.variantOptionSelected = {};
    $scope.variantImageSelected = {};
    $scope.newItem = {};
    $scope.addressSuggestions = [];
    $scope.lastKeySearchAddress = "";
    $scope.billingAddressSuggestions = [];
    $scope.isDiffirentBillingAddress = false;
    $scope.billingAddress = {};
    $scope.errorsBillingAddress = {};
    $scope.shippingInfos = [];
    $scope.responseShippingInfo = {};
    $scope.errorShippingInfos = null;
    $scope.sendFail = 0;
    $scope.startSend = 0;
    $scope.selectedShipping = {};
    $scope.shippingFromText = shippingFromText;
    $scope.shippingText = shippingText;
    $scope.textBusinessDays = textBusinessDays;
    $scope.textMoreShippingType = textMoreShippingType;
    $scope.freesshippingBoxPriceText = freesshippingBoxPriceText;
    $scope.askUsePointText = askUsePointText;
    $scope.isShowSuggest = false;
    $scope.customer = {
        token: token
    };
    $scope.tenancyToken = tenancyToken;
    $scope.errorImage = "";
    $scope.isShowPaymentType = true;
    $scope.showTips = showTips;
    $scope.tipsValue = [];
    $scope.tipsValueDefault = [];
    $scope.tipsValuePercent = [];
    $scope.modeCheckout = mode;
    $scope.discountType = 'normal';
    $scope.textBuyDesign = textBuyDesign;
    $scope.designFee = parseFloat(designFee);
    $scope.includeDesignFee = parseFloat(includeDesignFee);
    $scope.designFeeByProducts = {};
    $scope.totalDesignFee = 0;
    $scope.isChangeCurrency = priceConfig && priceConfig.ratio ? true : false;

    $scope.paymentUrlLian = "";

    if (tipsValue.length > 0) {
        $scope.tipsValue.push({
            "key": noTipsText,
            "value": 0
        })
        tipsValue.forEach(element => {
            $scope.tipsValue.push({
                "key": formatPrice(element, priceTempate),
                "value": parseFloat(element)
            })
        });
        $scope.tipsValueDefault = angular.copy($scope.tipsValue);
    } else {
        $scope.showTips = false;
    }
    if (tipsValuePercent.length > 0) {
        $scope.tipsValuePercent.push({
            "key": noTipsText,
            "value": 0
        })
        tipsValuePercent.forEach(element => {
            $scope.tipsValuePercent.push({
                "key": element + "%",
                "value": parseFloat(element)
            })
        });
    }
    $scope.isShowPercentTips = false;
    $scope.tipsAmount = 0;
    $scope.lastTips = 0;
    $scope.countries = countries;
    $scope.provinces = [];
    $scope.isSendVerify = false;
    $scope.realEmail = '';
    $scope.isVerifyEmail = false;
    $scope.resolve = false;
    $scope.canceler = $q.defer();
    $scope.firstLoadingCart = {
        is_show: true
    };
    $scope.totalCartItem = localStorage.getItem("cart-item") ? localStorage.getItem("cart-item") : 1;
    $scope.validApplePay = true;
    $scope.dataOrder = {};
    $scope.currency = currency_units[defaultCurrencyUnit] ? currency_units[defaultCurrencyUnit] : "$";
    $scope.isShowAfterPay = false;
    if (defaultCurrencyUnit == "USD" || defaultCurrencyUnit == "GBP" || defaultCurrencyUnit == "EUR" ) {
        $scope.isShowAfterPay = true;
    }

    $scope.user = user;
    $scope.states = {};
    $scope.addressBook = [];
    $scope.paypalType = null;
    $scope.validPaypal = true;
    $scope.actions = null;
    $scope.totalQuantity = 0;
    $scope.suspiciousFee = parseFloat(suspiciousFee);
    $scope.isSuspicious = false;
    $scope.taxFee = 0;
    $scope.taxes = taxes;
    $scope.calculateCheckoutText = calculateCheckoutText;
    $scope.gift = {
        is_check: false,
        name: "",
        phone: "",
    };
    $scope.errorsGift = {};
    $scope.giftWrapNote = "";
    $scope.isGiftWrap = false;
    $scope.isValidGiftWrap = false;
    $scope.giftWrapFee = parseFloat(giftWrapFee);
    $scope.paymentGateway = {
        isGooglePay: false,
        isApplePay: false,
    };

    $scope.customerRewards = {
        rewardsPercent: rewardsPercent,
        showRewards: showRewards,
        validRewards: 0,
        usedRewards: 0,
        useRewards: "",
        rewards: 0,
        pointEarn: 0
    };
    $scope.discountByVipBenefit = 0;
    $scope.discountByRefer = 0;
    $scope.isUsingDiscountByRefer = false;

    $scope.errorCheckout = 0;
    $scope.showModalPreOrder = false;
    $scope.preOrderNote = "";
    $scope.isBuyFreeshipPackage = false;
    $scope.isBuyFreeshipPackageByEmail = false;
    $scope.isShowFreeShippingPackage = false;
    $scope.freeshipPackageProduct = {};
    $scope.customerInfoByEmail = {};
    $scope.clickBuyFreeship = false;
    $scope.printLocations = printLocations;
    $scope.confirmRemoveItemText = confirmRemoveItemText;
    $scope.listRegularEmail = ["aol.com", "arcor.de", "att.net", "bellsouth.net", "bigpond.com", "blueyonder.co.uk", "btinternet.com", "charter.net", "comcast.net", "cox.net", "docomo.ne.jp", "earthlink.net", "ezweb.ne.jp", "free.fr", "freenet.de", "frontier.com", "gmail.com", "gmx.de", "gmx.net", "googlemail.com", "hotmail.co.uk", "hotmail.com", "hotmail.de", "hotmail.fr", "hotmail.it", "icloud.com", "laposte.net", "libero.it", "live.co.uk", "live.com", "live.com.au", "live.fr", "mac.com", "mail.com", "mail.ru", "me.com", "msn.com", "neuf.fr", "ntlworld.com", "optonline.net", "orange.fr", "outlook.com", "outlook.de", "outlook.fr", "protonmail.com", "rocketmail.com", "rogers.com", "sbcglobal.net", "sfr.fr", "shaw.ca", "sky.com", "t-online.de", "talktalk.net", "verizon.net", "virginmedia.com", "wanadoo.fr", "web.de", "yahoo.ca", "yahoo.co.jp", "yahoo.co.uk", "yahoo.com", "yahoo.com.au", "yahoo.de", "yahoo.fr", "yahoo.it", "ymail.com"];
    $scope.isCheckEmail = false;
    $scope.showModalRemoveCartItem = false;
    $scope.itemRemove = {};
    $scope.comments = [];
    $scope.isBulkOrder = false;
    $scope.originOrder = originOrder;
    $scope.stripePayment = ["STRIPE", "STRIPE_EXPRESS", "PRODUCT_EXPRESS", "RESERVE"];
    $scope.isSelectCountry = false;
    $scope.currentPrefix = "";
    $scope.currentPrefixFriend = "";
    $scope.isDisableEmail = false;
    $scope.validTax = false;
    $scope.isUsePoint = false;
    $scope.isFirstLoadPaypal = false;
    $scope.earnPointText = earnPointText;
    $scope.dropinAdyen = null;
    $scope.isValidAdyenState = false;
    $scope.configRangeByMarket = [];
    $scope.adyenData = {
        "session_id": "",
        "session_data": "",
        "environment": "",
        "client_key": "",
        "return_url": "",
    };
    $scope.cardData = null;
    $scope.showLoyaltyNoti = true;
    $scope.textAwayShippingFee = "";
    $scope.isValidateSpecialShippingFee = false;

    if (useCheckoutInForm) {
        $scope.registerElements = function(elements, formId) {
            var formSelector = '#' + formId;
            var formElm = document.querySelector(formSelector);

            var form = formElm.querySelector('form');
            var error = form.querySelector('.error');

            function triggerBrowserValidation() {
                // The only way to trigger HTML5 form validation UI is to fake a user submit
                // event.
                var submit = document.createElement('input');
                submit.type = 'submit';
                submit.style.display = 'none';
                form.appendChild(submit);
                submit.click();
                submit.remove();
            }

            // Listen for errors from each Element, and show error messages in the UI.
            var savedErrors = {};
            elements.forEach(function(element, idx) {
                element.on('change', function(event) {
                    if (event.error) {
                        error.classList.add('visible');
                        savedErrors[idx] = event.error.message;
                        $scope.$apply(function() {
                            $scope.errorCard = event.error.message;
                        });
                    } else {
                        savedErrors[idx] = null;

                        // Loop over the saved errors and find the first one, if any.
                        var nextError = Object.keys(savedErrors).sort().reduce(function(maybeFoundError, key) {
                            return maybeFoundError || savedErrors[key];
                        }, null);

                        if (nextError) {
                            // Now that they've fixed the current error, show another one.
                            $scope.errorCard = nextError;
                        } else {
                            // The user fixed the last error; no more errors.
                            error.classList.remove('visible');
                            $scope.$apply(function() {
                                $scope.errorCard = "";
                            });
                        }
                    }
                });
            });
        }
        $scope.elementStyles = {
            base: {
                color: 'black',
                fontWeight: 600,
                fontFamily: 'Roboto, sans-serif',
                fontSize: '16px',
                fontSmoothing: 'antialiased',

                ':focus': {
                    color: '#424770',
                },

                '::placeholder': {
                    color: '#9BACC8',
                },

                ':focus::placeholder': {
                    color: '#CFD7DF',
                },
            },
            invalid: {
                color: 'black',
                ':focus': {
                    color: '#FA755A',
                },
                '::placeholder': {
                    color: '#FFCCA5',
                },
            },
        };

        $scope.elementClasses = {
            focus: 'focus',
            empty: 'empty',
            invalid: 'invalid',
        };
        $scope.elements = stripe.elements({
            fonts: [
                {
                    cssSrc: 'https://fonts.googleapis.com/css?family=Roboto',
                },
            ],
        });

        $scope.cardNumber = $scope.elements.create('cardNumber', {
            style: $scope.elementStyles,
            classes: $scope.elementClasses,
        });
        $scope.cardNumber.mount('#credit-card-number');

        $scope.cardExpiry = $scope.elements.create('cardExpiry', {
            style: $scope.elementStyles,
            classes: $scope.elementClasses,
        });
        $scope.cardExpiry.mount('#credit-card-expiry');

        $scope.cardCvc = $scope.elements.create('cardCvc', {
            style: $scope.elementStyles,
            classes: $scope.elementClasses,
        });
        $scope.cardCvc.mount('#credit-card-cvc');

        $scope.registerElements([$scope.cardNumber, $scope.cardExpiry, $scope.cardCvc], 'payment-form');

    }
    $scope.getImageCdn = window.getImageCdn;

    $scope.getCountries = function () {
        return new Promise(function (resolve) {
            $scope.loading = true;
            $http({
                method: "GET",
                url: base_api_url + "/countries?page_size=-1",
            }).then(
                function successCallback(response) {
                    $scope.countries = response.data.result;
                    let hasCountry = false;
                    if (countryByIp) {
                        if (!$scope.shipingLocation.country || !$scope.shipingLocation.country.id) {
                            for (let index = 0; index < $scope.countries.length; index++) {
                                let _country = $scope.countries[index];
                                if (_country.iso == countryByIp.toUpperCase()) {
                                    $scope.shipingLocation.country = _country;
                                    $scope.changeCountry();
                                    hasCountry = true;
                                    break;
                                }
                            }
                        } else {
                            hasCountry = true;
                        }
                    }
                    if (!hasCountry) {
                        $scope.shipingLocation.country = {"id":226,"iso":"US","name":"UNITED STATES","nicename":"United States"};
                        $scope.changeCountry();
                    }
                    $scope.loading = false;
                    resolve();
                },
                function errorCallback(response) {
                    $scope.loading = false;
                    resolve();
                }
            ).catch(function errorCallback(error) {
                $scope.loading = false;
                resolve();
            });
        });
    };

    $scope.getPointEarn = function (amount) {
        if ($scope.isChangeCurrency) {
            amount = decimalAdjust('ceil', amount / priceConfig.ratio);
        }
        
        // Default to 0 points if amount is too small or no config available
        $scope.customerRewards.pointEarn = 0;
        
        // Return early if amount is too small or configRangeByMarket is not available
        if (!$scope.configRangeByMarket || !$scope.configRangeByMarket.tiers) {
            return;
        }

        // Build thresholds dynamically from configRangeByMarket data
        let thresholds = [];
        
        // Add flexible tier first (highest threshold)
        if ($scope.configRangeByMarket.flexible_tier) {
            const flexibleTier = $scope.configRangeByMarket.flexible_tier;
            thresholds.push({
                min: flexibleTier.min_amount,
                points: () => Math.round(amount * flexibleTier.cp_per_dollar * 100) / 100
            });
        }
        
        // Add fixed tiers in descending order
        if ($scope.configRangeByMarket.tiers && Array.isArray($scope.configRangeByMarket.tiers)) {
            // Sort tiers by min_amount in descending order to maintain priority
            const sortedTiers = [...$scope.configRangeByMarket.tiers].sort((a, b) => b.min_amount - a.min_amount);
            
            sortedTiers.forEach(tier => {
                thresholds.push({
                    min: tier.min_amount,
                    points: () => tier.cp
                });
            });
        }

        // Find the applicable tier (first one where amount >= min)
        const tier = thresholds.find(({ min }) => amount >= min);
        $scope.customerRewards.pointEarn = tier ? tier.points() : 0;
    };

    $scope.getProvinces = function (type = 'address') {
        var country_id = "";
        $scope.districts = [];
        if (type == 'address') {
            if (!$scope.shipingLocation.country || !$scope.shipingLocation.country.id) {
                return;
            }
            country_id = $scope.shipingLocation.country.id;
        } else if (type == 'billing') {
            if (!$scope.billingAddress.country || !$scope.billingAddress.country.id) {
                return;
            }
            country_id = $scope.billingAddress.country.id;
        }
        if (type == 'address') {
            $scope.provinces = $scope.shipingLocation.country.provinces;
            if ($scope.provinces && $scope.provinces.length > 0) {
                let isExists = $scope.provinces.find(i => i.id == -1);
                if (!isExists) {
                    $scope.provinces.push({
                        id: -1,
                        name: otherText
                    })
                }
            }
        } else if (type == 'billing') {
            $scope.provincesBillings = $scope.billingAddress.country.provinces;
            if ($scope.provincesBillings && $scope.provincesBillings.length > 0) {
                let isExists = $scope.provincesBillings.find(i => i.id == -1);
                if (!isExists) {
                    $scope.provincesBillings.push({
                        id: -1,
                        name: otherText
                    })
                }
            }
        }
    };

    $scope.getCart = function () {
        return new Promise(function (resolve) {
            var locale = '';
            if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
                locale = `/${localePrefix}`;
            }
            $scope.cart = false;
            $scope.loading = true;
            var url = `/cart/get-cart-items`;
            if (exchangeFingerprint && exchangeFingerprint != "" && $scope.originOrder) {
                url += `?token=${exchangeFingerprint}_${$scope.originOrder.id}`;
            }
            $http({
                method: "GET",
                url: url,
            }).then(
                async function successCallback(response) {
                    $scope.isBulkOrder = false;
                    response.data.result.forEach(function(item) {
                        item.url = `${siteBaseUrl}${item.url}`;
                    });
                    if (response.data.result.length == 0) {
                        window.location.replace(locale + "/cart");
                    }
                    let feeBuyDesign = 0;
                    let quantity = 0;
                    let items = response.data.result;
                    for (let key in items) {
                        if (items[key] && items[key].id) {
                            if (items[key].name_variant != "" && items[key].product_name && items[key].product_name.includes(", " + items[key].name_variant)) {
                                items[key].product_name = items[key].product_name.replace(", " + items[key].name_variant, "");
                            }
                            try {
                                let configurations = JSON.parse(items[key].configurations);
                                items[key].configurationsValue = items[key].configurations;
                                items[key].configurations = {};
                                for (let i in configurations) {
                                    if (typeof configurations[i] == 'string' || typeof configurations[i] == 'number') {
                                        items[key].configurations[i] = configurations[i];
                                    }
                                }
                                if (configurations && configurations.disable_make_change) {
                                    items[key].disable_make_change = true;
                                }
                                if (configurations && configurations.buy_design == 1) {
                                    items[key].buy_design  = true;
                                }
                                if (configurations && configurations.hire_designer != undefined) {
                                    items[key].hire_designer  = configurations.hire_designer;
                                }
                                if (configurations && configurations.design_fee) {
                                    feeBuyDesign += parseFloat(configurations.design_fee);
                                }
                               
                                if (configurations.edit_url) {
                                    items[key].url = configurations.edit_url.url;
                                }
                                if (configurations.price_addtocart) {
                                    items[key].disable_make_change = true;
                                }
                                if (configurations.price_by_quantity && configurations.price_by_quantity.discount == 1) {
                                    $scope.isBulkOrder = true;
                                }
                                if (configurations["Preview url"]) {
                                    items[key].preview_url = configurations["Preview url"]['image_url'];
                                }
                                if (configurations.config_by_print_location && Object.keys(configurations.config_by_print_location).length) {
                                    items[key].print_location_3d = Object.keys(configurations.config_by_print_location).map(text => cartTranslateText[text]).join(', ');
                                }
                            } catch (error) {
                                console.log(error);
                                items[key].configurations = {};
                            }   
                        }
                    }
                    $scope.items = items;
                    for (let index = 0; index < $scope.items.length; index++) {
                        const element = $scope.items[index];
                        quantity += element.quantity;
                    }
                    $scope.totalQuantity = quantity;
                    $scope.totalDesignFee = feeBuyDesign;
                    $scope.cart = response.data;
                    $scope.verifyEmail();
                    await $scope.getCustomerInfo();
                    let result = $scope.cart.sub_total + feeBuyDesign;
                    $scope.checkShowGiftWrap();
                    $scope.checkTrademarks();
                    $scope.checkTax();
                    if ($scope.isGiftWrap && $scope.isValidGiftWrap) {
                        result += $scope.giftWrapFee;
                    }
                    for (let index = 0; index < $scope.items.length; index++) {
                        const element = $scope.items[index];
                        element.total_amount = element.quantity * element.price;
                    }
                    if (priceConfig) {
                        result = 0;
                        for (let index = 0; index < $scope.items.length; index++) {
                            const element = $scope.items[index];
                            let priceItem = parseFloat(element.price);
                            priceItem += parseFloat(priceConfig.adding_price);
                            priceItem *= parseFloat(priceConfig.ratio);
                            element.total_amount = element.quantity * decimalAdjust('ceil', priceItem);
                            result += element.total_amount;
                        }
                        if (feeBuyDesign > 0) {
                            result += decimalAdjust('ceil', feeBuyDesign * parseFloat(priceConfig.ratio));
                        }
                        if ($scope.isGiftWrap && $scope.isValidGiftWrap) {
                            result += decimalAdjust('ceil', $scope.giftWrapFee * parseFloat(priceConfig.ratio));
                        }
                    }
                    $scope.cart.sub_total_origin = $scope.cart.sub_total
                    $scope.cart.sub_total = result;
                    $scope.loading = false;
                    if (useDiscount) {
                        $scope.getDiscountByCartItems();
                    }
                    $scope.getDiscountByVipBenefit();
                    await $scope.getDiscountByRefer();
                    if ($scope.isUsePoint) {
                        $scope.usePoint();
                    }
                    resolve();
                },
                function errorCallback(response) {
                    $scope.loading = false;
                    resolve();
                }
            ).catch(function errorCallback(error) {
                $scope.loading = false;
                resolve();
            })
        });
    };

    $scope.addBodyClass = function(event) {
        var target = event.currentTarget.getAttribute('data-target');
        if (target) {
            document.body.classList.add(target);
        }
    };

    $scope.clearBodyClassAndStyle = function() {
        document.body.className = '';
        document.body.removeAttribute('style');
    };

    $scope.removeAllBodyClasses = function() {
        document.body.className = '';
    };

    $scope.getCustomerToken = () => {
        return new Promise(function (resolve) {
            var locale = '';
            if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
                locale = `/${localePrefix}`;
            }
            $scope.loading = true;
            var url = `${locale}/cart/get-customer-token?ignore_localization=1`;
            $http({
                method: "GET",
                url: url,
            }).then(
                function successCallback(response) {
                    if (response.data.status == "successful") {
                        $scope.customer.token = response.data.result;
                    }
                    $scope.loading = false;
                    resolve();
                },
                function errorCallback(response) {
                    resolve();
                }
            );
        });
    }
    $scope.changeProvince = function (type = 'address', setTemp = false) {
        if (type === 'address') {
            if (setTemp) {
                $scope.blurAction("province", $scope.shipingLocation.province);
            }
            $("#state_name_parent").removeClass('active');
            $scope.listShippers = [];
            $scope.getDistricts();
        } else {
            $("#billing-state_name").parent().removeClass('active');
        }
    };

    $scope.selectCountry = async (item, isSelect = false) => {
        if(isSelect) {
            $scope.isSelectCountry = true;
        }
        $scope.shipingLocation.country = item;
        $scope.isShowSelectCountry = false;
        await $scope.changeCountry();
        $scope.change('country')

        window.dispatchEvent(new CustomEvent('selectCountry', {detail: item.iso}));
        window.dispatchEvent(new CustomEvent('selectCountryFriend', {detail: item.iso}));
    }

    $scope.openSelectCountry = () => {
        $scope.isShowSelectCountry = true;
        $scope.isShowSelectProvince = false;
        $scope.isShowSelectDistrict = false;
        setTimeout(() => {
            $(".filter-country").focus();
        }, 300);
    }

    $scope.closeSelectProvince = () => {
        $scope.isShowSelectProvince = false;
    }
    $scope.selectProvince = (item) => {
        $scope.shipingLocation.province = item;
        $scope.isShowSelectProvince = false;
        $scope.changeProvince();
        $scope.change('province')
    }

    $scope.openSelectProvince = () => {
        $scope.isShowSelectProvince = true;
        $scope.isShowSelectDistrict = false;
        setTimeout(() => {
            $(".filter-province").focus();
        }, 300);
    }

    $scope.closeSelectDistrict = () => {
        $scope.isShowSelectDistrict = false;
    }
    $scope.selectDistrict = (item) => {
        $scope.shipingLocation.district = item;
        $scope.isShowSelectDistrict = false;
        $scope.change('district')
    }

    $scope.openSelectDistrict = () => {
        $scope.isShowSelectDistrict = true;
        $scope.isShowSelectProvince = false;
        setTimeout(() => {
            $(".filter-district").focus();
        }, 300);
    }

    $scope.closeSelectCountry = () => {
        $scope.isShowSelectCountry = false;
    }
    $scope.changeCountry = function (type = 'address', setTemp = false) {
        return new Promise(async function (resolve) {
            $scope.loading = true;
            if (type == 'address') {
                //Reset State + Province
                $scope.shipingLocation.province = null;
                $scope.shipingLocation.state_name = "";
                $scope.shipingLocation.city_name = "";
                $scope.shipingLocation.optional_address = "";
                $scope.address = "";
                $scope.shipingLocation.zipcode = "";
                $("#state_name_parent").removeClass('active');
                $("#city_name_parent").removeClass('active');
                $("#optional_address").parent().removeClass('active');
                $("#zipcode_parent").removeClass('active');
                $("#address_parent").removeClass('active');
                $scope.blurAction("country", $scope.shipingLocation.country);
                $scope.changeProvince('address', setTemp);
                $scope.getProvinces();
                $scope.checkTax();
                $scope.shipping_type = "standard";
                await $scope.getShippingInfo();
                $scope.addressSuggestions = [];
            } else if (type == 'billing') {
                //Reset State + Province
                $scope.billingAddress.province = null;
                $scope.billingAddress.state_name = "";
                $scope.billingAddress.city_name = "";
                $scope.billingAddress.optional_address = "";
                $scope.billingAddress.address = "";
                $scope.billingAddress.zipcode = "";
                $("#billing-state_name").parent().removeClass('active');
                $("#billing-city_name").parent().removeClass('active');
                $("#billing-optional_address").parent().removeClass('active');
                $("#billing-zipcode").parent().removeClass('active');
                $("#billing-address").parent().removeClass('active');
                $scope.changeProvince('billing');
                $scope.getProvinces('billing');
                $scope.billingAddressSuggestions = [];
                $scope.loading = false;
            }
            resolve();
        });
    };

    $scope.getDistricts = () => {
        return new Promise(function (resolve) {
            if (!$scope.shipingLocation.province) {
                resolve();
            }
            $scope.loading = true;
            $http({
                method: "GET",
                url: base_api_url + "/district?page_size=-1&filters=province_id=" + $scope.shipingLocation.province.id,
            }).then(
                function successCallback(response) {
                    if (response.data.status == "successful") {
                        $scope.districts = response.data.result;
                    }
                    $scope.loading = false;
                    resolve();
                },
                function errorCallback(response) {
                    $scope.loading = false;
                    resolve();
                }
            ).catch(function errorCallback(error) {
                $scope.loading = false;
                resolve();
            })
        });
    }

    $scope.getShippingFee = function () {
        if (!$scope.shipingLocation.country || !$scope.shipingLocation.country.id) {
            $scope.loading = false;
            return;
        }
        let url = base_api_url + "/shipping-fee?token=" + $scope.customer.token + "&location_id=" + $scope.shipingLocation.country.id + "&type=" + $scope.shipping_type;
        if ($scope.user && $scope.user.id) {
            url += "&customerId=" + $scope.user.id;
        }
        $http({
            method: "GET",
            url: url
        }).then(function successCallback(response) {
            if (response.data.status == "successful") {
                // $scope.shipping_fee = response.data.result.shipping_fee;
                $scope.calculateShippingByType = response.data.calculateShippingByType;
                if ($scope.calculateShippingByType) {
                    for (const [key, value] of Object.entries($scope.calculateShippingByType)) {
                        var textFreeShippingTemplate = textFreeShippingTemplate;
                        var textAboveShippingTemplate = textAboveShippingTemplate;
                        let minDate = new Date();
                        let maxDate = new Date();
                        minDate.setDate(minDate.getDate() + parseInt(value.minTimeShipping));
                        maxDate.setDate(maxDate.getDate() + parseInt(value.maxTimeShipping));
                        value["minDateString"] = $scope.monthNames[minDate.getMonth()].replace("#date", minDate.getDate());
                        value["maxDateString"] = $scope.monthNames[maxDate.getMonth()].replace("#date", maxDate.getDate());
                        value["message"] = [];
                        if (value["feeLimit"] && value["feeLimit"].length > 0) {
                            var lastMessage = "";
                            value["feeLimit"].forEach(element => {
                                let type = "";
                                if (element.cateName && element.cateName != 'default') {
                                    type = uppercaseWords(element.cateName.replace("-", " ")) + " - ";
                                }
                                let message = "";
                                if (element["feeShippingLimit"] != 0) {
                                    if (element["feeIfLimit"] != 0) {
                                        message = textFreeShippingTemplate.replace('#freeIfLimit', `${$scope.formatPrice(element["feeIfLimit"])}`);
                                        message = message.replace('#value', `${$scope.formatPrice(element["feeShippingLimit"])}`);
                                        message = message.replace('#type', `${type}`);
                                    } else {
                                        message = textAboveShippingTemplate.replace('#value', `${$scope.formatPrice(element["feeShippingLimit"])}`);
                                        message = message.replace('#type', `${type}`);
                                    }
                                }
                                if (element.cate[0] == "default") {
                                    lastMessage = message;
                                } else {
                                    value["message"].push(message);
                                }
                            });
                            if (lastMessage != "") {
                                value["message"].push(lastMessage);
                            }
                        }
                    }
                }
                $scope.loading = false;
            }
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        })
    };

    $scope.getShippingInfo = async () => {
        $scope.loading = true;
        if (!$scope.shipingLocation.country || !$scope.shipingLocation.country.id) {
            $scope.loading = false;
            return;
        }
        let token = $scope.customer.token;
        if (exchangeFingerprint) {
            token = `${exchangeFingerprint}_${$scope.originOrder.id}`;
        }
        let url = base_api_url + "/shipping-fee/item/info?token=" + token + "&location_id=" + $scope.shipingLocation.country.id;
        if ($scope.user && $scope.user.id) {
            url += "&customerId=" + $scope.user.id;
        }
        if ($scope.tenancyToken) {
            url += "&tenancyToken=" + $scope.tenancyToken;
        }
        $scope.startSend = 1;
        await $http({
            method: "GET",
            url: url,
        }).then(function successCallback(response) {
            $scope.responseShippingInfo = response;
            $scope.responseShippingInfo.country = $scope.shipingLocation.country;
            if (response.data.status == "successful") {
                $scope.buildShippingInfo(response.data.result);
            }
            $scope.getShippingFeeV2();
            $scope.loading = false;
        }, function errorCallback(response) {
            $scope.errorShippingInfos = response;
            $scope.sendFail++;
            if ($scope.sendFail <= 1) {
                $scope.getShippingInfo();
            }
        }).catch(function errorCallback(error) {
            $scope.loading = false;
            $scope.errorShippingInfos = error;
        });
    }

    $scope.buildShippingInfo = (result) => {
        let dataShipping = result;
        dataShipping.forEach(shipping => {
            shipping.cartItems = [];
            if ($scope.items.length > 0) {
                $scope.items.forEach(element => {
                    if (shipping.cart_item_id.includes(element.id)) {
                        shipping.cartItems.push(element);
                    }
                });
            }
            shipping.selectedShipping = shipping.shipping_info[0];
            if ($scope.originOrder) {
                let shippingConfiguration = JSON.parse($scope.originOrder.shipping_configurations);
                let shippingId = shipping.selectedShipping.id;
                for (const key in shippingConfiguration) {
                    if (Object.hasOwnProperty.call(shippingConfiguration, key)) {
                        const element = shippingConfiguration[key];
                        shippingId = element;
                        break;
                    }
                }
                shipping.shipping_info.forEach(element => {
                    if (element.id == shippingId) {
                        shipping.selectedShipping = element;
                        $scope.shipping_type = element.type;
                    }
                });
            }
            shipping.shipping_info.forEach(element => {
                element["freeShipping"] = "";
                let minDate = new Date();
                let maxDate = new Date();
                minDate.setDate(minDate.getDate() + parseInt(element.shipping_min_time));
                maxDate.setDate(maxDate.getDate() + parseInt(element.shipping_max_time));
                // const startTime = calculateBusinessDaysFromNow(element.shipping_min_time, false);
                // const endTime = calculateBusinessDaysFromNow(element.shipping_max_time, false);
                let startTime = getNextBusinessDay(element.shipping_min_time);
                let endTime = getNextBusinessDay(element.shipping_max_time);
                element["textBusinessDays"] = $scope.textBusinessDays.replace("#date", element.shipping_min_time + " - " + element.shipping_max_time);
                element["minTime"] = element.shipping_min_time;
                element["maxTime"] = element.shipping_max_time;
                element["textMinBusinessDays"] = $scope.monthNames[startTime.getMonth()].replace("#date", startTime.getDate());
                element["textMaxBusinessDays"] = $scope.monthNames[endTime.getMonth()].replace("#date", endTime.getDate());
                element["minDateString"] = $scope.monthNames[minDate.getMonth()].replace("#date", minDate.getDate());
                element["maxDateString"] = $scope.monthNames[maxDate.getMonth()].replace("#date", maxDate.getDate());
                element["default_shipping_fee"] = element.shipping_fee;
                if (element["type"] == "standard") {
                    for (let i = 0; i < element["additional_info"].length; i++) {
                        const info = element["additional_info"][i];
                        if (parseFloat(info.fee_limit) > 0 && parseFloat(info.fee_if_limit) == 0 && false) {
                            element["freeShipping"] += `<div><span style="font-weight: 500;">Free Shipping</span>` + " on orders over " + `<span style="font-weight: 500;">` + $scope.formatPrice(parseFloat(info.fee_limit), 0, true) + "</span> " + `(${info.cate_name})</div>`
                        }
                        if (parseFloat(info.adding_fee) == 0 && info.cate_name == "Stickers") {
                            element["freeShipping"] += `<div><span style="font-weight: 500;">No extra shipping fee</span>` + " for additional items " + `(${info.cate_name})</div>`
                        }
                    }
                }
            });
        });
        $scope.shippingInfos = dataShipping;
        if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
            $scope.$apply();
        }
        let listApply = [];
        let standardShippingFee = 0;
        $scope.shippingInfos.forEach(element => {
            if (!listApply[element.selectedShipping.id]) {
                listApply[element.selectedShipping.id] = [];
            }
            var listNewApply = [];
            element.selectedShipping.shipping_fee = element.selectedShipping.default_shipping_fee;
            for (const [key, applyItem] of Object.entries(element.selectedShipping.apply_config_item)) {
                if (listApply[element.selectedShipping.id].includes(applyItem.id)) {
                    element.selectedShipping.shipping_fee = element.selectedShipping.default_shipping_fee - parseFloat(applyItem.default_shipping_fee) + parseFloat(applyItem.default_adding_item);
                }
                listNewApply.push(applyItem.id);
            }
            element.shipping_info.forEach(shippingInfo => {
                for (const [key, applyItem] of Object.entries(shippingInfo.apply_config_item)) {
                    if (listApply[shippingInfo.id] && listApply[shippingInfo.id].includes(applyItem.id)) {
                        shippingInfo.shipping_fee = shippingInfo.default_shipping_fee - parseFloat(applyItem.default_shipping_fee) + parseFloat(applyItem.default_adding_item);
                    } else {
                        shippingInfo.shipping_fee = shippingInfo.default_shipping_fee;
                    }
                }
                if (!priceConfig) {
                    shippingInfo.shipping_fee = decimalAdjust('ceil', shippingInfo.shipping_fee);
                } else {
                    shippingInfo.shipping_fee = decimalAdjust('ceil', parseFloat(shippingInfo.shipping_fee) * priceConfig.ratio);
                }
                if (($scope.isBuyFreeshipPackageByEmail || $scope.isBuyFreeshipPackage) && shippingInfo.type == 'standard') {
                    shippingInfo.shipping_fee = 0;
                }
                if (shippingInfo.type == 'standard') {
                    standardShippingFee += shippingInfo.shipping_fee;
                }
            });
            listApply[element.selectedShipping.id] = listApply[element.selectedShipping.id].concat(listNewApply);
        });
        $scope.isShowFreeShippingPackage = true;
        if (!$scope.isBuyFreeshipPackage
            && !$scope.isBuyFreeshipPackageByEmail
            && $scope.freeshipPackageProduct
            && $scope.freeshipPackageProduct.id
            && $scope.freeshipPackageProduct.price < standardShippingFee
        ) {
            $scope.isShowFreeShippingPackage = false;
        }

        $scope.checkShowGiftWrap();
    };

    $scope.closeLoyaltyNoti = function() {
        $scope.showLoyaltyNoti = false;
    };

    // Function to check if a given date is a weekend (Saturday or Sunday)
    function isWeekend(date) {
        const day = date.getDay();
        return day === 0 || day === 6;
    }
    function getNextBusinessDay(days) {
        const currentDate = new Date();
        let businessDayCount = 0;
      
        while (businessDayCount < days) {
            currentDate.setDate(currentDate.getDate() + 1); // Move to the next day
        
            // Check if it's a weekend (Saturday or Sunday)
            if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
                businessDayCount++; // If it's a business day, increment the count
            }
        }
      
        return currentDate;
    }
      
    // Function to calculate the next business day
    function calculateBusinessDay(date, considerHolidays = false) {
        const dayMilliseconds = 24 * 60 * 60 * 1000; // Number of milliseconds in a day
    
        // Check if the given date is a weekend
        if (isWeekend(date)) {
            // If it's Saturday, move to the next Monday
            if (date.getDay() === 6) {
                date.setDate(date.getDate() + 2);
            }
            // If it's Sunday, move to the next Monday
            else if (date.getDay() === 0) {
                date.setDate(date.getDate() + 1);
            }
        }
    
        // If holidays are considered, you can add your own logic here to check for holidays
        // For example, you could have an array of holiday dates and compare against them
    
        // Recursive call in case the next day is also a weekend or holiday
        if (isWeekend(date) || (considerHolidays && isHoliday(date))) {
            date.setTime(date.getTime() + dayMilliseconds); // Add one day
            return calculateBusinessDay(date, considerHolidays); // Recursively check the next day
        }
    
        return date;
    }
  
    // Function to calculate the number of business days from now to a given number of days ahead
    function calculateBusinessDaysFromNow(daysAhead, considerHolidays = false) {
        const dayMilliseconds = 24 * 60 * 60 * 1000; // Number of milliseconds in a day
        let currentDate = new Date(); // Start from the current date
        let businessDayCount = 0; // Counter for business days
    
        for (let i = 0; i < daysAhead; i++) {
            currentDate.setTime(currentDate.getTime() + dayMilliseconds); // Move to the next day
        
            // Check if the current date is a business day
            if (!isWeekend(currentDate) && (!considerHolidays || !isHoliday(currentDate))) {
                businessDayCount++;
            }
        }
    
        return businessDayCount;
    }

    $scope.changeShippingType = (shipping, shippingInfo) => {
        let isSameType = true;
        $scope.shippingInfos.forEach(element => {
            if (element.key == shippingInfo.key) {
                element.selectedShipping = shipping;
            }
        });
        let lastShippingType = null;
        $scope.shippingInfos.forEach(element => {
            if (lastShippingType == null) {
                lastShippingType = element.selectedShipping.type;
            }
            if (element.selectedShipping.type != lastShippingType) {
                isSameType = false;
            }
        });
        $scope.sameShippingType = isSameType;
        if (isSameType) {
            $scope.shipping_type = lastShippingType;
        }
        let listApply = [];
        let standardShippingFee = 0;
        $scope.shippingInfos.forEach(element => {
            if (!listApply[element.selectedShipping.id]) {
                listApply[element.selectedShipping.id] = [];
            }
            var listNewApply = [];
            element.selectedShipping.shipping_fee = element.selectedShipping.default_shipping_fee;
            for (const [key, applyItem] of Object.entries(element.selectedShipping.apply_config_item)) {
                if (listApply[element.selectedShipping.id].includes(applyItem.id)) {
                    element.selectedShipping.shipping_fee = element.selectedShipping.default_shipping_fee - parseFloat(applyItem.default_shipping_fee) + parseFloat(applyItem.default_adding_item);
                }
                listNewApply.push(applyItem.id);
            }
            element.shipping_info.forEach(shippingInfo => {
                for (const [key, applyItem] of Object.entries(shippingInfo.apply_config_item)) {
                    if (listApply[shippingInfo.id] && listApply[shippingInfo.id].includes(applyItem.id)) {
                        shippingInfo.shipping_fee = shippingInfo.default_shipping_fee - parseFloat(applyItem.default_shipping_fee) + parseFloat(applyItem.default_adding_item);
                    } else {
                        shippingInfo.shipping_fee = shippingInfo.default_shipping_fee;
                    }
                }
                if (!priceConfig) {
                    shippingInfo.shipping_fee = decimalAdjust('ceil', shippingInfo.shipping_fee);
                } else {
                    shippingInfo.shipping_fee = decimalAdjust('ceil', parseFloat(shippingInfo.shipping_fee) * priceConfig.ratio);
                }
                if (($scope.isBuyFreeshipPackageByEmail || $scope.isBuyFreeshipPackage) && shippingInfo.type == 'standard') {
                    shippingInfo.shipping_fee = 0;
                }
                if (shippingInfo.type == 'standard') {
                    standardShippingFee += shippingInfo.shipping_fee;
                }
            });
            listApply[element.selectedShipping.id] = listApply[element.selectedShipping.id].concat(listNewApply);
        });

        $scope.isShowFreeShippingPackage = true;
        if (!$scope.isBuyFreeshipPackage
            && !$scope.isBuyFreeshipPackageByEmail
            && $scope.freeshipPackageProduct
            && $scope.freeshipPackageProduct.id
            && $scope.freeshipPackageProduct.price < standardShippingFee
        ) {
            $scope.isShowFreeShippingPackage = false;
        }

        $scope.getShippingFeeV2();
        let result = $scope.cart.sub_total;
        if ($scope.isGiftWrap && $scope.isValidGiftWrap) {
            result -= $scope.giftWrapFee;
            if (priceConfig) {
                result = $scope.cart.sub_total;
                if ($scope.isGiftWrap && $scope.isValidGiftWrap) {
                    result -= decimalAdjust('ceil', $scope.giftWrapFee * parseFloat(priceConfig.ratio));
                }
            }
        }
        $scope.cart.sub_total = result;
        $scope.checkShowGiftWrap();
    }

    $scope.getShippingFeeV2 = () => {
        let shippingFee = 0;
        $scope.shippingInfos.forEach(shipping => {
            let element = shipping.selectedShipping;
            shippingFee += decimalAdjust('ceil', element.shipping_fee);
        });

        $scope.shipping_fee = shippingFee;
        $scope.isValidateSpecialShippingFee = false;
        if (typeof useSpecialShippingFee !== "undefined" && useSpecialShippingFee && $scope.shipping_type == 'standard' && $scope.sameShippingType && $scope.shipingLocation.country && $scope.shipingLocation.country.iso == 'US') {
            let subtotal = $scope.cart.sub_total;
            $scope.cart.special_shipping_fee = null;
            $scope.cart.original_special_shipping_fee = null;
            $scope.textSpecialShippingFee = "";
            if (shouldUseNewInterface == 'a') {
                if (subtotal >= 50) {
                    $scope.cart.special_shipping_fee = shippingFeeByLevel[0];
                    $scope.isValidateSpecialShippingFee = true;
                } else {
                    $scope.textSpecialShippingFee = textAwayShippingFee.replace("#amount", `<span class="highlight">` + $scope.formatPrice(50 - subtotal, 2, true) + "</span>" );
                    $scope.textSpecialShippingFee = $scope.textSpecialShippingFee.replace("#shipping_fee", $scope.formatPrice(shippingFeeByLevel[0], 2, true));
                }
                if (subtotal >= 100) {
                    $scope.cart.special_shipping_fee = shippingFeeByLevel[1];
                    $scope.isValidateSpecialShippingFee = true;
                } else {
                    if ($scope.textSpecialShippingFee == "") {
                        $scope.textSpecialShippingFee = textAwayShippingFeeLevel2.replace("#amount", `<span class="highlight">` + $scope.formatPrice(100 - subtotal, 2, true) + "</span>" );
                    }
                }
            } else if (shouldUseNewInterface == 'b') {
                $scope.cart.special_shipping_fee = shippingFeeByLevel[0];
                $scope.isValidateSpecialShippingFee = true;
                if (subtotal >= 80) {
                    $scope.cart.special_shipping_fee = shippingFeeByLevel[1];
                    $scope.isValidateSpecialShippingFee = true;
                } else {
                    $scope.textSpecialShippingFee = textAwayShippingFeeLevel2.replace("#amount", `<span class="highlight">` + $scope.formatPrice(80 - subtotal, 2, true) + "</span>" );
                }
            }
            if (priceConfig && $scope.isValidateSpecialShippingFee) {
                $scope.cart.original_special_shipping_fee = $scope.cart.special_shipping_fee;
                $scope.cart.special_shipping_fee = decimalAdjust('ceil', $scope.cart.special_shipping_fee * priceConfig.ratio);
            }
            if ($scope.isValidateSpecialShippingFee && $scope.promotionCode && $scope.promotionCode != "") {
                $scope.submitPromotionCode();
            }
            $scope.otherFee = $scope.calculateOtherFee();
        }
        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
            $scope.$apply();
        }
        if ($scope.promotionCode && $scope.promotionCode != "") {
            $scope.submitPromotionCode();
        }
    }

    const uppercaseWords = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase());

    $scope.saveCustomerInfo = function (field = null) {
        let customerInfo = {};
        if ($scope.name) {
            customerInfo.name = $scope.name;
        }
        if ($scope.shipingLocation.zipcode) {
            customerInfo.zipcode = $scope.shipingLocation.zipcode;
        }
        if ($scope.phone) {
            customerInfo.phone = $scope.phone;
        }
        if ($scope.shipingLocation.country) {
            customerInfo.country = $scope.shipingLocation.country;
        }
        if ($scope.shipingLocation.province) {
            customerInfo.province = $scope.shipingLocation.province;
        }
        if ($scope.shipingLocation.district) {
            customerInfo.district = $scope.shipingLocation.district;
        }
        if ($scope.shipingLocation.state_name) {
            customerInfo.state_name = $scope.shipingLocation.state_name;
        }
        if ($scope.shipingLocation.city_name) {
            customerInfo.city_name = $scope.shipingLocation.city_name;
        }
        if ($scope.email) {
            customerInfo.email = $scope.email;
        }
        if ($scope.delivery_note) {
            customerInfo.delivery_note = $scope.delivery_note;
        }
        if ($scope.address) {
            customerInfo.address = $scope.address;
        }
        if ($scope.shipingLocation.optional_address) {
            customerInfo.optional_address = $scope.shipingLocation.optional_address;
        }
        if ($scope.currentPrefix.length > 0) {
            customerInfo.currentPrefix = $scope.currentPrefix;
        }
        if ($scope.currentPrefixFriend.length > 0) {
            customerInfo.currentPrefixFriend = $scope.currentPrefixFriend;
        }
        localStorage.setItem("customerInfo", JSON.stringify(customerInfo));
    };

    $scope.loadCustomerInfo = async function () {
        let customerInfo = JSON.parse(localStorage.getItem("customerInfo") ? localStorage.getItem("customerInfo") : "{}");
        if ($scope.originOrder) {
            customerInfo = await $scope.buildCustomerInfoByOrigin($scope.originOrder);
        }
        if (!$scope.name && customerInfo.name) {
            let fullname = customerInfo.name;
            const noSpacePattern = /^\S+$/;
            const hasNoSpace = noSpacePattern.test(fullname);

            if (hasNoSpace) {
                $scope.first_name = fullname;
                $("#first_name_parent").addClass('active');
            } else {
                const firstSpaceIndex = fullname.indexOf(" "); // Find the index of the first space
                if (firstSpaceIndex) {
                    const firstPart = fullname.slice(0, firstSpaceIndex); // Extract the text before the first space
                    const secondPart = fullname.slice(firstSpaceIndex + 1); // Extract the text after the first space
                    $scope.first_name = firstPart;
                    $("#first_name_parent").addClass('active');
                    if (secondPart != "") {
                        $scope.last_name = secondPart;
                        $("#last_name_parent").addClass('active');
                    }
                }
            }
        }
        if (!$scope.phone && customerInfo.phone) {
            $scope.phone = customerInfo.phone;
            $("#phone_parent").addClass('active');
        }
        if (!$scope.email && customerInfo.email) {
            $scope.email = customerInfo.email;
            $("#email_parent").addClass('active');
            $scope.verifyEmail();
            if ($scope.user && $scope.user.email) {
                $scope.email = $scope.user.email;
            }
            await $scope.getCustomerInfo();
        } else {
            if ($scope.user && $scope.user.email) {
                $scope.email = $scope.user.email;
                $("#email_parent").addClass('active');
            }
            await $scope.getCustomerInfo();
        }
        if (customerInfo.country) {
            for (let index = 0; index < $scope.countries.length; index++) {
                const element = $scope.countries[index];
                if (element.id == customerInfo.country.id) {
                    $scope.shipingLocation.country = element;
                }
            }
            $("#country_parent").addClass('active');
            await $scope.changeCountry();
        }
        if (!$scope.shipingLocation.province && customerInfo.province) {
            $scope.shipingLocation.province = customerInfo.province;
            $scope.getDistricts();
            $("#province_parent").addClass('active');
        }
        if (!$scope.shipingLocation.district && customerInfo.district) {
            $scope.shipingLocation.district = customerInfo.district;
            $("#district").parent().addClass('active');
        }
        if ($scope.shipingLocation.province && $scope.shipingLocation.province.id == -1 && !$scope.shipingLocation.state_name && customerInfo.state_name) {
            $scope.shipingLocation.state_name = customerInfo.state_name;
            $("#state_name_parent").addClass('active');
        }

        if (!$scope.shipingLocation.city_name && customerInfo.city_name) {
            $scope.shipingLocation.city_name = customerInfo.city_name;
            $("#city_name_parent").addClass('active');
        }
        if (!$scope.shipingLocation.optional_address && customerInfo.optional_address) {
            $scope.shipingLocation.optional_address = customerInfo.optional_address;
            $("#optional_address").parent().addClass('active');
        }
        if (!$scope.shipingLocation.zipcode && customerInfo.zipcode) {
            $scope.shipingLocation.zipcode = customerInfo.zipcode;
            $("#zipcode_parent").addClass('active');
        }
        if (!$scope.delivery_note && customerInfo.delivery_note) {
            $scope.delivery_note = customerInfo.delivery_note;
            $("#delivery_note").parent().addClass('active');
        }
        if (!$scope.address && customerInfo.address) {
            $scope.address = customerInfo.address;
            $("#address_parent").addClass('active');
        }
        // let dataTips = JSON.parse(localStorage.getItem("dataTips") ? localStorage.getItem("dataTips") : "{}");
        // if (dataTips.tips && !originOrder) {
        //     $scope.changeTips("specific", {value: dataTips.tips});
        // }
        // if (dataTips.customTips) {
        //     $scope.customTips.value = dataTips.customTips;
        //     $('.tips-other-value').slideDown().addClass('active');
        //     $('#tips-other-value').focus();
        //     $scope.changeCustomTips();
        // }
        if (customerInfo.currentPrefix) {
            $scope.currentPrefix = customerInfo.currentPrefix;
            window.dispatchEvent(new CustomEvent('setCurrentPrefix', {detail: customerInfo.currentPrefix}));
        } else {
            $scope.getPrefixPhone();
        }
        if (customerInfo.currentPrefixFriend) {
            $scope.currentPrefixFriend = customerInfo.currentPrefixFriend;
            window.dispatchEvent(new CustomEvent('setCurrentPrefixFriend', {detail: customerInfo.currentPrefixFriend}));
        } else {
            $scope.getPrefixPhoneFriend();
        }
    };

    $scope.buildCustomerInfoByOrigin = async (dataOrder) => {
        let customerInfo = {};
        let customerInfoData = dataOrder.attributes.customer_info;
        customerInfo.name = customerInfoData.full_name;
        customerInfo.phone = customerInfoData.phone;
        customerInfo.email = customerInfoData.email;
        customerInfo.address = customerInfoData.address;
        customerInfo.optional_address = customerInfoData.optional_address;
        customerInfo.state_name = dataOrder.state_name;
        customerInfo.city_name = dataOrder.city_name;
        customerInfo.zipcode = dataOrder.zip_code;
        for (let index = 0; index < $scope.countries.length; index++) {
            const element = $scope.countries[index];
            if (element.id == dataOrder.country_id) {
                $scope.shipingLocation.country = element;
            }
        }
        await $scope.changeCountry();
        if ($scope.provinces && $scope.provinces.length > 0) {
            $scope.shipingLocation.province = {
                id: -1,
                name: otherText
            }
            for (let index = 0; index < $scope.provinces.length; index++) {
                const element = $scope.provinces[index];
                if (element.id == dataOrder.province_id) {
                    $scope.shipingLocation.province = element;
                }
            }
        }

        return customerInfo;
    }

    function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    function validatePhone(phone) {
        var num = phone.replace(/[^0-9]/g, "");
        if (num.length < 6 || num.length > 15) {
            return false;
        }
        var re = /^[+]?[0-9]{1,14}?$/;
        return re.test(num.replace(/\s/gm, ''));
    }

    $scope.validate = function () {
        if (typeof $scope.first_name == "undefined" || $scope.first_name == "" || $scope.first_name == null) {
            $scope.errors["first_name"] = enterFirstNameText;
        }
        if (typeof $scope.last_name == "undefined" || $scope.last_name == "" || $scope.last_name == null) {
            $scope.errors["last_name"] = enterLastNameText;
        }
        if (typeof $scope.phone == "undefined" || $scope.phone == "" || $scope.phone == null) {
            $scope.errors["phone"] = enterPhoneText;
        }
        if ($scope.phone && !validatePhone($scope.getPhone())) {
            $scope.errors["phone"] = $scope.getPhone() + "<br/>" + invaluePhoneText;
        }
        if (typeof $scope.email == "undefined" || $scope.email == "" || $scope.email == null) {
            $scope.errors["email"] = enterEmailText;
        }
        if ($scope.email && !validateEmail($scope.email)) {
            $scope.errors["email"] = invalidEmailText;
        }

        if (typeof $scope.shipingLocation.country == "undefined" || !$scope.shipingLocation.country) {
            $scope.errors["country"] = selectCountryText;
        }

        if ($scope.provinces && $scope.provinces.length) {
            if (typeof $scope.shipingLocation.province == "undefined" || $scope.shipingLocation.province == "" || $scope.shipingLocation.province == null) {
                $scope.errors["province"] = selectProvinceText;
            }
        }

        if ($scope.shipingLocation.country && $scope.shipingLocation.country.iso != 'VN' && (typeof $scope.shipingLocation.city_name == "undefined" || $scope.shipingLocation.city_name == "" || $scope.shipingLocation.city_name == null)) {
            $scope.errors["city_name"] = enterCityNameText;
        }
        if ($scope.districts && $scope.districts.length) {
            if (typeof $scope.shipingLocation.district == "undefined" || $scope.shipingLocation.district == "" || $scope.shipingLocation.district == null) {
                $scope.errors["district"] = selectDistrictText;
            }
        }

        if ($scope.provinces && $scope.provinces.length > 0 && $scope.shipingLocation.province && $scope.shipingLocation.province.id == -1) {
            if (typeof $scope.shipingLocation.state_name == "undefined" || $scope.shipingLocation.state_name == "" || $scope.shipingLocation.state_name == null) {
                $scope.errors["state_name"] = enterStateNameText;
            }
        }

        if (typeof $scope.shipingLocation.zipcode == "undefined" || $scope.shipingLocation.zipcode == "" || $scope.shipingLocation.zipcode == null) {
            $scope.errors["zipcode"] = enterZipcodeText;
        }

        if (typeof $scope.address == "undefined" || $scope.address == "" || $scope.address == null) {
            $scope.errors["address"] = enterAddressText;
        }
        if (typeof $scope.delivery_note !== "undefined" && $scope.delivery_note.length > 500) {
            $scope.errors["delivery_note"] = deliveryNoteLongText;
        }
        if ($scope.isDiffirentBillingAddress) {
            if (typeof $scope.billingAddress.name == "undefined" || $scope.billingAddress.name == "" || $scope.billingAddress.name == null) {
                $scope.errorsBillingAddress["name"] = enterNameText;
            }
            if (typeof $scope.billingAddress.country == "undefined" || !$scope.billingAddress.country) {
                $scope.errorsBillingAddress["country"] = selectCountryText;
            }

            if ($scope.provincesBillings && $scope.provincesBillings.length) {
                if (typeof $scope.billingAddress.province == "undefined" || $scope.billingAddress.province == "" || $scope.billingAddress.province == null) {
                    $scope.errorsBillingAddress["province"] = selectProvinceText;
                }
            }

            if (typeof $scope.billingAddress.city_name == "undefined" || $scope.billingAddress.city_name == "" || $scope.billingAddress.city_name == null) {
                $scope.errorsBillingAddress["city_name"] = enterCityNameText;
            }

            if ($scope.provincesBillings && $scope.provincesBillings.length > 0 && $scope.billingAddress.province && $scope.billingAddress.province.id == -1) {
                if (typeof $scope.billingAddress.state_name == "undefined" || $scope.billingAddress.state_name == "" || $scope.billingAddress.state_name == null) {
                    $scope.errorsBillingAddress["state_name"] = enterStateNameText;
                }
            }

            if (typeof $scope.billingAddress.zipcode == "undefined" || $scope.billingAddress.zipcode == "" || $scope.billingAddress.zipcode == null) {
                $scope.errorsBillingAddress["zipcode"] = enterZipcodeText;
            }
            if (typeof $scope.billingAddress.address == "undefined" || $scope.billingAddress.address == "" || $scope.billingAddress.address == null) {
                $scope.errorsBillingAddress["address"] = enterAddressText;
            }
        }
        if ($scope.gift.is_check) {
            if ($scope.gift.phone && !validatePhone($scope.gift.phone)) {
                $scope.errorsGift["phone"] = invaluePhoneText;
            }
        }
        if ($scope.isGiftWrap) {
            if (!$scope.giftWrapNote || $scope.giftWrapNote == "") {
                $scope.errorsGift["note"] = giftNoMessageText;
            }
            if ($scope.giftWrapNote && $scope.giftWrapNote.length > 500) {
                $scope.errorsGift["note"] = giftMessageLongText;
            }
        }
    };

    $scope.buildBillingAddressData = () => {
        let result = {};
        if ($scope.isDiffirentBillingAddress) {
            if ($scope.billingAddress.name) {
                result['name'] = $scope.billingAddress.name;
            }
            if ($scope.billingAddress.address) {
                result['address'] = $scope.billingAddress.address;
            }
            if ($scope.billingAddress.country) {
                result['country'] = $scope.billingAddress.country.id;
            }
            if ($scope.billingAddress.province && $scope.billingAddress.province.name) {
                result['state_name'] = $scope.billingAddress.province.name;
            }
            if ($scope.billingAddress.city_name) {
                result['city_name'] = $scope.billingAddress.city_name;
            }
            if ($scope.billingAddress.optional_address) {
                result['optional_address'] = $scope.billingAddress.optional_address;
            }
            if ($scope.billingAddress.state_name) {
                result['state_name'] = $scope.billingAddress.state_name;
            }
            if ($scope.billingAddress.zipcode) {
                result['zip_code'] = $scope.billingAddress.zipcode;
            }
        } else {
            if ($scope.name) {
                result['name'] = $scope.name;
            }
            if ($scope.address) {
                result['address'] = $scope.address;
            }
            if ($scope.shipingLocation.country.id) {
                result['country'] = $scope.shipingLocation.country.id;
            }
            if ($scope.shipingLocation.province && $scope.shipingLocation.province.name) {
                result['state_name'] = $scope.shipingLocation.province.name;
            }
            if ($scope.shipingLocation.city_name) {
                result['city_name'] = $scope.shipingLocation.city_name;
            }
            if ($scope.shipingLocation.optional_address) {
                result['optional_address'] = $scope.shipingLocation.optional_address;
            }
            if ($scope.shipingLocation.state_name) {
                result['state_name'] = $scope.shipingLocation.state_name;
            }
            if ($scope.shipingLocation.zipcode) {
                result['zip_code'] = $scope.shipingLocation.zipcode;
            }
        }

        return result;
    }

    $scope.changePreOrderNote = () => {
        $scope.errorPreOrderNote = "";
    }

    $scope.preOrder = () => {
        if ($scope.preOrderNote && $scope.preOrderNote.length > 500) {
            $scope.errorPreOrderNote = giftMessageLongText;
            return;
        }
        localStorage.setItem("reserve_order", 1);
        $scope.order("reserve");
    }

    $scope.order = async function (paymentType = null) {
        $scope.errors = {};
        $scope.errorImage = "";
        $scope.errorsBillingAddress = {};
        $scope.errorsGift = {};
        $scope.loading = true;
        $scope.validate();
        if (Object.keys($scope.errors).length > 0 && $scope.errors.constructor === Object) {
            if ($scope.errors.first_name || $scope.errors.last_name || $scope.errors.phone || $scope.errors.email) {
                $('html, body').animate({scrollTop: $('#form-checkout').offset().top - 20}, 700);
            } else {
                $('html, body').animate({scrollTop: $('#shipping-info-area').offset().top - 20}, 700);
            }
            $scope.loading = false;
            return;
        }
        if (Object.keys($scope.errorsBillingAddress).length > 0 && $scope.errorsBillingAddress.constructor === Object) {
            $scope.loading = false;
            $('html, body').animate({scrollTop: $('.BillingAddressWrapper').offset().top - 20}, 700);
            return;
        }
        if (Object.keys($scope.errorsGift).length > 0 && $scope.errorsGift.constructor === Object) {
            $scope.loading = false;
            if ($scope.errorsGift["note"]) {
                $('html, body').animate({scrollTop: $('.gift-packing-wrap').offset().top - 20}, 700);
            } else {
                $('html, body').animate({scrollTop: $('#gift-infomation').offset().top - 20}, 700);
            }
            return;
        }
        if ($scope.payment_type == 'stripe' && useCheckoutInForm && $scope.errorCard !== "") {
            $scope.loading = false;
            return;
        }
        let clickOrder = localStorage.getItem("clickOrder");
        let clickTime = 0;
        if (clickOrder) {
            let dataSplit = clickOrder.split("-");
            if (dataSplit.length == 2) {
                const timestampInMilliseconds = dataSplit[1];
                const currentTimestamp = Date.now();
                const fiveDaysAgoThreshold = currentTimestamp - 2 * 24 * 60 * 60 * 1000;
                if (timestampInMilliseconds >= fiveDaysAgoThreshold) {
                    clickTime = dataSplit[0];
                }
            }
        }
        if (!localStorage.getItem("reserve_order") && !$scope.first_name.includes("(") && !$scope.last_name.includes("(")) {
            clickTime++;
            if (clickTime >= 3 && paymentType != "stripe_express" && !$scope.originOrder) {
                $scope.loading = false;
                $scope.showPreOrderForm();
                localStorage.removeItem("clickOrder");
                return;
            } else {
                localStorage.setItem("clickOrder", clickTime + "-" + Date.now());
            }
        }
        $scope.name = $scope.first_name + ' ' + $scope.last_name;
        var headers = {
            token: $scope.customer.token,
        };
        if (exchangeFingerprint && exchangeFingerprint != "" && $scope.originOrder) {
            headers.token = `${exchangeFingerprint}_${$scope.originOrder.id}`;
        }
        if (paymentType == null) {
            paymentType = $scope.payment_type;
        }
        if (paymentType == "stripe_express") {
            $scope.changePayment("stripe_express");
        } else if (paymentType == "paypal_card") {
            paymentType = "paypal";
            $scope.paypalType = "card";
        }
        let usedRewards = 0;
        let usedPoints = 0;
        if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
            usedRewards = $scope.customerRewards.rewards;
            usedPoints = $scope.customerRewards.usedPoints;
        }
        let discount = $scope.discount - usedRewards;
        let totalAmount = $scope.shipping_fee + $scope.cart.sub_total - $scope.discount + $scope.otherFee;
        if (totalAmount <= 0) {
            discount = $scope.shipping_fee + $scope.cart.sub_total + $scope.otherFee - usedRewards;
            totalAmount = 0;
        }
        let tips = 0;
        if ($scope.tipsAmount > 0) {
            totalAmount += $scope.tipsAmount;
            tips = $scope.tipsAmount;
            if (priceConfig) {
                tips = tips / priceConfig.ratio;
            }
        }
        if (totalAmount == 0) {
            paymentType = "none";
        }
        if ($scope.shipingLocation.country && $scope.shipingLocation.country.iso == 'VN') {
            $scope.shipingLocation.city_name = $scope.shipingLocation.district.name;
        }
        $scope.saveCustomerInfo();
        let billingAddress = $scope.buildBillingAddressData();
        let shippingConfiguration = {};
        $scope.shippingInfos.forEach(shipping => {
            shipping.cart_item_id.forEach(element => {
                shippingConfiguration[element] = shipping.selectedShipping.id;
            });
        });
        if ($scope.originOrder) {
            discount = parseFloat($scope.originOrder.amount);
            if ($scope.originOrder.discount) {
                discount += parseFloat($scope.originOrder.discount);
            }
        }
        let currencyConfig = null;
        if (priceConfig) {
            currencyConfig = priceConfig;
            currencyConfig.tips = $scope.tipsAmount;
            currencyConfig.currency = defaultCurrencyUnit;
            discount = discount / priceConfig.ratio;
            usedRewards = usedRewards / priceConfig.ratio;
        }
        let deliveryNote = $scope.delivery_note;
        if ($scope.preOrderNote && $scope.preOrderNote.length > 0) {
            if (deliveryNote && deliveryNote.length > 0) {
                deliveryNote += " - " + $scope.preOrderNote;
            } else {
                deliveryNote = $scope.preOrderNote;
            }
        }
        let shippingFee = $scope.shipping_fee;
        if ($scope.discountType == 'freeship') {
            if ($scope.customerRewards.rewards == 0) {
                if ($scope.shipping_fee - $scope.discount > 0) {
                    shippingFee = $scope.shipping_fee - $scope.discount;
                } else {
                    shippingFee = 0;
                }
            } else if ($scope.customerRewards.rewards > 0) {
                if ($scope.shipping_fee - $scope.discount + $scope.customerRewards.rewards > 0) {
                    shippingFee = $scope.shipping_fee - $scope.discount + $scope.customerRewards.rewards;
                } else {
                    shippingFee = 0;
                }
            }
        }
        let userReferral = localStorage.getItem("referral_username");
        if (userReferral) {
            localStorage.removeItem("referral_username");
        }
        let data = {
            name: $scope.name,
            zipcode: $scope.shipingLocation.zipcode ? $scope.shipingLocation.zipcode : 0,
            phone: $scope.getPhone(),
            country: $scope.shipingLocation.country.id,
            province: $scope.shipingLocation.province && $scope.shipingLocation.province.id ? $scope.shipingLocation.province.id : null,
            district: $scope.shipingLocation.district && $scope.shipingLocation.district.id ? $scope.shipingLocation.district.id : null,
            city_name: $scope.shipingLocation.city_name,
            state_name: $scope.shipingLocation.state_name,
            optional_address: $scope.shipingLocation.optional_address,
            email: $scope.email.replace(/\s/gm,''),
            note: $scope.note,
            address: $scope.address,
            payment_type: paymentType,
            promotion_code: $scope.validPromotionCode,
            delivery_note: deliveryNote,
            shipping_type: $scope.shipping_type,
            discount: discount,
            tips: tips,
            billing_address: JSON.stringify(billingAddress),
            shipping_configuration: JSON.stringify(shippingConfiguration),
            currency_config: JSON.stringify(currencyConfig),
            discount_type: $scope.discountType,
            suspicious_fee: $scope.isSuspicious ? $scope.suspiciousFee : 0,
            shipping_fee: shippingFee,
            user_referral: userReferral,
            using_discount_by_refer: $scope.isUsingDiscountByRefer
        };
        if ($scope.originOrder && $scope.originOrder.id) {
            data.origin_order_id = $scope.originOrder.id;
            data.other_fee = $scope.otherFee;
        }
        if ($scope.isValidateSpecialShippingFee) {
            data.special_shipping_fee = $scope.cart.special_shipping_fee;
            if (priceConfig) {
                data.special_shipping_fee = $scope.cart.original_special_shipping_fee;
            }
        }
        if ($scope.isGiftWrap && $scope.isValidGiftWrap) {
            data.gift_wrap_fee = $scope.giftWrapFee;
            data.gift_wrap_note = $scope.giftWrapNote;
        }

        if (($scope.customerRewards.showRewards || $scope.originOrder) && $scope.customerRewards.rewards > 0) {
            data.used_rewards = usedRewards;
            data.used_points = usedPoints;
        }
        let tokenUserQuery = localStorage.getItem("token_user_query");
        if (tokenUserQuery) {
            data.token_user_query = tokenUserQuery;
        }
        if ($scope.tenancyToken) {
            data.tenancy_token = $scope.tenancyToken;
        }
        if ($scope.validTax) {
            data.other_tax_fee = $scope.calculateTrumpTax();
        }
        if (typeof productsBySeller != 'undefined' && Object.keys(productsBySeller).length > 0) {
            data.products_by_seller = JSON.stringify(productsBySeller);
        }
        data.cjevent_cookie = cjeventCookie;
        data.paypal_type = $scope.paypalType;
        if ($scope.gift.is_check) {
            data.gift_info = angular.copy($scope.gift);
            data.gift_info.phone = $scope.getGiftPhone();
            delete data.gift_info.is_check;
            data.gift_info = JSON.stringify(data.gift_info);
        }
        $scope.sendAction(data, 'clickCheckout');
        await $http({
            method: "POST",
            url: base_api_url + "/api/order",
            data: data,
            headers: headers,
        }).then(
            async function successCallback(response) {
                $scope.errors = false;
                if (response.data.status == "successful") {
                    if (response.data.msg != "") {
                        $scope.loading = false;
                        // Show error to your customer
                        $(".error-payment").addClass("visible");
                        $scope.errorPayment = response.data.msg;
                        setTimeout(() => {
                            $(".error-payment").removeClass("visible");
                            $scope.errorPayment = "";
                        }, 4000);
                    } else {
                        if (response.data.order && response.data.order.amount == 0 && $scope.originOrder) {
                            window.location.href = response.data.redirect;
                            return;
                        }
                        if (paymentType == "stripe") {
                            if (useCheckoutInForm) {
                                stripe.confirmCardPayment(response.data.redirect.payment_intent, {
                                    payment_method: {
                                        card: $scope.cardNumber,
                                    }
                                }).then(function(result) {
                                    if (result.error) {
                                        $scope.loading = false;
                                        // Show error to your customer
                                        $scope.$apply(function() {
                                            $(".error").addClass("visible");
                                            $scope.errorCard = result.error.message;
                                        });
                                        setTimeout(() => {
                                            $(".error").removeClass("visible");
                                            $scope.errorCard = "";
                                        }, 4000);
                                    } else {
                                        setTimeout(() => {
                                            let paymentIntent = result.paymentIntent;
                                            if (paymentIntent.status == "succeeded") {
                                                window.location.replace(response.data.redirect.redirect);
                                            }
                                            $scope.loading = false;
                                        }, 1500);
                                    }
                                });
                            
                            } else {
                                $scope.loading = false;
                                return stripe.redirectToCheckout({ sessionId: response.data.redirect });
                            }
                        } else if (paymentType == "paypal" || paymentType == "paypal_card") {
                            if ($scope.paypalType == 'express') {
                                await $scope.actions.order.patch([{
                                    "op": 'replace',
                                    "path": "/purchase_units/@reference_id=='default'/amount",
                                    "value": {
                                        "currency_code": currencyUnit.toUpperCase(),
                                        "value": $scope.getCartAmount(false),
                                    }
                                },
                                {
                                    "op": 'add',
                                    "path": "/purchase_units/@reference_id=='default'/invoice_id",
                                    "value": response.data.redirect,
                                }]);
                                let data = await $scope.actions.order.capture();
                                if (data.status == 'COMPLETED') {
                                    $http({
                                        method: "GET",
                                        url: base_api_url + "/paypal/express/finish?order_id=" + response.data.order.id + "&invoice_id=" + response.data.redirect + "&customer_token=" + $scope.customer.token,
                                    })
                                    localStorage.removeItem("clickOrder");
                                    window.location.href = "/finish?order_id=" + response.data.order.id;
                                }
                            } else if ($scope.paypalType == 'card') {
                                $scope.orderData = response.data.order;
                                $scope.paypalOrderId = response.data.redirect.id;
                                $scope.cardField.submit().then(() => {});
                            } else {
                                if (response.data.redirect) {
                                    window.location.replace(response.data.redirect + "&useraction=commit");
                                }
                            }
                            $scope.loading = false;
                        } else if (paymentType == "none" || paymentType == "cod" || paymentType == "reserve") {
                            $scope.loading = false;
                            localStorage.removeItem("clickOrder");
                            window.location.replace(response.data.redirect);
                        } else if (paymentType == "apple_google") {
                            $scope.loading = false;
                            return stripe.redirectToCheckout({ sessionId: response.data.redirect });
                        } else if (paymentType == "stripe_express") {
                            $scope.loading = false;
                            $scope.orderData = response.data.redirect;
                        } else if (paymentType == "adyen") {
                            let responseData = response.data.redirect;
                            $scope.adyenData.returnUrl = responseData.redirect;
                            $scope.submitAdyenPayment(response.data.order.code, responseData.invoice, responseData.redirect);
                        } else if (paymentType == 'lian') {
                            $scope.paymentUrlLian = response.data.redirect;
                            window.location.href = $scope.paymentUrlLian;
                        } else {
                            $scope.loading = false;
                            return stripe.redirectToCheckout({ sessionId: response.data.redirect });
                        }
                    }
                } else {
                    if (response.data.msg != "") {
                        $scope.loading = false;
                        // Show error to your customer
                        $(".error-payment").addClass("visible");
                        $scope.errorPayment = response.data.msg;
                        setTimeout(() => {
                            $(".error-payment").removeClass("visible");
                            $scope.errorPayment = "";
                        }, 4000);
                    } else {
                        $scope.loading = false;
                        $scope.sendFailCheckout(data);
                        $scope.errorCheckout++;
                        if (response.data.message) {
                            alert(response.data.message);
                        } else if (response.data.msg) {
                            alert(errorCheckoutText);
                            $scope.showErrorCheckout();
                        }
                    }
                }
            },
            function errorCallback(response) {
                $scope.loading = false;
                data.errorOrder = response.data;
                $scope.sendFailCheckout(data);
                $scope.errorCheckout++;
                $scope.showErrorCheckout();
                $('html, body').animate({scrollTop: $('#form-checkout').offset().top - 20}, 700);
            }
        ).catch(function (error) {
            $scope.loading = false;
            data.errorOrder = error;
            $scope.sendFailCheckout(data);
            $scope.errorCheckout++;
            $scope.showErrorCheckout();
        })
    };

    $scope.getPhone = function () {
        let prefix = document.getElementById('selectedCode');
        if (typeof prefix != 'undefined' && prefix && prefix.textContent && prefix.textContent !== "") {
            prefix = prefix.textContent;
            prefix = prefix.replace(/[^0-9]/g, '');
            return (prefix + $scope.phone).replace(/\s/gm,'');
        } else {
            return $scope.phone.replace(/\s/gm,'');
        }
    }

    $scope.getGiftPhone = function () {
        let prefix = document.getElementById('selectedCodeFriend');
        if (typeof prefix != 'undefined' && prefix && prefix.textContent && prefix.textContent !== "") {
            prefix = prefix.textContent;
            prefix = prefix.replace(/[^0-9]/g, '');
            return (prefix + $scope.gift.phone).replace(/\s/gm,'');
        } else {
            return $scope.gift.phone.replace(/\s/gm,'');
        }
    }

    $scope.saveShippingInfo = async function () {
        $scope.loading = true;
        if (orderCode && $scope.shipingLocation) {
            $http({
                method: 'POST',
                url: 'ticket/change-shipping-info',
                data: {
                    code: orderCode,
                    shipping_infos: {
                        zipcode: $scope.shipingLocation.zipcode ? $scope.shipingLocation.zipcode : 0,
                        country: $scope.shipingLocation.country.name,
                        province: $scope.shipingLocation.province && $scope.shipingLocation.province.name ? $scope.shipingLocation.province.name : '',
                        district: $scope.shipingLocation.district && $scope.shipingLocation.district.name ? $scope.shipingLocation.district.name : '',
                        city_name: $scope.shipingLocation.city_name,
                        state_name: $scope.shipingLocation.state_name,
                        optional_address: $scope.shipingLocation.optional_address,
                        address: $scope.address
                    }
                }
            })
                .then((response) => {
                    window.location.href = 'contact/ticket/found-solution';
                })
                .finally(() => {
                    $scope.loading = false;
                })
        }
    }

    $scope.sendFailCheckout = async (data) => {
        await $scope.captureAndSaveImage();
        data.token = $scope.customer.token;
        data.image = $scope.errorImage;
        data.shippingInfos = $scope.shippingInfos;
        data.responseShippingInfo = $scope.responseShippingInfo;
        data.errorShippingInfos = $scope.errorShippingInfos;
        data.sendFail = $scope.sendFail;
        data.startSend = $scope.startSend;
        $http({
            method: "POST",
            url: `/cart/fail-checkout`,
            data: data
        });
        let dataFail = angular.copy(data);
        delete dataFail.shippingInfos;
        delete dataFail.responseShippingInfo;
        delete dataFail.errorShippingInfos;
        $http({
            method: "POST",
            url: `/alert/fail-checkout`,
            data: {
                data: dataFail,
            }
        });
    }

    $scope.changeBillingAddress = () => {
        $scope.isDiffirentBillingAddress = !$scope.isDiffirentBillingAddress;
        $scope.billingAddress = {};
    }

    $scope.sendAction = function (orderData, type = 'clickCheckout') {
        let shippingConfiguration = {};
        $scope.shippingInfos.forEach(shipping => {
            shipping.cart_item_id.forEach(element => {
                shippingConfiguration[element] = shipping.selectedShipping.id;
            });
        });
        $http({
            method: "POST",
            url: `/cart/checkout-action`,
            data: {
                type: type,
                data: {
                    items: $scope.items,
                    amount: parseFloat($scope.cart.sub_total) + parseFloat($scope.shipping_fee) - $scope.discount,
                    shipping_fee: $scope.shipping_fee,
                    discount: $scope.discount,
                    payment_type: $scope.payment_type,
                    name: orderData.name,
                    email: orderData.email,
                    phone: orderData.phone,
                    promotion_code: orderData.promotion_code,
                    shippingConfiguration: JSON.stringify(shippingConfiguration)
                }
            }
        });
    }

    $scope.class = function (fieldName, type = 'address') {
        let retval = "";
        if (type == 'address') {
            if (fieldName == 'country') {
                retval = "address-col";
                if ($scope.errors && $scope.errors[fieldName]) {
                    retval += " is-invalid";
                } else if ($scope.shipingLocation.country && $scope.shipingLocation.country.id) {
                    retval += " active"
                }
            } else if (fieldName == 'province') {
                retval = "address-col active";
                if ($scope.errors && $scope.errors[fieldName]) {
                    retval += " is-invalid";
                }
            } else if (fieldName == 'district') {
                retval = "address-col active";
                if ($scope.errors && $scope.errors[fieldName]) {
                    retval += " is-invalid";
                }
            } else {
                retval = "form-control";
                if ($scope.errors && $scope.errors[fieldName]) {
                    retval = "form-control is-invalid";
                }
            }
        } else if (type == 'billing') {
            if (fieldName == 'country') {
                retval = "address-col";
                if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                    retval += " is-invalid";
                } else if ($scope.billingAddress.country && $scope.billingAddress.country.id) {
                    retval += " active"
                }
            } else if (fieldName == 'province') {
                retval = "address-col";
                if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                    retval += " is-invalid";
                } else if ($scope.billingAddress.province && $scope.billingAddress.province.id) {
                    retval += " active"
                }
            } else if (fieldName == 'district') {
                retval = "address-col";
                if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                    retval += " is-invalid";
                } else if ($scope.billingAddress.district && $scope.billingAddress.district.id) {
                    retval += " active"
                }
            } else {
                retval = "form-control";
                if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                    retval = "form-control is-invalid";
                }
            }
        } else {
            retval = "form-control";
            if ($scope.errorsGift && $scope.errorsGift[fieldName]) {
                retval = "form-control is-invalid";
            }
        }

        return retval;
    };

    $scope.hasError = function (fieldName, type = 'address') {
        let retval = false;
        if (type == 'address') {
            if ($scope.errors && $scope.errors[fieldName]) {
                retval = true;
            }
        } else if (type == 'billing') {
            if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                retval = true;
            }
        } else if (type == 'gift') {
            if ($scope.errorsGift && $scope.errorsGift[fieldName]) {
                retval = true;
            }
        }

        return retval;
    };

    $scope.getErrorMsg = function (fieldName, type = 'address') {
        let retval = "";
        if (type == 'address') {
            if ($scope.errors && $scope.errors[fieldName]) {
                retval = $scope.errors[fieldName];
            }
        } else if (type == 'billing') {
            if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                retval = $scope.errorsBillingAddress[fieldName];
            }
        } else if (type == 'gift') {
            if ($scope.errorsGift && $scope.errorsGift[fieldName]) {
                retval = $scope.errorsGift[fieldName];
            }
        }

        return retval;
    };

    $scope.change = function (fieldName, type = 'address') {
        if (type == 'address') {
            if ($scope.errors && $scope.errors[fieldName]) {
                $scope.errors[fieldName] = false;
            }
        } else if (type == 'billing') {
            if ($scope.errorsBillingAddress && $scope.errorsBillingAddress[fieldName]) {
                $scope.errorsBillingAddress[fieldName] = false;
            }
        } else if (type == 'gift') {
            if ($scope.errorsGift && $scope.errorsGift[fieldName]) {
                $scope.errorsGift[fieldName] = false;
            }
        }
    };

    $scope.changePayment = function (type) {
        if ((usePaypal && usePaypalByLimit) || useGiropay || useApplePay || useKlarna || useAfterPay || useLian) {
            if (useCheckoutInForm) {
                var creditInput = $('#show-payment-type .credit-form');
                if (type == "stripe") {
                    $(creditInput).slideUp(200);
                    $("#payment-form").slideDown(200);     
                } else if (type == 'paypal_card') {
                    $(creditInput).slideUp(200);
                    $("#paypal-card-form").slideDown(200);   
                } else if (type == 'paypal') {
                    $(creditInput).slideUp(200);
                    $("#paypal-form").slideDown(200);   
                } else if (type == 'giropay') {
                    $(creditInput).slideUp(200);
                    $("#giropay-form").slideDown(200);  
                } else if (type == 'apple_google') {
                    $(creditInput).slideUp(200);
                    $("#apple-google-form").slideDown(200);                  
                } else if (type == 'klarna') {
                    $(creditInput).slideUp(200);
                    $("#klarna-form").slideDown(200); 
                } else if (type == 'afterpay') {
                    $(creditInput).slideUp(200);
                    $("#afterpay-form").slideDown(200);
                } else if (type == 'cod') {
                    $(creditInput).slideUp(200);
                    $("#cod-form").slideDown(200); 
                } else if (type == 'adyen') {
                    $(creditInput).slideUp(200);
                    $("#adyen-form").slideDown(200); 
                } else if (type == 'lian') {
                    $(creditInput).slideUp(200);
                    // $("#lian-form").slideDown(200);
                } else {
                    $("#payment-form").slideUp(200);
                }

                if (type == 'stripe') {
                    $scope.otherFeePercent = stripeFee;
                    setTimeout(() => {
                        $scope.cardNumber.focus();
                    }, 300);
                } else if (type == 'paypal') {
                    $scope.otherFeePercent = paypalFee;
                    $scope.paypalType = 'normal';
                } else if (type == 'paypal_card') {
                    $scope.otherFeePercent = paypalFee;
                } else if (type == 'giropay') {
                    $scope.otherFeePercent = giropayFee;
                } else if (type == 'apple_google' || type == 'stripe_express') {
                    $scope.otherFeePercent = applepayFee;
                } else if (type == 'klarna') {
                    $scope.otherFeePercent = klarnaFee;
                } else if (type == 'afterpay') {
                    $scope.otherFeePercent = afterpayFee;
                } else if (type == 'cod') {
                    $scope.otherFeePercent = codFee;
                } else if (type == 'adyen') {
                    $scope.otherFeePercent = adyenFee;
                } else if (type == 'lian') {
                    $scope.otherFeePercent = lianFee;
                }

                $scope.otherFee = $scope.calculateOtherFee();
            }
            $scope.payment_type = type;
            if ($scope.promotionCode) {
                $scope.submitPromotionCode();
            }
        }
    };

    $scope.moneyToString = function (price) {
        if (price == null || price.toString().match(/^\-?[0-9]+(\.[0-9]+)?$/) == null) {
            return "NA";
        }
        return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    };

    $scope.submitPromotionCode = function () {
        if ($scope.promotionCode == '') {
            return;
        }
        $scope.loadingSubmitPromotionCode = true;
        var promotionCode = $scope.promotionCode;
        $scope.discountByPromotionCode = 0;
        $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer);
        if (promotionCode && useDiscount && !$scope.isUsePoint) {
            $("#submit_promotion_code").addClass("disabled");
            var quantity = 0;
            for (var i = 0; i < $scope.cart.result.length; i++) {
                quantity += parseInt($scope.cart.result[i].quantity);
            }
            var products = [];
            for (var i = 0; i < $scope.cart.result.length; i++) {
                products.push({
                    price: $scope.cart.result[i].quantity * parseFloat($scope.cart.result[i].price),
                    id: $scope.cart.result[i].product_id,
                    quantity: $scope.cart.result[i].quantity,
                });
            }
            let shippingFee = $scope.shipping_fee;
            if (priceConfig) {
                shippingFee = $scope.shipping_fee / priceConfig.ratio;
            }
            var data = {
                "code": promotionCode,
                "amount": parseFloat($scope.cart.sub_total_origin) + $scope.totalDesignFee - parseFloat($scope.discountByProduct),
                "quantity": quantity,
                "products": products,
                "shipping_fee": shippingFee,
                "shipping_type": $scope.sameShippingType ? $scope.shipping_type : "",
                "payment_type": $scope.payment_type,
                "phone": $scope.phone ? $scope.phone.replace(/\s/gm, '') : '',
                "email": $scope.email ? $scope.email: '',

            };

            $http({
                method: "POST",
                url: "/discount/apply-code",
                data,
            }).then(function successCallback(response) {
                $scope.successPromotionCode = "";
                $scope.errorPromotionCode = "";
                if (response.data.status == "successful") {
                    $scope.errorPromotionCode = "";
                    $scope.successPromotionCode = applyCodeSuccessText;
                    $scope.validPromotionCode = $scope.promotionCode;
                    var tmpDiscount = response.data.result;
                    if (!response.data.discountType || (response.data.discountType && response.data.discountType == 'normal')) {
                        if (priceConfig) {
                            if (response.data.discountPercent) {
                                tmpDiscount = parseFloat($scope.cart.sub_total_origin) * parseFloat(response.data.discountPercent) / 100;
                                if (response.data.maxDiscount && parseFloat(response.data.maxDiscount) != 0) {
                                    if (tmpDiscount > parseFloat(response.data.maxDiscount)) {
                                        tmpDiscount = parseFloat(response.data.maxDiscount);
                                    }
                                }
                                tmpDiscount = tmpDiscount * priceConfig.ratio;
                            } else {
                                tmpDiscount = tmpDiscount * priceConfig.ratio;
                            }
                        }
                        $scope.discountByPromotionCode = tmpDiscount;
                        $scope.discount = decimalAdjust('ceil', parseFloat(tmpDiscount) + parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer));
                        $scope.discountType = 'normal';
                    } else {
                        $scope.discountByPromotionCode = tmpDiscount;
                        $scope.discount = tmpDiscount;
                        $scope.discountType = response.data.discountType;
                    }
                    if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                        $scope.discount += $scope.customerRewards.rewards;
                    }
                    if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                        $scope.$apply();
                    }
                } else {
                    if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                        $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + $scope.customerRewards.rewards;
                    }
                    $scope.errorPromotionCode = response.data.message;
                    $scope.discountType = 'normal';
                }

                $("#submit_promotion_code").removeClass("disabled");
                $scope.loadingSubmitPromotionCode = false;
            }).catch(function errorCallback() {
                $scope.loadingSubmitPromotionCode = false;
            });

        } else {
            $scope.discountType = 'normal';
            $scope.successPromotionCode = "";
            $scope.errorPromotionCode = enterCodeText;
            if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + $scope.customerRewards.rewards;
            }
            $scope.loadingSubmitPromotionCode = false;
        }
    };

    $scope.handleBlurPromotion = () => {
        if (!$scope.loadingSubmitPromotionCode) {
            $scope.submitPromotionCode();
        }
    }
    $scope.formatPrice = function(price, numberAdd = 1, format = true) {
        if (format && price != 0) {
            if (priceConfig) {
                price = (parseFloat(price) + parseFloat(priceConfig.adding_price) * numberAdd) * parseFloat(priceConfig.ratio);
            }
            price = decimalAdjust('ceil', price);
        }
        return formatPrice(price, priceTempate);
        
    };
    function decimalAdjust(type, value) {
        let matches = priceTempate.match(/{money}{([^a-zA-z0-9]+)}{([0-9]+)}/);
        let exp = -2;
        if (matches.length == 3) {
            exp = parseInt(matches[2] * (matches[2] ? -1 : 1));
        }
        // If the exp is undefined or zero...
        if (typeof exp === 'undefined' || +exp === 0) {
        return Math[type](value);
        }
        value = +value;
        exp = +exp;
        // If the value is not a number or the exp is not an integer...
        if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
            return NaN;
        }
        // Shift
        value = value.toString().split('e');
        value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
        // Shift back
        value = value.toString().split('e');
        return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }

    $scope.getDiscountByCartItems = function () {
        $http({
            method: "GET",
            url: "/discount/total",
        }).then(function successCallback(response) {
            if (response.data.status == "successful") {
                $scope.discountByProduct = 0;
                const result = response.data.result;
                for (const [key, value] of Object.entries(result)) {
                    $scope.discountByProduct += parseFloat(value.total_discount)
                }
                if (priceConfig) {
                    $scope.discountByProduct = decimalAdjust('ceil', $scope.discountByProduct * priceConfig.ratio);
                }
                $scope.discount = parseFloat($scope.discountByPromotionCode) + parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + parseFloat($scope.discountByOriginOrder);
                if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                    $scope.discount += $scope.customerRewards.rewards;
                }
            }
        }).catch(function errorCallback() {
        });
    }

    $scope.calculateOtherFee = (otherFeePercent = null) => {
        if (!otherFeePercent) {
            otherFeePercent = $scope.otherFeePercent;
        }
        let fee = 0;
        if ($scope.cart && $scope.cart.sub_total) {
            let amount = parseFloat($scope.cart.sub_total);
            if ($scope.isValidateSpecialShippingFee && ($scope.cart.special_shipping_fee || $scope.cart.special_shipping_fee == 0)) {
                amount = amount - parseFloat($scope.discount) + parseFloat($scope.cart.special_shipping_fee);
            } else {
                amount = amount - parseFloat($scope.discount) + parseFloat($scope.shipping_fee);
            }
            fee = amount * parseFloat(otherFeePercent) / 100;
        }
        if ($scope.isSuspicious) {
            let suspiciousFee = $scope.suspiciousFee;
            if (priceConfig) {
                amount = 0;
                suspiciousFee *= parseFloat(priceConfig.ratio);
                suspiciousFee += parseFloat(priceConfig.adding_price);
                suspiciousFee = decimalAdjust('ceil', suspiciousFee);
            }
            fee += suspiciousFee;
        }
        fee = decimalAdjust('ceil', fee);

        if (fee < 0) fee = 0;
        if ($scope.originOrder && Math.abs(fee - parseFloat($scope.originOrder.other_fee)) <= 0.02) {
            fee = parseFloat($scope.originOrder.other_fee);
        }
        if ($scope.isBulkOrder) {
            fee = 0;
        }
        return fee;
    }
    $scope.changeTips = (type, item = {}) => {
        let dataTips = JSON.parse(localStorage.getItem("dataTips") ? localStorage.getItem("dataTips") : "{}");
        $scope.tipsType = type;
        if (type == 'specific') {
            $scope.tips = item.value;
            $scope.tipsAmount = item.value;
            dataTips.tips = item.value;
            delete dataTips.customTips;
            $('.tips-other-value').slideUp();
        } else {
            $scope.customTips.value = "";
            $scope.tips = 0;
            $scope.tipsAmount = 0;
            $('.tips-other-value').slideDown().addClass('active');
            $('#tips-other-value').focus();
        }
        localStorage.setItem("dataTips", JSON.stringify(dataTips));
    }
    $scope.changeCustomTips = () => {
        let dataTips = JSON.parse(localStorage.getItem("dataTips") ? localStorage.getItem("dataTips") : "{}");
        if ($scope.customTips.value < 0 || $scope.customTips.value == "" || !$scope.customTips.value) {
            $scope.customTips.value = "";
            $scope.tips = 0;
            $scope.tipsAmount = 0;
        }
        if ($scope.customTips && $scope.customTips.value && $scope.customTips.value != '' && $scope.customTips.value >= 0) {
            $scope.tips = parseFloat($scope.customTips.value);
            $scope.tipsAmount = $scope.tips;
            dataTips.customTips = $scope.customTips.value;
            delete dataTips.tips;
        }
        localStorage.setItem("dataTips", JSON.stringify(dataTips));
    }
    $scope.changeFocusStateName = (type) => {
        $scope.isFocusStateName = type;
    }

    $scope.$watch('shipping_fee', function() {
        $scope.$applyAsync(function() {
            $scope.otherFee = $scope.calculateOtherFee();
            $scope.isShowPaymentType = $scope.showPaymentType();
            $scope.updateApplePayment();
        });
    });
    $scope.$watch('cart', function() {
        $scope.$applyAsync(function() {
            $scope.otherFee = $scope.calculateOtherFee();
            $scope.isShowPaymentType = $scope.showPaymentType();
            $scope.updateApplePayment();
        })
    });
    $scope.$watch('discount', function() {
        $scope.$applyAsync(function() {
            $scope.otherFee = $scope.calculateOtherFee();
            $scope.isShowPaymentType = $scope.showPaymentType();
            $scope.updateApplePayment();
        });
    });
    $scope.$watch('tips', function() {
        $scope.$applyAsync(function() {
            $scope.otherFee = $scope.calculateOtherFee();
            $scope.isShowPaymentType = $scope.showPaymentType();
            $scope.updateApplePayment();
        });
    });

    $scope.getCartAmount = (formatPrice = true, addTaxes = true) => {
        let amount = 0;
        if ($scope.cart && $scope.cart.sub_total) {
            amount = $scope.cart.sub_total;
            $scope.getPointEarn(amount);
            if ($scope.isValidateSpecialShippingFee && ($scope.cart.special_shipping_fee || $scope.cart.special_shipping_fee == 0)) {
                amount += $scope.cart.special_shipping_fee - $scope.discount + $scope.otherFee;
            } else {
                amount += $scope.shipping_fee - $scope.discount + $scope.otherFee;
            }
        }
        if (amount < 0) {
            amount = 0;
        }
        if ($scope.tips > 0) {
            let tipsVal = 0;
            if ($scope.isShowPercentTips && tipsValuePercent.length > 0 && $scope.tipsType == 'specific') {
                $scope.tipsAmount = Math.round(($scope.tips * $scope.cart.sub_total / 100) * 10) / 10;
                $scope.tipsAmount = decimalAdjust('ceil', $scope.tipsAmount);
                tipsVal = Math.round(($scope.tips * $scope.cart.sub_total / 100) * 10) / 10;
                tipsVal = decimalAdjust('ceil', tipsVal);
            } else {
                $scope.tipsAmount = $scope.tips;
                tipsVal = $scope.tips;
            }
            amount += tipsVal;
        }
        if (addTaxes && useTaxes) {
            let taxes = $scope.calculateTaxFee(false);
            amount += taxes;
        }
        if ($scope.validTax) {
            const tax = $scope.calculateTrumpTax();
            amount += tax;
        }
        amount = Math.round(amount * 1000) / 1000;
        amount = decimalAdjust('ceil', amount);
        $scope.calculateRoundTip(amount);
        if (formatPrice) {
            amount = $scope.formatPrice(amount, 0, false);
        }
        return amount;
    }

    $scope.calculateRoundTip = (amount) => {
        if ($scope.locale == "jp" || $scope.tips > 0 || $scope.isShowPercentTips) {
            return;
        }
        let rounded = Math.ceil(amount / 5) * 5;
        let tips = parseFloat((rounded - amount).toFixed(2));
        if ($scope.lastTips == tips) {
            return;
        }
        $scope.lastTips = tips;
        if (tips > 0) {
            try {
                let minIndex = 0;
                let minTips = 10000;
                let tipsValue = angular.copy($scope.tipsValueDefault);
                for (let index = 0; index < tipsValue.length; index++) {
                    const element = tipsValue[index];
                    if (minTips > element.value && element.value > 0) {
                        minIndex = index;
                        minTips = element.value;
                    }
                }
                if (minIndex > 0) {
                    tipsValue[minIndex].value = tips;
                    tipsValue[minIndex].key = formatPrice(tips, priceTempate);
                    $scope.tipsValue = tipsValue;
                }
            } catch (error) {
                console.log(error);
                $scope.tipsValue = angular.copy($scope.tipsValueDefault);
            }
        }
    }

    $scope.calculateTrumpTax = (formatPrice = false) => {
        let amount = 0;
        if ($scope.cart && $scope.cart.sub_total) {
            amount = $scope.cart.sub_total;
            if ($scope.isValidateSpecialShippingFee && ($scope.cart.special_shipping_fee || $scope.cart.special_shipping_fee == 0)) {
                amount += $scope.cart.special_shipping_fee - $scope.discount;
            } else {
                amount += $scope.shipping_fee - $scope.discount;
            }
        }
        if (amount < 0) {
            amount = 0;
        }
        let taxPercent = 20;
        let taxAmount = amount * taxPercent / 100;
        taxAmount = decimalAdjust('ceil', taxAmount);
        if (formatPrice) {
            return $scope.formatPrice(taxAmount, 0, false);
        } else {
            return taxAmount;
        }
    }

    $scope.calculateTaxFee = (formatPrice = true) => {
        let amount = $scope.getCartAmount(false, false);
        let taxFee = 0;
        let isExists = false;
        if ($scope.shipingLocation.country && $scope.shipingLocation.country.iso == 'US') {
            if ($scope.shipingLocation.province && $scope.shipingLocation.province.id) {
                let taxPercent = $scope.taxes[$scope.shipingLocation.province.id];
                taxFee = taxPercent * amount / 100;
                taxFee = decimalAdjust('ceil', taxFee);
                isExists = true;
            }
        }
        if (taxFee > 0) {
            if (formatPrice) {
                taxFee = $scope.formatPrice(taxFee, 0, false);
                return "+" + taxFee;
            } else {
                return taxFee;
            }
        } else {
            if (formatPrice) {
                if (isExists) {
                    return $scope.formatPrice(taxFee, 0, false);;
                } else {
                    return $scope.calculateCheckoutText;
                }
            } else {
                return taxFee
            }
        }
    }

    $scope.getAmountAfterPay = () => {
        let afterPayOtherFee = $scope.calculateOtherFee(afterpayFee);
        let amount = 0;
        if ($scope.cart && $scope.cart.sub_total) {
            amount = $scope.cart.sub_total;
            if ($scope.isValidateSpecialShippingFee && ($scope.cart.special_shipping_fee || $scope.cart.special_shipping_fee == 0)) {
                amount += $scope.cart.special_shipping_fee - $scope.discount + afterPayOtherFee;
            } else {
                amount += $scope.shipping_fee - $scope.discount + afterPayOtherFee;
            }
        }
        if (amount < 0) {
            amount = 0;
        }
        if ($scope.tips > 0) {
            let tipsVal = 0;
            if ($scope.isShowPercentTips && tipsValuePercent.length > 0 && $scope.tipsType == 'specific') {
                tipsVal= Math.round(($scope.tips * $scope.cart.sub_total / 100) * 10) / 10;
            } else {
                tipsVal= $scope.tips;
            }
            amount += tipsVal;
        }
        amount = decimalAdjust('ceil', amount / 4);
        amount = $scope.formatPrice(amount, 0, false);
        return amount;
    }

    $scope.showPaymentType = () => {
        let result = true;
        let amount = 0;
        if ($scope.cart && $scope.cart.sub_total) {
            amount = $scope.shipping_fee + $scope.cart.sub_total - $scope.discount + $scope.otherFee;
        }
        if (amount <= 0) {
            result = false;
        }
        if ($scope.tips > 0) {
            result = true;
        }
        return result;
    }

    $scope.openFormChangeVariant = (item) => {
        if (item.disable_make_change) {
            return;
        }
        item.loadingMakeChange = true;
        window.dispatchEvent(new CustomEvent('makeChangeProduct', {detail: item}));
    }

    window.addEventListener('makeChangeProductDone', function (event, data) {
        let item = angular.copy(event.detail);
        for (let index = 0; index < $scope.items.length; index++) {
            const element = $scope.items[index];
            if (element.id == item.id) {
                element.loadingMakeChange = false;
                $scope.$apply(function() {})
            }
        }
    });

    function findGetParameter(parameterName) {
        var result = null,
            tmp = [];
        var items = location.search.substr(1).split("&");
        for (var index = 0; index < items.length; index++) {
            tmp = items[index].split("=");
            if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        }
        return result;
    }

    $scope.buildShippingInfoPaypal = async (dataOrder) => {
        let data = dataOrder;
        let purchase_units = data && data.purchase_units ? data.purchase_units[0] : null;
        if (purchase_units) {
            let shipping = purchase_units.shipping;
            let country = null;
            for (let index = 0; index < $scope.countries.length; index++) {
                const element = $scope.countries[index];
                if (element.iso == shipping.address.country_code) {
                    country = element;
                }
            }
            let isChange = false;
            $scope.$apply(function() {
                $scope.name = shipping.name.full_name;
                $scope.email = purchase_units.payee.email_address;
                if ($scope.shipingLocation.country && $scope.shipingLocation.country.iso != country.iso) {
                    $scope.shipingLocation.country = country;
                    isChange = true;
                }
            });
            if (isChange) {
                await $scope.changeCountry();
            }
            let state = null;
            if ($scope.provinces.length > 0) {
                for (let index = 0; index < $scope.provinces.length; index++) {
                    const element = $scope.provinces[index];
                    if (element.name == shipping.address.admin_area_1) {
                        state = element;
                    }
                }
            }
            $scope.$apply(function() {
                if (state) {
                    $scope.shipingLocation.province = state;
                } else {
                    if ($scope.provinces.length > 0) {
                        $scope.shipingLocation.province = {
                            id: -1,
                            name: otherText
                        };
                        $scope.shipingLocation.state_name = shipping.address.admin_area_1;
                        $scope.shipingLocation.city_name = shipping.address.admin_area_2;
                    } else {
                        $scope.shipingLocation.city_name = shipping.address.admin_area_1;
                    }
                }
                $scope.address = shipping.address.address_line_1;
                $scope.optional_address = shipping.address.address_line_2;
                $scope.shipingLocation.zipcode = shipping.address.postal_code;
            });
            $("#city_name_parent").addClass('active');
            $("#state_name_parent").addClass('active');
            $("#zipcode_parent").addClass('active');
            $("#address_parent").addClass('active');
            $("#name_parent").addClass('active');
            $("#email_parent").addClass('active');
            if (shipping.address.address_line_2) {
                $("#optional_address_parent").addClass('active');
            }
        }
    }
    $scope.initial = async () => {
        var sku = findGetParameter("sku");
        if (sku) {
            await $scope.addItemToCartBySku(sku);
        }
        await $scope.getCustomerToken();
        await $scope.getConfigRangeByMarket();
        await $scope.getCustomerPoint();
        await $scope.getCart();
        await $scope.changeCountry();
        await $scope.loadCustomerInfo();
        $scope.getProductsDesignWatermark();
        $scope.getDesignFee();
        $scope.findFreeshipPackageProduct();
        $scope.firstLoadingCart.is_show = false;
        $(".loading-item-box").attr('style', 'display: none !important');
        $("#promotion_code").on("keypress", function (e) {
            if (e.which === 13) {
                $scope.submitPromotionCode();
            }
        });
        $("#use_rewards").on("keypress", function (e) {
            if (e.which === 13) {
                $scope.changeUseRewards();
            }
        });
        $("#promotion_code").on("change", function () {
            $scope.errorPromotionCode = "";
            $scope.successPromotionCode = "";
        });
        var promoCode = findGetParameter("pcode");
        if (promoCode) {
            $scope.promotionCode = promoCode;
            $scope.submitPromotionCode();
            let box = $(".coupon-select-input-container");
            $('.js-click-show-promotion').addClass("js-collapse-promote");
            box.addClass("open-promotion-code").addClass("active");
        }
        
        var typingTimer;
        $('.filter-country').on('keyup', function() {
            clearTimeout(typingTimer);
            var $this = $(this);
            if ($this.val) {
                typingTimer = setTimeout(function() {
                    var str = $this.val().toLowerCase();
                    var options = $this.parent().parent().find('ul>li');
                    if (str != '') {
                        for (var i = 0; i < options.length; i++) {
                            var option = options.eq(i);
                            var name = option.text().toLowerCase();
                            var res = name.indexOf(str);
                            if (res !== -1) {
                                option.removeClass('hidden');
                            } else {
                                option.addClass('hidden').removeClass('active');
                            }
                        }
                    } else {
                        options.removeAttr('class');
                    }
                }, 500);
            }
        });
        var typingTimerProvince;
        $('.filter-province').on('keyup', function() {
            clearTimeout(typingTimerProvince);
            var $this = $(this);
            if ($this.val) {
                typingTimerProvince = setTimeout(function() {
                    var str = $this.val().toLowerCase();
                    var options = $this.parent().parent().find('ul>li');
                    if (str != '') {
                        for (var i = 0; i < options.length; i++) {
                            var option = options.eq(i);
                            var name = option.text().toLowerCase();
                            var res = name.indexOf(str);
                            if (res !== -1) {
                                option.removeClass('hidden');
                            } else {
                                option.addClass('hidden').removeClass('active');
                            }
                        }
                    } else {
                        options.removeAttr('class');
                    }
                }, 500);
            }
        });
        if ($scope.cart && $scope.cart.sub_total > 80 && tipsValuePercent.length > 0 && $scope.locale != "jp") {
            $scope.isShowPercentTips = true;
            $scope.tipsValue = $scope.tipsValuePercent;
        }
        if ($scope.originOrder) {
            if ($scope.stripePayment.includes($scope.originOrder.payment_type)) {
                $scope.payment_type = "stripe";
            } else {
                if ($scope.originOrder.payment_type == "PAYPAL") {
                    $scope.payment_type = "paypal";
                } else if ($scope.originOrder.payment_type == "APPLE_GOOGLE") {
                    $scope.payment_type = "apple_google";
                } else if ($scope.originOrder.payment_type == "AFTERPAY") {
                    $scope.payment_type = "afterpay";
                }
            }
            $scope.changePayment($scope.payment_type);
        }
        if (paypalExpressCheckout && paypal && paypal.CardFields) {
            // Create the Card Fields Component and define callbacks
            $scope.cardField = paypal.CardFields({
                createOrder: async function (data) {
                    return $scope.paypalOrderId;
                },
                onApprove: async function (data) {
                    const { orderID } = data;
                    await $scope.capturePaypalCard(orderID);
                },
                onError: function (error) {
                    try {
                        if (error.message) {
                            const errorMessageMatch = error.message.match(/"message":"(.*?)"/);
                            if (errorMessageMatch && errorMessageMatch.length > 1) {
                                const errorMessage = errorMessageMatch[1];
                                $("#paypal-card-errors").addClass("visible");
                                $scope.$apply(function() {
                                    $scope.errorCard = errorMessage;
                                })
                                setTimeout(() => {
                                    $("#paypal-card-errors").removeClass("visible");
                                    $scope.$apply(function() {
                                        $scope.errorCard = "";
                                    })
                                }, 5000);
                            }
                        }
                    } catch (error) {
                        console.log(error)
                    }
                },
            });
            // Render each field after checking for eligibility
            console.log("isEligible", $scope.cardField.isEligible());
            if ($scope.cardField.isEligible()) {
                const nameFieldStyle = {
                    'input': {
                        'font-size': '16px',
                        'font-weight': '400',
                        'color': '#444',
                        'padding': '10px 12px',
                        'border-color':'#e1e1e1',
                        'border-width':'2px'
                    },
                    '.invalid': {
                        'color': 'purple',
                    },
                };
                const numberField = $scope.cardField.NumberField({
                    style: nameFieldStyle
                });
                numberField.render("#card-number");
                const nameField = $scope.cardField.NameField({
                    style: nameFieldStyle
                });
                nameField.render("#card-name");

                const cvvField = $scope.cardField.CVVField({
                    style: nameFieldStyle
                });
                cvvField.render("#card-cvv");

                const expiryField = $scope.cardField.ExpiryField({
                    style: nameFieldStyle
                });
                expiryField.render("#card-expiry");
            }
        }
        const appearance = {
            theme: 'stripe',
            variables: {
                borderRadius: '4px',
            }
        }
        const expressCheckoutOptions = {
            buttonHeight: 55,
            buttonType: {
                applePay: 'plain',
                googlePay: 'buy',
                paypal: 'buynow'
            }
        }
        const elements = stripe.elements({
            mode: 'payment',
            amount: 1099,
            currency: defaultCurrencyUnit.toLowerCase(),
            appearance,
        })
        const expressCheckoutElement = elements.create(
            'expressCheckout',
            expressCheckoutOptions
        )
        const handleError = (error) => {
            const messageContainer = document.querySelector('#error-message');
            messageContainer.textContent = error.message;
        }
        if (useApplePay && useExpressCheckout) {
            expressCheckoutElement.mount('#express-checkout-element')
            expressCheckoutElement.on('click', function(event) {
                $scope.errors = {};
                $scope.errorImage = "";
                $scope.errorsBillingAddress = {};
                $scope.errorsGift = {};
                if ($scope.validApplePay) {
                    $scope.payment_type = "apple_google";
                    $scope.changePayment("apple_google");
                } else {
                    if ($scope.payment_type != "stripe") {
                        $scope.payment_type = "stripe";
                        $scope.changePayment("stripe");
                    }
                }
                $scope.validate();
                $scope.$apply(function() {});
                elements.update({
                    amount: $scope.formatPriceByCurrency($scope.getCartAmount(false), '*')
                });
                if (Object.keys($scope.errors).length > 0 && $scope.errors.constructor === Object) {
                    if ($scope.errors.first_name || $scope.errors.last_name || $scope.errors.phone || $scope.errors.email) {
                        $('html, body').animate({scrollTop: $('#form-checkout').offset().top - 20}, 700);
                    } else {
                        $('html, body').animate({scrollTop: $('#shipping-info-area').offset().top - 20}, 700);
                    }
                    $scope.loading = false;
                    return;
                }
                if (Object.keys($scope.errorsBillingAddress).length > 0 && $scope.errorsBillingAddress.constructor === Object) {
                    $scope.loading = false;
                    $('html, body').animate({scrollTop: $('.BillingAddressWrapper').offset().top - 20}, 700);
                    return;
                }
                if (Object.keys($scope.errorsGift).length > 0 && $scope.errorsGift.constructor === Object) {
                    $scope.loading = false;
                    if ($scope.errorsGift["note"]) {
                        $('html, body').animate({scrollTop: $('.gift-packing-wrap').offset().top - 20}, 700);
                    } else {
                        $('html, body').animate({scrollTop: $('#gift-infomation').offset().top - 20}, 700);
                    }
                    return;
                }
                event.resolve();
            });
            expressCheckoutElement.on('confirm', async (event) => {
                $scope.orderData = null;
                const {error: submitError} = await elements.submit();
                if (submitError) {
                    handleError(submitError);
                    return;
                }
            
                await $scope.order("stripe_express");
                if (!$scope.orderData) {
                    if ($scope.validApplePay) {
                        $scope.payment_type = "apple_google";
                        $scope.changePayment("apple_google");
                    } else {
                        $scope.payment_type = "stripe";
                        $scope.changePayment("stripe");
                    }
                    return;
                }
                const {error} = await stripe.confirmPayment({
                    // `elements` instance used to create the Express Checkout Element
                    elements,
                    // `clientSecret` from the created PaymentIntent
                    clientSecret: $scope.orderData.payment_intent,
                    confirmParams: {
                        return_url: $scope.orderData.redirect,
                    },
                });
            
                if (error) {
                    // This point is only reached if there's an immediate error when
                    // confirming the payment. Show the error to your customer (for example, payment details incomplete)
                    handleError(error);
                    if ($scope.validApplePay) {
                        $scope.payment_type = "apple_google";
                        $scope.changePayment("apple_google");
                    } else {
                        $scope.payment_type = "stripe";
                        $scope.changePayment("stripe");
                    }
                } else {
                    // The payment UI automatically closes with a success animation.
                    // Your customer is redirected to your `return_url`.
                }
            });
        }
        if (useCheckoutInForm &&
            useApplePay &&
            $scope.shipingLocation.country &&
            $scope.shipingLocation.country.iso &&
            validCountry.includes($scope.shipingLocation.country.iso)
        ) {
            $scope.paymentRequest = stripe.paymentRequest({
                country: $scope.shipingLocation.country.iso,
                currency: currencyUnit,
                total: {
                    label: 'Checkout',
                    amount: 10000,
                },
                requestPayerName: true,
                requestPayerEmail: true,
            });
            $scope.prButton = $scope.elements.create('paymentRequestButton', {
                paymentRequest: $scope.paymentRequest,
                style: {
                    paymentRequestButton: {
                        type: 'default',
                        // One of 'default', 'book', 'buy', or 'donate'
                        // Defaults to 'default'

                        theme: 'dark',
                        // One of 'dark', 'light', or 'light-outline'
                        // Defaults to 'dark'

                        height: '64px'
                        // Defaults to '40px'. The width is always '100%'.
                    },
                },
            });
            $scope.paymentRequest.canMakePayment().then(function(result) {
                $scope.paymentGateway.isApplePay = false;
                $scope.paymentGateway.isGooglePay = false;
                if (result && (result.applePay || result.googlePay)) {
                    $scope.validApplePay = true;
                    if (result.applePay) {
                        $scope.$apply(function() {
                            $scope.paymentGateway.isApplePay = true;
                        })
                    } else {
                        $scope.$apply(function() {
                            $scope.paymentGateway.isGooglePay = true;
                        })
                    }
                } else {
                    $scope.validApplePay = false;
                    document.getElementById('payment-request-button').style.display = 'none';
                    document.getElementById('express-checkout-element').style.display = 'none';
                    document.getElementById('label-applepay').style.display = 'none';
                }
            }); 
            $scope.paymentRequest.on('paymentmethod', async function(ev) {
                if ($scope.dataOrder && $scope.dataOrder.order.id) {
                    // Confirm the PaymentIntent without handling potential next actions (yet).
                    stripe.confirmCardPayment(
                        $scope.dataOrder.redirect.payment_intent,
                        {payment_method: ev.paymentMethod.id},
                        {handleActions: false}
                    ).then(function(confirmResult) {
                        if (confirmResult.error) {
                            // Report to the browser that the payment failed, prompting it to
                            // re-show the payment interface, or show an error message and close
                            // the payment interface.
                            alert(errorCheckoutText);
                            ev.complete('fail');
                        } else {
                            // Report to the browser that the confirmation was successful, prompting
                            // it to close the browser payment method collection interface.
                            ev.complete('success');
                            // Check if the PaymentIntent requires any actions and if so let Stripe.js
                            if (confirmResult.paymentIntent.status === "requires_action") {
                                // Let Stripe.js handle the rest of the payment flow.
                                stripe.confirmCardPayment($scope.dataOrder.redirect.payment_intent).then(function(result) {
                                if (result.error) {
                                    // The payment failed -- ask your customer for a new payment method.
                                    alert(errorCheckoutText);
                                } else {
                                    // The payment has succeeded.
                                    window.location.replace($scope.dataOrder.redirect.redirect);
                                }
                                });
                            } else {
                                // The payment has succeeded.
                                window.location.replace($scope.dataOrder.redirect.redirect);
                            }
                        }
                    });
                }
            });
        } else {
            $scope.validApplePay = false;
            document.getElementById('payment-request-button').style.display = 'none';
            document.getElementById('express-checkout-element').style.display = 'none';
            document.getElementById('label-applepay').style.display = 'none';
        }
        if (cardForm == 'adyen') {
            $scope.initAdyenCheckout();
        }
        window.addEventListener('change-cart', async function (event, data) {
            if (event.detail) {
                localStorage.setItem("change-cart", Date.now());
                await Promise.all([
                    $scope.getCart()
                ]);
                $scope.loadingRemoveItem = true;
                await $scope.getShippingInfo();
                $scope.loadingRemoveItem = false;
                $scope.getProductsDesignWatermark();
                $scope.getDesignFee();
                if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                    $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + $scope.customerRewards.rewards;
                }
                if ($scope.promotionCode) {
                    $scope.submitPromotionCode();
                }
            }
        });

        $(window).on("storage", async function (e) {
            let storageEvent = e.originalEvent;
            if (storageEvent.key == "change-cart") {
                $scope.loadingRemoveItem = true;
                await Promise.all([
                    $scope.getCart()
                ]);
                await $scope.getShippingInfo();
                $scope.loadingRemoveItem = false;
                $scope.getProductsDesignWatermark();
                if ($scope.customerRewards.showRewards && $scope.customerRewards.rewards > 0) {
                    $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + $scope.customerRewards.rewards;
                }
                if ($scope.promotionCode) {
                    $scope.submitPromotionCode();
                }
            }
        });
        /*
        * check is customer logged in
        * */
        if ($scope.user && typeof $scope.user.id !== 'undefined') {
            let address = await getAddressBook();
            if (address && address.length) {
                // console.log('apply address')
                // @todo default address
            }
            if (document.getElementsByClassName("address-book-close") && document.getElementsByClassName("address-book-close")[0]) {
                document.getElementsByClassName("address-book-close")[0].onclick = function() {
                    closeAddressModal();
                };
            }
            window.onclick = function(event) {
                if (event.target === addressBookModal) {
                    closeAddressModal();
                }
            }

        }
        await $scope.getShippingInfo();
        if ($scope.originOrder) {
            if ($scope.originOrder.discount) {
                $scope.discountByOriginOrder += parseFloat($scope.originOrder.discount);
                $scope.discount = parseFloat($scope.discountByProduct) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + parseFloat($scope.discountByOriginOrder);
            }
            if ($scope.originOrder.used_rewards) {
                $scope.customerRewards.rewards = parseFloat($scope.originOrder.used_rewards);
                $scope.discount += parseFloat($scope.customerRewards.rewards);
            }
            if ($scope.originOrder.tips) {
                $scope.tips = parseFloat($scope.originOrder.tips);
            }
        }
        $scope.eventViewCheckoutInsider();
    }

    $scope.eventRemoveCartInsider = function (item) {
        var localeInsider = 'us';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            localeInsider = localePrefix;
        }
        let {color, size, taxonomy} = $scope.getSizeAndColorAndTaxonomy(item.cart_item_insider ?? null);
        let data = {
            type: 'remove_from_cart',
            value: {
                id: 'sku-' + item.product_sku_id,
                name: item.product_name,
                groupcode: localeInsider + '-' + item.product_id,
                taxonomy: taxonomy,
                unit_price: parseFloat(item.high_price),
                unit_sale_price: parseFloat(item.price),
                quantity: parseInt(item.quantity),
                url: item.url,
                color: color ?? "",
                size: size ?? "",
                product_image_url: item.image_url,
                custom: {
                    merchandiser: "",
                    country: localeInsider
                }
            }
        }
        $scope.pushEventToInsider(data);
    }

    $scope.getSizeAndColorAndTaxonomy = function(dataInsider) {
        let color = '';
        let size = '';
        let taxonomy = [];
        if (dataInsider) {
            try {
                dataInsider = JSON.parse(dataInsider);
                color = dataInsider.color;
                size = dataInsider.size;
                taxonomy = dataInsider.array_category_name;
            } catch (error) {
                console.warn(error);
            }
        }
        return {color: color, size: size, taxonomy: taxonomy};
    }

    $scope.eventViewCheckoutInsider = function() {
        var localeInsider = 'us';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            localeInsider = localePrefix;
        }
        let data = {
            type: 'checkout',
            value: {
                shipping_cost: $scope.shipping_fee,
                total: $scope.getCartAmount(false),
                items: []
            }
        }
        $scope.items.forEach(function(item) {
            let {color, size, taxonomy} = $scope.getSizeAndColorAndTaxonomy(item.cart_item_insider ?? null);
            data.value.items.push({
                id: 'sku-' + item.product_sku_id,
                name: item.product_name,
                groupcode: localeInsider + '-' + item.product_id,
                taxonomy: taxonomy,
                unit_price: parseFloat(item.high_price),
                unit_sale_price: parseFloat(item.price),
                quantity: parseInt(item.quantity),
                url: item.url,
                color: color ?? "",
                size: size ?? "",
                product_image_url: item.image_url,
                custom: {
                    merchandiser: "",
                    country: localeInsider
                }
            });
        });
        $scope.pushEventToInsider(data);
    }

    $scope.pushEventToInsider = function (data) {
        const newEvent = new CustomEvent('eventInsider', {
            detail: data,
            bubbles: true,
            cancelable: true
        });
        document.dispatchEvent(newEvent);
    }

    $scope.submitAdyenPayment = (orderCode, reference, returnUrl) => {
        if ($scope.isValidAdyenState) {
            // Gửi payment với orderCode
            $http({
                method: 'POST',
                url: adyenServiceUrl + '/api/adyen/payment/submit',
                headers: { 'Content-Type': 'application/json' },
                data: {
                    amount: $scope.formatPriceByCurrency($scope.getCartAmount(false), '*'),
                    currency: currencyUnit.toUpperCase(),
                    reference: reference,
                    returnUrl: returnUrl,
                    countryCode: $scope.shipingLocation.country.iso,
                    paymentMethod: $scope.cardData,
                    orderCode: orderCode,
                },
              }).then(paymentResponse => {
                console.log("Server payment response:", JSON.stringify(paymentResponse.data, null, 2));
                if (paymentResponse.data.action) {
                    $scope.cardComponent.handleAction(paymentResponse.data.action); // Xử lý 3D Secure
                } else if (paymentResponse.data.resultCode === "Authorised") {
                    console.log("Payment authorised successfully");
                    window.location.href = returnUrl;
                } else {
                    console.error("Payment failed");
                    $(".error-payment").addClass("visible");
                    $scope.errorPayment = invalidCardText;
                    setTimeout(() => {
                        $(".error-payment").removeClass("visible");
                        $scope.errorPayment = null;
                    }, 4000);
                    $scope.loading = false;
                }
              }).catch(error => {
                console.error("Payment submission failed:", error);
                $(".error-payment").addClass("visible");
                $scope.errorPayment = invalidCardText;
                setTimeout(() => {
                    $(".error-payment").removeClass("visible");
                    $scope.errorPayment = null;
                }, 4000);
                $scope.loading = false;
            });
        } else {
            console.error("Payment submission failed:");
            $(".error-payment").addClass("visible");
            $scope.errorPayment = invalidCardText;
            setTimeout(() => {
                $(".error-payment").removeClass("visible");
                $scope.errorPayment = null;
            }, 4000);
            $scope.loading = false;
        }
    }

    $scope.initAdyenCheckout = async () => {
        const globalConfiguration = {
            environment: adyenEnvironment, // Hoặc 'live'
            clientKey: adyenClientKey, // Thay bằng clientKey thật
            countryCode: "US",
            locale: 'en-US',
            showPayButton: false, // Ẩn nút "Pay" mặc định của Adyen
            paymentMethodsConfiguration: {
                card: {
                    hasHolderName: false,
                    holderNameRequired: false,
                    billingAddressRequired: false,
                    showPayButton: false,
                },
            },
            onChange: (state, component) => {
                $scope.cardData = state.data.paymentMethod;
                $scope.isValidAdyenState = state.isValid;
                $scope.$apply();
            },
            onError: (error) => {
                console.error("Card error:", error);
                $(".error-payment").addClass("visible");
                $scope.errorPayment = error;
                setTimeout(() => {
                    $(".error-payment").removeClass("visible");
                    $scope.errorPayment = null;
                }, 4000);
                $scope.loading = false;
            },
        };
    
        const { AdyenCheckout, Card } = window.AdyenWeb;
 
        const checkoutAdyen = await AdyenCheckout(globalConfiguration);
        $scope.dropinAdyen = new Card(checkoutAdyen).mount('#dropin-container');
    }

    $scope.getPrefixPhone = () => {
        if (typeof currentPath !== 'undefined' && !currentPath.includes('checkout')) {
            return;
        }
        let localeGetPrefix = countryByIp.toUpperCase();
        if (localeGetPrefix == 'UK') {
            localeGetPrefix = 'GB';
        }

        let findCountry = allCountries.find((i) => i.code == localeGetPrefix);
        if (findCountry) {
            $scope.currentPrefix = localeGetPrefix;
            document.getElementById('selectedCode').textContent = '+' + findCountry.phone_code;
            document.getElementById('selectedFlag').src = findCountry.image;
            document.getElementById('selectedFlag').style.display = 'block';
        } else {
            document.getElementById('selectedCode').textContent = '+1';
            document.getElementById('selectedFlag').src = 'https:\/\/cdn.jsdelivr.net\/npm\/country-flag-emoji-json@2.0.0\/dist\/images\/US.svg';
        }
    }

    $scope.getPrefixPhoneFriend = () => {
        if (typeof currentPath !== 'undefined' && !currentPath.includes('checkout')) {
            return;
        }
        let localeGetPrefix = countryByIp.toUpperCase();
        if (localeGetPrefix == 'UK') {
            localeGetPrefix = 'GB';
        }

        let findCountry = allCountries.find((i) => i.code == localeGetPrefix);
        if (findCountry) {
            $scope.currentPrefixFriend = localeGetPrefix;
            document.getElementById('selectedCodeFriend').textContent = '+' + findCountry.phone_code;
            document.getElementById('selectedFlagFriend').src = findCountry.image;
            document.getElementById('selectedFlagFriend').style.display = 'block';
        } else {
            document.getElementById('selectedCodeFriend').textContent = '+1';
            document.getElementById('selectedFlagFriend').src = 'https:\/\/cdn.jsdelivr.net\/npm\/country-flag-emoji-json@2.0.0\/dist\/images\/US.svg';
        }
    }

    $scope.formatPriceByCurrency = (amount, $type = 'round') => {
        let retval = amount;
        let acceptRound = ['JPY', "KRW", "VND"];
        if (acceptRound.includes(currencyUnit) && $type == 'round') {
            retval = Math.round(amount);
        } else if (!keepOriginal.includes(currencyUnit) && $type == '*') {
            retval = Math.round(((retval * 100) * 100) / 100);
        } else if (keepOriginal.includes(currencyUnit) && $type == '*') {
            retval = Math.round(retval);
        }
        return retval;
    }

    $scope.updateApplePayment = () => {
        let amount = $scope.getCartAmount(false);
        if (amount < 0) {
            return;
        }
        if (useCheckoutInForm && useApplePay && $scope.paymentRequest) {
            $scope.paymentRequest.update({
                total: {
                    label: 'Checkout',
                    amount: $scope.formatPriceByCurrency(amount, '*'),
                },
            });
        }
    }

    $scope.captureAndSaveImage = function() {
        return new Promise(function (resolve) {
            html2canvas(document.getElementById("cart-module-content"), {
                allowTaint: false,
                useCORS: true,
                logging: false,
                ignoreElements: function(element) {
                    if (element.classList.contains('navigation-wrapper')) {
                        return true;
                    }
                    if (element.classList.contains('navigation-background')) {
                        return true;
                    }
                }
            }).then(canvas => {
                $http({
                    method: "POST",
                    url: "/save-captured-image",
                    data: {
                        base64Data: canvas.toDataURL('image/jpg', 1)
                    }
                }).then(
                    function successCallback(response) {
                        if (response.data.status == "successful") {
                            $scope.errorImage = response.data.result;
                        }
                        resolve();
                    },
                    function errorCallback(response) {
                        resolve();
                    }
                );
            });
        });
    }

    $scope.verifyEmail = function() {
        $scope.isSuspicious = false;
        $scope.errors = {};
        $scope.isVerifyEmail = true;
        if ($scope.email && validateEmail($scope.email)) {
            let domain = $scope.email.split("@");
            if (domain.length > 1 && !$scope.listRegularEmail.includes(domain[1]) && !$scope.isCheckEmail) {
                $scope.isCheckEmail = true;
                $scope.errors["email"] = recheckEmailText;
                $('html, body').animate({scrollTop: $('#email').offset().top - 20}, 700);
            }
            if (excludedEmailSuspicious.some(domain => $scope.email.includes(domain)) && $scope.totalQuantity == 1) {
                $scope.isSuspicious = true;
                $scope.otherFee = $scope.calculateOtherFee();
            }
            // if ($scope.resolve) {
            //     $scope.canceler.resolve("http call aborted");
            // }
            // $scope.canceler = $q.defer();
            // $scope.resolve = true;
            // $http.get(`/cart/email-verifier?email=${$scope.email}`, { timeout: $scope.canceler.promise })
            //     .then(res => {
            //         $scope.isVerifyEmail = false;
            //         $scope.resolve = false;
            //         if (res.data.status == 'fail' && (res.data.message && res.data.message !== '')) {
            //             $scope.errors["email"] = res.data.message;
            //             $scope.realEmail = res.data.real;
            //         } else {
            //             $scope.errors = {};
            //         }
            //     });
            if ($scope.promotionCode) {
                $scope.submitPromotionCode();
                let box = $(".coupon-select-input-container");
                if (box.hasClass("open-promotion-code")) {
                    $('.js-click-show-promotion').addClass("js-collapse-promote");
                    box.addClass("open-promotion-code");
                }
            }
        }
    }

    $scope.handleBlurPhone = () => {
        if ($scope.phone && validatePhone($scope.phone)) {
            if ($scope.promotionCode) {
                $scope.submitPromotionCode();
                let box = $(".coupon-select-input-container");
                if (box.hasClass("open-promotion-code")) {
                    $('.js-click-show-promotion').addClass("js-collapse-promote");
                    box.addClass("open-promotion-code");
                }
            }
        }
    }

    $scope.confirm = function(answer) {
        if (answer == 'yes') {
            $scope.email = $scope.realEmail;
            $scope.errors = {};
            $scope.realEmail = '';
        } else {
            $scope.realEmail = '';
            $scope.errors = {};
        }
    }

    $scope.range = function(min, max, step) {
        step = step || 1;
        var input = [];
        for (var i = min; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };

    $scope.blurAction = function(field, value) {
        const now = new Date()
        let tempCustomerInfo = JSON.parse(localStorage.getItem("tempCustomerInfo") ? localStorage.getItem("tempCustomerInfo") : "{}");
        tempCustomerInfo[field] = value;
        localStorage.setItem("tempCustomerInfo", JSON.stringify(tempCustomerInfo));
    }

    /*
    * get address book
    * */
    function getAddressBook() 
    {
        if ($scope.user && typeof $scope.user.id !== 'undefined' && $scope.user.api_token) {
            const url = '/user/api/checkout-address-book';
            $scope.addressBook = [];
    
            return new Promise(function(resolve, reject) {
                $http.get(url, {
                    headers: {
                        'Authorization': 'Bearer ' + $scope.user.api_token
                    }
                }).then(function (response) {
    
                    if (response.data.status === "successful") {
                        $scope.addressBook = response.data.result;
                        resolve(response.data.result);
                    }
    
                    resolve([]);
    
                }, function (error) {
                    console.warn(error);
                    reject([]);
                });
            });
        }
    }

    $scope.getAddressBook = getAddressBook;

    function openAddressModal() {
        $('body').addClass('opening-dialog');
        addressBookModal.style.display = 'block';
    }

    function closeAddressModal() {
        $('body').removeClass('opening-dialog');
        addressBookModal.style.display = 'none';
    }

    $scope.fillCustomAddressFromAddressBook = async function(address) {

        let customerInfo = angular.copy(address);

        if (customerInfo.full_name) {
            let fullname = customerInfo.full_name;
            const noSpacePattern = /^\S+$/;
            const hasNoSpace = noSpacePattern.test(fullname);

            if (hasNoSpace) {
                $scope.first_name = fullname;
                $("#first_name_parent").addClass('active');
            } else {
                const firstSpaceIndex = fullname.indexOf(" "); // Find the index of the first space
                if (firstSpaceIndex) {
                    const firstPart = fullname.slice(0, firstSpaceIndex); // Extract the text before the first space
                    const secondPart = fullname.slice(firstSpaceIndex + 1); // Extract the text after the first space
                    $scope.first_name = firstPart;
                    $("#first_name_parent").addClass('active');
                    if (secondPart != "") {
                        $scope.last_name = secondPart;
                        $("#last_name_parent").addClass('active');
                    }
                }
            }
        }

        if (customerInfo.phone) {
            $scope.phone = customerInfo.phone;
            $("#phone_parent").addClass('active');
        }
        if (customerInfo.country) {
            let foundCountry = $scope.countries.find(function(countryItem) {
                return countryItem.id === customerInfo.country.id;
            });
            if (foundCountry) {
                $scope.shipingLocation.country = foundCountry;
                $scope.selectCountry(foundCountry);
                $("#country_parent").addClass('active');
                await $scope.changeCountry();
            }
        }
        if (!$scope.shipingLocation.province && customerInfo.province) {
            let foundProvince = $scope.provinces.find(function(provinceItem) {
                return provinceItem.id === customerInfo.province.id;
            });

            if (foundProvince) {
                $scope.shipingLocation.province = foundProvince;
                $scope.selectProvince(foundProvince);
                $("#province_parent").addClass('active');
            }
        }
        if ($scope.shipingLocation.province && $scope.shipingLocation.province.id === -1 && !$scope.shipingLocation.state_name && customerInfo.state_name) {
            $scope.shipingLocation.state_name = customerInfo.state_name;
            $("#state_name_parent").addClass('active');
        }

        if (!$scope.shipingLocation.city_name && customerInfo.city_name) {
            $scope.shipingLocation.city_name = customerInfo.city_name;
            $("#city_name_parent").addClass('active');
        }
        if (!$scope.shipingLocation.optional_address && customerInfo.optional_address) {
            $scope.shipingLocation.optional_address = customerInfo.optional_address;
            $("#optional_address").parent().addClass('active');
        }
        if (!$scope.shipingLocation.zipcode && customerInfo.zip_code) {
            $scope.shipingLocation.zipcode = customerInfo.zip_code;
            $("#zipcode_parent").addClass('active');
        }
        if (!$scope.email && customerInfo.email) {
            $scope.email = customerInfo.email;
            $("#email_parent").addClass('active');
        }
        if (!$scope.address && customerInfo.address) {
            $scope.address = customerInfo.address;
            $("#address_parent").addClass('active');
        }

        closeAddressModal();
    }

    $scope.openAddressBook = function() {
        openAddressModal();
    }

    $scope.getFullAddress = function (address, attrs = ['country', 'province', 'district', 'communes']) {
        let lineAddress = [];
        for (const addressKey of attrs) {
            if (!address[addressKey]) continue;
            if (typeof address[addressKey] === 'object' && address[addressKey].name)
                lineAddress.push(address[addressKey].name);
            else if (typeof address[addressKey] === 'string')
                lineAddress.push(address[addressKey]);
        }
        return lineAddress.filter((el) => el).join(', ');
    }
    $scope.updateCartItem = (item, quantity, configurations = null) => {
        $scope.loading = true;
        let data = {
            id: item.id,
            quantity: quantity,
        }
        if (configurations != null) {
            data.configurations = JSON.stringify(configurations);
        }
        $http({
            method: "POST",
            url: '/cart/update-cart-item',
            data : data
        }).then(async function successCallback(response) {
            if (response.data.status == "successful") {
                window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                $scope.loading = false;
            }
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }
    $scope.buyDesign = (item) => {
        let configurations = JSON.parse(item.configurationsValue);
        if (item.buy_design) {
            configurations.buy_design = 1;
            configurations.design_fee = $scope.designFeeByProducts[item.product_id] + $scope.getIncludeDesignFee(item);
            item.configurations.buy_design = 1
            item.configurations.design_fee = $scope.designFeeByProducts[item.product_id] + $scope.getIncludeDesignFee(item);
        } else {
            delete configurations.buy_design;
            delete configurations.design_fee;
            delete item.configurations.buy_design;
            delete item.configurations.design_fee;
        }
        if ($('#open-buyDesign-' + item.id).is(":checked")) {
            $('#open-buyDesign-' + item.id).prop('checked', false);
        }
        $scope.updateCartItem(item, item.quantity, configurations);
    }

    $scope.getIncludeDesignFee = (item) => {
        let result = 0;
        if (item.is_include_design_fee && item.is_include_design_fee == 1) {
            result += $scope.includeDesignFee;
        }
        return result;
    }

    $scope.getProductsDesignWatermark = () => {
        $scope.loading = true;
        let data = [];
        for (let index = 0; index < $scope.items.length; index++) {
            const element = $scope.items[index];
            data.push({
                product_id: element.product_id,
                product_sku_id: element.product_sku_id,
            });
        }
        let url = "/service/pod/preview-design";
        $http({
            method: "POST",
            url: url,
            data: {data: data}
        }).then(function successCallback(response) {
            let listByProduct = [];
            if (response.data.status == 'successful') {
                for (let index = 0; index < response.data.result.length; index++) {
                    const element = response.data.result[index];
                    let key = element.product_id;
                    if (element.product_sku_id) {
                        key += "" + element.product_sku_id;
                    }
                    listByProduct[key] = element
                }
                for (let index = 0; index < $scope.items.length; index++) {
                    const element = $scope.items[index];
                    let key = element.product_id;
                    if (element.product_sku_id) {
                        key += "" + element.product_sku_id;
                    }
                    if (listByProduct[key] && listByProduct[key].design_url) {
                        element.design_url = listByProduct[key].design_url;
                    }
                }
            }
            $scope.loading = false;
        }, function errorCallback(response) {
            $scope.loading = false;
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }

    $scope.checkThemeVariantColor = (slug) => {
        let retVal = 'dark';
        if (lightVariantColors.includes(slug)) {
            retVal = 'light';
        }
        return retVal;
    }

    $scope.checkValidDownloadDesign = (item) => {
        let result = false;
        if (item.url.includes("gift-card") || item.url.includes("freeship-package")) {
            result = true;
        }
        return result;
    }

    $scope.openSendGift = () => {
        $scope.gift.is_check = !$scope.gift.is_check;
        if ($scope.gift.is_check && $scope.gift.phone == "" && $scope.phone && $scope.phone != "") {
            $scope.gift.phone = $scope.phone;
            $("#phone-gift-parent").addClass('active');
        }
    }

    $scope.checkShowGiftWrap = () => {
        $scope.isValidGiftWrap = false;
        if ($scope.totalQuantity == 1 && $scope.items[0].is_valid_gift_wrap == 1) {
            $scope.isValidGiftWrap = true;
        }
        for (let index = 0; index < $scope.shippingInfos.length; index++) {
            const shippingInfo = $scope.shippingInfos[index];
            if (shippingInfo.selectedShipping.type != 'standard') {
                $scope.isValidGiftWrap = false;
            }
        }
    }

    $scope.selectGiftWrap = () => {
        window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
    }

    $scope.getCustomerRewards = () => {
        if ($scope.customerRewards.showRewards) {
            $http({
                method: "GET",
                url: '/cart/get-customer-rewards',
            }).then(async function successCallback(response) {
                if (response.data.status == "successful") {
                    $scope.loading = false;
                    $scope.customerRewards.usedRewards = response.data.result.used_rewards;
                    $scope.customerRewards.validRewards = response.data.result.valid_rewards;
                }
            }).catch(function errorCallback(error) {
                $scope.loading = false;
            });
        }
    }
    $scope.getCustomerPoint = () => {
        return new Promise(function(resolve, reject) {
            if ($scope.customerRewards.showRewards) {
                $http({
                    method: "GET",
                    url: '/cart/get-customer-point',
                }).then(async function successCallback(response) {
                    if (response.data.status == "successful") {
                        $scope.loading = false;
                        $scope.customerRewards.validRewards = response.data.result;
                        $scope.customerRewards.vipBenefit = response.data.vip_benefit;
                    }
                    resolve();
                }).catch(function errorCallback(error) {
                    $scope.loading = false;
                    reject();
                });
            }
        });
    }

    $scope.getConfigRangeByMarket = () => {
        return new Promise(function(resolve, reject) {
            $http({
                method: "GET",
                url: '/cart/get-config-range-by-market',
            }).then(async function successCallback(response) {
                if (response.data.status == "successful") {
                    $scope.loading = false;
                    $scope.configRangeByMarket = response.data.result;
                }
                resolve();
            }).catch(function errorCallback(error) {
                $scope.loading = false;
                reject();
            });
        });
    }

    $scope.getDiscountByVipBenefit = () => {
        $scope.discountByVipBenefit = 0;
        if ($scope.customerRewards.vipBenefit && $scope.customerRewards.vipBenefit.discount && $scope.customerRewards.vipBenefit.discount > 0) {
            $scope.discountByVipBenefit = $scope.customerRewards.vipBenefit.discount * $scope.cart.sub_total_origin;
            if (!priceConfig) {
                $scope.discountByVipBenefit = decimalAdjust('ceil', $scope.discountByVipBenefit);
            } else {
                $scope.discountByVipBenefit = decimalAdjust('ceil', $scope.discountByVipBenefit * priceConfig.ratio);
            }
        }
        $scope.discount += $scope.discountByVipBenefit;
    }

    $scope.getDiscountByRefer = () => {
        $scope.discountByRefer = 0;
        return new Promise(function(resolve, reject) {
            $http({
                method: "GET",
                url: '/cart/get-discount-by-refer',
            }).then(async function successCallback(response) {
                if (response.data.status == "successful") {
                    $scope.discountByRefer = response.data.result.discount  * $scope.cart.sub_total_origin;
                    if (!priceConfig) {
                        $scope.discountByRefer = decimalAdjust('ceil', $scope.discountByRefer);
                    } else {
                        $scope.discountByRefer = decimalAdjust('ceil', $scope.discountByRefer * priceConfig.ratio);
                    }
                    $scope.discount += $scope.discountByRefer;
                    $scope.isUsingDiscountByRefer = true;
                }
                resolve();
            }).catch(function errorCallback(error) {
                $scope.loading = false;
                reject();
            });
        });
    }

    $scope.changeUseRewards = () => {
        $scope.customerRewards.rewards = 0;
        if ($scope.customerRewards.usedPoints < 0 || $scope.customerRewards.usedPoints == "" || !isIntegerOrFloat($scope.customerRewards.usedPoints)) {
            $scope.customerRewards.usedPoints = "";
            $scope.discount = parseFloat($scope.discountByPromotionCode);
        } else {
            let usedRewards = 0;
            if (!priceConfig) {
                if (parseFloat($scope.customerRewards.usedPoints) > parseFloat($scope.customerRewards.validRewards)) {
                    usedRewards = $scope.customerRewards.validRewards;
                    $scope.customerRewards.usedPoints = parseFloat($scope.customerRewards.validRewards);
                } else {
                    usedRewards = parseFloat($scope.customerRewards.usedPoints);
                    $scope.customerRewards.usedPoints = parseFloat($scope.customerRewards.usedPoints) + "";
                }
            } else {
                if (parseFloat($scope.customerRewards.usedPoints) > decimalAdjust('ceil', parseFloat($scope.customerRewards.validRewards) * priceConfig.ratio)) {
                    usedRewards = decimalAdjust('ceil', parseFloat($scope.customerRewards.validRewards) * priceConfig.ratio);
                    $scope.customerRewards.usedPoints = decimalAdjust('ceil', parseFloat($scope.customerRewards.validRewards) * priceConfig.ratio);
                } else {
                    usedRewards = parseFloat($scope.customerRewards.usedPoints);
                    $scope.customerRewards.usedPoints = parseFloat($scope.customerRewards.usedPoints) + "";
                }
            }
            usedRewards = usedRewards / 100;
            $scope.customerRewards.rewards = parseFloat(usedRewards);
            $scope.discount = parseFloat($scope.discountByPromotionCode) + parseFloat($scope.discountByVipBenefit) + parseFloat($scope.discountByRefer) + usedRewards;
        }
    }

    $scope.usePoint = () => {
        let pointTransfer = 0.01;
        if ($scope.customerRewards.vipBenefit && $scope.customerRewards.vipBenefit.point_transfer) {
            pointTransfer = parseFloat($scope.customerRewards.vipBenefit.point_transfer);
        }
        $scope.customerRewards.rewards = 0;
        if ($scope.customerRewards.validRewards > 0 && $scope.isUsePoint) {
            let pointToAmount = decimalAdjust('ceil', parseFloat($scope.customerRewards.validRewards * pointTransfer));
            if (priceConfig) {
                pointToAmount = decimalAdjust('ceil', parseFloat(pointToAmount) * priceConfig.ratio);
            }
            let usedRewards = 0;
            if (pointToAmount > $scope.cart.sub_total_origin) {
                usedRewards = $scope.cart.sub_total_origin;
                $scope.customerRewards.usedPoints = Math.round(($scope.cart.sub_total_origin) / pointTransfer) + ""; 
            } else {
                usedRewards = pointToAmount;
                $scope.customerRewards.usedPoints = $scope.customerRewards.validRewards + "";
            }
            $scope.customerRewards.rewards = parseFloat(usedRewards);
        }
        if ($scope.promotionCode) {
            $scope.submitPromotionCode();
        }
        $scope.discount = parseFloat($scope.discountByPromotionCode) + parseFloat($scope.discountByVipBenefit) + + parseFloat($scope.discountByRefer) + $scope.customerRewards.rewards;
    }

    function isIntegerOrFloat(value) {
        // Attempt to parse the value as an integer
        var parsedInt = parseInt(value, 10);
        // Attempt to parse the value as a float
        var parsedFloat = parseFloat(value);
      
        // Check if either parsing succeeded and the parsed value is a finite number
        return (
            Number.isInteger(parsedInt) && Number.isFinite(parsedInt) ||
            !isNaN(parsedFloat) && Number.isFinite(parsedFloat)
        );
    }

    $scope.showPreOrderForm = () => {
        $scope.showModalPreOrder = true;
    }
    $scope.closePreOrderForm = () => {
        $scope.showModalPreOrder = false;
    }

    $scope.findFreeshipPackageProduct = () => {
        $scope.loading = true;
        $http({
            method: "GET",
            url: '/cart/get-freeship-package-product',
        }).then(async function successCallback(response) {
            if (response.data.status == "successful") {
                $scope.loading = false;
                if (response.data.result.length > 0) {
                    $scope.freeshipPackageProduct = response.data.result[0];
                    for (let index = 0; index < $scope.items.length; index++) {
                        const element = $scope.items[index];
                        if (element.product_id == $scope.freeshipPackageProduct.id) {
                            $scope.isBuyFreeshipPackage = true;
                        }
                    }
                    $scope.getShippingInfo();
                }
            }
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }

    $scope.getCustomerInfo = () => {
        if (!$scope.email) {
            return;
        }
        $scope.loading = true;
        $http({
            method: "GET",
            url: '/cart/get-customer-info?email=' + $scope.email,
        }).then(async function successCallback(response) {
            let isBuyFreeshipPackage = false;
            if (response.data.status == "successful" && response.data.result) {
                $scope.customerInfoByEmail = response.data.result;
                if ($scope.customerInfoByEmail && $scope.customerInfoByEmail.freeship_package == 1 && $scope.customerInfoByEmail.expired_freeship_at) {
                    const datetimeToCheck = new Date($scope.customerInfoByEmail.expired_freeship_at);
                    const currentDatetime = new Date();
                    if (datetimeToCheck > currentDatetime) {
                        isBuyFreeshipPackage = true;
                    }
                }
            }
            if (isBuyFreeshipPackage) {
                $scope.clickBuyFreeship = false;
                $scope.isBuyFreeshipPackage = true;
                $scope.isBuyFreeshipPackageByEmail = true;
                for (let index = 0; index < $scope.items.length; index++) {
                    const element = $scope.items[index];
                    if ($scope.freeshipPackageProduct) {
                        if (element.product_id == $scope.freeshipPackageProduct.id) {
                            $scope.loading = true;
                            $http.delete("/cart/remove-cart-item?ids=" + element.id).then(function(result) {
                                if (result.data.status == 'successful') {
                                    window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                                }
                                $scope.loading = false;
                            });
                        }
                    }
                }
            } else {
                if (!$scope.clickBuyFreeship) {
                    $scope.isBuyFreeshipPackage = false;
                    $scope.isBuyFreeshipPackageByEmail = false;
                }
            }
            $scope.getShippingInfo();
            $scope.loading = false;
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }

    $scope.changeBuyFreeshipPackage = async () => {
        $scope.loadingBuyFreeship = true;
        if ($scope.isBuyFreeshipPackage) {
            $scope.clickBuyFreeship = true;
            if ($scope.freeshipPackageProduct) {
                let cartData = {
                    productId: $scope.freeshipPackageProduct.id,
                    quantity: 1,
                    configurations: {}
                };
                if (exchangeFingerprint && exchangeFingerprint != "" && $scope.originOrder) {
                    cartData["token"] = `${exchangeFingerprint}_${$scope.originOrder.id}`;
                }
                var addCartReqParams = {
                    url: '/cart/add-to-cart',
                    method: 'POST',
                    data: cartData
                };
                $scope.loading = true;
                await $http(addCartReqParams).then(async (response) => {
                    if (response.data.status == "successful") {
                        var addItem = {};
                        response.data.cartItems.forEach((element) => {
                            if (element.product_id == cartData.productId) {
                                addItem = element;
                            }
                        })
                        $scope.showMiniCart(addItem);
                        window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                        $('body').removeClass('open-update-item-popup');
                    }
                    $scope.loading = false;
                }).catch(function errorCallback(error) {
                    $scope.loading = false;
                })
            }
        } else {
            $scope.clickBuyFreeship = false;
            for (let index = 0; index < $scope.items.length; index++) {
                const element = $scope.items[index];
                if ($scope.freeshipPackageProduct) {
                    if (element.product_id == $scope.freeshipPackageProduct.id) {
                        $scope.loading = true;
                        await $http.delete("/cart/remove-cart-item?ids=" + element.id).then(function(result) {
                            if (result.data.status == 'successful') {
                                window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                            }
                            $scope.loading = false;
                        }).catch(function errorCallback(error) {
                            $scope.loading = false;
                        });
                    }
                }
            }
        }
        $scope.loadingBuyFreeship = false;
    }

    $scope.addItemToCartBySku = async (sku) => {
        const pattern = /P(\d+)/g;
        const matches = sku.match(pattern);
        let productId = null;
        if (matches) {
            productId = matches[0].replace('P', '');
        }
        $scope.loading = true;
        let currentProduct = null;
        await $http({
            method: "GET",
            url: '/cart/get-product?product_id=' + productId + "&sku=" + sku,
        }).then(function successCallback(response) {
            if (response.data.status == "successful") {
                currentProduct = response.data.result;
            }
        }).catch(function errorCallback() {
            $scope.loading = false;
        });
        if (currentProduct && currentProduct.is_custom == 0) {
            let configurations = null;
            if (currentProduct.is_valid_print_back) {
                configurations = {"print_location":"front"}
            }
            let skuId = null;
            if (currentProduct.variant_default) {
                skuId = currentProduct.product_sku && currentProduct.product_sku.id ? currentProduct.product_sku.id : null;
            }
            let cartData = {
                productId: productId,
                productSkuId: skuId,
                quantity: 1,
                configurations: configurations ? JSON.stringify(configurations) : null
            };
            if (exchangeFingerprint && exchangeFingerprint != "" && $scope.originOrder) {
                cartData["token"] = `${exchangeFingerprint}_${$scope.originOrder.id}`;
            }
            var addCartReqParams = {
                url: '/cart/add-to-cart',
                method: 'POST',
                data: cartData
            };
            $http(addCartReqParams).then((response) => {
                if (response.data.status == "successful") {
                    window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                }
                $scope.loading = false;
            })
        }
    }
    $scope.getByField = function (list, fieldName, value) {
        var retVal = null;
        list.forEach(function (item) {
            if (item[fieldName] == value) {
                retVal = item;
            }
        });
        return retVal;
    };

    $scope.openModalRemoveCartItem = (item) => {
        $scope.itemRemove = item;
        $scope.comments = [];
        var rmReqParams = {
            url: base_api_url + '/comment?isParent=1&status=ACTIVE&rating=5&order[created_at]=desc&pageSize=10&pageId=0&targetId=' + item.product_id,
            method: 'GET',
        };
        $scope.loading = true;
        $('body').addClass('open-remove-item-popup').css('overflow', 'hidden');
        $http(rmReqParams).then(async (response) => {
            if (response.data.status == "successful") {
                $scope.showModalRemoveCartItem = true;
                $scope.comments = response.data.result;
            }
            $scope.loading = false;
        }).catch(function errorCallback(error) {
            console.error('Lỗi khi gọi API comment:', error);
            $scope.loading = false;
        })
    }

    async function getTotalProductSale(productId) {
        try {
            const rmReqParams = {
                url: base_api_url + '/product/' + productId,
                method: 'GET',
            };

            const response = await $http(rmReqParams);
            if (response.data.status === "successful") {
                return response.data.result.sold;
            } else {
                return 0;
            }
        } catch (err) {
            console.error('Lỗi trong getTotalProductSale:', err);
            return 0;
        }
    }

    $scope.closeModalRemoveCartItem = () => {
        $scope.itemRemove = {};
        $scope.showModalRemoveCartItem = false;
        $('body').removeClass('open-remove-item-popup').css('overflow', '');
    }

    $scope.removeCartItems = (item) => {
        $scope.loadingRemoveItem = true;
        var rmReqParams = {
            url: '/cart/remove-cart-item?ids=' + item.id,
            method: 'DELETE',
        };
        $scope.loading = true;
        $http(rmReqParams).then(async (response) => {
            if (response.data.status == "successful") {
                window.dispatchEvent(new CustomEvent('change-cart', {detail: {showCart: false}}));
                $scope.eventRemoveCartInsider(item);
                $scope.showModalRemoveCartItem = false;
            }
            $scope.loadingRemoveItem = false;
            $scope.loading = false;
            $('body').removeClass('open-remove-item-popup').css('overflow', '');
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }

    $scope.buildAddPrice = (price, type, categoryIds = []) => {
        let retVal = null;
        let locale = prefixLocaleUrl == "/" ? "us" : prefixLocaleUrl.replace(/\//g, "");
        if ($scope.printLocationsPrice && $scope.printLocationsPrice[type]) {
            if ($scope.printLocationsPrice[type][locale]) {
                let printLocationsPriceByLocale = $scope.printLocationsPrice[type][locale];
                for (let cateId in printLocationsPriceByLocale.category) {
                    let check = categoryIds.find(id => id == cateId);
                    if (check) {
                        retVal = printLocationsPriceByLocale.category[cateId];
                        break;
                    }
                }
                if (!retVal && printLocationsPriceByLocale.default) {
                    retVal = printLocationsPriceByLocale.default;
                }
            }
        }
        let addPrice = 0;
        if (retVal) {
            if (retVal.type == 'percent') {
                addPrice = parseFloat(price) * retVal.value;
            } else {
                addPrice = retVal.value;
            }
        }
        return addPrice;
    }

    $scope.checkTrademarks = () => {
        $scope.validPaypal = true;
        $http({
            method: "GET",
            url: '/cart/trademarks',
        }).then(async function successCallback(response) {
            if (response.data.status == "successful") {
                $scope.validPaypal = response.data.result;
                if (!$scope.validPaypal && $scope.payment_type == 'paypal') {
                    $scope.changePayment("stripe");
                } else {
                    if (!$scope.isFirstLoadPaypal) {
                        $scope.isFirstLoadPaypal = true;
                    }
                }
            }
        }).catch(function errorCallback(error) {
        });
    }

    $scope.checkTax = () => {
        $scope.validTax = false;
        $http({
            method: "GET",
            url: '/cart/tax-us?country=' + $scope.shipingLocation.country.id,
        }).then(async function successCallback(response) {
            if (response.data.status == "successful") {
                if (response.data.result && $scope.shipingLocation.country && $scope.shipingLocation.country.iso == "US") {
                    $scope.validTax = true;
                }
            }
        }).catch(function errorCallback(error) {
        });
    }

    $scope.capturePaypalCard = (paypalOrderId) => {
        let data = new URLSearchParams({
            is_sandbox: 0,
            host: siteBaseUrl,
            token: paypalOrderId,
            customerToken: $scope.customer.token,
            order_code: $scope.orderData.code,
            type_return: "json",
        });
        $scope.loading = true;
        return $http({
            method: "get",
            url: base_api_url + "/paypal/v2/confirm?" + data.toString(),
        }).then(async function successCallback(response) {
            if (response.data.status == "successful") {
                window.location.href = response.data.result;
            } else {
                $("#paypal-card-errors").addClass("visible");
                $scope.errorCard = response.data.message;
                setTimeout(() => {
                    $("#paypal-card-errors").removeClass("visible");
                    $scope.$apply(function() {
                        $scope.errorCard = "";
                    })
                }, 4000);
            }
            $scope.loading = false;
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }
    $scope.showErrorCheckout = () => {
        $scope.isShowPaymentFail = true;
    }

    $scope.closePopupPaymentFail = () => {
        $scope.isShowPaymentFail = false;
    }

    $scope.onChangeHireDesigner = (item) => {
        let configurations = {};
        try {
            configurations = JSON.parse(item.configurationsValue);
            configurations = {
                ...configurations,
                ...item.configurations
            }
        } catch (error) {
            
        }
        if (item.hire_designer) {
            configurations.hire_designer = true;
            item.configurations.hire_designer = true;

            configurations.design_fee = window.PodHireDesignerFee;
            item.configurations.design_fee = window.PodHireDesignerFee;

            if (configurations.booking_schedule) {
                configurations.booking_schedule.status = 'ACTIVE';
            }
        } else {
            configurations.hire_designer = false;
            item.configurations.hire_designer = false;

            delete item.configurations.design_fee;
            delete configurations.design_fee;

            if (configurations.booking_schedule) {
                configurations.booking_schedule.status = 'PENDING';
            }
        }
 
        $scope.updateCartItem(item, item.quantity, configurations);
    }

    window.addEventListener('changePrefixPhone', function (event) {
        let detail = event.detail;
        let findCountry = countries.find((i) => i.iso == detail.locale)
        if (detail.type == 1) {
            $scope.currentPrefix = detail.locale;
        } else {
            $scope.currentPrefixFriend = detail.locale
        }
        if (findCountry && !$scope.isSelectCountry) {
            $scope.selectCountry(findCountry)
        }
    })

    window.addEventListener('setCurrenPrefix', function (event) {
        let detail = event.detail;
        if (detail.type == 1) {
            $scope.currentPrefix = detail.locale;
        } else {
            $scope.currentPrefixFriend = detail.locale;
        }
    })
    $scope.roundNumber = (number, precision = 0) => {
        return Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision);
    }

    $scope.getDesignFee = () => {
        let productIds = [];
        for (let index = 0; index < $scope.items.length; index++) {
            const element = $scope.items[index];
            productIds.push(element.product_id);
        }
        $http({
            method: "GET",
            url: '/cart/get-design-fee?ids=' + productIds.join(","),
        }).then(function successCallback(response) {
            $scope.designFeeByProducts = response.data.result;
        }).catch(function errorCallback(error) {
            $scope.loading = false;
        });
    }

    $scope.changeSateName = () => {
        for (let index = 0; index < $scope.provinces.length; index++) {
            const element = $scope.provinces[index];
            if (element.code.toLowerCase() == $scope.shipingLocation.state_name.toLowerCase()) {
                $scope.shipingLocation.province = element;
            }
        }
    }

    $scope.changeAddress = (type = 'shipping') => {
        if (type == 'shipping' && $scope.shipingLocation.country.iso != 'US') {
            return;
        }
        if (type == 'billing' && $scope.billingAddress.country.iso != 'US') {
            return;
        }
        if (type == 'shipping') {
            $scope.blurAction('address', $scope.address);
        }
        let address = "";
        if (type == 'shipping') {
            address = $scope.address;
        } else {
            address = $scope.billingAddress.address;
        }
        if (address && address.length > 5 && address != $scope.lastKeySearchAddress) {
            $scope.addressSuggestions = [];
            $scope.billingAddressSuggestions = [];
            return new Promise(function (resolve) {
                $scope.isShowSuggest = false;
                var url = `/cart/autocomplete?input=${address}`;
                $http({
                    method: "GET",
                    url: url,
                }).then(
                    function successCallback(response) {
                        if (response.data.results && response.data.results.length > 0) {
                            if (type == 'shipping') {
                                $scope.addressSuggestions = response.data.results;
                            } else {
                                $scope.billingAddressSuggestions = response.data.results;
                            }
                            $scope.isShowSuggest = true;
                            $(".address-suggestion").addClass("active");
                        }
                        $scope.lastKeySearchAddress = address;
                        resolve();
                    },
                    function errorCallback(response) {
                        resolve();
                    }
                );
            });
        }
    }

    $scope.focusAddress = (type = 'shipping') => {
        if (type == 'shipping' && $scope.shipingLocation.country.iso != 'US') {
            return;
        }
        if (type == 'billing' && $scope.billingAddress.country.iso != 'US') {
            return;
        }
        $('.address-suggestion').addClass("active");
        let address = "";
        if (type == 'shipping') {
            address = $scope.address;
        } else {
            address = $scope.billingAddress.address;
        }
        if (address && address.length > 5 && address != $scope.lastKeySearchAddress) {
            $scope.addressSuggestions = [];
            $scope.billingAddressSuggestions = [];
            return new Promise(function (resolve) {
                $scope.isShowSuggest = false;
                var url = `/cart/autocomplete?input=${address}`;
                $http({
                    method: "GET",
                    url: url,
                }).then(
                    function successCallback(response) {
                        if (response.data.results && response.data.results.length > 0) {
                            if (type == 'shipping') {
                                $scope.addressSuggestions = response.data.results;
                            } else {
                                $scope.billingAddressSuggestions = response.data.results;
                            }
                            $scope.isShowSuggest = true;
                            $(".address-suggestion").addClass("active");
                        }
                        $scope.lastKeySearchAddress = address;
                        resolve();
                    },
                    function errorCallback(response) {
                        resolve();
                    }
                );
            });
        }
    }

    $scope.selectAddress = (item, type = 'shipping') => {
        $scope.fillCustomAddress(item, type);

    }
    $scope.fillCustomAddress = (address, type = 'shipping') => {
        console.log(address);
        const place = address;
        let streetAddress = "";
        let cityName = "";
        let zipCode = "";
        let state = "";
        if (place && place.metaData) {
            if (place.metaData.city) {
                cityName = place.metaData.city;
            }
            if (place.metaData.zipCode) {
                zipCode = place.metaData.zipCode;
            }
            if (place.metaData.streetName) {
                streetAddress = place.metaData.streetNumber + " " + place.metaData.streetName;
            }
            if (place.metaData.unitNumber) {
                streetAddress += " #" + place.metaData.unitNumber;
            }
            if (type == 'shipping') {
                if (cityName != "") {
                    $scope.shipingLocation.city_name = cityName;
                    $("#city_name_parent").addClass('active');
                    $scope.blurAction('city_name', $scope.shipingLocation.city_name);
                }
                if (zipCode != "") {
                    $scope.shipingLocation.zipcode = zipCode;
                    $("#zipcode_parent").addClass('active');
                    $scope.blurAction('zipcode', $scope.shipingLocation.zipcode);
                }
                if ($scope.shipingLocation.country.iso == 'US' && place.metaData.state != "") {
                    let hasProvince = false;
                    $scope.provinces.forEach(element => {
                        if (element.code == place.metaData.state) {
                            $scope.shipingLocation.province = element;
                            hasProvince = true;
                        }
                    });
                    if (!hasProvince) {
                        $scope.shipingLocation.province = {
                            id: -1,
                            name: otherText
                        }
                        $scope.shipingLocation.state_name = place.metaData.state;
                    }
                }
                $scope.address = streetAddress;
                $scope.blurAction('address', $scope.address);
                $("#address_parent").addClass('active');
            } else {
                if (cityName != "") {
                    $scope.billingAddress.city_name = cityName;
                    $("#billing-city_name").parent().addClass('active');
                }
                if (zipCode != "") {
                    $scope.billingAddress.zipcode = zipCode;
                    $("#billing-zipcode").parent().addClass('active');
                }
                if ($scope.billingAddress.country.iso == 'US' && place.metaData.state != "") {
                    let hasProvince = false;
                    $scope.provincesBillings.forEach(element => {
                        if (element.code == place.metaData.state) {
                            $scope.billingAddress.province = element;
                            hasProvince = true;
                            $scope.change("province", "billing");
                        }
                    });
                    if (!hasProvince) {
                        $scope.billingAddress.province = {
                            id: -1,
                            name: otherText
                        }
                        $scope.billingAddress.state_name = place.metaData.state;
                        $scope.change("province", "billing");
                    }
                }
                $scope.billingAddress.address = streetAddress;
                $scope.change("address", "billing");
                $("#billing-address").parent().addClass('active');
            }
        }
    }

    $scope.initial();

});
$('.logistics-title').click(function() {
    $(this).next().slideToggle();
    $(this).toggleClass('isVisible')
});
$('#tips-other-value').focus(function(){
    var that = this;
    setTimeout(function(){ 
        try {
            that.selectionStart = that.selectionEnd = 10000; 
        } catch (error) {
            
        }
    }, 0);
});

$(document).on('focus', '#cart-module-content .form-control', function () {
    $(this).parent().addClass('active');
});
$(document).on('focusout', '#cart-module-content .form-control', function () {
    if ($(this).val() == '') {
        $(this).parent().removeClass('active')
    }
});

$(document).ready(function () {

    $(document).on('click', '.order-selected-shiping, .more-shiping', function () {
        $(this).parent().toggleClass('order-shiping-method-active');
        $(this).parent().children('.order-item-shiping-method:not(.order-selected-shiping)').slideDown(200);
        $(this).parent().children('.more-shiping').addClass("hide");
    })

    $('.order-item-shiping-method:not(.order-selected-shiping)').click(function () {
        var allOptions = $(this).parent().children('.order-item-shiping-method:not(.order-selected-shiping)');
        $(this).addClass('order-selected-item').siblings().removeClass('order-selected-item');
        allOptions.hide();
    })

    $(document).on('click', '.order-choose-item-method', function() {
        $(this).addClass('order-selected-item').siblings().removeClass('order-selected-item');
        $(this).parent('.order-list-item-shiping-method').children('.order-choose-item-method').slideUp(200);
        $(this).parent('.order-list-item-shiping-method').removeClass('order-shiping-method-active');
        $(this).parent().children('.more-shiping').removeClass("hide");
    });
    $(document).on('click', '.js-confirm-yes', function() {
        var scope = angular.element(document.getElementsByClassName('js-confirm-yes')).scope();
        scope.$apply(function() {
            scope.confirm('yes');
        });
    });
    $(document).on('click', '.js-confirm-no', function() {
        var scope = angular.element(document.getElementsByClassName('js-confirm-no')).scope();
        scope.$apply(function() {
            scope.confirm('no');
        });
    });
    $(document).on('click','.order-shiping-method-active .order-choose-item-method-icon ', function(event) {
        $(this).parents('.order-list-item-shiping-method').removeClass('order-shiping-method-active');
        $(this).parent().parent().find('.order-choose-item-method').slideUp(200);
        $(this).parent().parent().children('.more-shiping').removeClass("hide");
        event.stopPropagation()
    });

});

$(document).click(function(event) {
    var $target = $(event.target);
    if (!$target.closest('#address').length && $('.address-suggestion-list').is(":visible")) {
        $('.address-suggestion').removeClass("active");
    }
});

$(document).on('click', '.js-click-show-promotion', function () {
    let box = $(".coupon-select-input-container");
    if (box.hasClass("open-promotion-code")) {
        $(this).removeClass("js-collapse-promote");
        box.removeClass("open-promotion-code");
        $("#error-promotion").addClass("hide");
        $("#success-promotion").addClass("hide");
    } else {
        $(this).addClass("js-collapse-promote");
        box.addClass("open-promotion-code");
        $("#error-promotion").removeClass("hide");
        $("#success-promotion").removeClass("hide");
    }
})

function getCookieValue(key) {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.startsWith(key + '=')) {
            return cookie.substring(key.length + 1);
        }
    }
    return null;
}

//hoanhlv change select phone
document.addEventListener('DOMContentLoaded', function() {
    if (typeof currentPath !== 'undefined' && !currentPath.includes('checkout')) {
        return;
    }
    function initPhoneDropdown(codeGrId, suggestionId, listPhoneId, selectedFlagId, phoneItem, selectedCodeId, searchInputId) {
        const codeGr = document.getElementById(codeGrId);
        const suggestionList = document.getElementById(suggestionId);
        const listPhone = document.getElementById(listPhoneId);
        const searchInput = document.getElementById(searchInputId);
        const phoneItems = listPhone.querySelectorAll(phoneItem);
        const selectedFlag = document.getElementById(selectedFlagId);
        const selectedCode = document.getElementById(selectedCodeId);
        let currentIndex = -1;
        let isSelectPrefix = false;
        var nameEventSetCurrentPrefix = '';
        var nameEventSelectCountry = '';
        if (codeGrId == 'code-gr') {
            nameEventSetCurrentPrefix = 'setCurrentPrefix';
            nameEventSelectCountry = 'selectCountry';
        } else {
            nameEventSetCurrentPrefix = 'setCurrentPrefixFriend';
            nameEventSelectCountry = 'selectCountryFriend';
        }

        // Các sự kiện xử lý tương tự
        codeGr.addEventListener('click', function(e) {
            e.stopPropagation();
            suggestionList.classList.toggle('show');
            searchInput.focus();
        });

        document.addEventListener('click', function(e) {
            if (!codeGr.contains(e.target) && !suggestionList.contains(e.target)) {
                suggestionList.classList.remove('show');
                searchInput.blur();
            }
        });

        searchInput.addEventListener('input', function() {
            const searchTerm = searchInput.value.toLowerCase();
            phoneItems.forEach(item => {
                const countryName = item.querySelector('.country-name').innerText;
                item.style.display = countryName.toLowerCase().includes(searchTerm) ? 'flex' : 'none';
            });
            currentIndex = -1;
        });

        searchInput.addEventListener('keydown', function(e) {
            const visibleItems = Array.from(phoneItems).filter(item => item.style.display !== 'none');
            if (visibleItems.length === 0) return;

            if (e.key === 'ArrowDown') {
                currentIndex = (currentIndex + 1) % visibleItems.length;
                updateSelection(visibleItems);
            } else if (e.key === 'ArrowUp') {
                currentIndex = (currentIndex - 1 + visibleItems.length) % visibleItems.length;
                updateSelection(visibleItems);
            } else if (e.key === 'Enter' && currentIndex !== -1) {
                e.preventDefault();
                selectItem(visibleItems[currentIndex]);
            }
        });

        function updateSelection(visibleItems) {
            phoneItems.forEach(item => item.classList.remove('selected'));
            const selectedItem = visibleItems[currentIndex];
            selectedItem.classList.add('selected');
            selectedFlag.src = selectedItem.querySelector('img').src;
            selectedCode.innerText = selectedItem.querySelector('.country-code').innerText;
        }

        function selectItem(item, type = 1) {
            selectedFlag.src = item.querySelector('img').src;
            selectedFlag.style.display = 'block';
            selectedCode.innerText = item.querySelector('.country-code').innerText;
            suggestionList.classList.remove('show');
            const locale = item.dataset.locale;
            let detail = {
                locale: locale
            }
            if (item.classList.contains('phone-item-1')) {
                detail.type = 1;
            } else {
                detail.type = 2;
            }
            if (type == 1) {
                if (item.classList.contains('phone-item-1')) {
                    window.dispatchEvent(new CustomEvent('selectCountryFriend', {detail: locale}));
                } else {
                    window.dispatchEvent(new CustomEvent('selectCountry', {detail: locale}));
                }
                window.dispatchEvent(new CustomEvent('changePrefixPhone', {detail: detail}));
            } else {
                window.dispatchEvent(new CustomEvent('setCurrenPrefix', {detail: detail}));
            }
        }

        phoneItems.forEach(item => {
            item.addEventListener('click', function() {
                isSelectPrefix = true;
                selectItem(item);
            });
        });

        window.addEventListener(`${nameEventSetCurrentPrefix}`, function (event) {
            let locale = event.detail;
            const targetItem = document.querySelector(`${phoneItem}[data-locale="${locale}"]`);
            if (targetItem) {
                selectItem(targetItem, 2)
            }
        })

        window.addEventListener(`${nameEventSelectCountry}`, function (event) {
            let locale = event.detail;
            const targetItem = document.querySelector(`${phoneItem}[data-locale="${locale}"]`);
            if (targetItem && !isSelectPrefix) {
                selectItem(targetItem, 2)
            }
        })
    }

    // Khởi tạo cho cả hai dropdown
    initPhoneDropdown('code-gr', 'suggestion-phone', 'list-phone', 'selectedFlag', '.phone-item-1', 'selectedCode', 'jsSearchPhone');
    initPhoneDropdown('code-gr-friend', 'suggestion-phone-friend', 'list-phone-friend', 'selectedFlagFriend', '.phone-item-2', 'selectedCodeFriend', 'jsSearchPhoneFriend');
});


