<?php
/*
 * Author: Bandie <bandie@chaospott.de>
 */


include('config.php');


/** Set the status array for publishing the new™ status
 * @param array &$status - Status array which will be written into the status.json
 * @param array $decoded - Decoded json coming from client
 * @param string $loc - 'aerie' or 'cellar'
 * @return bool - Value has been updated or not?
 */
function setStatus(&$status, $decoded, $loc){
  $locno = null;

  switch($loc) {
    case 'aerie':
      $locno = 0;
      break;
    case 'cellar':
      $locno = 1;
      break;
  }

  if(isset($decoded[$loc]) && is_bool($decoded[$loc])){
    if($status["sensors"]["door_locked"][$locno]["value"] != $decoded[$loc]){
      $status["sensors"]["door_locked"][$locno]["value"] = $decoded[$loc];
      return true;
    }
  }

  return false;
}	

// Is this a POST?
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  header("HTTP/1.1 405 Method Not Allowed");
  header("Content-Type: application/json");
  echo(json_encode(['status' => 'No POST. Received: '. $_SERVER['REQUEST_METHOD']]));
  error_log('No POST.');
  exit();
}


// Is it application/json?
$content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';
if ($content_type != 'application/json') {
  header("HTTP/1.1 403 Forbidden");
  header("Content-Type: application/json");
  echo(json_encode(['status' => 'FAILED - not application/json - '. $content_type]));
  error_log('No application/json');
  exit();
}


// Do we even have a payload?
$payload = trim(file_get_contents("php://input"));
if (empty($payload)) {
  header("HTTP/1.1 403 Forbidden");
  header("Content-Type: application/json");
  echo(json_encode(['status' => 'No payload']));
  error_log('No payload');
  exit();
}

// Is the payload even JSON?
$decoded = json_decode($payload, true);
if (json_last_error() !== JSON_ERROR_NONE) {
  header("HTTP/1.1 403 Forbidden");
  header("Content-Type: application/json");
  echo(json_encode(['status' => 'FAILED - json decode - '. json_last_error()]));
  error_log('JSON decode error');
  exit();
}


// Is the authorisation aight m8?
if($decoded['consumer_key'] != $consumer_key || $decoded['consumer_secret'] != $consumer_secret) {
  header("HTTP/1.1 403 Forbidden");
  header("Content-Type: application/json");
  echo(json_encode(['status' => 'Wrong key/secret.']));
  error_log('Wrong key/secret.');
  exit();
}


// Is this API even active?
if(!$active){
  header("HTTP/1.1 403 Forbidden");
  header("Content-Type: application/json");
  echo(json_encode(["status" => "API deactivated."]));
  error_log('API deactivated');
  exit();
}


// Get me the previous status
$status = json_decode(file_get_contents($statusJSONFile), true);

// Manipulate the $status variable. If we have an update, update the timestamp.
if(setStatus($status, $decoded, 'aerie') | setStatus($status, $decoded, 'cellar')){
  $status["state"]["lastchange"] = time();
}

// Are we open or not?
if(!$status["sensors"]["door_locked"][0]["value"] || !$status["sensors"]["door_locked"][1]["value"]){
  $status["state"]["open"] = true;
} else {
  $status["state"]["open"] = false;
}

// Encode this shit
$json = json_encode($status);

// Write this shit
file_put_contents($statusJSONFile, $json);

// Show what we've done!
echo($json);

?>