<?php
/*
    Server-side part of an embedded viewer (2D, 3D or dashboard).

    Your page puts an <iframe> on the screen whose src is this script:
        <iframe src="/embed.php?view=2d&file=MYFILE"></iframe>

    This script calls the BAPLIE Viewer Online API with your keys (they never reach the browser) and sends the answer to the browser
    unchanged. The answer is a small HTML page that opens the viewer inside your iframe.

    Run it:  export BVO_API_KEY=... BVO_PRIVATE_KEY=...   then   php -S 127.0.0.1:8080
*/
$baseUrl    = getenv('BVO_BASE_URL') ?: 'https://api-gateway.baplieviewer.com/v4';
$apiKey     = getenv('BVO_API_KEY');
$privateKey = getenv('BVO_PRIVATE_KEY');

$views  = ['2d' => 'view/2D', '3d' => 'view/3D', 'dashboard' => 'view/dashboard'];
$view   = $_GET['view'] ?? '';
$fileId = $_GET['file'] ?? '';
if (!isset($views[$view]) || !preg_match('/^[A-Za-z0-9_-]+$/', $fileId)) {
    http_response_code(400);
    exit('Bad request');
}

// 1. YOUR access check: make sure the person using your application may see this file. Without it anyone could ask for any file_id.
// if (!current_user_may_view($fileId)) { http_response_code(403); exit; }

// 2. The id of the person using your application. It names the container list that restricts what this person sees (view/restrictContainers).
//    Letters, digits and "-" only.
$userId = 'user-1';

// 3. The hash: view/2D and view/3D = file_id + user_id + private key; view/dashboard = file_id + private key
if ($view === 'dashboard') {
    $fields = ['file_id' => $fileId, 'hash' => hash('sha512', $fileId . $privateKey)];
} else {
    $fields = ['file_id' => $fileId, 'user_id' => $userId, 'hash' => hash('sha512', $fileId . $userId . $privateKey)];
}

$ch = curl_init($baseUrl . '/' . $views[$view]);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($fields),
    CURLOPT_HTTPHEADER     => ['x-api-key: ' . $apiKey],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
$answer = curl_exec($ch);
curl_close($ch);

// A failure comes back as JSON ({"ack":"failed",...}); a success is the HTML page that opens the viewer
if ($answer === false || strpos(ltrim($answer), '{') === 0) {
    http_response_code(502);
    exit('The viewer could not be opened: ' . htmlspecialchars((string)$answer));
}
header('Content-Type: text/html; charset=utf-8');
echo $answer;
