<?php
$mode = strtolower((string)($argv[1] ?? 'server'));
$enabled = (string)($argv[2] ?? '1') === '1';
if (!in_array($mode, ['server', 'branch', 'agent'], true)) {
  throw new RuntimeException('Unsupported install mode.');
}

require_once dirname(__DIR__) . '/app_runtime.php';

$GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
  'install_type' => $mode,
  'security' => [
    'idle_timeout_enabled' => $enabled,
    'idle_timeout_minutes' => 5,
  ],
];

session_id('ua-idle-test-' . bin2hex(random_bytes(6)));
session_start();
$_SESSION = [
  'admin_id' => 77,
  'ua_last_activity' => time() - 601,
];
session_write_close();

require_once dirname(__DIR__) . '/security.php';

$shouldExpire = $enabled;
if ($shouldExpire) {
  if (!empty($_SESSION['admin_id']) || empty($_SESSION['ua_login_err'])) {
    throw new RuntimeException('Expired session was not cleared.');
  }
} else {
  if ((int)($_SESSION['admin_id'] ?? 0) !== 77) {
    throw new RuntimeException('Session expired while inactivity protection was disabled.');
  }
  if (isset($_SESSION['ua_last_activity'])) {
    throw new RuntimeException('Disabled policy left a stale activity timestamp.');
  }
}

$_SESSION = [];
session_destroy();
unset($GLOBALS['UA_INSTALL_CONFIG_OVERRIDE']);
echo "idle_timeout_session_test ($mode," . ($enabled ? 'enabled' : 'disabled') . "): OK\n";
