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

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

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

function getOrdersData(page, search) {
	try {
		document.getElementById('orderHistory').innerHTML = `
			<div class="row justify-content-center">
				<!-- Item Components -->
				<div class="col-12 col-lg-11 col-xl-9 col-xxl-8">
					<!-- Loading/Spinning -->
					<div class="d-flex component hide" id="loading">
						<div class="spinner-border text-secondary" role="status">
							<span class="visually-hidden">Loading...</span>
						</div>
					</div>
				</div>
			</div>`;
		let orderid = '';
		if (params.has("orderID")) {
			orderid = params.get("orderID");
		}

		let html = '';
		let orderCount = 0;
		let itemCount = 0;
		let noOfItems = 0;
		let totalPages = 0;
		let itemTotalSegment = '';
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/orderData.asp?page=" + page + "&orderid=" + orderid + "&search=" + search + "&query=get", true);

		xhr.onload = function () {
			console.log(this.responseText);
			if (this.responseText.startsWith("{")) {
				let response = JSON.parse(this.responseText);
				let subIncTax = "";
				let taxIncTax = "";
				let noOfItems = "";
				let printOrder = "";
				let cancelOrder = "";
				let updates = "";

				// General Order History
				if (response.orderid == undefined) {
					totalPages = parseInt(response.totalOrders / response.ordersPerPage)
					if ((response.totalOrders % response.ordersPerPage) > 0) { totalPages++; }

					let disablePrev = '';
					let disableNext = '';
					if (response.page == 1) { disablePrev = "disabled"; }
					if (response.page == totalPages) { disableNext = "disabled"; }

					html += `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8">
								<div class="breadcrumbs">
									<span>Profile</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Order History
								</div>
								<div class="component pageHeader">
									<input class="form-control pageHeader-search" type="search" name="search" id="search" placeholder="Search (Order No.)" aria-label="Search" onkeypress="submitSearch(event)">
									<div class="pageHeader-pagination">
										<div class="btn pagination-previous ${disablePrev}" onclick="previousPage()"><i class="fa fa-angle-left fw-bold" aria-hidden="true"></i></div>
										<input type="text" class="cart-qty-amount" id="currPage" value="${response.page}" readonly />
										<span class="pageHeader-label" id="totalPage" data-totalPage="${totalPages}">&nbsp;&nbsp;of ${totalPages}&nbsp;&nbsp;</span>
										<div class="btn pagination-next ${disableNext}" onclick="nextPage()"><i class="fa fa-angle-right fw-bold" aria-hidden="true"></i></div>
									</div>
								</div>
								<div class="component">`;

					response.orders.forEach(order => {
						itemCount = 0;
						noOfItems = "";
						if (orderCount != 0) { html += `<hr class="orderDiv">`; }
						let htmlSegment = `<div class="orderDetails">
											<div>
												<span class="orderDetails-label">Order No: </span>${order.orderid}
											</div>
											<div>
												<span class="orderDetails-label">Date: </span>${order.date}
											</div>
										</div>
										<div class="list-group">`;
						order.items.forEach(item => {
							if (!item.itemDeleted) {
								let itemDisc = '';
								if (item.showItemDisc && item.discount > 0) {
									itemDisc = `<p class="orderHistory-itemDisc"><span class="orderHistory-oriPrice">${response.currcode}${priceFormatter.format(item.oriPrice)}</span>&nbsp;&nbsp;<span class="orderHistory-discLabel">-${item.discount}%</span></p>`;
								}

								let priceUpdates = '';
								let quantityUpdates = '';
								if (item.priceUpdated || item.quantityUpdated) {
									updates = `<span class="orderHistory-itemDisc"><span style="color: red;">*</span>Updated by ADMIN</span>`;
									if (item.priceUpdated) {priceUpdates = `<span style="color: red;">*</span>`;}
									if (item.quantityUpdated) {quantityUpdates = `<span style="color: red;">*</span>`;}
								}

								let deliveredQty = '';
								let pendingQty = '';
								if (item.delivered != 0) {
									deliveredQty = `<div>
								        				<span class="orderHistory-qty-label Completed">Delivered</span>
							        					<span class="orderHistory-qty-amount Completed">x${item.delivered}</span>
							        				</div>`;
								}

								if (item.pending != 0) {
									pendingQty = `<div>
							        				<span class="orderHistory-qty-label Pending">Pending</span>
						        					<span class="orderHistory-qty-amount Pending">x${item.pending}</span>
						        				</div>`;
								}

								if (itemCount < response.itemsPerOrder) {
									htmlSegment += `<div class="list-group-item orderHistory-list-item">
														<div style="background: url('${item.pictpath}');" class="orderHistory-list-item-img"></div>

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

										        			<div class="orderHistory-qty">
											        			<div>
											        				<span class="orderHistory-qty-label">Quantity</span>
										        					<span class="orderHistory-qty-amount">x${item.quantity}${quantityUpdates}</span>
										        				</div>
										        				${deliveredQty}
										        				${pendingQty}
										        			</div>
														</div>
													</div>`;
								}
								itemCount++;
							}
						});

						if (itemCount > response.itemsPerOrder) {
							if (itemCount - response.itemsPerOrder > 1) {
								noOfItems = "+" + (itemCount - response.itemsPerOrder) + " items";
							} else {
								noOfItems = "+1 item";
							}
						}
							
						htmlSegment += `<div class="list-group-item orderHistory-list-item extra">
											<div class="orderHistory-qty">
						        				${noOfItems}
						        			</div>
						        			<div class="orderHistory-qty link">
						        				<span onclick="viewOrderDetails('${order.orderid}')">View full details</span>
						        				&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>
						        			</div>
										</div>
										<div class="list-group-item orderTotal">
											<div class="orderHistory-qty">
												<p class="orderTotal-qty-label ${order.status}">${order.shippingStatus}</p>
						        				<p class="orderTotal-qty-label">Order total: </p>
					        					<p class="orderTotal-price">
							        				<span class="orderTotal-price-label">${response.currcode}</span>${priceFormatter.format(order.totalAmount)}
							        			</p>
						        			</div>
										</div>
									</div>`;
						html += htmlSegment;
						orderCount++;
					});

					html += `</div>
							</div>`;

				} else { // Detailed Order History
					if (document.referrer.endsWith("checkout.asp")) {
						back = "location.href = 'orderHistory.asp?endvar='";
					} else {
						back = "history.back()";
					}
					html += `<div class="col-11 breadcrumbs">
								<span class="link" onclick="${back}">Order History</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Order No: ${response.orderid}
							</div>
							<!-- Checkout Components -->
							<div class="col-11 col-xl-8 px-0 px-xl-2 pb-0 pb-xl-2">
								<div class="component orderHistory-custDetails">
									<div class="list-group">
										<div class="list-group-item custDetails" id="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">
													${response.add1 + " " + response.add2 + " " + response.add3 + " " + response.add4}
												</div>
											</div>
										</div>
									</div>
								</div>
								<div class="component">
									<div class="list-group" id="checkoutList">`;

					if (response.status == "Ongoing") {
						cancelOrder = `<div class="btn btn-danger cancelBtn" onclick="cancelOrder()">CANCEL ORDER</div>`;
					}

					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 priceUpdates = '';
						let quantityUpdates = '';
						let commentUpdates = '';
						let itemDisabled = '';
						if (item.itemDeleted) {
							itemDisabled = `<div class="itemRemoved">
												Item Removed
											</div>`;
						} else {
							if (item.priceUpdated || item.quantityUpdated || item.commentUpdated) {
								updates = `<span class="orderHistory-itemDisc"><span style="color: red;">*</span>Updated by ADMIN</span>`;
								if (item.priceUpdated) {priceUpdates = `<span style="color: red;">*</span>`;}
								if (item.quantityUpdated) {quantityUpdates = `<span style="color: red;">*</span>`;}
								if (item.commentUpdated) {commentUpdates = `<span style="color: red;">*</span>`;}
							}
						}

						let deliveredQty = '';
						let pendingQty = '';
						if (item.delivered != 0) {
							deliveredQty = `<div>
						        				<span class="orderHistory-qty-label Completed">Delivered</span>
					        					<span class="orderHistory-qty-amount Completed">x${item.delivered}</span>
					        				</div>`;
						}

						if (item.pending != 0) {
							pendingQty = `<div>
					        				<span class="orderHistory-qty-label Pending">Pending</span>
				        					<span class="orderHistory-qty-amount Pending">x${item.pending}</span>
				        				</div>`;
						}
						
						html += `		<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)}${priceUpdates}</p>
									        	${itemDisc}

							        			<div class="checkout-qty">
							        				<div>
								        				<span class="orderHistory-qty-label">Quantity</span>
							        					<span class="orderHistory-qty-amount">x${item.quantity}${quantityUpdates}</span>
							        				</div>
							        				${deliveredQty}
							        				${pendingQty}
							        			</div>

							        			${itemDisabled}
											</div>
										</div>
										<div class="list-group-item commentSection">
											<div class="checkout-comment-label">Comments${commentUpdates} :</div>
											<div class="checkout-list-item-desc">
												<input class="form-control checkout-comment-input" type="text" placeholder="No Comment" value="${item.comments}" readonly>
											</div>
										</div>`;
						itemCount++;
					});

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

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

					if (response.status != "Cancelled") {
						printOrder = `<div class="btn btn-primary printBtn" onclick="printOrder('SO', '${response.orderid}')">PRINT ORDER</div>`;
					}

					if (response.status == "Ongoing") {
						cancelOrder = `<div class="btn btn-danger cancelBtn" onclick="cancelOrder()">CANCEL ORDER</div>`;
					}

					let relatedDocs = '';
					if (response.showRelatedDocs) {
						relatedDocs += `<table class="checkout-calc-summary">
										<tr>
											<td colspan="2">
												<hr>
											</td>
										</tr>
										<tr>
											<td class="checkout-calc-header" colspan="2">Related Documents</td>
										</tr>`;
						response.relatedDocs.forEach(relatedDoc => {
							let DO = '';
							if (relatedDoc.type == "DO") {
								relatedDocs += `<tr>
												<td class="checkout-calc-label">D/O</td>
												<td class="checkout-calc-amount">
													<span class="checkout-price-label relatedDocs" onclick="printOrder('DO', '${relatedDoc.ref}')">${relatedDoc.ref}</span>
												</td>
											</tr>`;
							}

							let IN = '';
							if (relatedDoc.type == "IN") {
								relatedDocs += `<tr>
												<td class="checkout-calc-label">
													INV
												</td>
												<td class="checkout-calc-amount">
													<span class="checkout-price-label relatedDocs" onclick="printOrder('IN', '${relatedDoc.ref}')">${relatedDoc.ref}</span>
												</td>
											</tr>`;
							}
						});

						relatedDocs += `</table>`;
					}

					if (response.remarks1 == "" && response.remarks2 != "") {
						response.remarks1 = response.remarks2;
						response.remarks2 = "";
					}
					
					html += `		</div>
								${updates}</div>
							</div>

							<div class="col-11 col-xl-3 px-0 px-xl-1 pb-2">
								<div class="component checkout-calc" id="orderSummary">
									<table class="checkout-calc-summary">
										<tr>
											<td class="checkout-calc-header">Order Summary</td>
											<td class="checkout-calc-amount ${response.status}">${response.shippingStatus}</td>
										</tr>
										<tr>
											<td class="checkout-calc-label">
												Order No
											</td>
											<td class="checkout-calc-amount">
												<span class="checkout-price-label">${response.orderid}</span>
											</td>
										</tr>
										<tr>
											<td class="checkout-calc-label">
												Date
											</td>
											<td class="checkout-calc-amount">
												<span class="checkout-price-label">${response.date}</span>
											</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(response.subtotal)}</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(response.taxtotal)}</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(response.totalamount)}</span>
											</td>
										</tr>
										<tr>
											<td colspan="2">
												<hr>
											</td>
										</tr>
										<tr>
											<td class="checkout-calc-header remarks" colspan="2">Remarks</td>
										</tr>
										<tr>
											<td class="checkout-calc-label" colspan="2">
												<input class="checkout-calc-label form-control" type="text" value="${response.remarks1}" placeholder="No Remarks" readonly>
											</td>
										</tr>
										<tr>
											<td class="checkout-calc-label" colspan="2">
												<input class="checkout-calc-label form-control" type="text" value="${response.remarks2}" readonly>
											</td>
										</tr>
									</table>
									${printOrder}
									${cancelOrder}
									${relatedDocs}
								</div>
							</div>`;
				}
			} else if (this.responseText == "Order Not Found") {
				html = `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8 breadcrumbs">
							<span class="link" onclick="location.reload()">Order History</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Order Not Found
						</div>`;

				if (!params.has("orderID")) {
					html += `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8 component pageHeader">
								<input class="form-control pageHeader-search" type="search" name="search" id="search" placeholder="Search" aria-label="Search" onkeypress="submitSearch(event)">
								<div class="pageHeader-pagination">
									<div class="btn pagination-previous disabled" onclick="previousPage()"><i class="fa fa-angle-left fw-bold" aria-hidden="true"></i></div>
									<input type="text" class="cart-qty-amount" id="currPage" value="0" readonly />
									<span class="pageHeader-label" id="totalPage" data-totalPage="0">&nbsp;&nbsp;of 0&nbsp;&nbsp;</span>
									<div class="btn pagination-next disabled" onclick="nextPage()"><i class="fa fa-angle-right fw-bold" aria-hidden="true"></i></div>
								</div>
							</div>`;
				}

				html += `<!-- Error -->
						<div id="error" class="error col-12 col-lg-11 col-xl-9 col-xxl-8 component">
							<h2>Order Not Found</h2>
							<p>Please ensure it is a valid order ID to see your order history.</p>
						</div>`;
			} else {
				html = `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8 breadcrumbs">
							<span>Profile</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Order History
						</div>
						<!-- Error -->
						<div id="error" class="error col-12 col-lg-11 col-xl-9 col-xxl-8 component">
							<h2>You have no order history</h2>
							<p>Please complete an order to see your order history.</p>
						</div>`;
			}

			document.getElementById('orderHistory').innerHTML = html;

			if (!params.has("orderID") && this.responseText != "Failed") {
				document.getElementById('search').value = search;
			}
		}

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

