<?php

$APIS = [
    'bioc' => ['id' => 'bioc', 'endpoints' => ['https://elwig.at/organic/external/bioc/operators']],
    'bioqs' => ['id' => 'bioqs', 'endpoints' => ['https://elwig.at/organic/external/bioqs/operators', 'https://elwig.at/organic/external/bioqs/attachments']],
    'easy-cert' => ['id' => 'easy-cert', 'endpoints' => ['https://elwig.at/organic/external/easy-cert/operators']],
    'lkv' => ['id' => 'lkv', 'endpoints' => ['https://elwig.at/organic/external/lkv/operators']],
];

function jenc($data): string {
    return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
    header('Status: 405');
    header('Content-Length: 56');
    header('Allow: GET, HEAD');
    echo "{\"error\":\"method not allowed\",\"allow\":[\"GET\",\"HEAD\"]}\n";
    exit;
}

if ($_SERVER['PATH_INFO'] !== '') {
    $code = rtrim(substr($_SERVER['PATH_INFO'], 1), '/');
    header('Content-Type: application/json; charset=UTF-8');
    if (array_key_exists($code, $APIS)) {
        echo jenc($APIS[$code]);
        echo "\n";
        exit;
    }
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
}

echo "{\"apis\":[\n";
$first = true;
foreach ($APIS as $api) {
    if (!$first) echo ",\n";
    echo "  " . jenc($api);
    $first = false;
}
echo "\n]}\n";
