<?php
require_once('utils.php');

configure_session_lifetime(12);

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Reverse session bridge: if the user came in carrying an `st_session`
// cookie issued by the new Python login (fapi-vega-viz), populate
// $_SESSION from the gateka.sessions table so the rest of this PHP page
// recognises them without any other code change. No-op when $_SESSION
// is already set via the legacy PHPSESSID flow.
bridge_st_session_to_php();

if(!isset($_SESSION['email'])) {
  // Login form is now served by fapi-vega-viz at /login (Phase C of the
  // PHP→Python migration). The legacy index.php was deleted along with
  // the *.php redirect shims; pages still using header.php (jupyter.php,
  // 404.php, retrieve_mails.php) bounce here.
  header("location:/login");
  exit;
}

require_once('controller.php');

$isindex = basename($_SERVER['PHP_SELF']) === 'index.php';
$avatarUrl = '';
$hasJupyter = false;
$userRole = 'user';
$dbres = do_query("SELECT u.avatar_url, u.role, (SELECT 1 FROM user_products WHERE usid=u.usid AND product='jupyter') AS jupyter FROM users u WHERE u.usid=" . intval($userid));
if ($row = mysqli_fetch_assoc($dbres)) {
    $avatarUrl = $row['avatar_url'] ?? '';
    $hasJupyter = intval($row['jupyter'] ?? 0) > 0;
    $userRole = $row['role'] ?? 'user';
}
$userFullName = trim($_SESSION['firstname'] ?? '');
$userInitials = '';
if (!empty($_SESSION['firstname'])) {
  $userInitials .= strtoupper(substr((string)$_SESSION['firstname'], 0, 1));
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta charset="UTF-8">
    <title>Stealth — Gateka</title>
    <link rel="icon" href="img/favicon.ico" />
    <link href="./lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="./css/style.css" rel="stylesheet">
    <script>
      (function(){
        var t = localStorage.getItem('gk-theme') || 'dark';
        document.documentElement.setAttribute('data-theme', t);
      })();
    </script>
    <script defer src="./gk.js" data-site="stealth.gateka.fr"></script>
  </head>

  <body class="<?php echo $isindex ? 'has-index-topbar' : ''; ?>">
    <div
      id="chakra_header_root"
      data-profile-name="<?php echo htmlspecialchars($userFullName !== '' ? $userFullName : 'User', ENT_QUOTES, 'UTF-8'); ?>"
      data-avatar-url="<?php echo htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8'); ?>"
      data-username="<?php echo htmlspecialchars(strtolower(trim($_SESSION['firstname'] ?? '')), ENT_QUOTES, 'UTF-8'); ?>"
      data-has-jupyter="<?php echo $hasJupyter ? '1' : '0'; ?>"
      data-user-role="<?php echo htmlspecialchars($userRole, ENT_QUOTES, 'UTF-8'); ?>"
    ></div>

    <script type="module" src="./js-build/header_root.js?v=<?php echo urlencode((string)(@filemtime(__DIR__ . '/js-build/header_root.js') ?: time())); ?>"></script>

<?php if (isset($_SESSION['admin_original_usid'])): ?>
    <div style="position:fixed;top:0;left:0;right:0;z-index:9999;background:#f59e0b;color:#1a1a1a;padding:6px 20px;display:flex;align-items:center;gap:10px;font-size:13px;font-weight:600;">
      <i class="fa-solid fa-user-secret"></i>
      Viewing as: <?php echo htmlspecialchars($_SESSION['firstname'] . ' ' . ($_SESSION['lastname'] ?? '')); ?>
      <button onclick="fetch('controller.php?api=1&action=admin_restore').then(function(r){return r.json();}).then(function(d){if(d.msg==='ok')window.location.href='admin.php';else alert(d.res);});"
        style="margin-left:auto;padding:4px 12px;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:#ef4444;color:#fff;">
        <i class="fa-solid fa-arrow-rotate-left"></i> Restore
      </button>
    </div>
    <style>body { padding-top: 32px !important; }</style>
<?php endif; ?>

    <script>
      (function () {
        function applyIndexTopOffset() {
          var navbar = document.querySelector('.header-shell') || document.querySelector('.navbar-fixed-top');
          var breadcrumb = document.querySelector('ol.breadcrumb');
          var sidebar = document.querySelector('.sidebar');
          if (!navbar) {
            return;
          }

          var navbarHeight = navbar.offsetHeight;
          var breadcrumbHeight = 0;
          if (breadcrumb) {
            breadcrumb.style.top = navbarHeight + 'px';
            breadcrumbHeight = breadcrumb.offsetHeight;
          }

          var totalTopOffset = navbarHeight + breadcrumbHeight;
          document.body.style.paddingTop = totalTopOffset + 'px';

          if (sidebar) {
            sidebar.style.top = totalTopOffset + 'px';
          }
        }

        function applyWhenReady() {
          var navbar = document.querySelector('.header-shell') || document.querySelector('.navbar-fixed-top');
          if (navbar) {
            applyIndexTopOffset();
          } else {
            requestAnimationFrame(applyWhenReady);
          }
        }
        document.addEventListener('DOMContentLoaded', applyWhenReady);
        window.addEventListener('resize', applyIndexTopOffset);
      })();
    </script>

