<?php
//ESP Temperature, humitidy and pressure logger based on BME280 sensor and ESP32. Pushes the data to a web database for display. 
//See full project at http://projects.xief.net
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files.
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
// Get's called by ESP and posts the data to the database. 


//get parameters and helper functions
include 'config.php';





$api_key= $sensorID = $location = $temperature = $humidity = $pressure = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $location = test_input($_POST["location"]);
        $temperature = test_input($_POST["temperature"]);
        $humidity = test_input($_POST["humidity"]);
        $pressure = test_input($_POST["pressure"]);
        
        // Create connection
        $conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql = "INSERT INTO SensorData (location, temperature, humidity, pressure)
        VALUES ('" . $location . "', '" . $temperature . "', '" . $humidity . "', '" . $pressure . "')";
        
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } 
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    
        $conn->close();
    }
    else {
        echo "Wrong API Key provided.";
    }

}
else {
    echo "No data posted with HTTP POST.";
}

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