<?php
include "stuff.php";
$con = mysqli_connect($server,$user,$password,$db);
$debug = true;
$debug = false;

// init...
$calibro_module_id= "6a83eb2e-d222-11e8-858b-525400ae9f4a";
$espr_module_id   = "6a720b48-d222-11e8-8c8e-525400ae9f4a";
$create_model_url = "https://h2g-platform-core.nobatek.com/api/v0/models/";
$getcookie_url    = "https://h2g-platform-core.nobatek.com/api/v0/auth/cert";
$pmid_chk_url     = "https://h2g-platform-core.nobatek.com/api/v0/outputs/events/";
$mkevent_url      = "https://h2g-platform-core.nobatek.com/api/v0/events/";
$pam = array("NULL","comfort","comfort_visual","iaq"); // thermal and visual comfort pams

/*
AVAILABLE ESTATES
name       site_id
challenger 5044e65c-d220-11e8-814d-525400ae9f4a
NUIG       21354d90-d21e-11e8-985e-525400ae9f4a

AVAILABLE BUILDINGS
name                         id
NUIG Engineering Building    213a1910-d21e-11e8-985e-525400ae9f4a
South Triangle               505c8064-d220-11e8-8c8e-525400ae9f4a
North Triangle               5072f59c-d220-11e8-814d-525400ae9f4a
Technical Building           5e858126-43e1-11e9-ad44-0800270bcf2d
*/

$rid = 0;
if(isset($_GET['rid']))$rid=$_GET['rid'];
if($debug)echo("<h1>rid = {$rid}</h1>");
$res = mysqli_query($con,"SELECT models.id,models.portal_model_id,models.purpose,models.name,results.pam,results.requested_at,results.sim_start,results.sim_stop FROM results INNER JOIN models ON results.model = models.id WHERE results.id = {$rid}");
$row = mysqli_fetch_array($res);
$mid = $row[0];
$pmid = $row[1]; // portal_model_id
$mpurpose = $row[2];
$mname = $row[3];
$pamid = $row[4];
$exec_time = $row[5];
$sim_start = $row[6];
$sim_stop = $row[7];

$res = mysqli_query($con,"SELECT models.portal_building_id,estates.portal_site_id FROM estates INNER JOIN models ON models.estate = estates.id WHERE models.id = {$mid}");
$row = mysqli_fetch_array($res);
$building_id = $row[0];
$site_id = $row[1];
if($debug)echo("<h1>model id = {$mid}</h1>");

// step 1 get portal_model_id
if(is_string($pmid) && $pmid != ""){ // pmid has previously been set so do nothing
  if($debug)echo("<h2>Step 1</h2>pmid is already set to {$pmid}");
}else{ // pmid has not been set, so create id on portal, link this model to it and create pmid
  $cookie = getcookie();

  // Create a model on portal
  // first create json data
  $json_buffer = array();
  $parameters = array();
  $parameters[] = array( "value" => 0, "name" => "unused variable");
  $json_buffer["description"] = $mpurpose;
  $json_buffer["name"] = $mname;
  $json_buffer["service_id"] = $espr_module_id;
  $json_buffer['parameters'] = $parameters;
  $data_string = json_encode($json_buffer);
  unset($json_buffer);

  // curl -d @espr_model_input.json -H "Content-Type: application/json" -X POST https://h2g-platform-core.nobatek.com/api/v0/models/ --cookie "session=XXXX" -v
  $url      = $create_model_url;
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST,true); // -X POST
  curl_setopt($ch,CURLOPT_VERBOSE,true); // -v
  curl_setopt($ch,CURLOPT_HEADER,false); // do not get headers
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);// Set the result output to be a string.
  curl_setopt($ch,CURLOPT_COOKIE,"session=".$cookie);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
  curl_setopt($ch,CURLOPT_HTTPHEADER,array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($data_string))
  );
  $response = curl_exec($ch);
  if(is_bool($response)){if(!$response)die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));} // exception handling
  $data = json_decode($response,true);
  $pmid = $data['id'];
  curl_close($ch);
  if($debug)echo("<h2>Step 1</h2>");
  if($debug)echo($response);
  mysqli_query($con,"UPDATE models SET portal_model_id='{$pmid}' WHERE id = {$mid}");
} // end if-else; pmid is now set

// step 2 OK pmid has been set so
// check if this model is authorised to generate events
// curl -s "https://h2g-platform-core.nobatek.com/api/v0/outputs/events/?module_id=${service_id}" --cookie "session=${session_cookie}"
$cookie = getcookie();
$url = $pmid_chk_url . "?module_id={$espr_module_id}&model_id={$pmid}";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_VERBOSE,true); // -v
curl_setopt($ch,CURLOPT_HEADER,false); // do not get headers
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);// Set the result output to be a string.
curl_setopt($ch,CURLOPT_COOKIE,"session=".$cookie);
$response = curl_exec($ch);
if(is_bool($response)){if(!$response)die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));} // exception handling
curl_close($ch);
$data = json_decode($response,true);
if($debug)echo("<h2>Step 2</h2>");
if($debug)echo($response);

