<?php
declare(strict_types=1);

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('Surrogate-Control: no-store');

$codeDir = __DIR__ . '/code';

require_once $codeDir . '/.lib/app_version.php';

$version = ysp_app_version($codeDir);

$html = file_get_contents($codeDir . '/index.html');
if ($html === false) {
  http_response_code(500);
  echo 'Could not load app';
  exit;
}

$scriptDir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? ''))), '/');
if ($scriptDir === '' || $scriptDir === '.') $scriptDir = '';
$apiBase = $scriptDir . '/code/api.php';
$head = '<head>' . "\n" .
  '  <base href="code/">' . "\n" .
  '  <script>window.YSP_API_BASE=' . json_encode($apiBase, JSON_UNESCAPED_SLASHES) . ';</script>';
$html = preg_replace('/<head>/', $head, $html, 1) ?? $html;

echo str_replace('__APP_VERSION__', (string)$version, $html);
