function itemsCountStorage() {
  var itemsCount = 0;
  $.each(localStorage, function (key, value) {
    if (key.indexOf("cartProduct") >= 0) {
      var product = JSON.parse(value);
      itemsCount = itemsCount + parseInt(product.quantity);
    }
  });
  return itemsCount;
}


function displayItemsCount() {
  var itemsCount = itemsCountStorage()
  if (itemsCount < 100) $("#itemsCount").text(itemsCountStorage());
  else if (itemsCount >= 100) $("#itemsCount").text("99+");
  else $("#itemsCount").text("0");
}

function prixTTC() {

  var priceTotal = 0;
  $.each(localStorage, function (key, value) {
    if (key.indexOf("cartProduct") >= 0) {
      var product = JSON.parse(value);
      priceTotal += parseInt(product.quantity) * parseFloat(product.prix_ttc);
    }
  });

  $('#priceTotal').html('');
  $('#priceTotal').append(priceTotal.toFixed(2) + '<i class="bi bi-currency-euro"></i>');
}

function cartProductList() {
  var tbody = '';
  $.each(localStorage, function (key, value) {
    if (key.indexOf("cartProduct") >= 0) {
      var product = JSON.parse(value);
      var quantity = parseInt(product.quantity);
      var prix_ht = parseFloat(product.prix_ht);
      var prix_ttc = parseFloat(product.prix_ttc);
      var product_ttc = quantity * prix_ttc;
      var product_ht = quantity * prix_ht;
      var product_tva = product_ttc - product_ht;

      tbody += '<tr id="tr-p_' + product.id + '"><td><img class="cart-img"  src="' + product.image + '" /></td><td>' + product.produit + '</td > <td class="text-end">' + parseFloat(product.prix_ttc).toFixed(2) + '<i class="bi bi-currency-euro"></i></td><td><input class="form-control" type="number" value="' + product.quantity + '" min="1" onchange="updateQuantity(this, ' + product.id + ')"></td><td id="td-p_ttc_' + product.id + '" class="text-end">' + parseFloat(product_ttc).toFixed(2) + '<i class="bi bi-currency-euro"></i></td><td id="td-p_ht_' + product.id + '" class="text-end">' + product_ht.toFixed(2) + '<i class="bi bi-currency-euro"></i></td><td class="text-end" id="td-p_tva_' + product.id + '">' + product_tva.toFixed(2) + '<i class="bi bi-currency-euro"></i></td><td class="col-auto"><button type="button" class="btn" onclick="removeFromCart(' + product.id + ')"><i class="bi bi-x"></i></button></td></tr>';
    }
  });

  $('#cartProductList tbody').append(tbody);
  $('#cartContent').removeClass('d-none');

  prixTTC();
}

function addToCart(product) {
  if (jQuery.type(parseInt(product["id"])) == 'number') {
    var quantity;
    if (localStorage.getItem("cartProduct" + product["id"]) === null) {
      if ($("#quantityInput").length == 1) quantity = parseInt($("#quantityInput").val());
      else quantity = 1;
    } else {
      if ($("#quantityInput").length == 1) quantity = parseInt(JSON.parse(localStorage.getItem("cartProduct" + product["id"])).quantity) + parseInt($("#quantityInput").val());
      else quantity = parseInt(JSON.parse(localStorage.getItem("cartProduct" + product["id"])).quantity) + 1;
    }

    product["quantity"] = quantity;
    localStorage.setItem("cartProduct" + product["id"], JSON.stringify(product));
    displayItemsCount();
    $.toast({ heading: 'Panier', text: product["produit"] + ': est ajouté dans votre panier', icon: 'success', loader: true });
  } else {
    $.toast({ heading: 'Panier', text: 'Erreur inconnue', icon: 'error', loader: true });
  }
}

function removeFromCart(productId) {
  localStorage.removeItem('cartProduct' + productId);
  if (itemsCountStorage() > 0) {
    $("#tr-p_" + productId).remove();
    displayItemsCount();
  } else {
    $('#itemsCount').text('0');
    $('#cartContent').html('');
    $('#cart-empty').removeClass('d-none')
  }
}

function emptyCart() {
  $.each(localStorage, function (key, value) {
    if (key.indexOf("cartProduct") >= 0) localStorage.removeItem(key);
  });

  $('#itemsCount').text('0');
  $('#cartContent').html('');
  $('#cart-empty').removeClass('d-none');
}

function updateQuantity(productInput, productId) {
  let quantity = parseFloat($(productInput).val());
  var product = JSON.parse(localStorage.getItem("cartProduct" + productId));
  var prix_ttc = (parseFloat(product.prix_ttc) * quantity).toFixed(2);
  var prix_ht = (parseFloat(product.prix_ht) * quantity).toFixed(2);
  var prix_tva = parseFloat(prix_ttc - prix_ht).toFixed(2);
  product.quantity = quantity;
  product.prix_ttc = prix_ttc;
  product.prix_ht = prix_ht;
  product.prix_tva = prix_tva;
  localStorage.setItem("cartProduct" + productId, JSON.stringify(product));
  $('#td-p_ttc_' + productId).html(prix_ttc + '<i class="bi bi-currency-euro"></i>');
  $('#td-p_ht_' + productId).html(prix_ht + '<i class="bi bi-currency-euro"></i>');
  $('#td-p_tva_' + productId).html(prix_tva + '<i class="bi bi-currency-euro"></i>');
  displayItemsCount();
  prixTTC();
}


function checkout(btn) {
  var btnText = $(btn).html();
  var productId = [];
  var productQuantity = [];

  $.each(localStorage, function (key, value) {
    if (key.indexOf("cartProduct") >= 0) {
      var product = JSON.parse(value);
      productId.push(product.id);
      productQuantity.push({ key: 'quantite-' + product.id, value: product.quantity.toString() });
    }
  });

  $.ajax({
    url: dataCart.checkout_pdf_link,
    type: 'POST',
    timeout: 400000,
    data: {
      'product_id': productId,
      'product_quantity': productQuantity,
    },
    dataType: 'json',
    beforeSend: function () {
      $(btn).html('<i class="fa fa-refresh fa-spin"></i> Chargement...').addClass('btn-loading');
    },
    success: function (data) {
      respdf = data.url;
      if ((window.location.hostname).includes('192.168.0.210')) respdf = 'http://' + window.location.hostname + data.url;
      else respdf = 'https://' + window.location.hostname + data.url;
      // hrefg = respdf.replace("/checkout/basket/pdf", "/PDF") + '.pdf';
      hrefg = respdf;
      var anchor = document.createElement('a');
      anchor.href = hrefg;
      anchor.download = 'Devis.pdf';
      anchor.target = "_blank";
      anchor.dispatchEvent(new MouseEvent('click'));
    },
    complete: function () {
      $(btn).text(btnText).removeClass('btn-loading');
    }
  });
}

$(document).ready(function () {
  displayItemsCount();
});

$(window).on("load", function () {
  $('#spinner').fadeOut();
  if (itemsCountStorage() > 0) cartProductList();
  else $('#cart-empty').removeClass('d-none');
});