function searchOrder() {
	try {
		getOrdersData(1, document.getElementById("search").value);
	} catch (error) {
		console.log(error);
	}
}

function submitSearch(evt) {
	try {
		// Only Enter key is allowed
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if (ASCIICode != 13) {
			return true;
		} else {
			searchOrder();
		}
	} catch (error) {
		console.log(error);
	}
}

function viewOrderDetails(orderid) {
	try {
		location.search = "orderID=" + orderid;
	} catch (error) {
		console.log(error);
	}
}

function nextPage() {
	try {
		let currPage = document.getElementById('currPage');
		let search = document.getElementById('search').value;

		if (document.body.scrollTop > 125 || document.documentElement.scrollTop > 125) {
			document.body.scrollTop = 125; // For Safari
  			document.documentElement.scrollTop = 125; // For Chrome, Firefox, IE and Opera
		}

		getOrdersData(parseInt(currPage.value) + 1, search);
	} catch (error) {
		console.log(error);
	}
}

function previousPage() {
	try {
		let currPage = document.getElementById('currPage');
		let search = document.getElementById('search').value;

		if (document.body.scrollTop > 125 || document.documentElement.scrollTop > 125) {
			document.body.scrollTop = 125; // For Safari
  			document.documentElement.scrollTop = 125; // For Chrome, Firefox, IE and Opera
		}

		getOrdersData(parseInt(currPage.value) - 1, search);
	} catch (error) {
		console.log(error);
	}
}

function printOrder(doctype, ref) {
	try {
		let orderid = params.get("orderID");
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/orderData.asp?orderID=" + orderid + "&Ref=" + ref + "&doctype=" + doctype + "&query=print", true);

		xhr.onload = function () {
			if (this.responseText.startsWith("../")) {
				window.open(this.responseText, "_blank");
			} else {
				feedback(this.responseText);
			}
		}

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

function cancelOrder() {
	try {
		let cancelOrder = confirm("Are you sure you want to cancel your order?");
		if (cancelOrder) {
			toggleModal();
			let orderid = params.get("orderID");
			let xhr = new XMLHttpRequest();

			xhr.open("GET", "data/orderData.asp?orderid=" + orderid + "&query=cancel", true);

			xhr.onload = function () {
				// console.log(this.responseText);
				if (this.responseText != "Failed") {
					toggleCancelOrderSuccess();
				} else {
					toggleCancelOrderFailed();
				}
				
				setTimeout(function () { location.reload(); }, 2000);
			}

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

getOrdersData(1, "");