let itemCount = 0;
let itemTotal = 0;
let itemSubTotal = 0;
let itemTaxTotal = 0;

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

function toggleModal() {
	try {
		document.getElementById('modal').classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function toggleOrderSuccess() {
	try {
		document.getElementById('loading').classList.toggle("hide");
		document.getElementById('orderSuccess').classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function toggleOrderFailed() {
	try {
		document.getElementById('loading').classList.toggle("hide");
		document.getElementById('orderFailed').classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function getCheckoutData() {
	try {
		let html = '';
		let xhr = new XMLHttpRequest();

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

		xhr.onload = function () {
			console.log(this.responseText);
			if (this.responseText != "Failed") {
				let response = JSON.parse(this.responseText);
				let subIncTax = "";
				let taxIncTax = "";
				let noOfItems = "";

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

					let htmlSegment = `<div class="list-group-item checkout-list-item">
										<div style="background: url('${item.pictpath}');" class="checkout-list-item-img"></div>

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

						        			<div class="checkout-qty">
						        				<p class="checkout-qty-label">Quantity</p>
					        					<p class="checkout-qty-amount">x${item.quantity}</p>
						        			</div>
										</div>
									</div>
									<div class="list-group-item commentSection">
										<div class="checkout-comment-label">Comments :</div>
										<div class="checkout-list-item-desc">
											<input class="form-control checkout-comment-input" type="text" id="c-${itemCount}" data-itemNo="${item.item_no}" maxlength="60" placeholder="Comments">
										</div>
									</div>`;
					html += htmlSegment;
					itemTaxTotal += parseFloat(item.tax);
					itemSubTotal += parseFloat(item.total);
					itemCount++;
				});

				itemTotal = itemSubTotal + itemTaxTotal;

				if (response.priceinctax) {
					subIncTax = "(incl. tax*)";
					taxIncTax = "*";
					itemTotal = itemSubTotal;
				}

				if (itemCount == 1) {
					noOfItems = "(" + itemCount + " item)";
				} else {
					noOfItems = "(" + itemCount + " items)";
				}

				htmlSegment = `<table class="checkout-calc-summary">
								<tr>
									<td class="checkout-calc-header" colspan="2">Order Summary</td>
								</tr>
								<tr>
									<td class="checkout-calc-label">
										Subtotal ${subIncTax}
									</td>
									<td class="checkout-calc-amount">
										<span class="checkout-price-label">${response.currcode}</span><span id="subtotal-amount">${priceFormatter.format(itemSubTotal)}</span>
									</td>
								</tr>
								<tr>
									<td class="checkout-calc-label">
										${taxIncTax}Tax
									</td>
									<td class="checkout-calc-amount">
										<span class="checkout-price-label">${response.currcode}</span><span id="tax-amount">${priceFormatter.format(itemTaxTotal)}</span>
									</td>
								</tr>
								<tr>
									<td colspan="2">
										<hr>
									</td>
								</tr>
								<tr>
									<td class="checkout-calc-label">
										Total ${noOfItems}
									</td>
									<td class="checkout-calc-amount checkout-price">
										<span class="checkout-price-label">${response.currcode}</span><span id="total-amount">${priceFormatter.format(itemTotal)}</span>
									</td>
								</tr>
								<tr>
									<td colspan="2">
										<hr>
									</td>
								</tr>
								<tr>
									<td class="checkout-calc-label" colspan="2">
										<input class="checkout-calc-label form-control" type="text" maxlength="40" placeholder="Remarks 1" id="remarks1">
									</td>
								</tr>
								<tr>
									<td class="checkout-calc-label" colspan="2">
										<input class="checkout-calc-label form-control" type="text" maxlength="40" placeholder="Remarks 2" id="remarks2">
									</td>
								</tr>
							</table>
							<div class="btn btn-success checkoutBtn" onclick="placeOrder()">PLACE ORDER</div>`;

				htmlSegment2 = `<div class="list-group" data-bs-toggle="dropdown" aria-expanded="false" id="custDetails-btn">
									<div class="list-group-item custDetails">
										<div class="custDetails-logo">
											<i class="fa fa-map-marker" style="font-size: 26px; color: var(--bs-red); position: relative; top: 3px; left: 1px; z-index: 9;" aria-hidden="true"></i>
											<i class="fa fa-map" style="font-size: 28px; color: #CCC; position: relative; top: -10px;" aria-hidden="true"></i>
										</div>
										<div>
											<div class="custDetails-name">
												${response.name2 + ", " + response.name}
											</div>
											<div class="custDetails-telno">
												${response.phone}
											</div>
											<div class="custDetails-addr" id="address" data-shipCode="${response.code}">
												${response.add1 + " " + response.add2 + " " + response.add3 + " " + response.add4}
											</div>
										</div>
									</div>
								</div>

								<div class="dropdown-menu custDetails-list-container" id="addList" aria-labelledby="custDetails">
									<div class="custDetails-list" style="font-weight: bold; cursor: default;">Shipping Address</div>`;

				response.shipAddress.forEach(shipAdd => {
					htmlSegment2 += `<div class="custDetails-list" data-shipCode="${shipAdd.code}" onclick="updateAdd(this)">
										${shipAdd.add1} ${shipAdd.add2} ${shipAdd.add3} ${shipAdd.add4}
									</div>`;
				});

				htmlSegment2 += `</div>`;
					
				document.getElementById('checkoutList').innerHTML = html;
				document.getElementById('orderSummary').innerHTML = htmlSegment;
				document.getElementById('custDetails').innerHTML = htmlSegment2;
			} else {			
				// Go to main page
				location.href = "catalogue.asp?&endvar=";
			}
		}

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

function updateAdd(ref) {
	try {
		let address = document.getElementById("address");

		address.setAttribute("data-shipCode", ref.getAttribute("data-shipCode"));
		address.innerHTML = ref.innerHTML;
	} catch (error) {
		console.log(error);
	}
}

function placeOrder() {
	try {
		let placeOrder = confirm("Do you want to confirm your order?");
		if (placeOrder) {
			toggleModal();
			let html = '';
			let xhr = new XMLHttpRequest();
			let index = 0;
			let shipCode = document.getElementById("address").getAttribute("data-shipCode");
			let itemList = "";
			let cList = "";
			let remarks1 = document.getElementById("remarks1").value;
			let remarks2 = document.getElementById("remarks2").value;

			while (document.getElementById("c-" + index) != undefined) {
				if (itemList != "") { itemList += "+"; cList += "+"; }
				itemList += document.getElementById("c-" + index).getAttribute("data-itemNo");
				cList += document.getElementById("c-" + index).value;

				index++;
			}

			xhr.open("GET", "data/checkoutData.asp?" + "shipCode=" + shipCode + "&subtotal=" + itemSubTotal + "&taxtotal=" + itemTaxTotal + "&total=" + itemTotal + "&itemList=" + encodeURIComponent(itemList) + "&cList=" + encodeURIComponent(cList) + "&remarks1=" + encodeURIComponent(remarks1) + "&remarks2=" + encodeURIComponent(remarks2) + "&query=order", true);

			xhr.onload = function () {
				// console.log(this.responseText);
				if (this.responseText != "Failed" && this.responseText.length < 15) {
					toggleOrderSuccess();
					let orderid = this.responseText;
					setTimeout(function () { location.href = "orderHistory.asp?orderID=" + orderid; }, 2000);
				} else {
					toggleOrderFailed();
					setTimeout(function () { location.reload(); }, 2000);
				}
			}

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

getCheckoutData();

window.onclick = function (evt) {
	let custDetails = document.querySelector(".custDetails-list");

	if (evt.target == custDetails || evt.target == document.getElementById("addList")) {
		document.getElementById("custDetails-btn").click();
	}
};