function viewCart(ref) {
	try {
		document.getElementById('cart-body').classList.toggle('close');
		document.getElementById('cart-list').classList.toggle('close');

		if (ref.innerHTML == "Close Cart") {
			ref.innerHTML = "View Cart";
			ref.classList.remove("btn-danger");
			ref.classList.add("btn-warning");
		} else {
			ref.innerHTML = "Close Cart";
			ref.classList.remove("btn-warning");
			ref.classList.add("btn-danger");
			getCartData();
		}
	} catch (error) {
		console.log(error);
	}
}

function toggleAddToCartLoading() {
	try {
		document.getElementById('addToCart').classList.toggle("disabled");
		document.getElementById('addToCartLoading').classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function toggleCartQtyLoading(itemNo) {
	try {
		document.getElementById("minusQty-" + itemNo).classList.toggle("disabled");
		document.getElementById("addQty-" + itemNo).classList.toggle("disabled");
		document.getElementById("loading-" + itemNo).classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function toggleCartError() {
	try {
		if (document.getElementById('cart-group-container').innerHTML != '') {
			document.getElementById('cart-group-container').classList.remove("hide");
			document.getElementById('error-cart').classList.add("hide");
		} else {
			document.getElementById('cart-group-container').classList.add("hide");
			document.getElementById('error-cart').classList.remove("hide");
		}
	} catch (error) {
		console.log(error);
	}
}

function getCartData() {
	try {
		let query = location.search;
		if (query == "") { query = "?"; }

		let html = '';
		let itemTotalSegment = '';
		let itemCount = 0;
		let itemTotal = 0;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/cartData.asp" + query + "&query=get", true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("{")) {
				let response = JSON.parse(this.responseText);

				response.items.forEach(item => {
					let disabled = '';
					if (item.quantity == response.maxOrderPerItem) { disabled = 'disabled'; }

					let itemDisc = '';
					if (item.showItemDisc && item.discount > 0) {
						itemDisc = `<p class="cart-itemDisc"><span class="cart-oriPrice">${response.currcode}${priceFormatter.format(item.oriPrice)}</span>&nbsp;&nbsp;<span class="cart-discLabel">-${item.discount}%</span></p>`;
					}

					let htmlSegment = `<div class="list-group-item cart-list-item">
										<div class="btn btn-outline-danger deleteCart" onclick="deleteCart('${itemCount}')">
											<i class="fa fa-trash" aria-hidden="true"></i>
										</div>
								    	<div style="background: url('${item.pictpath}');" class="cart-list-item-img"></div>

										<div class="cart-list-item-desc">
											${item.gcatalogue}
						        			<p class="cart-itemLabel">${item.icatalogue}</p>
						        			<p class="cart-itemNo">${item.item_no} ${item.item_no2}</p>
						        			<p class="cart-price"><span class="item-price-label">${response.currcode}</span>${priceFormatter.format(item.price)}</p>
						        			${itemDisc}

						        			<div class="cart-qty">
					        					<span class="btn btn-danger cart-qty-btn" id="minusQty-${itemCount}" onclick="minusCartQty('${itemCount}')">
					        						<i class="fa fa-minus" aria-hidden="true"></i>
					        					</span>

					        					<input type="text" class="cart-qty-amount" id="${itemCount}" onkeypress="return validateCartQty(event, '${itemCount}', ${response.maxOrderPerItem})" onblur="updateCart('${itemCount}')" onfocus="this.select()" value="${item.quantity}" maxlength="${response.maxOrderPerItem.toString().length}" data-itemNo="${item.item_no}" />

					        					<span class="btn btn-success cart-qty-btn ${disabled}" id="addQty-${itemCount}" onclick="addCartQty('${itemCount}', ${response.maxOrderPerItem})">
					        						<i class="fa fa-plus" aria-hidden="true"></i>
					        					</span>

												<!-- Loading/Spinning -->
												<div class="d-flex hide" id="loading-${itemCount}">
													<div class="spinner-border text-secondary" role="status">
														<span class="visually-hidden">Loading...</span>
													</div>
												</div>
						        			</div>
										</div>
									</div>`;
					html += htmlSegment;
					itemCount++;
					itemTotal += parseFloat(item.total);
				});

				let htmlSegment = `<div class="btn btn-outline-danger clearCart" onclick="clearCart()">Clear Cart</div>`;
				html += htmlSegment;
				itemTotalSegment = `<span class="cart-price-label">${response.currcode}</span> ${priceFormatter.format(itemTotal)}`;
			} else {
				itemTotalSegment = `<span class="cart-price-label">${this.responseText}</span> ${priceFormatter.format(itemTotal)}`;
			}

			document.getElementById('cart-group-container').innerHTML = html;
			document.getElementById('total-items').innerHTML = itemCount;
			document.getElementById('cart-price-total').innerHTML = itemTotalSegment;
			enableCheckoutBtn(itemTotal);
			toggleCartError();
		}

		xhr.send();
	} catch (error) {
		console.log(error);
	}
}

function addToCart() {
	try {
		toggleAddToCartLoading();
		let query = location.search;
		if (query == "") { query = "?"; }

		let qty = document.getElementById('item-qty').value;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/cartData.asp" + query + "&qty=" + qty + "&query=add", true);

		xhr.onload = function () {
			getCartData();
			feedback(this.responseText);
			// console.log(this.responseText);
			toggleAddToCartLoading();
		}

		xhr.send();
	} catch (error) {
		console.log(error);
	}
}

function updateCart(index) {
	try {
		let qty = document.getElementById(index).value;

		if (qty > 0) {
			toggleCartQtyLoading(index);
			let itemNo = document.getElementById(index).getAttribute("data-itemNo");
			let xhr = new XMLHttpRequest();

			xhr.open("GET", "data/cartData.asp?" + "itemNo=" + itemNo + "&qty=" + qty + "&query=update", true);

			xhr.onload = function () {
				toggleCartQtyLoading(index);
				getCartData();
				feedback(this.responseText);
				// console.log(this.responseText);
			}

			xhr.send();
		} else {
			deleteCart(itemNo);
		}
	} catch (error) {
		console.log(error);
	}
}

function deleteCart(index) {
	try {
		let del = confirm("Are you sure you want to delete the item from your cart?");

		if (del) {
			let itemNo = document.getElementById(index).getAttribute("data-itemNo");
			let xhr = new XMLHttpRequest();

			xhr.open("GET", "data/cartData.asp" + "?itemNo=" + itemNo + "&query=delete", true);

			xhr.onload = function () {
				getCartData();
				feedback(this.responseText);
				// console.log(this.responseText);
			}

			xhr.send();
		} else {
			getCartData();
		}
	} catch (error) {
		console.log(error);
	}
}

function clearCart() {
	try {
		let clear = confirm("Are you sure you want to clear your cart?");

		if (clear) {
			let xhr = new XMLHttpRequest();

			xhr.open("GET", "data/cartData.asp?query=clear", true);

			xhr.onload = function () {
				getCartData();
				feedback(this.responseText);
				// console.log(this.responseText);
			}

			xhr.send();
		} else {
			getCartData();
		}
	} catch (error) {
		console.log(error);
	}
}

function validateCartQty(evt, index, max) {
	try {
		let qty = document.getElementById(index);
		// Only numbers are allowed
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if ((ASCIICode < 48 || ASCIICode > 57) && ASCIICode != 127 && ASCIICode != 8) {
			return false;
		} else {
			if (parseFloat(qty.value + evt.key) >= max) {
				qty.value = max;
				enableAddCartQty(index, qty.value, max);
				return false;
			}

			enableAddCartQty(index, qty.value, max);
			return true;
		}
	} catch (error) {
		console.log(error);
	}
}

function addCartQty(index, max) {
	try{
		let qty = document.getElementById(index);

		if (qty.value < max) { 
			qty.value = parseInt(qty.value) + 1;
			updateCart(index);
		}

		enableAddCartQty(index, qty.value, max);
	} catch (error) {
		console.log(error);
	}
}

function minusCartQty(index) {
	try{
		let qty = document.getElementById(index);

		if (qty.value > 1) { 
			qty.value = parseInt(qty.value) - 1;
			updateCart(index);
		} else { 
			deleteCart(index);
		}
	} catch (error) {
		console.log(error);
	}
}

function enableAddCartQty(index, value, max) {
	try {
		if (value >= max) {
			document.getElementById("addQty-" + index).classList.add("disabled");
		} else {
			document.getElementById("addQty-" + index).classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function enableCheckoutBtn(itemTotal) {
	try {
		if (itemTotal > 0) {
			document.getElementById('checkoutBtn').classList.remove("disabled");
		} else {
			document.getElementById('checkoutBtn').classList.add("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function checkout() {
	try {
		location.href = "checkout.asp";
	} catch (error) {
		console.log(error);
	}
}

getCartData();