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

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

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

if (empty($_SESSION['user']) && !empty($_SESSION['admin_user'])) {
  $_SESSION['user'] = (string)$_SESSION['admin_user'];
}
if (empty($_SESSION['admin_user']) && !empty($_SESSION['user'])) {
  $_SESSION['admin_user'] = (string)$_SESSION['user'];
}
if (!isset($_SESSION['admin_logged_in'])) {
  $_SESSION['admin_logged_in'] = true;
}

$role = (string)($_SESSION['admin_role'] ?? $_SESSION['role'] ?? 'editor');
if ($role !== 'admin' && !empty($_SESSION['admin_user']) && strtolower((string)$_SESSION['admin_user']) === 'admin') {
  $role = 'admin';
}
$_SESSION['role'] = $role;
$_SESSION['admin_role'] = $role;

$page = basename($_SERVER['PHP_SELF'] ?? '', '.php');
$adminOnly = ['users'];
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);
}
?>
