<?php
include 'config.php';
include 'functions.php';

// CORS
header("Access-Control-Allow-Origin: *");
header('Access-Control-Max-Age: 86400');    // cache for 1 day
if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
	http_response_code(204);
	header("Access-Control-Allow-Headers: origin, content-type, accept");
	header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
	header("Access-Control-Allow-Private-Network: true");
	exit(0);
}

// Read the raw POST data
$data = json_decode(file_get_contents('php://input'), true)
	or die(return_error(400, 'Invalid data'));

switch ($data['event']) {
	case "DEVICE_READY":
	case "ALREADY_TESTING":
	case "TEST_STARTED":
	case "CONTINUE_TEST":
		echo return_success();
		send_notification($data['event']);
		break;

	case "NEW_DATA":
		echo return_success();
		break;

	case "TEST_FINISHED":
		test_finished();
		break;
	
	default:
		die(return_error(400, 'Unknown event ' . $data['event']));
		break;
}

function send_notification($msg, $url = null) {
	global $hawebhook;

	if ($hawebhook != "") {
		$post = [ 'message' => $msg ];
		if ($url != null) $post['url'] = $url;
	
		$ch = curl_init($hawebhook);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
		$rc = curl_exec($ch);
		curl_close($ch);
	}
}

function test_finished() {
	global $dbconnstring;
	global $data;
	global $test_url;

	$dbconn = pg_connect($dbconnstring)
		or die(return_error(500, 'connect Datenbankfehler: ' . pg_last_error()));

	$query = "INSERT INTO tests VALUES (DEFAULT, $1, $2) RETURNING id";

	$date = $data['test']['data']['temperatureSamples'][0]['time'];
	$values = [ $date, json_encode($data) ];

	$rc = pg_query_params($dbconn, $query, $values);
	
	if ($rc) {
		$id = pg_fetch_result($rc, 0, 0);
		echo return_success();
		send_notification("Test fertig. Ergebnis: " . $data['test']['result']['detectionResult'], $test_url . $id);
	} else {
		echo return_error(500, 'insert Datenbankfehler: ' . pg_last_error());
	}

	pg_close($dbconn);
}

?>
