<?php

require '../.php/pdf.php';

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;
}

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

$info = substr($_SERVER['PATH_INFO'], 1);
if (strlen($info) !== 31) {
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
    exit;
}

$cert = parse_pdf("$info.pdf");
$appendix = parse_pdf("$info.appendix.pdf");

if ($cert === null && $appendix === null) {
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
    exit;
}

if ($cert !== null) $cert['pdfUrl'] = "https://elwig.at/organic/certificates/$info.pdf";
if ($appendix !== null) $appendix['pdfUrl'] = "https://elwig.at/organic/certificates/$info.appendix.pdf";

echo jenc([
    'traces' => $cert,
    'appendix' => $appendix,
]);
