let page = 0;
let totalTransfers = 0;

// Modules functions
// Page 1 - Listing
function checkMarkReceived(orderID, orderID2, locCode) {
	try {
		location.search = "moduleName=check&orderID=" + orderID + "&orderID2=" + orderID2 + "&locationCode=" + encodeURIComponent(locCode);
	} catch (error) {
		console.log(error);
	}
}

function loadRecords() {
	try {
		// This section is commented out due to change in onLoad behaviour
		// let recPerPage = document.body.getAttribute("data-maxRec");
		// let itemHeight = document.querySelector('.list-group-item').clientHeight;
		// let availableSpace = screen.availHeight - document.querySelector('header').clientHeight - document.getElementById('header').clientHeight - document.getElementById('footer').clientHeight;

		// if (document.body.scrollTop > (recPerPage * itemHeight * (page + 1)) - availableSpace || document.documentElement.scrollTop > (recPerPage * itemHeight * (page + 1)) - availableSpace) {
		// 	// Code to retrieve records
		// }

		page++;

		let records = '';
		let count = document.querySelectorAll('.list-group-item').length;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/markReceivedData.asp?q=" + page, true);

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

				// Generate Content
				response.transfers.forEach(transfer => {
						count++;

						let evenRow = "";
						if (count % 2 == 0) { evenRow = "evenRow"; }

						let orderID = "";
						let receivedID = "";
						if (transfer.orderID2 != "") {
							orderID = transfer.orderID2;
							receivedID = transfer.receivedID2;
						} else {
							orderID = transfer.orderID;
							receivedID = transfer.receivedID;
						}

						let status = "";
						let marked = "";

						if (transfer.received != "") {
							status = `<div class="markReceived-listing-sb">
										<div class="markReceived-listing-status">
											<b>${receivedID}</b>
										</div>
										<div class="markReceived-listing-status">
											${transfer.receivedDate}
										</div>
									</div>
									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-label markReceived-listing-status">
											Location
										</div>
										<div class="markReceived-listing-status">
											${transfer.location}
										</div>
									</div>
									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-label markReceived-listing-status">
											Loc. Desc
										</div>
										<div class="markReceived-listing-status">
											${transfer.locationDesc}
										</div>
									</div>
									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-label markReceived-listing-status">
											Promoter ID
										</div>
										<div class="markReceived-listing-status" id="received${count}">
											<b>${transfer.received}</b>
										</div>
									</div>`;

							marked = "MARKED";
						} else {
							status = `<div class="markReceived-listing-sb">
										<b>${orderID}</b>&nbsp;&nbsp;
										<span class="markReceived-listing-date">${transfer.daterecorded}</span>
									</div>
									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-label">
											Location
										</div>
										<div>
											${transfer.location}
										</div>
									</div>
									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-label">
											Loc. Desc
										</div>
										<div>
											${transfer.locationDesc}
										</div>
									</div>`;
						}

						records += `<div class="list-group-item ${evenRow}" id="transfer${count}" data-code="${transfer.orderID}" data-code2="${transfer.orderID2}" data-loc="${transfer.location}">
									${status}

									<hr style="margin: 5px 0;">

									<div class="markReceived-listing-sb">
										<div class="Marked">${marked}</div>

										<button class="btn btn-primary checkBtn" onclick="checkMarkReceived('${transfer.orderIDURL}', '${transfer.orderID2URL}', '${transfer.location}')" id="checkBtn${count}">CHECK</button>
									</div>
								</div>`;
					});

				toggleModal();

				document.getElementById('recordList').innerHTML += records;
				
				updateProgress(count);

				loadRecords();
			} else {
				// document.getElementById("submitBtn").classList.remove("disabled");
			}

		}

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

function updateProgress(current) {
	try {
		let container = document.getElementById("progressBar-container");
		let progress = document.getElementById("progressBar-progress");

		let percentage = current / totalTransfers * 100;

		progress.style.width = percentage + "%";
	} catch (error) {
		console.log(error);
	}
}

// Page 2 - Check
function markReceived(orderID, orderID2, locCode) {
	try {
		location.search = "moduleName=mark&orderID=" + orderID + "&orderID2=" + orderID2 + "&locationCode=" + encodeURIComponent(locCode);
	} catch (error) {
		console.log(error);
	}
}

