File size: 5,434 Bytes
b28567d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6448b0
 
b28567d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6448b0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
async function updateCartIcon() {
    const cart = await getCarts();
    const count = cart.length;
    const cartIcon = document.getElementById("cart-icon");
    if (cartIcon) {
        cartIcon.innerHTML = `
    <i class="bi bi-cart"></i>
    <span class="m-1">
      <span class="nd-720">Keranjang</span>
      <span class="nd-512">(${count})</span>
    </span>`;
    }
}

document.addEventListener("DOMContentLoaded", async function () {
    setInterval(await updateCartIcon, 10000);
});

async function promptQuantityAndAdd(productId) {
    checkUID("addToCart");
    let [qtyStr, isCancel] = await prompt(
        "Masukkan jumlah produk yang ingin ditambahkan ke keranjang:",
        "number"
    );

    console.log(qtyStr, isCancel);

    if (isCancel) {
        return;
    }

    if (!qtyStr) {
        alert("Jumlah tidak boleh kosong.", false);
        return;
    }

    let qty = parseInt(qtyStr);

    if (isNaN(qty) || qty <= 0) {
        alert("Masukkan jumlah produk yang valid.", false);
        return;
    }

    await addToCart(productId, qty);
}

async function addToCart(productId, quantity = 1) {
    checkUID("addToCart");

    console.log(productId, quantity);

    const cart = await getCarts();

    let userData = await getUserData();

    for (let i = 0; i < quantity; i++) {
        cart.push(productId);
    }

    userData.cart = cart;
    localStorage.setItem("cart", JSON.stringify(cart));

    await updateUserDataToGitHub(userData);
    await updateCartIcon();

    alert(
        `Produk telah ditambahkan ke keranjang sebanyak ${quantity} item.`,
        false
    );
}

function addToCartFromProduct(productId) {
    checkUID("addToCart");

    const qtyInput = document.getElementById("quantity");
    let quantity = parseInt(qtyInput.value);
    if (isNaN(quantity) || quantity <= 0) {
        alert("Masukkan jumlah produk yang valid.", false);
        return;
    }

    addToCart(productId, quantity);
}

async function loadCart() {
    do {
        const cart = await getCarts();
        const params = new URLSearchParams(window.location.search);
        const message = params.get("message") || "";

        if (message) alert(message, false);

        let cartCount = {};
        cart.forEach((id) => {
            cartCount[id] = (cartCount[id] || 0) + 1;
        });

        const cartItemsContainer = document.getElementById("cart-items");
        cartItemsContainer.innerHTML = "";
        let total = 0;

        if (Object.keys(cartCount).length === 0) {
            cartItemsContainer.innerHTML = "<p>Keranjang kosong.</p>";
        } else {
            cartItemsContainer.innerHTML = `<span class="text-center text-muted">${message}</span>`;
            let index = 1;
            for (let id in cartCount) {
                const product = products.find((p) => p.id === parseInt(id));
                if (product) {
                    const qty = cartCount[id];
                    const subtotal = product.price * qty;
                    total += subtotal;
                    cartItemsContainer.innerHTML += `
          <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
            <div>
              <h5>${product.name}</h5>
              <p class="mb-0">
                ${formatRupiah(product.price)} x 
                <input class="form-control form-control-lg" type="number" value="${qty}" min="1" style="width:60px;" 
                  onchange="updateQuantity(${product.id}, this.value)">
              </p>
            </div>
            <button class="btn btn-danger btn-lg" onclick="removeFromCart(${
                product.id
            })">Hapus</button>
          </div>`;
                    index++;
                }
            }
        }
        const cartSummary = document.getElementById("cart-summary");
        cartSummary.innerHTML = `<h4>Total: ${formatRupiah(total)}</h4>`;

        if (cartItemsContainer.innerHTML.trim() == "") {
            cartItemsContainer.innerHTML = "";
            alert("Jika daftar keranjang tidak muncul, silahkan muat ulang halaman ini", false)
        }

        await new Promise((resolve) => setTimeout(resolve, 1000));
    } while (cartItemsContainer.innerHTML.trim() == "");
}

async function updateQuantity(productId, newQty) {
    newQty = parseInt(newQty);
    if (isNaN(newQty) || newQty <= 0) {
        alert("Masukkan jumlah produk yang valid.", false);
        return;
    }

    const cart = await getCarts();
    const newCart = cart.filter((id) => id !== productId);

    for (let i = 0; i < newQty; i++) {
        newCart.push(productId);
    }
    localStorage.setItem("cart", JSON.stringify(newCart));

    let userData = await getUserData();
    userData.cart = newCart;
    await updateUserDataToGitHub(userData);

    await loadCart();
    await updateCartIcon();
}

async function removeFromCart(productId) {
    const cart = await getCarts();
    const index = cart.indexOf(productId);
    if (index !== -1) {
        cart.splice(index, 1);
        localStorage.setItem("cart", JSON.stringify(cart));

        let userData = await getUserData();
        userData.cart = cart;

        await updateUserDataToGitHub(userData);
        await loadCart();
        await updateCartIcon();
    }
}

document.addEventListener("DOMContentLoaded", function () {
    AOS.init();
    if (document.getElementById("cart-items")) {
        loadCart();
    }
});