<?php
/**
 * User: vincent (2016-2020), bernd@nr18.space (2020-2022)
 */

$status = getStatus();

function getContent() {
    $pagename = filter_input(INPUT_GET, 'title', FILTER_SANITIZE_URL);
    $page = $root_url . '/content/' . $pagename . '.txt';
    $file = fopen($page, 'rb');
    if($file) {
        echo stream_get_contents($file);
        fclose($file);
    } else {
        echo "Page not found";
    }
}

/**
 * @return string[][]
 */
function apiRequest()
{
    $ch = curl_init('https://status.kraut.space/api');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result, true);
}

/**
 * @return bool
 */
function getStatus(): bool
{
    try { return apiRequest()['state']['open']; }
    catch (Error $e) { return false; }
}

function getKrautButton(bool $status)
{
    if ($status) {
        echo '<img alt="Raumstatus Icon - Raum ist geöffnet"
	class="icon-img" src="./images/icons/users.svg">';
    } else {
        echo '<img alt="Raumstatus Icon - Raum ist geschlossen"
	class="icon-img" src="./images/icons/user-times.svg">';
    }
}
