$("#searchInput").focus(function () {
  $("#searchInput").css({});
  $("#searchInput").prop("placeholder", "");
});

$("#searchInput").blur(function () {
  $("#searchInput").css({
    "background-image": "url('https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/search-24.png')",
  });
  $("#searchInput").prop("placeholder", "Search..");
});

var signed = false;
var tax_free = false;
if ($("#username_sp").text()) signed = true;

//add product to cart
async function add_to_cart(product_id, qty = 1) {
  var qty = parseInt(qty);
  var cart_product = {};

  if (signed) {
    cart_product._id = product_id;
    cart_product.qty = qty;
    await fetch("/new/cart/product", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ cart_product }),
    }).then(response => response.json())
      .then(data => {
        if (data.message == "success") {
          $('.toast').toast('show');
          return true;
        }
      });
    cart_num();
    return true;
  }

  var cart_products = sessionStorage.getItem("cart_products");
  //I might need this product info later to check availability or stock
  fetch("/product/details/" + product_id + "/json")
    .then(data => { return data.json(); }).then(function (res) {
      if (res.message == "success") {
        if (!cart_products) {
          cart_products = [];
        }
        else {
          cart_products = JSON.parse(sessionStorage.getItem("cart_products"));
          var found = cart_products.some(current_cr_p => current_cr_p._id === product_id);
          $('.toast').toast('show');
          if (found) {
            cart_products.find(current_cr_p => current_cr_p._id == product_id).qty += qty;
            sessionStorage.setItem("cart_products", JSON.stringify(cart_products));
            fill_cart();
            return true;
          }
        }
        cart_product._id = res.product._id;
        cart_product.qty = qty;
        cart_products.push(cart_product);
        sessionStorage.setItem("cart_products", JSON.stringify(cart_products));
        $('.toast').toast('show');
        cart_num();
      }
    });
}


//edit cart product quantity
function cart_qty(product_id, qty_input) {
  var qty = parseInt(qty_input.value);
  if (qty < 0) {
    qty = qty_input.value = 0;
  }

  if (signed) {
    fetch("/cart/product_quantity", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ product_id, qty }),
    }).then(response => response.json())
      .then(data => {
        if (data.message == "success") {
          fill_cart();
        }
      });
    return true;
  }

  var cart_products = JSON.parse(sessionStorage.getItem("cart_products"));

  cart_products.find(cart_product => cart_product._id == product_id).qty = qty;

  sessionStorage.setItem("cart_products", JSON.stringify(cart_products));
  fill_cart();
}


//remove item from cart
function cart_rm(product_id) {
  if (signed) {
    fetch("/cart/remove/product/" + product_id, {
      method: 'DELETE'
    }).then(response => response.json())
      .then(data => {
        if (data.message == "success") {
          fill_cart();
        } else cart_num();
      });
    return true;
  }
  var cart_products = JSON.parse(sessionStorage.getItem("cart_products"));
  cart_products = cart_products.filter(function (cur_product) {
    return cur_product._id !== product_id;
  });
  if (cart_products.length == 0) document.querySelector("#cart-div .badge").textContent = "0";
  sessionStorage.setItem("cart_products", JSON.stringify(cart_products));
  fill_cart();
};


//search
function search() {
  var searchField = $("#searchInput").val();
  if (searchField && searchField[0] != " ") {
    window.location.href = "/search/products/" + searchField;
  }
}


//start doc ready*/
$(document).ready(function () {
  $('#cart-toast').toast({ delay: 2500 });

  $('#searchInput').keypress(function (e) {
    var key = e.which;
    if (key == 13)  // the enter key code
    {
      search();
    }
  });

  cart_num();
  $("#checkout-form").submit(function (event) {
    console.log('signed', signed);
    if (signed) {
      this.action = "/user/checkout_setup";
      this.submit();
    }
    event.preventDefault();
    var cart_products = sessionStorage.getItem("cart_products");
    console.log('cart_products', cart_products);
    $("#cart-prs-input").val(cart_products);
    if (signed) this.action = "/user/checkout_setup";
    this.submit();
  });
  //end document ready
});


