<?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: " . ah_login_url() . "?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: " . ah_login_url());
  exit;
}

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

$GLOBALS['CAN_VIEW'] = true;
$GLOBALS['CAN_EDIT'] = ah_user_can_edit_page($role, $permissions, $page);
