<?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;
}

if (!function_exists('smurf_auth_denied')) {
  function smurf_auth_denied(string $msg = 'You do not have permission to use that tool right now.'): void {
    http_response_code(403);
    die('<h1>Access Denied</h1><p>' . htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') . '</p>');
  }
}

if (!function_exists('smurf_session_perm_list')) {
  function smurf_session_perm_list(): array {
    $raw = trim((string)($_SESSION['permissions'] ?? ''));
    if ($raw === '' || strtolower($raw) === 'all') return [];
    return array_values(array_filter(array_map(static function ($item) {
      return trim(basename((string)$item, '.php'));
    }, explode(',', $raw))));
  }
}

$page = basename($_SERVER['PHP_SELF'], '.php');
$role = strtolower((string)($_SESSION['role'] ?? 'viewer'));
if ($role === 'dj') $role = 'viewer';
$isAdmin = in_array($role, ['master','admin'], true) || strtolower(trim((string)($_SESSION['permissions'] ?? ''))) === 'all';
$editablePages = smurf_session_perm_list();

$GLOBALS['CAN_VIEW'] = true;
$GLOBALS['CAN_EDIT'] = $isAdmin || in_array($page, $editablePages, true);
