
<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$timeout = 4 * 60 * 60;
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
  session_unset(); session_destroy();
  header('Location: /admin/login.php?timeout=1'); exit;
}
$_SESSION['last_activity'] = time();

// Backwards compatibility: map Thunder login session -> Smurf-style session
if (!isset($_SESSION['user']) && !empty($_SESSION['admin_logged_in'])) {
  $_SESSION['user'] = $_SESSION['admin_user'] ?? 'admin';
  $_SESSION['role'] = (($_SESSION['admin_user'] ?? '') === 'admin') ? 'admin' : 'editor';
  if (!empty($_SESSION['admin_access']) && is_array($_SESSION['admin_access'])) {
    $perms = [];
    foreach ($_SESSION['admin_access'] as $f) {
      $perms[] = basename($f, '.php');
    }
    $_SESSION['permissions'] = implode(',', array_unique($perms));
  }
}
// Backwards compatibility: map Smurf session -> Thunder flags
if (isset($_SESSION['user']) && empty($_SESSION['admin_logged_in'])) {
  $_SESSION['admin_logged_in'] = true;
  $_SESSION['admin_user'] = $_SESSION['user'];
  $base = ['index.php','about.php','comments.php','djs.php','friends.php','requests.php','schedule.php','poll.php','logout.php'];
  $extra = ['newsreel_admin.php','admin-webstats.php','create_user.php','applications.php','contact_messages.php','backup.php','chat.php','events.php','fans.php','media.php','navigation.php','pages.php','player.php','radiostats.php','top50.php','users.php','westats.php','news.php'];
  $_SESSION['admin_access'] = array_unique(array_merge($base, $extra));
}

if (!isset($_SESSION['user']) && empty($_SESSION['admin_logged_in'])) {
  header('Location: /admin/login.php'); exit;
}

$page = basename($_SERVER['PHP_SELF'], '.php');
$adminOnly = ['users'];
$role = $_SESSION['role'] ?? ((($_SESSION['admin_user'] ?? '') === 'admin') ? 'admin' : 'editor');
if ($role !== 'admin' && in_array($page, $adminOnly, true)) {
  http_response_code(403);
  die("<div class='container mt-5'><div class='alert alert-danger'>Access denied: This page is for administrators only.</div></div>");
}
$GLOBALS['CAN_VIEW'] = true;
if ($role === 'admin') {
  $GLOBALS['CAN_EDIT'] = true;
} else {
  $editablePages = array_filter(array_map('trim', explode(',', (string)($_SESSION['permissions'] ?? ''))));
  $GLOBALS['CAN_EDIT'] = in_array($page, $editablePages, true);
}
?>
