<?php
	include_once("db.php");

	//make result object
	$result = array();
	$result['ok'] = true;
	$result['errors'] = [];
 	$result['post'] = $_POST;

	//get post data
	$sensor = $_POST['sensor_id'];
	$sensortime = $_POST['timestamp'];

	$result['gotsensor'] = $sensor;
	$result['gotsensortime'] = $sensortime;

	// $addmeasurement= pg_prepare($dbconn, "addmeasurement", "insert into measurement (idrace, sensor, sensortime, manual) values ((select min(activerace) from config), $1, $2, false)");

	$addmeasurement= pg_prepare($dbconn, "addmeasurement", "insert into measurement (idrace, sensor, sensortime, manual) values (
		(select min(activerace) from config), $1,
		TIMESTAMP WITH TIME ZONE 'epoch' + ($2::float/1000) * INTERVAL '1 second',
		false
	)");
	$result['debug1'] = pg_last_error();
	$addmeasurement= pg_execute($dbconn, "addmeasurement", array($sensor, $sensortime));
	$result['debug2'] = pg_last_error();

	// if($sensor==null || $sensortime==null) {
	// 	$result['ok'] = false;
	// 	$result['errors'][] = 'Have to get sensor_id ('.$sensor.') and timestamp ('.$sensortime.') in the post array...';
	// }
	//
	// if($result['ok']) {
	// 	$addmeasurement= pg_prepare($dbconn, "addmeasurement", "insert into measurement (idrace, sensor, sensortime, manual) values ((select min(activerace) from config), $1, $2, false)");
	// 	if($addmeasurement===FALSE) {
	// 		$result['ok'] = false;
	// 		$result['errors'][] = 'Could not prepare measurement query: '+pg_last_error($dbconn);
	// 	}
	// }
	// if($result['ok']) {
	// 	$addmeasurement= pg_execute($dbconn, "addmeasurement", array($sensor, $sensortime));
	// 	if($addmeasurement===FALSE) {
	// 		$result['ok'] = false;
	// 		$result['errors'][] = 'Could not execute measurement query: '+pg_last_error($dbconn);
	// 	}
	// }

	//print message
	$resultjson =  json_encode($result);
	echo $resultjson;
?>
