<?php

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

$base = 'https://' . $_SERVER['SERVER_NAME'] . explode('?', $_SERVER['REQUEST_URI'])[0];

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 = $_SERVER['PATH_INFO'];
if ($info !== '') {
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
    exit;
}

$country = $_GET['country'] ?? null;
$postalCode = $_GET['postalCode'] ?? null;

$m = curl_multi_init();
$requests = [];
foreach (['bioc', 'bioqs', 'easy-cert', 'lkv'] as $api) {
    $s = curl_init("https://elwig.at/organic/external/$api/operators?country=$country&postalCode=$postalCode");
    $requests[] = $s;
    curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($m, $s);
}

$running = 1;
do {
    curl_multi_exec($m, $running);
    if ($running) usleep(250_000);
} while ($running);
foreach ($requests as $r) {
    curl_multi_remove_handle($m, $r);
}
curl_multi_close($m);
$data = [];
foreach ($requests as $s) {
    if (($json = curl_multi_getcontent($s)) === null) {
        header('Status: 500');
        header('Content-Length: 34');
        echo "{\"error\":\"internal server error\"}\n";
        exit;
    }
    $data[] = json_decode($json, true)['data'];
}

$operators = [];

foreach ($data[2] as $op) $operators[] = ['easyCert' => $op];
foreach ($data[0] as $op) {
    if (($m = array_find($operators, fn($o) => isset($o['easyCert']) && $o['easyCert']['id'] === $op['id'])) !== null) {
        $m['bioc'] = $op;
    } else if (isset($op['details']) && ($m = array_find($operators, fn($o) => isset($o['easyCert']) && $o['easyCert']['idNr'] === $op['details']['idNr'])) !== null) {
        $m['bioc'] = $op;
    } else if (isset($op['details']) && ($m = array_find($operators, fn($o) => isset($o['bioc']['details']) && isset($op['details']) && $o['bioc']['name'] === $op['name'] && $o['bioc']['details']['address'] === $op['details']['address'])) !== null) {
        $m['bioc'] = $op;
    } else {
        $operators[] = ['bioc' => $op];
    }
}
foreach ($data[1] as $op) {
    if (false) {

    } else {
        $operators[] = ['bioqs' => $op];
    }
}
foreach ($data[3] as $op) $operators[] = ['lkv' => $op];

// for (const op of easyCert.data) operators.push({easyCert: op});
//        for (const op of bioc.data) {
//            let m;
//            if ((m = operators.find(o => o.easyCert?.id === op.id))) {
//                m.bioc = op;
//            } else if ((m = operators.find(o => o.easyCert?.idNr === op.details.idNr))) {
//                m.bioc = op;
//            } else if ((m = operators.find(o => o.bioc?.name === op.name && o.bioc?.details.address === op.details.address))) {
//                m.bioc2 = op;
//            } else {
//                operators.push({bioc: op});
//            }
//        }
//        for (const op of bioqs.data) {
//            let m;
//            if (op.lfbisNr && (m = operators.find(o => o.easyCert?.idNr === op.lfbisNr))) {
//                m.bioqs = op;
//            } else if (op.lfbisNr && (m = operators.find(o => o.bioc?.details.idNr === op.lfbisNr))) {
//                m.bioqs = op;
//            } else if (op.idNr && (m = operators.find(o => o.bioc?.details.idNr === op.idNr))) {
//                m.bioqs = op;
//            } else if ((m = operators.find(o => (o.easyCert?.name ?? o.bioc?.name) === op.name && (o.easyCert?.details.address ?? o.bioc?.details.address) === op.address))) {
//                m.bioqs = op;
//            } else {
//                operators.push({bioqs: op});
//            }
//        }
//        for (const op of lkv.data) operators.push({lkv: op});
//
//        for (const op of operators) {
//           op.name = op.easyCert?.name ?? op.bioc?.name ?? op.bioqs?.name ?? op.lkv?.name ?? null;
//           op.address = op.easyCert?.details.address ?? op.bioc?.details.address ?? op.bioqs?.address ?? op.lkv?.address ?? null;
//           op.postalCode = op.easyCert?.postalCode ?? op.bioc?.postalCode ?? op.bioqs?.postalCode ?? op.lkv?.postalCode ?? null;
//           op.city = op.easyCert?.city ?? op.bioc?.city ?? op.bioqs?.city ?? op.lkv?.city ?? null;
//           op.countryCode = op.easyCert?.countryCode ?? op.bioc?.details.countryCode ?? 'AT';
//           op.lfbisNr = op.bioqs?.lfbisNr ?? null;
//           const certNrs = [...new Set([].concat(
//                   op.easyCert?.details.certificates.map(c => c.nr) ?? [],
//                   op.bioc?.details.certificates.map(c => c.nr) ?? [],
//                   op.bioqs?.certificates.map(c => c.nr) ?? [],
//                   op.lkv?.certificates.map(c => c.nr) ?? []
//           ))];
//           op.ooId = certNrs
//                   .map(nr => nr.match(/[A-Z]{2}-.{3}-[0-9]{3}\.[0-9]{3}-[0-9]{7}\.[0-9]{4}\.[0-9]{3}/))
//                   .filter(nr => nr !== null)
//                   .map(nr => nr[0].split('.')[1])[0] ?? null;
//        }
//
//        operators.sort((a, b) => a.name.localeCompare(b.name));

$first = true;
echo "{\"data\":[\n";
foreach ($operators as $op) {
    if (!$first) echo ",\n";
    echo "  ";
    echo jenc($op);
    $first = false;
}
echo "\n]}\n";
