<?php
declare(strict_types=1);

/**
 * File:        /var/www/shtml/index.php
 * Description: Public landing is the link-in-bio. Auth, register, profile,
 *              OAuth, and administrators CRUD are MySQL userdb + email MFA.
 *              Legacy htpasswd Application lives at /indexHtPassword.php.
 *
 * @package    SecureUserManagement
 * @version    2.0.1
 */

require_once '/var/www/lib/autoload.php';
require_once '/var/www/lib/Core/OauthGate.php';
require_once '/var/www/lib/Core/MysqlAuth.php';

use Lib\Core\MysqlAuth;
use Lib\Config\BaseConfig;
use Lib\Controller\SecurityHeaders;

const VERSION = '2.0.1';

$debug = false;
$path = '';
if (isset($_GET['path']) && is_string($_GET['path'])) {
    $path = strtolower(trim($_GET['path']));
}

$bio = '/var/www/lib/src/python3/bio.html';
$avatar = '/var/www/lib/src/python3/avatar.jpg';

try {
    if ($path === 'avatar') {
        if (!is_readable($avatar)) {
            http_response_code(404);
            header('Content-Type: text/plain; charset=utf-8');
            echo "avatar missing\n";
            exit;
        }
        header('Content-Type: image/jpeg');
        header('X-Content-Type-Options: nosniff');
        header('Cache-Control: public, max-age=86400');
        readfile($avatar);
        exit;
    }

    if (in_array($path, ['htpasswd', 'app', 'legacy'], true)) {
        header('Location: /indexHtPassword.php', true, 302);
        exit;
    }

    if ($path === '' || $path === 'bio') {
        if (!is_readable($bio)) {
            http_response_code(500);
            header('Content-Type: text/plain; charset=utf-8');
            echo "bio.html missing\n";
            exit;
        }
        header('Content-Type: text/html; charset=utf-8');
        header('X-Content-Type-Options: nosniff');
        header('Cache-Control: no-store');
        $cfg = new BaseConfig(false);
        $sec = new SecurityHeaders([], false, $cfg);
        $sec->sendSecurityHeaders();
        $html = (string)file_get_contents($bio);
        $cfgProbe = new BaseConfig(false);
        $probeAbort = (int)$cfgProbe->get('security.spa.abort_ms', 2500);
        $probeRetry = (int)$cfgProbe->get('security.spa.retry_ms', 400);
        $probeTries = (int)$cfgProbe->get('security.spa.max_tries', 3);
        $probeKey = json_encode((string)$cfgProbe->get('security.spa.storage_key', 'mdptrade_whoami_timing'));
        $probeDebug = $cfgProbe->get('security.spa.debug_log', false) ? 'true' : 'false';
        $probe = '<script>
(function () {
  var KEY = ' . $probeKey . ';
  var ABORT_MS = ' . $probeAbort . ';
  var RETRY_MS = ' . $probeRetry . ';
  var MAX_TRIES = ' . $probeTries . ';
  var DEBUG = ' . $probeDebug . ';
  function log(row) {
    if (!DEBUG) return;
    try {
      var prev = JSON.parse(sessionStorage.getItem(KEY) || "[]");
      prev.push(row);
      if (prev.length > 12) prev.shift();
      sessionStorage.setItem(KEY, JSON.stringify(prev));
    } catch (e) {}
    if (window.console && console.log) console.log("[whoami]", row);
  }
  function load(tryN) {
    var t0 = performance.now();
    var ctrl = new AbortController();
    var timer = setTimeout(function () { ctrl.abort(); }, ABORT_MS);
    fetch("/mdptrade/settings/whoami", { credentials: "include", signal: ctrl.signal })
      .then(function (r) { return r.json(); })
      .then(function (d) {
        clearTimeout(timer);
        var ms = Math.round(performance.now() - t0);
        log({ try: tryN, ms: ms, ok: !!(d && d.ok), user: (d && d.user) || "", src: "index.php" });
        if (d && d.ok) {
          var card = document.querySelector("a.card.featured");
          if (card) {
            var sub = card.querySelector(".copy span");
            if (sub) sub.textContent = "Session ready — open dashboard";
          }
          return;
        }
        if (tryN + 1 < MAX_TRIES) { setTimeout(function () { load(tryN + 1); }, RETRY_MS); }
      })
      .catch(function (err) {
        clearTimeout(timer);
        var ms = Math.round(performance.now() - t0);
        log({ try: tryN, ms: ms, ok: false, err: (err && err.name) || "error", src: "index.php" });
        if (tryN + 1 < MAX_TRIES) { setTimeout(function () { load(tryN + 1); }, RETRY_MS); }
      });
  }
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", function () { load(0); });
  } else {
    load(0);
  }
})();
</script>';
        echo $html;
        exit;
    }

    $gate = new MysqlAuth($debug);
    $gate->dispatch($path, $debug);
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Error</title></head><body>';
    echo '<h1>500</h1><p>Something went wrong.</p></body></html>';
    exit;
}
