<?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.
//
//This files fetches the data from the database that is called from linegraph.php


//setting header to json
header('Content-Type: application/json');

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


//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
  die("Connection failed: " . $mysqli->error);
}


$sensorName = mysqli_real_escape_string($mysqli, $_GET["sensorName"]);
$sensorName = str_replace(" ", "", $sensorName);
$sensorName= substr($sensorName,0,20); //db only set up for max 20 length, truncating everything else

	
	
$daysback = floatval(	isset($_GET["daysback"]) ? $_GET["daysback"] : 1);  //by changing to float shoudl be tamper proof


//query to get data from the table
//$query = sprintf("SELECT * FROM SensorData WHERE location='outside1' ORDER BY reading_time DESC LIMIT 1000");
$query = sprintf("SELECT * FROM SensorData WHERE location='" . $sensorName . "' AND reading_time >= now() - INTERVAL " .strval($daysback*24*60) ." MINUTE");
//print($query);


//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $i =>$row) {
  $data[] = $row;
  $data[$i]['dewPoint'] = dewPoint($data[$i]['temperature'],$data[$i]['humidity']);
}


//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);