// Page 3 - Confirm
function clearPassword() {
	try {
		document.getElementById("password").value = "";
		document.getElementById("errMsg").innerHTML = "";
	} catch (error) {
		console.log(error);
	}
}

function enableConfirmMarkReceived() {
	try {
		let password = document.getElementById("password").value;

		if (password != "") {
			document.getElementById("confirmBtn").classList.remove("disabled");
		} else {
			document.getElementById("confirmBtn").classList.add("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function confirmMarkReceived(orderID) {
	try {
		toggleModal();
		let password = document.getElementById("password").value;
		let listItems = document.querySelectorAll(".commentSection");
		let commentStr = "";

		for (let i = 0; i < listItems.length; i++) {
			if (listItems[i].value.trim() != "") {
				if (commentStr != "") { commentStr += "||"; }
				commentStr += listItems[i].value.trim();
			}
		}

		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/markReceivedData.asp?moduleName=confirm&orderID=" + orderID + "&password=" + encodeURIComponent(password) + "&commentStr=" + encodeURIComponent(commentStr), true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("S")) {
				toggleSuccess(this.responseText);
				setTimeout(function () { toggleModal(); location.href = 'markReceived.asp'; }, 1500);
			} else {
				toggleModal();
				document.getElementById("errMsg").innerHTML = this.responseText;
			}
		}

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

function submitPassword(evt) {
	try {
		// Enter key to confirm
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if (ASCIICode == 13) {
			if (!document.getElementById("confirmBtn").classList.contains("disabled")) {
				document.getElementById("confirmBtn").click();
			}
		}
	} catch (error) {
		console.log(error);
	}
}

// Search functions
function filterSearch() {
	try {
		let searchVal = document.getElementById("search").value.toUpperCase();

		if (!params.has("moduleName")) {
			let listItems = document.querySelectorAll(".list-group-item");
			for (let i = 0; i < listItems.length; i++) {
				if (listItems[i].getAttribute("data-code").includes(searchVal) || listItems[i].getAttribute("data-code2").includes(searchVal) || listItems[i].getAttribute("data-loc").includes(searchVal)) {
					listItems[i].classList.add("visible");
					listItems[i].classList.remove("hide");
				} else {
					listItems[i].classList.remove("visible");
					listItems[i].classList.add("hide");
				}
			}
		} else {
			let listItems = document.querySelectorAll(".itemRow");
			let count = 0;
			let qty = 0;
			for (let i = 0; i < listItems.length; i++) {
				if (listItems[i].getAttribute("data-code").includes(searchVal) || listItems[i].getAttribute("data-group").includes(searchVal) || listItems[i].getAttribute("data-desc").includes(searchVal)) {
					listItems[i].classList.add("visible");
					listItems[i].classList.remove("hide");
					if (listItems[i].getAttribute("data-code") != "") {
						count++;
						qty += parseInt(listItems[i].childNodes[5].innerHTML);
					}
				} else {
					listItems[i].classList.remove("visible");
					listItems[i].classList.add("hide");
				}
			}

			document.getElementById("totalItem").innerHTML = count;
			document.getElementById("totalQty").innerHTML = qty;
		}
		
	} catch (error) {
		console.log(error);
	}
}

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

// Main Mark Received Data function
function getMarkReceivedData() {
	try {
		toggleModal();
		let query = location.search;
		if (query == "") { query = "?"; }

		let moduleName = "";
		if (params.has("moduleName")) {
			moduleName = params.get("moduleName"); 
		}

		let header = '';
		let main = '';
		let footer = '';
		let count = 0;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/markReceivedData.asp" + query, true);

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

				if (moduleName == "") {
					// Generate Header
					header += `<!-- User Details -->
							<h1>USER ID: ${response.curuser}<br><span class="secHeader">(${response.name})</span></h1>

							<!-- Search Bar -->
							<div role="search" class="row searchBar">
					        	<div class="col-10 g-0">
					        		<input class="form-control" type="search" name="search" id="search" placeholder="Search" aria-label="Search" onkeydown="submitSearch(event)" onkeyup="filterSearch()">
					        	</div>
					        	<label for="searchBtn" class="col-2 g-0 searchBtn">
					        		<i class="fa fa-search" aria-hidden="true" style="font-size: 18px;"></i>
					        	</label>
					        	<input type="button" id="searchBtn" onclick="filterSearch()" hidden>
					        </div>`;

					totalTransfers = response.totalTransfers;

					// Generate Content
					main += `<!-- Page 1 - Listing -->
							<div class="list-group markReceived-listing" id="recordList">`;

					if (response.noTransfer) {
						main += `<h1 class="markReceived-listing-label">${response.noTransfer}</h1>`
					} else {
						response.transfers.forEach(transfer => {
							count++;

							let evenRow = "";
							if (count % 2 == 0) { evenRow = "evenRow"; }

							let orderID = "";
							let receivedID = "";
							if (transfer.orderID2 != "") {
								orderID = transfer.orderID2;
								receivedID = transfer.receivedID2;
							} else {
								orderID = transfer.orderID;
								receivedID = transfer.receivedID;
							}

							let status = "";
							let marked = "";

							if (transfer.received != "") {
								status = `<div class="markReceived-listing-sb">
											<div class="markReceived-listing-status">
												<b>${receivedID}</b>
											</div>
											<div class="markReceived-listing-status">
												${transfer.receivedDate}
											</div>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label markReceived-listing-status">
												Location
											</div>
											<div class="markReceived-listing-status">
												${transfer.location}
											</div>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label markReceived-listing-status">
												Loc.&nbsp;Desc
											</div>
											<div class="markReceived-listing-status" style="text-align: right;">
												${transfer.locationDesc}
											</div>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label markReceived-listing-status">
												Promoter ID
											</div>
											<div class="markReceived-listing-status" id="received${count}">
												<b>${transfer.received}</b>
											</div>
										</div>`;

								marked = "MARKED";
							} else {
								status = `<div class="markReceived-listing-sb">
											<b>${orderID}</b>&nbsp;&nbsp;
											<span class="markReceived-listing-date">${transfer.daterecorded}</span>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label">
												Location
											</div>
											<div>
												${transfer.location}
											</div>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label">
												Loc. Desc
											</div>
											<div>
												${transfer.locationDesc}
											</div>
										</div>`;
							}

							main += `<div class="list-group-item ${evenRow}" id="transfer${count}" data-code="${transfer.orderID}" data-code2="${transfer.orderID2}" data-loc="${transfer.location}">
										${status}

										<hr style="margin: 5px 0;">

										<div class="markReceived-listing-sb">
											<div class="Marked">${marked}</div>

											<button class="btn btn-primary checkBtn" onclick="checkMarkReceived('${transfer.orderIDURL}', '${transfer.orderID2URL}', '${transfer.location}')" id="checkBtn${count}">CHECK</button>
										</div>
									</div>`;
						});
					}

					main += `</div>`;

				} else if (moduleName == "check") {
					let orderID = "";
					if (response.orderID2 != "") {
						orderID = response.orderID2;
					} else {
						orderID = response.orderID;
					}

					// Generate Header
					header += `<div class="header-content">
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										TR No.
									</div>
									<div>
										${orderID}
									</div>
								</div>
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										Location
									</div>
									<div style="text-align: right;">
										${response.locationCode} - ${response.locationDesc}
									</div>
								</div>
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										Date
									</div>
									<div>
										${response.daterecorded}
									</div>
								</div>
							</div>
							<!-- Search Bar -->
							<div role="search" class="row searchBar">
					        	<div class="col-10 g-0">
					        		<input class="form-control" type="search" name="search" id="search" placeholder="Search" aria-label="Search" onkeydown="submitSearch(event)" onkeyup="filterSearch()">
					        	</div>
					        	<label for="searchBtn" class="col-2 g-0 searchBtn">
					        		<i class="fa fa-search" aria-hidden="true" style="font-size: 18px;"></i>
					        	</label>
					        	<input type="button" id="searchBtn" onclick="filterSearch()" hidden>
					        </div>`;

					// Generate Content
					main += `<!-- Page 2 - Details -->
							<table class="markReceived-table" cellpadding="3px" cellspacing="0">
								<tr class="table-header" align="center">
									<td></td>
									<td>Item</td>
									<td width="50">Qty</td>
									<td width="75">Price</td>
								</tr>`;

					let totalQty = 0;

					response.items.forEach(item => {
						count++;
						totalQty += parseInt(item.quantity);
						let maxQty = 99999;
						let evenRow = "";
						if (count % 2 == 0) {
							evenRow = "evenRow";
						}

						if (item.itemID != "") {
							main += `<tr class="itemRow ${evenRow}" align="center" data-code="${item.itemID}" data-group="${item.group}" data-desc="${item.description}">
										<td width="25">${item.rowNumber}</td>
										<td style="padding-left: 5px;" align="left">
											<b>${item.itemID}</b><br>
											<span class="markReceived-listing-label markReceived-priceLevel">${item.priceLevel}</span>
											<br>
											<span class="markReceived-listing-itemDesc">${item.description}</span>
										</td>
										<td>${item.quantity}</td>
										<td>${priceFormatter.format(item.price)}</td>
									</tr>`;
						} else {
							main += `<tr class="itemRow ${evenRow}" align="center" data-code="" data-group="" data-desc="${item.description}">
										<td width="25">${item.rowNumber}</td>
										<td style="padding-left: 5px;" align="left" colspan="3">
											Comment:&nbsp;&nbsp;&nbsp;&nbsp;${item.description}
										</td>
									</tr>`;
						}
					});

					main += `	<tr>
									<td colspan="4">
										<hr style="margin: 5px;">
									</td>
								</tr>
								<tr align="center">
									<td style="padding: 0 0 10px 5px;" align="left" colspan="2">Total Rows (<span id="totalItem">${count}</span>)</td>
									<td style="padding-bottom: 10px;" align="center" id="totalQty">
										${totalQty}
									</td>
									<td>&nbsp;</td>
								</tr>
							</table>
							<input type="text" id="count" value="${count}" hidden>`;				

					// Generate Footer
					let mDisable = "";

					if (response.received != "") {
						mDisable = "disabled";
					}

					footer += `<button class="btn btn-danger doneBtn ${mDisable}" onclick="markReceived('${response.orderIDURL}', '${response.orderID2URL}', '${response.locationCode}');">MARK</button>`;

				} else if (moduleName == "mark") {
					let orderID = "";
					if (response.orderID2 != "") {
						orderID = response.orderID2;
					} else {
						orderID = response.orderID;
					}

					// Generate Header
					header += `<div class="header-content">
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										TR No.
									</div>
									<div>
										${orderID}
									</div>
								</div>
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										Location
									</div>
									<div>
										${response.locationCode} - ${response.locationDesc}
									</div>
								</div>
								<div class="markReceived-listing-sb">
									<div class="markReceived-listing-label">
										Date
									</div>
									<div>
										${response.daterecorded}
									</div>
								</div>
							</div>`;

					// Generate Content
					main += `<!-- Page 3 - Confirm -->
							<div class="list-group markReceived-listing">
								<div class="list-group-item">
									<div>
										<div class="markReceived-listing-bl" style="font-size: 18px; margin-bottom: 5px;">
											<b>Comment :</b>
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="markReceived-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
									</div>
								</div>
								<br>
								<div class="list-group-item">
									<div>									
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label" style="margin-bottom: 10px;">
												Promoter ID : <span style="color: #000; font-size: 16px;">${response.name} (${response.curuser})</span>
											</div>
										</div>
										<div class="markReceived-listing-sb">
											<div class="markReceived-listing-label">
												Password :
											</div>
											<div>
												<input type="password" id="password" class="form-control" onfocus="this.scrollIntoView();" onkeyup="enableConfirmMarkReceived()" onkeydown="submitPassword(event)">
											</div>
										</div>
									</div>

									<hr style="margin: 5px 0;">

									<div class="markReceived-listing-sb">
										<div class="markReceived-listing-itemStatus" id="errMsg"></div>

										<button class="btn btn-secondary checkBtn" onclick="clearPassword()">CLEAR</button>
									</div>
								</div>
							</div>`;
					

					// Generate Footer
					footer += `<button class="btn btn-success doneBtn disabled" id="confirmBtn" onclick="confirmMarkReceived('${response.orderIDURL}', '${response.orderID2URL}');">CONFIRM</button>`;

				}
			} else {
				toggleFailed(this.responseText);
				setTimeout( function () { toggleModal(); history.back(); }, 1000);
			}

			document.getElementById('header').innerHTML = header;
			document.getElementById('main').innerHTML = main;
			document.getElementById('footer').innerHTML = footer;

			// Onload Functions
			if (moduleName == "") {
				loadRecords();
				updateProgress(count);
			}

			toggleModal();
		}

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

getMarkReceivedData();