<?php
$method = isset($_GET['method']) ? $_GET['method'] : "view";
$server_address = "195.187.2.134";
$dbuser = "lora";
$dbpass = "LoRa2018!";
$dbname = "lora";

$conn = new mysqli($server_address, $dbuser, $dbpass, $dbname);

if($conn->connect_error) {
	die("MySQL connection failed: ". $conn->connect_error);
}

/**
 * Metoda uwierzytelnia uzytkownika
 * i zwraca ID sesji w odpowiedzi
 **/
if($method == "auth") {
	if(isset($_GET["uname"]) && isset($_GET["pwd"])) {
		$username = $_GET["uname"];
		$passwd = $_GET["pwd"];
		if($username != null && $passwd != null) {
			$sql = "SELECT `password` FROM `accounts` WHERE username LIKE '".$username."';";
			$result = $conn->query($sql);
			if($result && $result->num_rows > 0) {
				$row = $result->fetch_assoc();
				$dbpass = $row["password"];
				$passwd = strtoupper(sha1(sha1($passwd, true)));
				$passwd = '*' . $passwd;
				if ($passwd == $dbpass) {
					$sessionid =  uniqid($username);
					$sql = "UPDATE `accounts` SET lastlogin = now(3), lastsessionid = '".$sessionid."', sessionvalidto = now(3) + interval 10 second WHERE `username` LIKE '".$username."';";
					$conn->query($sql);
					header("HTTP/1.1 202 Accepted");
					echo $sessionid;
				} else {
					header("HTTP/1.1 401 Unauthorized");
					echo 'Invalid password.';
				}
			} else {
				header("HTTP/1.1 401 Unauthorized");
				die("User not found in database!");
			}
		} else {
			header("HTTP/1.1 406 Not Acceptable");
			die("Username and password cannot be empty!");
		}
	} else {
		header("HTTP/1.1 406 Not Acceptable");
		die("Username and password cannot be empty!");
	}
}

if($method == "insert") {
	if(isset($_GET["auth"])) {
		$auth = $_GET["auth"];
		if($auth != null && $auth != "") {
			$sql = "SELECT true FROM `lora`.`accounts` WHERE lastsessionid = '".$auth."' AND sessionvalidto > now(3)";
			$result = true;
			if($result) {
				$sender_ID = $_GET["sender_ID"];
				$rec_ID = $_GET["rec_ID"];
				$rec_TIME = $_GET["rec_TIME"];
				$rec_FRONT = $_GET["rec_FRONT"];
				$rec_RIGHT = $_GET["rec_RIGHT"];
				$rec_REAR = $_GET["rec_REAR"];
				$rec_LEFT = $_GET["rec_LEFT"];
				$gps_SAT = $_GET["gps_SAT"];
				$gps_HDOP = $_GET["gps_HDOP"];
				$gps_LAT = $_GET["gps_LAT"];
				$gps_LON = $_GET["gps_LON"];
				$gps_FIX = $_GET["gps_FIX"];
				$gps_DATE = $_GET["gps_DATE"];
				$gps_TIME = $_GET["gps_TIME"];
				$gps_ALT = $_GET["gps_ALT"];
				$gps_COURSE = $_GET["gps_COURSE"];
				$gps_SPEED = $_GET["gps_SPEED"];
				$rssi = $_GET["rssi"];
				$battery = $_GET["battery"];
				$receiver_LAT = $_GET["receiver_LAT"];
				$receiver_LON = $_GET["receiver_LON"];
				$sql = 'INSERT INTO `lora`.`measurement`'.
				' (`timestamp`,`sender_ID`,`rec_ID`,`rec_TIME`,`rec_FRONT`,`rec_RIGHT`,`rec_REAR`,`rec_LEFT`,`gps_SAT`,`gps_HDOP`,`gps_LAT`,`gps_LON`,`gps_FIX`,`gps_DATE`,`gps_TIME`,`gps_ALT`,`gps_COURSE`,`gps_SPEED`,`rssi`,`battery`,`receiver_LAT`,`receiver_LON`)'.
				' VALUES (now(3),\''.$sender_ID.'\',\''.$rec_ID.'\',\''.$rec_TIME.'\',\''.$rec_FRONT.'\',\''.$rec_RIGHT.'\',\''.$rec_REAR.'\',\''.$rec_LEFT.'\',\''.$gps_SAT.'\',\''.$gps_HDOP.'\',\''.$gps_LAT.'\',\''.$gps_LON.'\',\''.$gps_FIX.'\',\''.$gps_DATE.'\',\''.$gps_TIME.'\',\''.$gps_ALT.'\',\''.$gps_COURSE.'\',\''.$gps_SPEED.'\',\''.$rssi.'\',\''.$battery.'\',\''.$receiver_LAT.'\',\''.$receiver_LON.'\');';
				echo 'Query: '.$sql;
				if($conn->query($sql) === TRUE) {
					header("HTTP/1.1 202 Accepted");
					echo "Query executed successfully";
				} else {
					header("HTTP/1.1 406 Not Acceptable");
					echo "SQL error:<br>".$conn->error;
				}
			} else {
				header("HTTP/1.1 401 Unauthorized");
				die("Session has expired or not exists!");
			}
		} else {
			header("HTTP/1.1 401 Unauthorized");
			die("User not found in database!");
		}
	} else {
		header("HTTP/1.1 401 Unauthorized");
		die("User not found in database!");
	}
}

