// Item Details
async function getItemData() {
	try {
		toggleLoading();
		let query = location.search;
		if (query == "") { query = "?"; }

		let html = '';
		let xhr = new XMLHttpRequest();

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

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText != "Failed") {
				let item = JSON.parse(this.responseText);
				let itemPrice = '';
				let itemDisc = '';
				let stockList = '';
				let pictpaths = item.pictpath;
				let picCount = 0;
				let priceCount = 0;
				let stockCount = 0;

				let htmlSegment = `<!-- Item Description -->
								<div class="component" id="itemDesc">
									<div class="row row-cols-md-2 g-2">
										<!-- Item Images -->
										<div class="item-img-container col-md-6 col-lg-5 col-xl-4">
											<div class="item-detail-img" id="item-detail-img" style="background: url('${pictpaths[0]}');"></div>
											<!-- Image Pagination -->
											<nav aria-label="Image navigation">
											  	<ul class="pagination" id="img-page-container">
											    	<!-- Image Pagination buttons -->`;

				pictpaths.forEach(pictpath => {
					if (pictpath != "") {
						if (picCount == 0) {
							htmlSegment += `		<li class="img-page-item" data-img="${pictpath}" onclick="updateImagePagination(this)">
														<span class="img-page-link active" style="background: url('${pictpath}');"></span>
													</li>`;
						} else {
							htmlSegment += `		<li class="img-page-item" data-img="${pictpath}" onclick="updateImagePagination(this)">
														<span class="img-page-link" style="background: url('${pictpath}');"></span>
													</li>`;
						}

						picCount++;
					}
				});

				if (item.showPriceHistory) {
					itemPrice += `<p class="item-price dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" id="price"><span class="item-price-label">${item.currcode}</span>${priceFormatter.format(item.price)}</p>
									<ul class="dropdown-menu priceHistory" id="priceHistory" aria-labelledby="price">
										<li class="priceHistory-list" style="font-weight: bold;">Price History</li>`;

					item.priceHistory.forEach(price => {
						itemPrice += `<li class="dropdown-item priceHistory-list"><div>${price.date}</div><div>&nbsp;||&nbsp;</div><div>${item.currcode} ${priceFormatter.format(price.netPrice)}</div><div>&nbsp;||&nbsp;</div><div>${price.itemDisc}%</div></li>`;
						priceCount++;
					});

					if (priceCount == 0) {
						itemPrice += `<li class="dropdown-item priceHistory-list">No Price History was found</li>`;
					}

					itemPrice += `</ul>`;
				} else {
					itemPrice = `<p class="item-price"><span class="item-price-label">${item.currcode}</span>${priceFormatter.format(item.price)}</p>`;
				}

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

				if (item.showStock) {
					stockList += `<div class="item-qty-onhand dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" id="stock">
						        Stock
						    </div>
						    <ul class="dropdown-menu stock" id="stockList" aria-labelledby="stock">
								<li class="stockList" style="font-weight: bold;">Stock by Location</li>`;

					item.stocks.forEach(stock => {
						stockList += `<li class="dropdown-item stockList"><div>${stock.location}</div><div>${stock.quantity}</div></li>`;
						stockCount++;
					});

					if (stockCount == 0) {
						stockList += `<li class="dropdown-item stockList">No Stock was found</li>`;
					}

					stockList += `</ul>`;
				}

				htmlSegment += `				</ul>
											</nav>					
										</div>

										<!-- Item Detail -->
										<div class="item-desc col-md-5 col-lg-6 col-xl-7">
						        			${item.gcatalogue}
						        			<p class="item-itemLabel">${item.icatalogue}</p>
						        			<p class="item-itemNo">Product Code:&nbsp;&nbsp;&nbsp;&nbsp;${item.item_no} ${item.item_no2}</p>
						        			${itemPrice}
						        			${itemDisc}

						        			<div class="item-qty">
						        				<p class="item-qty-label">Quantity</p>

						        				<div class="item-qty-container">
						        					<span class="btn btn-danger item-qty-btn disabled" onclick="minusQty()" id="minusQty">
						        						<i class="fa fa-minus" aria-hidden="true"></i>
						        					</span>

						        					<input type="text" class="item-qty-amount" id="item-qty" onkeypress="return validateQty(event, this, ${item.maxOrderPerItem})" onblur="setDefaultQty(this, ${item.maxOrderPerItem})" onfocus="this.select()" value="1" maxlength="${item.maxOrderPerItem.toString().length}" />

						        					<span class="btn btn-success item-qty-btn" id="addQty" onclick="addQty(${item.maxOrderPerItem})"	>
						        						<i class="fa fa-plus" aria-hidden="true"></i>
						        					</span>
						        				</div>

						        				${stockList}
						        			</div>
							        		<div class="addToCart">
							        			<div class="btn btn-warning" id="addToCart" onclick="addToCart()">Add to Cart</div>

												<!-- Loading/Spinning -->
												<div class="d-flex hide" id="addToCartLoading">
													<div class="spinner-border text-secondary" role="status">
														<span class="visually-hidden">Loading...</span>
													</div>
												</div>
											</div>
						     			</div>
									</div>
								</div>

								<!-- Item Further Description -->
								<div class="component">
									<div>
										<div class="item-fDesc-label">${item.item_no} ${item.item_no2} > Further Description</div>
										<hr>
										<div class="item-fDesc-container">
											${item.f_desc}
										</div>
									</div>
								</div>`;
				html += htmlSegment;

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

				toggleLoading();
			} else {
				toggleError();
			}
		}

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

