<!DOCTYPE html>
<html>

<!--
AJAX script: https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php
-->

<head>
	<title>Hygiene Inspection</title>
	<style>
		#searchForm {
			position: absolute;
			right: 0px;
		}

		#buttonRow {
			width: 80%;
		}

		.pagesButton {
			padding: 15 px 32px;
			font-size: 16px;
		}

		table {
			border-collapse: collapse;
			width: 100%;
		}

		th,
		td {
			text-align: left;
			padding: 8px;
			border-right: 1px solid #ddd;
			border-left: 1px solid #ddd;
		}

		th {
			background-color: #88e0dd;
		}

		tr:nth-child(even) {
			background-color: #f2f2f2
		}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	<script>
		//TASK 1.1

		//1.1 Write an HTML page containing a title, some text explaining what the page does, and an empty table. Use 
		//JQuery and an AJAX request to the server-side script to populate the table with the first page of results when 
		//the page loads. You may omit the id of the inspection record in your table. Also you want to avoid visualising 
		//the postcode twice.

		// This URL variable passes page=1 as a parameter to retrieve the first page. It is always the data which is displayed
		// upon initial loadup.
		var hygieneURLPage1 = "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php?op=retrieve&page=1";

		//Once all elements in the DOM have loaded, we can proceed.
		$(document).ready(function () {
			$.ajax({
				url: hygieneURLPage1,
				method: "get",
				dataType: "json",
				success: function (data) {
					// We are only looking for 4 of the supplied pieces of data.
					// 2.1 - Updated - we are now looking to add 5 columns per row.

					// the three variables set the ids of <td> tags containing business names, business addresses, and buttons
					// these are used when getting the rating of a business from the rating.php file in Q2.1
					var busi = 1;
					var addr = 2;
					var butt = 3;
					$.each(data, function () {
						$("#tableBody").append("<tr> <td id='" + busi + "'>" + this.business + "</td> <td id='" + addr + "'>" +
							this.address + "</td> <td>" + this.rating + "</td> <td>" + this.date +
							"</td> <td><button type='button' class='ratingButton' id='" + butt + "'>Get Rating</button></td> </tr>");
						busi += 3;
						addr += 3;
						butt += 3;
					});
				}
			});

			// TASK	1.2

			//1.2 Your page should now perform an additional AJAX request when the page loads. This request should find out 
			//the number of pages of inspection results that are available from the server-side script. Once you have found	
			//this out, create a row of buttons, one for each page. Each button should be labelled with a page number.	

			//Clicking one of the paginator	buttons	should empty the results table,	perform	an AJAX	request	to the serverside
			//script to	fetch the requested page of	results, and display them in the table.


			// This URL variable passes pages as a parameter to retrieve the number of pages. We use that number to create an
			// appropriate number of buttons.

			var hygieneURLPages = "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php?op=pages";
			$.ajax({
				url: hygieneURLPages,
				method: "get",
				dataType: "json",
				success: function (data) {
					// Creates buttons, named starting from 1 up to the number of pages, located in the div with id = 'buttonRow'
					for (i = 1; i <= data.pages; i++) {
						$("#buttonRow").append("<button type='button' class='pagesButton' value='" + i + "'>" + i + "</button>");
					}

					// When a button is clicked, go to the corresponding page (uses the button's value)
					$(".pagesButton").on("click", function () {
						var pageToLoad = "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php?op=retrieve&page=" + $(
							this).val();
						$.ajax({
							url: pageToLoad,
							method: "get",
							dataType: "json",
							success: function (data) {
								//clears everything from the table body, but not the head. This is why <thead> and <tbody> are explicitly declared in the HTML.
								$("#tableBody").empty();
								// the three variables set the ids of <td> tags containing business names, business addresses, and buttons
								// these are used when getting the rating of a business from the rating.php file in Q2.1
								var busi = 1;
								var addr = 2;
								var butt = 3;
								$.each(data, function () {
									$("#tableBody").append("<tr> <td id='" + busi + "'>" + this.business + "</td> <td id='" + addr +
										"'>" + this.address + "</td> <td>" + this.rating + "</td> <td>" + this.date +
										"</td> <td><button type='button' class='ratingButton' id='" + butt +
										"'>Get Rating</button></td> </tr>");
									busi += 3;
									addr += 3;
									butt += 3;
								});
							}
						});
					});
				}
			});

			//TASK 1.3		

			//1.3 Add a form to the bottom of your search page containing a text input and a search button. When the user 
			//enters text in the text input and clicks the button, your page should clear the results table, perform an AJAX 
			//request to the server-side script to retrieve any relevant results, and display them.

			$("#searchForm").submit(function () {
				var hygieneURLSearch = "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php?op=searchname&name=" +
					$("#searchBox").val();
				$.ajax({
					url: hygieneURLSearch,
					method: "get",
					dataType: "json",
					success: function (data) {
						//clears everything from the table body, but not the head. This is why <thead> and <tbody> are explicitly declared in the HTML.
						$("#tableBody").empty();
						// the three variables set the ids of <td> tags containing business names, business addresses, and buttons
						// these are used when getting the rating of a business from the rating.php file in Q2.1
						var busi = 1;
						var addr = 2;
						var butt = 3;
						$.each(data, function () {
							$("#tableBody").append("<tr> <td id='" + busi + "'>" + this.business + "</td> <td id='" + addr + "'>" +
								this.address + "</td> <td>" + this.rating + "</td> <td>" + this.date +
								"</td> <td><button type='button' class='ratingButton' id='" + butt +
								"'>Get Rating</button></td> </tr>");
							busi += 3;
							addr += 3;
							butt += 3;
						});
					}
				});
			});

			// TASK 2.1				

			//Extend each row of the table with one button that allows the user to retrieve the customers’ ratings for the 
			//business in that row.	Each button must trigger an AJAX request directed at the server-side script
			//rating.php. The customer rating for the (one) selected business must be displayed in a pop up window.

			$("#tableBody").on("click", ".ratingButton", function () {

				//To find the correct rating page to load, the button id is an int which will always be 2 higher than the corresponding
				//business name cell, and 1 higher than the corresponding business address cell. (e.g. name id = 1, address id = 2, button id = 3)
				//
				//The process of getting the correct business name and rating is slightly complicated, and has been broken down.
				//The running code may be slightly wasteful with variable assignation, but it should be easier to follow than if it were to be combined.


				//I am also aware that I could have got the hygiene address postcode directly, without string operations, but only remembered this fact after writing it all.
				//As such I have left it as I wrote it originally, slightly less efficient but still, as far as I know, working.

				var buttonId = $(this).attr('id');
				// converts from string to int, subtracts 2, and reconverts to string, resulting in the correct id for the <td>
				var businessId = String((parseInt(buttonId) - 2));
				// gets name, with spaces, from the cell
				var selectedBusiness = $('#' + businessId).text();
				// replaces spaces with plus symbols for use in the URL
				var stringFix = selectedBusiness.split(' ').join('+');
				var ratingToLoad = "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/rating.php?name=" + stringFix;

				$.ajax({
					url: ratingToLoad,
					method: "get",
					dataType: "json",
					success: function (data) {
						// converts from string to int, subtracts 1, and reconverts to string, resulting in the correct id for the <td>
						var hygieneAddressId = String((parseInt(buttonId) - 1));
						// gets name, with spaces, from the cell
						var selectedHygieneAddress = $('#' + hygieneAddressId).text();
						// extracts the postcode from the address. Addresses are held in the format:
						//		110-111 Northgate, Canterbury, CT1 1BH
						// and so we get the characters from 7 spaces before the end, up to the end
						var hygienePostcode = selectedHygieneAddress.slice(selectedHygieneAddress.length - 7,
							selectedHygieneAddress.length);
						// foundMatch is used to check if a rating was found, and therefore if a message should be displayed
						var foundMatch = false;
						$.each(data, function () {
							var ratingAddress = this.address;
							// extracts the postcode from the address. Addresses are held in the format:
							//		111 Northgate, Canterbury CT1 1BH, United Kingdom
							// and so we get the characters from the start of the postcode, up to the end of the postcode
							var ratingPostcode = ratingAddress.slice(ratingAddress.length - 23, ratingAddress.length - 16);
							if (ratingPostcode == hygienePostcode) {
								foundMatch = true;
								alert(this.rating);
							}

						});
						if (!foundMatch) {
							alert("No rating is available");
						}
					}
				});
			});
		});
	</script>
</head>

<body>
	<div id="topRow">
		<h3>Hygiene Inspection</h3>
		<!-- We use onsubmit="return false" so the page does not reload when the button is clicked -->
		<form id="searchForm" onsubmit="return false">
			Search:
			<input type="text" id="searchBox"></input>
			<input type="submit" value="Submit"></input>
		</form>
	</div>

	<div id="buttonRow">
		Page:
	</div>
	<br></br>
	<!-- 
			<thead> and <tbody> are explicitly declared to make clearing the table without removing the headers easier to do.
			Tables are cleared with the jQuery .empty() command.
		-->
	<table>
		<thead id="tableHead">
			<tr>
				<th>Business</th>
				<th>Address</th>
				<th>Hygiene</th>
				<th>Date</th>
				<th>Rating</th>
			</tr>
		</thead>
		<tbody id="tableBody">
		</tbody>
	</table>
</body>

</html>