if($method == "view" || $method == "One record per device" || $method == "All rows (limit 100)") { ?>
	<html>
	<head>
		<?php
		if(!isset($_GET["autorefresh"])) {
			$autorf = false;
		} else {
			if($_GET["autorefresh"] == "on") {
				$autorf = true;
			} else {
				$autorf = false;
			}
		}
		if($autorf) {
			$url1=$_SERVER['REQUEST_URI'];
			header("Refresh: 5; URL=$url1");
		}
		?>
	</head>
	<body>
	<form name="options" id="options" action="mysql.php">
		<label><input type="checkbox" name="autorefresh" <?php if($autorf) echo "checked"; ?> onchange="submit()">Enable autorefresh</label><br>
		<select name="method" id="viewtypes" value="3" style="margin-top: 5px;" onchange="submit()">
			<?php if($method == "One record per device") {
				echo "<option selected=\"selected\">One record per device</option>";
				echo "<option>All rows (limit 100)</option>";
			} else {
				echo "<option>One record per device</option>";
				echo "<option selected=\"selected\">All rows (limit 100)</option>";
			} ?>
		</select>
		<br>
	</form>
	<?php
	if($method == "One record per device") {
		$sql = "SELECT * FROM `lora`.`measurement` WHERE id IN (SELECT MAX(id) FROM `lora`.`measurement` GROUP BY sender_ID) ORDER BY timestamp DESC;";
	} else {
		$sql = "SELECT * FROM `measurement` ORDER BY `timestamp` DESC LIMIT 100";
	}
	
	$result = $conn->query($sql);
	$rowno = 1;
	if($result->num_rows > 0) {
		echo "<table style=\"width:100%; border: 1px solid black;border-collapse: collapse;text-align: left;\">";
		echo "<tr style=\"background:#d6f1ba;\"><th>id</th><th>timestamp</th><th>sender_ID</th><th>rec_ID</th><th>rec_TIME</th><th>rec_FRONT</th><th>rec_RIGHT</th><th>rec_REAR</th><th>rec_LEFT</th><th>gps_SAT</th><th>gps_HDOP</th><th>gps_LAT</th><th>gps_LON</th><th>gps_FIX</th><th>gps_DATE</th><th>gps_TIME</th><th>gps_ALT</th><th>gps_COURSE</th><th>gps_SPEED</th><th>rssi</th><th>battery</th><th>receiver_LAT</th><th>receiver_LON</th></tr>";
		while($row = $result->fetch_assoc()) {
			if($rowno == 2) {
				echo "<tr style=\"background: #fdf9ef;\"><td>";
				$rowno = 0;
			} else {
				echo "<tr><td>";
			}
			$rowno++;
			echo $row["id"];
			echo "</td><td>";
			 echo$row["timestamp"];
			echo "</td><td>";
			 echo$row["sender_ID"];
			echo "</td><td>";
			 echo$row["rec_ID"];
			echo "</td><td>";
			 echo$row["rec_TIME"];
			echo "</td><td>";
			 echo$row["rec_FRONT"];
			echo "</td><td>";
			 echo$row["rec_RIGHT"];
			echo "</td><td>";
			 echo$row["rec_REAR"];
			echo "</td><td>";
			 echo$row["rec_LEFT"];
			echo "</td><td>";
			 echo$row["gps_SAT"];
			echo "</td><td>";
			 echo$row["gps_HDOP"];
			echo "</td><td>";
			 echo$row["gps_LAT"];
			echo "</td><td>";
			 echo$row["gps_LON"];
			echo "</td><td>";
			 echo$row["gps_FIX"];
			echo "</td><td>";
			 echo$row["gps_DATE"];
			echo "</td><td>";
			 echo$row["gps_TIME"];
			echo "</td><td>";
			 echo$row["gps_ALT"];
			echo "</td><td>";
			 echo$row["gps_COURSE"];
			echo "</td><td>";
			 echo$row["gps_SPEED"];
			echo "</td><td>";
			 echo$row["rssi"];
			echo "</td><td>";
			 echo$row["battery"];
			echo "</td><td>";
			 echo$row["receiver_LAT"];
			echo "</td><td>";
			 echo$row["receiver_LON"];
			echo "</td></tr>";
		}
		echo "</table>";
	} else {
		echo "0 results";
	}
	?> </body> <?php
}
$conn->close();
?>
