document.addEventListener("alpine:init", () => {
/*
    Alpine.data("products",()=>({
          items:[
            {
                id: 1,
                name: "AR Nano",
                img: "ar-care-section-3-image-scent.png",
                price: 100,
                weight: 1500,
            },
            {
                id: 2,
                name: "AR 3000",
                img: "ar-care-section-4-image-3.png",
                price: 100,
                weight: 6700,
            },
        ]
      }));
      */

    Alpine.data("products",()=>({
          items:[],
          init(){
            fetch('product-data')
                  .then(response => response.json())
                  .then(data => this.items = data)
          },
    }));

    Alpine.data("fragrances",()=>({
          items:[],
          init(){
            fetch('fragrance-data')
                  .then(response => response.json())
                  .then(data => this.items = data)
          },
    }));

    Alpine.data("provinsi",()=>({
      open:false,
      search:'',
      selected: '',
      items: [],
      init(){
        fetch('province-data')
              .then(response => response.json())
              .then(data => this.items = data)
      },
      get searchResults () {
          if(this.search.length > 2){
              const filterItems = this.items.filter((item) => {
                  return item.name.toLowerCase().includes(this.search.toLowerCase())
              })

              if(filterItems.length < this.items.length && filterItems.length > 0) {
                  this.open = true
                  return filterItems

              } else {
                  //this.open = false                           
              }
          }
      },
    }));

    Alpine.store("cart", {
        items: [],
        total: 0,
        quantity: 0,
        grandTotal: 0,
        grandWeight: 0,
        shippingCost: 0,
        totalShippingCost: 0,
        districtId:0,
        add(newItem) {
            if(newItem.size == null){
                alert("Anda belum memilih ukuran!");
                return;
            }
            
            //cek apakah ada barang yang sama di cart
            const cartItem = this.items.find((item) => item.id === newItem.id && item.size === newItem.size);

            // jika belum ada / cart masih kosong
            if (!cartItem) {
                this.items.push({
                    ...newItem,
                    quantity:1, 
                    total: parseInt(newItem.price),
                    size: newItem.size,
                    sizeId: newItem.sizeId,
                    totalWeight: parseInt(newItem.weight),
                });
                this.quantity++;
                this.total = this.total + parseInt(newItem.price);
                this.grandWeight += parseInt(newItem.weight);
                this.grandTotal = this.total + this.shippingCost;
                this.sumGrandTotal();

                Swal.fire({
                    type: 'success',
                    icon: 'success',
                    title: `Item telah di tambahkan ke keranjang.`,
                    showConfirmButton: false,
                    timer: 3000
                });
                
            } else {

            // jika barang sudah ada di cart, cek apakah barang beda atau sama di cart
                this.items = this.items.map((item) => {
                //jika barang beda
                if (item.id !== newItem.id || item.size !== newItem.size) {
                    return item;
                } else {
                  // jika barang sudah ada, tambah quantity dan subtotal
                    item.quantity++;
                    item.total = parseInt(item.price) * parseInt(item.quantity);
                    item.totalWeight += parseInt(item.weight);
                    this.quantity++;
                    this.total = this.total + parseInt(item.price);
                    
                    this.grandWeight += parseInt(item.weight);
                    this.grandTotal = this.total + this.shippingCost;
                    this.sumGrandTotal();
                    return item;
                }
            });
        }
    },
    remove(id) {
      //ambil item yang mau di remove berdasarkan id
      const cartItem = this.items.find((item) => item.id === id);

      //jika item lebih dari 1
      if (cartItem.quantity > 1) {
        //telusuri 1 per 1
        this.items = this.items.map((item) => {
          //jika bukan barang yang diklik
          if (item.id !== id) {
            return item;
          } else {
            item.quantity--;
            item.total = item.price * item.quantity;
            item.totalWeight -= item.weight;
            this.quantity--;
            this.total -= item.price;
            this.grandWeight -= item.weight;
            this.sumGrandTotal();
            return item;
          }
        });
      } else if (cartItem.quantity === 1) {
        //jika barang sisa 1
        
        this.items = this.items.filter((item) => item.id !== id);
        this.quantity--;
        this.total -= cartItem.price;
        this.grandWeight -= cartItem.weight;
        this.sumGrandTotal();
      }
    },
    shippingCharge(shipment){
        this.districtId = shipment.id;
        this.shippingCost =0;
        this.totalShippingCost=0;          
        this.shippingCost = parseInt(shipment.cost);
        this.sumGrandTotal();
    },
    sumGrandTotal(){
      if(this.shippingCost > 0){
          let myShippingCost = this.shippingCost;

          if(this.grandWeight > 1000){

            let multiply = Math.floor(this.grandWeight/1000);
            console.log(multiply);

            for(let i=1 ; i <= multiply; i++){
              if(i % 1 == 0){
                myShippingCost += 5000;
              }
            }  

          }

          this.totalShippingCost = myShippingCost;
      }

      this.grandTotal = this.total + this.totalShippingCost;

    },
  });
});

