window.addEventListener("load", function () {
	addUnichemShippingDisclaimer();
	//loadPopUp();
	restrictProductsByCountry().then(function () {});
	document.querySelector('body').style.display = 'unset';
	let input = document.querySelector('body.login #user_pass');
  if(input){
    input.removeAttribute('disabled')
  }
})


async function restrictProductsByCountry() {
  let country_name = await checkIPLocation();
  let path = location.pathname;
  let restricted_paths = ['/', 'shop'];

  if (restricted_countries.includes(country_name)) {
    hideShopMenu(country_name);
    if (restricted_paths.includes(path)) {
      return redirectToRestrictedPage(country_name)
    } else if (path.includes("/product-category/")) {
      if (!path.includes(country_name)) {
        return redirectToRestrictedPage(country_name)
      }
    }
    if (location.pathname === '/checkout/' && !location.search.includes('?payment')) {
      window.location.search = 'payment'
    }
  }
  /*if (document.querySelector('body.home')
    || document.querySelector('body.woocommerce-shop')
    || document.querySelector('body.tax-product_cat')) {
  }else if(document.querySelector('body.single-product')){
    let country_name = await checkIPLocation();
   // returnFromProductPage(country_name)
  }*/
}

function hideShopMenu(country_name) {
  let shop_menu = document.querySelectorAll('.mk-good-shop');
  if (shop_menu.length > 0) {
    shop_menu.forEach(function (menu) {
      menu.innerText = "SHOP";
      menu.style.cursor = "pointer"
      menu.addEventListener('click', function () {
        location.pathname = `/product-category/${country_name}-only`;
      })
    })
  }
}

function redirectToRestrictedPage(country_name) {
  return location.pathname = `/${country_name}-only`;
}


async function checkIPLocation() {
  let stored_country_ips = localStorage.getItem('ip_country');
  let user_ip = getUserIP();
  let saved_ips = {};
  let country_name = null;
  if (!stored_country_ips) {
    country_name = await saveCountryIntoStore(saved_ips, user_ip).then(_ => _);
  } else {
    saved_ips = JSON.parse(stored_country_ips);
    country_name = saved_ips[user_ip];
    if (!country_name) {
      country_name = await saveCountryIntoStore(saved_ips, user_ip).then(_ => _);
    }
  }
  return country_name;
}

async function getCountry() {
  return fetch('https://api.db-ip.com/v2/free/self', {}
  ).then(function (data) {
    return data.json();
  })
}

async function saveCountryIntoStore(saved_ips, user_ip) {
  let country_object = await getCountry();
  //let ip_address = country_object['ipAddress'];
  let ip_address = "127.0.0.1";

  if(ip_address !== user_ip){
	  if(country_object['countryName']){
    saved_ips[user_ip] = country_object['countryName'].toLowerCase().split(" ").join('-');
  saved_ips[ip_address] = country_object['countryName'].toLowerCase().split(" ").join('-');
  localStorage.setItem('ip_country', JSON.stringify(saved_ips));
  return saved_ips[user_ip] || saved_ips[ip_address]
}
  }
}
function getUserIP() {
  let body_classes = document.querySelector('body').classList;
  let user_ip = null;
  for (let i = 0; i < body_classes.length; i++) {
    let _class = body_classes[i];
    let split = _class.split('mkgood_user_ip_');
    if (split.length === 2) {
      user_ip = split[1]
    }
  }
  return user_ip;
}

let restricted_countries = [
  'australia'
];

function addUnichemShippingDisclaimer() {
  if(document.querySelector('body.single.single-product')){
    let product_detail = document.querySelector('.product_cat-unichem-pharmaceuticals');
    if(product_detail){
      let short_description = product_detail.querySelector('.product-short-description ul');
      if(short_description){
        let textEl = document.createElement('h3');
        textEl.innerHTML = `<strong>Please note that this product would be shipped from a separate warehouse compared to other products. If you purchase other product(s) from a different warehouse, your order would be delivered twice and your shipping bill would be double the normal amount.</strong>`

        short_description.appendChild(textEl)
      }
    }
  }
  if(document.querySelector('.woocommerce-cart .unichem-product-in-cart')){
    let shipping = document.querySelector('.cart_totals .woocommerce-shipping-totals ul#shipping_method');
    let textEl = document.createElement('h3');
    textEl.innerHTML = `Please note that because you purchased products from different warehouses, the billing had to be doubled, and also note that your shipment will arrive in two different packages.`
    shipping.appendChild(textEl)
  }
}

function loadPopUp() {

  if(location.pathname === '/'){
    let imageURL = `${location.origin}/wp-content/uploads/2022/02/ambassadors.png`;
    let box = document.createElement("div");
    box.innerHTML = `<a href="/become-an-ambassador"><img src="${imageURL}" alt="" /> </a><button>X Close X</button>`;
    box.classList = 'ambassador-pop-up-box';
    let body = document.querySelector('body');
    body.appendChild(box);

    let button = box.querySelector('button');
    button.addEventListener('click', function(){
      box.classList.add('hide')
    });
    console.log(imageURL)
  }
}