//fill cart
function fill_cart() {
  var cart_products = JSON.parse(sessionStorage.getItem("cart_products"));
  let ids = [];
  var table_body = document.querySelector("#cartModal table tbody");
  table_body.innerHTML = "";
  var total = 0;
  var TTC = 0;
  var totalElement = document.querySelector("#total-cart");

  if (!signed) {
    if (!cart_products) {
      cart_products = [];
      sessionStorage.setItem("cart_products", JSON.stringify(cart_products));
      document.querySelector("#checkout-btn").disabled = true;
      totalElement.textContent = total + " DH";
      return false;
    }
  }
  if (cart_products != null) {
    cart_products.forEach(cart_product => {
      ids.push(cart_product._id);
    });
    if (ids.length == 0) {
      document.querySelector("#checkout-btn").disabled = true;
      totalElement.textContent = total + " DH";
    }
  } else {
    cart_products = [];
  }
  document.querySelector("#checkout-btn").disabled = false;
  fetch("/cart_products", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ cart_products }),
  }).then(response => response.json())
    .then(data => {
      if (data.message == "success") {
        console.log(data);
        var full_products_cart = data.full_products_cart;
        var table_body = document.querySelector("#cartModal table tbody");
        table_body.innerHTML = "";
        if (!full_products_cart.length) {
          document.querySelector("#checkout-btn").disabled = true;
          cart_num();
          return false;
        }
        full_products_cart.forEach(function (product_cart, indx) {
          total += (product_cart.product.price * product_cart.qty);
          TTC += (product_cart.product.TTC * product_cart.qty);

          table_body.innerHTML += `<tr> <td class="w-25" >
          <img src="`+ product_cart.product.images?.[0].secure_url + `"
            class="img-fluid img-thumbnail">
        </td>
        <td>`+ product_cart.product.name + `</td>
        <td class="cart_product_price" data-oprice='`+ product_cart.product.TTC + `'>` + product_cart.product.price + `</td>
        <td class="qty" style="min-width:8vmax"><input style="width:100%;" min="0" onchange="cart_qty('`+ product_cart.product._id + `', this)" type="number" class="form-control" id="input1" value="` + product_cart.qty + `"></td>
        <td  class="cart_product_price_qty" data-ototal='`+ (product_cart.product.TTC * product_cart.qty) + `'>` + (product_cart.product.price * product_cart.qty) + `</td>
        <td>
          <a onclick="cart_rm('`+ product_cart.product._id + `')" class="btn btn-danger btn-sm">
            <i class="fa fa-times"></i>
          </a>
        </td>
      </tr>`;
        });
        document.querySelector("#total-cart").textContent = total + " DH";
        document.querySelector('#total-cart').dataset.ototal = TTC + " DH"; //setter
        cart_num();
      } else {
        alert("something is wrong");
      }
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

function cart_num() {
  if (!signed) {
    var cart_products = JSON.parse(sessionStorage.getItem("cart_products"));
    if (cart_products) {
      if (cart_products.length > 0) {
        document.querySelector("#cart-div .badge").textContent = cart_products.length;
      }
      else { $("#cart-div .badge").fadeTo("fast", 0); }
    }
  }
  else {
    fetch("/user/signed/cart").then(response => response.json())
      .then(data => {
        if (data.message == "success") {
          if (data.cart?.Product_qty) {
            if (data.cart?.Product_qty.length > 0) {
              document.querySelector("#cart-div .badge").textContent = data.cart.Product_qty.length;
              $("#cart-div .badge").fadeTo("fast", 1);
            }
            else {
              document.querySelector("#cart-div .badge").textContent = "0";
              $("#cart-div .badge").fadeTo("fast", 0);
            }
          }
          else {
            document.querySelector("#cart-div .badge").textContent = "0";
            $("#cart-div .badge").fadeTo("fast", 0);
          }
        }
      });
  }
}

function change_prices() {
  //price
  document.querySelectorAll(".cart_product_price").forEach(function (e) {
    var temp = e.textContent;
    e.textContent = e.dataset.oprice;
    e.dataset.oprice = temp;
  });

  //price * qty
  document.querySelectorAll(".cart_product_price_qty").forEach(function (e) {
    var temp = e.textContent;
    e.textContent = e.dataset.ototal;
    e.dataset.ototal = temp;
  });

  //final total
  var total_el = document.querySelector("#total-cart");
  var temp = total_el.textContent;
  total_el.textContent = total_el.dataset.ototal;
  total_el.dataset.ototal = temp;

  var selected_text = $("#tax-option").data("selected");
  if (selected_text == 1) {
    $("#tax-option").text("View cart with taxes");
    $("#tax-option").data("selected", 2);
  }
  else {
    $("#tax-option").text("See the tax-free Cart");
    $("#tax-option").data("selected", 1);
  }
}
function init_text() {
  $("#tax-option").text("See the tax-free Cart");
  $("#tax-option").data("selected", 1);
}