<?php
	error_reporting(E_ALL);
	header('Content-Type: text/xml');
	printf("<?xml version='1.0' encoding='UTF-8'?>\n");
?>
<body>
<?php
#################### MYSQL CONNECTION #######

	$servername 	= "localhost";
	$username 		= "db4navtom_dp";
	$password 		= "qfupKZ_0Y";
	$dbname			= "db4vut_dp";
	
	// Create connection
	$conn = mysqli_connect($servername, $username, $password, $dbname);

	// Check connection
	if (!$conn) {
		printf("1 DBERR: " . mysqli_connect_error());
	}

#################### API ####################
	
	// query = write -> insert new value into database
	if ($_GET['q'] == "w" && $_GET['cid'] != "" && $_GET['aid'] != "" && $_GET['val'] != "")	{
		
		$sql = sprintf("INSERT INTO `readouts` (`readout_id`, `customer_id`, `employee_id`, `value`, `date`) VALUES (NULL, '%u', (SELECT `person_id` FROM `devices` WHERE `aid` = %u), '%u', CURRENT_TIMESTAMP);", $_GET['cid'], $_GET['aid'], $_GET['val']);
		
		if (mysqli_query($conn, $sql)) {
			
			printf("0 DONE");
			
		} else {
			
			printf("1 DBERR: " . mysqli_error($conn));
		}
		
	}

	// query = read -> show records for one customer
	elseif ($_GET['q'] == "r" && $_GET['cid'] != "") {
		
		$sql = sprintf("SELECT * FROM `readouts` WHERE `customer_id` = '%u' ORDER BY `date` DESC;", $_GET['cid']);
		$result = mysqli_query($conn, $sql);
		
		if (mysqli_num_rows($result) > 0) {
			
			$format = "<item><date>%s</date><value>%u</value></item>\n";
			
			while($row = mysqli_fetch_assoc($result)) {				
				
				printf($format, $row['date'], $row['value']);
				
			}
			
		} else {
			
			printf("1 DBERR: " . mysqli_error($conn));
		}
		
	}
	// query = customer -> get customer info
	elseif ($_GET['q'] == "c" && $_GET['cid'] != "") {
		$sql = sprintf("SELECT * FROM `customers` WHERE `id` = '%u';", $_GET['cid']);

		$result = mysqli_query($conn, $sql);
		
		if (mysqli_num_rows($result) > 0) {
			
			$format = "<info>%s</info>\n";
			
			while($row = mysqli_fetch_assoc($result)) {				
				
				printf($format, $row['info']);
				
			}
			
		} else {
			
			printf("1 DBERR: " . mysqli_error($conn));
		}

	}
	else {
		
		printf("99 QUERY");
		
	}
	
?>
</body>
<?php

	mysqli_close($conn);

?>