<?php

$servername = "164.30.188.25";
$dbname = "mydwh";
$username = "gerhard";
$password = "!1qaY?0UA_45";

// Keep this API Key value to be compatible with the ESP32 code provided in the project page. 
// If you change this value, the ESP32 sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";

$x = $id = $ts = $level = $tag = $log = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//	$api = json_decode(test_input($_POST["x"]));
	$x = $_POST["x"];	// funktioniert mit: http.addHeader("Content-Type", "application/x-www-form-urlencoded");
//	die ($x);
//	$api = json_decode($x);
//	$x = '{"api_key":"tPmAT5Ab3j7F9","IP":"599531172","dataset":[["90","4173044256","0","my_ESP32_Test/RunTask3","send NTP packet to timeserver: 901521060"]]}';
//	$x = '{"api_key":"tPmAT5Ab3j7F9","sensorid":"000008656c47","dataset":[["1590937328000","22.47"],["1590937318000","22.41"]]}';
  $api = json_decode($x);
//	die("json_decode failed: " . json_last_error () . " --> " . $api->api_key . " --> " . $api->IP . " --> " . $api->dataset . " --> " . $x);
    if($api->api_key == $api_key_value) {
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
		mysqli_autocommit($conn, true);
		$statement = $conn->stmt_init();
		$statement->prepare("INSERT IGNORE INTO mydwh.esp32log (ip, id, ts, level, tag, log) VALUES (?, ?, from_unixtime(?), ?, ?, ?)");
		$statement->bind_param('iiiiss',$api->IP,$id,$ts,$level,$tag,$log);
		foreach ($api->dataset as $mw) {
			$id = $mw[0];
			$ts = $mw[1];
			$level = $mw[2];
			$tag = $mw[3];
			$log = $mw[4];
			$statement->execute();   
		}
		$statement->store_result();
		mysqli_query($conn, "commit");
		if ($statement->error ==0) {echo "Logs saved to DB!";} else {echo "Error: ", $statement->error . " --> " . $x;}
		
		/* schließe Anweisung */
		$statement->close();
        $conn->close();
    }
    else {
        echo "Wrong API Key provided." . $x;
//        echo "Wrong API Key provided." . $api->api_key;
    }
}
else {
    echo "No data posted with HTTP POST.";
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_NOQUOTES); //
    return $data;
}

    if (!function_exists('json_last_error_msg')) {
        function json_last_error_msg() {
            static $ERRORS = array(
                JSON_ERROR_NONE => 'No error',
                JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
                JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
                JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
                JSON_ERROR_SYNTAX => 'Syntax error',
                JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
            );

            $error = json_last_error();
            return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
        }
    }
?>