<?php
if (getBearerToken() !== trim(file_get_contents(".bearer_token"))) {
	http_response_code(403);
	die('Forbidden');
}

$rq = json_decode(file_get_contents('php://input'));
$output="Most recently, I was seen ";
if ($rq->status->checkedIn === true){
	if (is_null($rq->status->toStation->name)) {
		$output = $output . 'in <span style="color: #D291BC;">' . $rq->status->train->type . " " . $rq->status->train->no . "</span>.";
	}
	else {
		$output = $output . 'in <span style="color: #D291BC;">' . $rq->status->train->type . " " . $rq->status->train->no . '</span> on the way to <span style="color: #b295cf">' . $rq->status->toStation->name . "</span>.";
	}
}

else {
    if (is_null($rq->status->toStation->name)) {
        $output = $output . 'at <span style="color: #D291BC;">an unknon train station in Germany</span>.';
    }
    else {
        $output = $output . 'at <span style="color: #b295cf;">' . $rq->status->toStation->name . "</span>.";
    }
}

atomic_put_contents("travelynx.txt", $output);
echo ($output);

function atomic_put_contents($filename, $data)
{
    // Copied largely from http://php.net/manual/en/function.flock.php
    $fp = fopen($filename, "w+");
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, $data);
        flock($fp, LOCK_UN);
    }
    fclose($fp);
}

function getAuthorizationHeader(){
    $headers = null;
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    }
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        //print_r($requestHeaders);
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }
    return $headers;
}

function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}