// form validation
const checkoutButton = document.querySelector("#checkout-button");
checkoutButton.disabled = true;
const codButton = document.querySelector("#cod-button");
codButton.disabled = true;
//const invoiceButton = document.querySelector("#invoice");
//invoiceButton.disabled = true;

const form = document.querySelector("#checkoutForm");

form.addEventListener("keyup", function () {
  for (let i = 0; i < form.elements.length; i++) {
    if (form.elements[i].value.length !== 0) {
      checkoutButton.classList.remove("disabled");
      checkoutButton.classList.add("disabled");
      codButton.classList.remove("disabled");
      codButton.classList.add("disabled");
      //invoiceButton.classList.remove("disabled");
      //invoiceButton.classList.add("disabled");
    } else {
      return false;
    }
  }

  checkoutButton.disabled = false;
  checkoutButton.classList.remove("disabled");
  codButton.disabled = false;
  codButton.classList.remove("disabled");
  //invoiceButton.disabled = false;
  //invoiceButton.classList.remove("disabled");
});

// kirim data ketika tombol checkout diklik
checkoutButton.addEventListener("click", async function (e) {
    e.preventDefault();

    const formData = new FormData(form);
    const data = new URLSearchParams(formData);

    //minta transaction token menggunakan ajax / fetch
    try {
        const response = await fetch("place-order", {
            method: "POST",
            body: data,
        });
    
        const token = await response.text();
        //console.log(token);
        window.snap.pay(token);
        
    } catch (err) {
        console.log(err.message);
    }
   
});

// kirim data ketika tombol COD diklik
codButton.addEventListener("click", async function (e) {
    e.preventDefault();
    
    if(confirm("Pesanan COD Anda segera kami proses!")){
        const formData = new FormData(form);
        const data = new URLSearchParams(formData);
    
        //minta transaction token menggunakan ajax / fetch
        try {
            const response = await fetch("place-cod", {
                method: "POST",
                body: data,
            });
        
            const result = await response.text();
            //console.log(result);
            window.location.href = "/";
        } catch (err) {
            console.log(err.message);
        }
    }
});

// kirim data ketika tombol Invoice diklik
/*
invoiceButton.addEventListener("submit", async function (e) {
  e.preventDefault();

  if(confirm("Pesanan Anda segera kami proses!")){
      const formData = new FormData(form);
      const data = new URLSearchParams(formData);
  
      //window.location.href = "/invoice?test=123";
      fetch("/invoice", {
        method: "POST",
        body: JSON.stringify({
          userId: 1,
          title: "Fix my bugs",
          completed: false
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      });
  }
});
*/

//konversi ke rupiah
const rupiah = (number) => {
  return new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
    minimumFractionDigits: 0,
  }).format(number);
};
