<?php

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
    header('Status: 405');
    header('Content-Length: 0');
    header('Allow: GET, HEAD');
    exit;
}

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

$info = $_SERVER['PATH_INFO'];
if ($info !== '') {
    $id = substr($info, 1);
    header('Status: 404');
    header('Content-Length: 0');
    exit;
}

$source_groups = [
    [ '',
        '0892fdd7-6649-cb3b-75ef-a60649cfebfd', 'fde4ccef-0f36-4db9-9f2f-9bb6009c872a',
        '8e6d20d3-6bbe-c7ae-7a77-fb7fa80ee291', '830b3bd7-f1da-e20e-300d-e561bfb8205b',
        'ed025d59-056f-ffd0-79e0-05348fe88d59', '95d536c8-c869-9f72-1bce-4256a2a4ce49'
    ], [ '',
        'bef6b49a-3186-ba7f-fffb-281bfb4ca2d2', 'fc7a0cc3-c4b4-a4fb-5b7e-5cf9b68ed198',
        '9aecd829-8f3c-6829-449f-9cb511e0c1ff', 'e7a7089b-0fd7-60b9-48af-c0988a90ec37',
        '63d570d8-0ab2-b793-fe11-62e0777e4236'
    ],
];

$country = [
    'AT' => 'a1e51f85-27b5-a1e3-65f7-561569884d38',
    'DE' => '1be4d468-ba47-08f1-f048-f45869af856f',
][$_GET['country'] ?? null] ?? null;
$postalCode = $_GET['postalCode'] ?? null;
$name = $_GET['name'] ?? null;
$idNr = $_GET['idNr'] ?? null;

if ($country === null) {
    header('Status: 400');
    header('Content-Length: 0');
    exit;
}

$data = [];

$url = "https://www.bioc.info/search/producerSearchQuery?search[name]=" . urlencode($name) . "&search[citycode]=" . urlencode($postalCode) . "&search[operatorId]=" . urlencode($idNr) . "&search[country]=$country";
if ($_GET['allDBs'] === 'true') {
    $s = curl_init($url . implode('&sources[]=', $source_groups[0]));
    curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
    if (($json = curl_exec($s)) === false) {
        header('Status: 500');
        header('Content-Length: 0');
        exit;
    }
    $res = json_decode($json, true)['results'];
    foreach ($res as $r) {
        $data[$r['id']] = $r['row'];
    }
}

$s = curl_init($url . implode('&sources[]=', $source_groups[1]));
curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
if (($json = curl_exec($s)) === false) {
    header('Status: 500');
    header('Content-Length: 0');
    exit;
}
$res = json_decode($json, true)['results'];
foreach ($res as $r) {
    $data[$r['id']] = $r['row'];
}

header('Content-Type: application/json; charset=UTF-8');

$first = true;
echo "{\"data\":[\n";
foreach ($data as $id => $row) {
    if (!$first) echo ",\n";
    $row = explode("</", $row);
    $auth = explode(' ', substr($row[3], strrpos($row[3], '>') + 1), 2);
    echo "  ";
    echo jenc([
        'id' => $id,
        'name' => substr($row[0], strrpos($row[0], '>') + 1),
        'postalCode' => substr($row[1], strrpos($row[1], '>') + 1),
        'city' => substr($row[2], strrpos($row[2], '>') + 1),
        'authorityCode' => $auth[0],
        'authorityName' => $auth[1],
    ]);
    $first = false;
}
echo "\n]}\n";

