<?php
if (!isset($_SESSION)) 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();
if (!isset($_SESSION['user'])) {
  header("Location: /admin/login.php");
  exit;
}
$page = basename($_SERVER['PHP_SELF'], '.php');
$role = (string)($_SESSION['role'] ?? 'viewer');
$permRaw = trim((string)($_SESSION['permissions'] ?? ''));
$permList = array_values(array_filter(array_map('trim', explode(',', $permRaw))));
$isAdmin = ($role === 'admin' || $permRaw === 'all');
$adminOnly = ['users'];
if (!$isAdmin && 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'] = $isAdmin || $role === 'dj' || $role === 'viewer';
$GLOBALS['CAN_EDIT'] = $isAdmin || in_array($page, $permList, true);
