document.addEventListener("alpine:init", () => {
  Alpine.data("products", () => ({
    items: [
      { id: 1, name: "Brazil Robusta", img: "2.jpg", price: 145000 },
      { id: 2, name: "Arabica Blend", img: "1.jpg", price: 165000 },
      { id: 3, name: "Liberica Blend", img: "3.jpg", price: 150000 },
      { id: 4, name: "Excelsa Blend A", img: "4.jpg", price: 175000 },
      { id: 5, name: "Excelsa Blend B", img: "5.jpg", price: 200000 },
    ],
  }));

  Alpine.store("cart", {
    items: [],
    total: 0,
    quantity: 0,
    add(newItem) {
      const cartItem = this.items.find((item) => item.id === newItem.id);

      // Jika Belum ada di Cart
      if (!cartItem) {
        this.items.push({ ...newItem, quantity: 1, total: newItem.price });
        this.quantity++;
        this.total += newItem.price;
      } else {
        // Jika Sudah ada di Cart
        this.items = this.items.map((item) => {
          if (item.id !== newItem.id) {
            return item;
          } else {
            item.quantity++;
            item.total = item.quantity * item.price;
            this.quantity++;
            this.total += item.price;
            return item;
          }
        });
      }
    },
    remove(id) {
      const cartItem = this.items.find((item) => item.id === id);

      if (cartItem.quantity > 1) {
        this.items = this.items.map((item) => {
          if (item.id !== id) {
            return item;
          } else {
            item.quantity--;
            item.total = item.quantity * item.price;
            this.quantity--;
            this.total -= item.price;
            return item;
          }
        });
      } else if (cartItem.quantity === 1) {
        this.items = this.items.filter((item) => item.id !== id);
        this.quantity--;
        this.total -= cartItem.price;
      }
    },
  });
});

// Form Validation
const checkoutButton = document.querySelector(".checkoutBtn");
const form = document.querySelector("#checkoutForm");

checkoutButton.disabled = true;

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

// Kirim data ketika checkout
checkoutButton.addEventListener("click", async function (e) {
  e.preventDefault();
  const formData = new FormData(form);
  const data = new URLSearchParams(formData);
  const objData = Object.fromEntries(data);
  // const messageWA = formatMessage(objData);
  // window.open(
  //   "https://wa.me/6285899844534?text=" + encodeURIComponent(messageWA),
  //   "_blank"
  // );

  // Minta token dari server
  try {
    const response = await fetch("php/placeOrder.php", {
      method: "POST",
      body: data,
    });
    const token = await response.text();
    // console.log(token);
    window.snap.pay(token);
  } catch (error) {
    console.log(error.message);
  }
});

// Format pesan whatsapp
const formatMessage = (obj) => {
  return `*Order Details*
    Name: ${obj.name}
    Email: ${obj.email}
    Phone: ${obj.phone}
    \n
      *Items Ordered*
      ${JSON.parse(obj.items).map(
        (item) => `- ${item.name} (${item.quantity}) x ${rupiah(item.total)} \n`
      )}
    Total Price: ${rupiah(obj.total)}
    Thank you for your order! :)`;
};

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