<?php
/*
    BAPLIE Viewer Online API: minimal PHP client (curl extension).

        export BVO_API_KEY=...  BVO_PRIVATE_KEY=...
        php bvo_api.php my_baplie.edi
*/
$baseUrl    = getenv('BVO_BASE_URL') ?: 'https://api-gateway.baplieviewer.com/v4';
$apiKey     = getenv('BVO_API_KEY');
$privateKey = getenv('BVO_PRIVATE_KEY');

// sha512 of the field values joined in the documented order, followed by the private key. Lowercase hex.
function make_hash($privateKey, ...$values) {
    return hash('sha512', implode('', $values) . $privateKey);
}

// POST form fields to an API call and return the reply body as text
function call_api($baseUrl, $apiKey, $path, $fields) {
    $ch = curl_init($baseUrl . '/' . $path);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($fields),
        CURLOPT_HTTPHEADER     => ['x-api-key: ' . $apiKey, 'Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
    ]);
    $body = curl_exec($ch);
    if ($body === false) { throw new RuntimeException(curl_error($ch)); }
    curl_close($ch);
    return $body;
}

function call_json($baseUrl, $apiKey, $path, $fields) {
    $reply = json_decode(call_api($baseUrl, $apiKey, $path, $fields), true);
    if (!is_array($reply) || ($reply['ack'] ?? '') !== 'success') {
        throw new RuntimeException("$path failed: " . json_encode($reply));
    }
    return $reply;
}

$edi    = file_get_contents($argv[1]);
$fileId = 'demo' . time();

// upload: hash = data + file_id + main_json + anomalies_json + private key
$up = call_json($baseUrl, $apiKey, 'upload', [
    'file_id' => $fileId, 'data' => $edi, 'main_json' => '0', 'anomalies_json' => '0', 'api_file_type' => 'BAPLIE',
    'hash' => make_hash($privateKey, $edi, $fileId, '0', '0')]);
$fileUploadId = (string)$up['file_upload_id'];
echo "uploaded: file_upload_id $fileUploadId\n";

// read the file back as JSON: hash = file_id + private key
$data = call_json($baseUrl, $apiKey, 'read/json', ['file_id' => $fileId, 'hash' => make_hash($privateKey, $fileId)]);
echo "read/json ok, top level keys: " . implode(',', array_slice(array_keys($data), 0, 4)) . "\n";

// 2D view: the reply is an HTML page that opens the viewer (see the integration guide).
// user_id names the person using YOUR application. If this facility has no container list for that user the call answers error 502:
// call view/restrictContainers once first (all_bays=1 lets the user see everything).
$html = call_api($baseUrl, $apiKey, 'view/2D', ['file_id' => $fileId, 'user_id' => 'user-1', 'hash' => make_hash($privateKey, $fileId, 'user-1')]);
echo "view/2D returned " . strlen($html) . " bytes of HTML\n";

// delete: hash = file_id + file_upload_id + private key
call_json($baseUrl, $apiKey, 'delete/file', ['file_id' => $fileId, 'file_upload_id' => $fileUploadId, 'hash' => make_hash($privateKey, $fileId, $fileUploadId)]);
echo "deleted\n";
