<?php
if (!isset($_SESSION)) 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: /admin/login.php?timeout=1");
  exit;
}
$_SESSION['last_activity'] = time();

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

/* Admin-only pages */
$page = basename($_SERVER['PHP_SELF'], '.php');
$adminOnly = ['users'];
if (($_SESSION['role'] ?? 'viewer') !== 'admin' && in_array($page, $adminOnly, true)) {
  http_response_code(403);
  die("<h1>Access Denied</h1><p>This page is for administrators only.</p>");
}

/* View/edit permissions */
$GLOBALS['CAN_VIEW'] = true;
if (($_SESSION['role'] ?? 'viewer') === 'admin') {
  $GLOBALS['CAN_EDIT'] = true;
} else {
  $editablePages = array_filter(array_map('trim', explode(',', (string)($_SESSION['permissions'] ?? ''))));
  $GLOBALS['CAN_EDIT'] = in_array($page, $editablePages, true);
}