// step 3 if model is not authorised to generate events then authorise the model
if(sizeof($data) <= 0){
   // curl -d @event_auth.json -H "Content-Type: application/json" -X POST https://h2g-platform-core.nobatek.com/api/v0/outputs/events/ --cookie "session=XXXX" -v
   $json_buffer = array();
   $json_buffer["model_id"] = $pmid;
   $json_buffer["module_id"] = $espr_module_id;
   $data_string = json_encode($json_buffer);
   //$fh=fopen("tmpdata","w");fwrite($fh,$data_string);fclose($fh);
   unset($json_buffer);
   $cookie = getcookie();
   $url = $pmid_chk_url;
   $ch = curl_init();
   curl_setopt($ch,CURLOPT_URL,$url);
   curl_setopt($ch,CURLOPT_POST,true); // -X POST
   curl_setopt($ch,CURLOPT_VERBOSE,true); // -v
   curl_setopt($ch,CURLOPT_HEADER,false); // do not get headers
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);// Set the result output to be a string.
   curl_setopt($ch,CURLOPT_COOKIE,"session=".$cookie);
   curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
   curl_setopt($ch,CURLOPT_HTTPHEADER,array(
       'Content-Type: application/json',
       'Content-Length: ' . strlen($data_string))
   );
   $response = curl_exec($ch);
   if(is_bool($response)){if(!$response)die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));} // exception handling
   curl_close($ch);
   if($debug)echo("<h2>Step 3</h2>");
   if($debug)echo($response);
}

// step 4 generate event from this model
if($debug)echo("generate event for model_id {$pmid}");
$json_buffer = array();
$json_buffer["application"] = $espr_module_id;
$json_buffer["model"] = $pmid;
$msg = date("Y-m-d H:i:s",time());
$msg = str_replace(" ","T",$msg);
$msg .= "Z";

$start_time = substr($sim_start,6,4)."-".substr($sim_start,3,2)."-".substr($sim_start,0,2)."T00:00:00Z";
$stop_time = substr($sim_stop,6,4)."-".substr($sim_stop,3,2)."-".substr($sim_stop,0,2)."T23:59:59Z";

$json_buffer["execution_timestamp"] = $msg; //$exec_time; //$msg;
$json_buffer["site_id"] = $site_id;
$json_buffer["building_id"] = $building_id;
$json_buffer["floor_id"] = "string";
$json_buffer["space_id"] = "string";
$json_buffer["sensor_ids"] = [];
$json_buffer["level"] = "INFO";
$json_buffer["category"] = $pam[$pamid];
$json_buffer["start_time"] = $start_time; //$msg;
$json_buffer["min_start_time"] = $start_time; //$msg;
$json_buffer["max_start_time"] = $start_time; //$msg;
$json_buffer["end_time"] = $stop_time; //$msg;
$json_buffer["min_end_time"] = $stop_time; //$msg;
$json_buffer["max_end_time"] = $stop_time; //$msg;
$json_buffer["reliability"] = 1;
$json_buffer["description"] = "http://130.159.21.45/liveservices/h2g/Results/{$rid}/data.json"; // TODO
$data_string = json_encode($json_buffer);
unset($json_buffer);
// curl -d @event_input.json -H "Content-Type: application/json" -X POST https://h2g-platform-core.nobatek.com/api/v0/events/ --cookie "session=XXXX" -v
$cookie = getcookie();
$url = $mkevent_url;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true); // -X POST
curl_setopt($ch,CURLOPT_VERBOSE,true); // -v
curl_setopt($ch,CURLOPT_HEADER,false); // do not get headers
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);// Set the result output to be a string.
curl_setopt($ch,CURLOPT_COOKIE,"session=".$cookie);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
$response = curl_exec($ch);
if(is_bool($response)){if(!$response)die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));} // exception handling
curl_close($ch);
if($debug)echo("<h2>Step 4</h2>");
if($debug)echo($response);
$data = json_decode($response,true);
$json_string = json_encode($data, JSON_PRETTY_PRINT);
if(strpos($json_string, 'error') !== false) {
  echo("<h2>There was an error saving to Hit2Gap portal. Contact site admin.</br> <a href='../dashboard.php'>click here to go back</a></h2>");
  exit;
}
//echo $json_string;
$prid = $data['id'];
echo ("PRID + >>>>{$prid}<<<<");
mysqli_query($con,"UPDATE results SET portal_result_id='{$prid}' WHERE id = {$rid}");

mysqli_close($con);
echo("<h2>The result has been saved to portal. </br> event id = {$prid} </br><a href='../dashboard.php'>click here to go back</a></h2>");
exit;
header("location: ../index.php");

// Check to see if cookies.txt is 1hour old.
// If less than 1hr
//        then return content of file cookies.txt
// Else
//        Issue the equivalent of
//        curl -X POST -vs -k $url --cert-type PEM --cert $cert
//        to get cookie and return its value
function getcookie(){
  global $getcookie_url;
  $cookieFile = "cookies.txt";
  if(file_exists($cookieFile)){
    $timenow = time();
    $span = time() - filemtime($cookieFile);
    if($span < 3500){
      $ch = fopen($cookieFile,"r");
      $line = fread($ch,filesize($cookieFile));
      fclose($ch);
      return $line;
    }
  }

  // cookie older than 3500sec so generate a new one
  $url = $getcookie_url;
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST,true); // -X POST
  curl_setopt($ch,CURLOPT_VERBOSE,true); // -v
  curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__) . '/uos_bps.keycrt.pem'); // --cert with dirname... i.e. full path
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); // -k (insecure i.e. trust any certificate)
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);// Set the result output to be a string.
  curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); // --cert-type
  curl_setopt($ch,CURLOPT_HEADER,true); // get headers too, session-cookie is in the header
  $response = curl_exec($ch);
  if(is_bool($response)){if(!$response)die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));} // exception handling
  curl_close($ch);
  $cookie = get_string_between($response, "session=", ";");
  $ch = fopen($cookieFile,"w"); // write this to cookieFile
  fwrite($ch,$cookie);
  fclose($ch);
  return $cookie;
}
?>
