<?php
$response = [];
$response['context'] = "poi3dSensorQuery";

if ( isset($_POST['data']) ) {
  
  $postData = json_decode ( $_POST['data']);
  $queryData = $postData->queryData;
  
  //format of posted data:
  /*
  data:
  {
    queryData:
    {
      sensorUrl:"", //the id or URL which accesses the sensor
      uName:"",     //the user name
      uPwd:""       //the password
    }
  }
  */
  
  if($queryData == null)
  {
    $response['success'] = false;
    $response['infoText'] = "invalid post data";
    $response['value'] = 0.0;
    echo json_encode($response);  
    exit;
  }
  
  //enable CORS
  //Allow from any origin https://stackoverflow.com/questions/8719276/cross-origin-request-headerscors-with-php-headers
  if(isset($_SERVER["HTTP_ORIGIN"]))
  {
    // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
  }
  else
  {
    //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
    header("Access-Control-Allow-Origin: *");
  }
  
  header("Access-Control-Allow-Credentials: true");
  header("Access-Control-Max-Age: 600");    // cache for 10 minutes
  
  if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
  {
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
      header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  
    //Just exit with 200 OK with the above headers for OPTIONS method
    exit(0);
  }

  if ( empty( $queryData->sensorUrl ) ) {
    $response['success'] = false;
    $response['infoText'] = "no sensor URL given";
    $response['value'] = 0.0;
    echo json_encode($response);  
    exit;
  }
  
  //test sensor
  if ($queryData->sensorUrl == "test" ) {
    $response['success'] = true;
    $response['infoText'] = "test sensor value returned";
    $response['value'] = 1.23;
    echo json_encode($response);  
    exit;
  }

  // ---------- query implementation for sensor values ----------



  // ------------------------------------------------------------

  //std error
  $response['success'] = false;
  $response['infoText'] = "could not query sensor";
  $response['value'] = 0.0;
  echo json_encode($response);  
}
else {
  // initial condition failed
  $response['success'] = false;
  $response['infoText'] = "no query data given";
  $response['value'] = 0.0;
  echo json_encode($response);  
}
?>