function updateImagePagination(ref) {
	try {
		let imgLinks = document.querySelectorAll('.img-page-link');
		let imgContainer = document.getElementById('item-detail-img');

		imgContainer.style.background = "url('" + ref.getAttribute("data-img") + "')";

		imgLinks.forEach(imgLink => {
			if (imgLink.classList.contains("active")) {
				imgLink.classList.remove("active");
			}
		});
		ref.firstElementChild.classList.add("active");
	} catch (error) {
		console.log(error);
	}
}

function validateQty(evt, ref, max) {
	try {
		// 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 (parseInt(ref.value + evt.key) >= max) {
				ref.value = max;
				enableAddQty(ref.value, max);
				return false;
			}
			
			enableMinusQty(parseInt(ref.value + evt.key));
			enableAddQty(parseInt(ref.value + evt.key), max);

			return true;
		}
	} catch (error) {
		console.log(error);
	}
}

function setDefaultQty(ref, max) {
	try {
		if (!(ref.value > 0)) {
			ref.value = 1;
		}

		enableMinusQty(ref.value);
		enableAddQty(ref.value, max);
	} catch (error) {
		console.log(error);
	}
}

function addQty(max) {
	try{
		let qty = document.getElementById('item-qty');

		if (qty.value < max) { 
			qty.value = parseInt(qty.value) + 1;
			document.getElementById('minusQty').classList.remove("disabled");
		}

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

function minusQty() {
	try{
		let qty = document.getElementById('item-qty');

		if (qty.value > 1) { 
			qty.value = parseInt(qty.value) - 1;
			document.getElementById('addQty').classList.remove("disabled");
		}

		enableMinusQty(qty.value);
	} catch (error) {
		console.log(error);
	}
}

function enableMinusQty(value) {
	try {
		if (value <= 1) {
			document.getElementById('minusQty').classList.add("disabled");
		} else {
			document.getElementById('minusQty').classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function enableAddQty(value, max) {
	try {
		if (value >= max) {
			document.getElementById('addQty').classList.add("disabled");
			document.getElementById('minusQty').classList.remove("disabled");
		} else {
			document.getElementById('addQty').classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function toggleLoading() {
	document.getElementById('itemDetails').classList.toggle("hide");
	document.getElementById('loading').classList.toggle("hide");
}

function toggleError() {
	document.getElementById('loading').classList.toggle("hide");
	document.getElementById('error').classList.toggle("hide");
}

getItemData();

window.onclick = function (evt) {
	let priceHistory = document.querySelectorAll(".priceHistory-list");

	for (let i = 0; i < priceHistory.length; i++) {
		if (evt.target == priceHistory[i] || evt.target == document.getElementById("priceHistory")) {
			document.getElementById("price").click();
			break;
		}

		let priceHistoryChild = priceHistory[i].children;
		let j = 0;

		for (j = 0; j < priceHistoryChild.length; j++) {
			if (evt.target == priceHistoryChild[j]) {
				document.getElementById("price").click();
				break;
			}
		}

		if (j != priceHistoryChild.length) {
			break;
		}
	}

	let stockList = document.querySelectorAll(".stockList");

	for (let i = 0; i < stockList.length; i++) {
		if (evt.target == stockList[i] || evt.target == document.getElementById("stockList")) {
			document.getElementById("stock").click();
			break;
		}

		let stockListChild = stockList[i].children;
		let j = 0;

		for (j = 0; j < stockListChild.length; j++) {
			if (evt.target == stockListChild[j]) {
				document.getElementById("stock").click();
				break;
			}
		}

		if (j != stockListChild.length) {
			break;
		}
	}
};