<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/../includes/auth_paths.php';

/* 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 = strtolower((string)($_SESSION['role'] ?? 'guest'));
if ($role === 'dj') {
  $role = 'viewer';
  $_SESSION['role'] = 'viewer';
}
if (!$user && !($_SESSION['username'] ?? null)) {
  header("Location: /login/index.php");
  exit;
}

$page = basename($_SERVER['PHP_SELF'], '.php');
$adminOnly = ['users','manage_users','backup','westats','radiostats'];
$permissions = $_SESSION['permissions'] ?? [];
if (!is_array($permissions)) $permissions = [];

if (!in_array($role, ['master','admin','viewer'], 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'] = ah_user_can_access_page($role, $permissions, $page);
$GLOBALS['CAN_EDIT'] = ah_user_can_edit_page($role, $permissions, $page);

if (!$GLOBALS['CAN_VIEW']) {
  http_response_code(403);
  die("<h1>Access Denied</h1><p>You do not have permission to access this page.</p>");
}
