//Alpinejs Fashion Section
document.addEventListener("alpine:init", () => 
    {
        Alpine.data("products",()=>({
            items:[],
            init(){
                fetch('product-data')
                    .then(response => response.json())
                    .then(data => this.items = data)
            },
        }));
    
        Alpine.data("provinsi",()=>({
            open:false,
            search:'',
            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
                  }
              }
          },
        }));
    
        Alpine.store("cart", {
            items: Alpine.$persist([]).as("items"),
            total: Alpine.$persist(0).as("total"),
            quantity: Alpine.$persist(0).as("quantity"),
            grandTotal: Alpine.$persist(0).as("grandTotal"),
            grandWeight: Alpine.$persist(0).as("grandWeight"),
            shippingCost: Alpine.$persist(0).as("shippingCost"),
            totalShippingCost: Alpine.$persist(0).as("totalShippingCost"),
            districtId:Alpine.$persist(0).as("districtId"),
            
            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,
                        sizeId: newItem.sizeId,
                        total: parseInt(newItem.price),
                        size: newItem.size,
                        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,sizeId,idx) {
                //ambil item yang mau di remove berdasarkan id
                const cartItem = this.items.find((item) => item.id === id && item.sizeId === sizeId);
    
                //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 && item.sizeId === sizeId) {
                            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 {
                            return item;
                        }
                    });
                } else if (cartItem.quantity === 1) {
                    //jika barang sisa 1
                    //this.items = this.items.filter((item) => item.id !== id);
                    this.items.splice(idx,1);
                    this.quantity--;
                    this.total -= cartItem.price;
                    this.grandWeight -= cartItem.weight;
                    this.sumGrandTotal();
                }
            },
            
            shippingCharge(shipment){
                this.districtId = shipment.id;
                this.shippingCost = 0;
                
                this.totalShippingCost = 0;
                if(shipment.cost == 0){
                    this.shippingCost = 10000; //Minimum shipping charge
                }else{
                    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);
                        for(let i=1 ; i <= multiply; i++){
                            if(i % 1 == 0){
                                myShippingCost += 5000;
                            }
                        }
                    }
                    this.totalShippingCost = myShippingCost;
                }
                this.grandTotal = this.total + this.totalShippingCost;
            },

            clearCartData(){
                this.items = [];
                this.total = 0;
                this.quantity = 0;
                this.grandTotal = 0;
                this.grandWeight = 0;
                this.shippingCost = 0;
                this.totalShippingCost = 0;
                this.districtId = 0;
            },
            
        });
    }
);

//Javascript section
// form validation
const checkoutButton = document.querySelector("#checkout-button");
checkoutButton.disabled = true;
const codButton = document.querySelector("#cod-button");
codButton.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");
    } else {
      return false;
    }
  }

  checkoutButton.disabled = false;
  checkoutButton.classList.remove("disabled");
  codButton.disabled = false;
  codButton.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);
        }
    }
});


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