<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* 4 hour session timeout */
$timeout = 4 * 60 * 60;
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
  session_unset();
  session_destroy();
  header("Location: /login/index.php?timeout=1");
  exit;
}
$_SESSION['last_activity'] = time();

$user = $_SESSION['user'] ?? ($_SESSION['username'] ?? null);
$role = $_SESSION['role'] ?? 'guest';
if (!$user && !($_SESSION['username'] ?? null)) {
  header("Location: /login/index.php");
  exit;
}

/* Map AlmostHeaven roles to Smurf admin expectations */
$page = basename($_SERVER['PHP_SELF'], '.php');
$adminOnly = ['users','backup','westats','radiostats'];
if (!in_array($role, ['master','admin','dj'], true)) {
  http_response_code(403);
  die("<h1>Access Denied</h1><p>You do not have permission to access this page.</p>");
}
if (!in_array($role, ['master','admin'], true) && in_array($page, $adminOnly, true)) {
  http_response_code(403);
  die("<h1>Access Denied</h1><p>This page is for administrators only.</p>");
}

$GLOBALS['CAN_VIEW'] = true;
if (in_array($role, ['master','admin'], true)) {
  $GLOBALS['CAN_EDIT'] = true;
} else {
  $perms = $_SESSION['permissions'] ?? [];
  $pageKey = $page;
  $GLOBALS['CAN_EDIT'] = isset($perms[$pageKey]) && $perms[$pageKey] === 'full';
}
