
<?php
ini_set('session.gc_maxlifetime', 7200);
session_set_cookie_params(['lifetime' => 7200,'path' => '/','secure' => false,'httponly' => true,'samesite' => 'Lax']);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$error = '';
$timeout = 1800;
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > $timeout) { session_unset(); session_destroy(); }
$_SESSION['last_activity'] = time();
$usersFile = 'C:/inetpub/Authentication/thunder/users.json';
function thunder_load_users(string $usersFile): array {
  if (!file_exists($usersFile)) return [];
  $decoded = json_decode((string)file_get_contents($usersFile), true);
  if (!is_array($decoded)) return [];
  $rows = $decoded['users'] ?? $decoded;
  $out = [];
  foreach ((array)$rows as $row) {
    if (!is_array($row)) continue;
    $u = trim((string)($row['username'] ?? ''));
    if ($u === '') continue;
    $out[$u] = ['password'=>(string)($row['password'] ?? ''),'role'=>(string)($row['role'] ?? 'viewer'),'permissions'=>(string)($row['permissions'] ?? '')];
  }
  return $out;
}
function thunder_verify_password(string $input, string $stored): bool {
  if ($stored === '') return false;
  $info = password_get_info($stored);
  if (($info['algo'] ?? 0) !== 0) return password_verify($input, $stored);
  return hash_equals($stored, $input);
}
function thunder_save_users(string $usersFile, array $users): void {
  $rows=[];
  foreach ($users as $username=>$row) {
    $rows[]=['username'=>(string)$username,'password'=>(string)($row['password'] ?? ''),'role'=>(string)($row['role'] ?? 'viewer'),'permissions'=>(string)($row['permissions'] ?? ''),'display_name'=>(string)($row['display_name'] ?? '')];
  }
  $dir=dirname($usersFile);
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  @file_put_contents($usersFile, json_encode(['users'=>$rows], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim((string)($_POST['username'] ?? ''));
  $password = trim((string)($_POST['password'] ?? ''));
  $users = thunder_load_users($usersFile);
  if (isset($users[$username]) && thunder_verify_password($password, (string)$users[$username]['password'])) {
    if (password_get_info((string)$users[$username]['password'])['algo'] == 0) {
      $users[$username]['password'] = password_hash($password, PASSWORD_DEFAULT);
      thunder_save_users($usersFile, $users);
    }
    $role = ((string)($users[$username]['role'] ?? 'viewer') === 'admin') ? 'admin' : 'editor';
    $permissions = (string)($users[$username]['permissions'] ?? '');
    $_SESSION['admin_logged_in']=true;
    $_SESSION['admin_user']=$username;
    $_SESSION['admin_role']=$role;
    $_SESSION['user']=$username;
    $_SESSION['role']=$role;
    $_SESSION['permissions']=$permissions;
    $_SESSION['admin_access']=[];
    $_SESSION['last_activity']=time();
    header('Location: index.php');
    exit;
  }
  $error = 'Invalid username or password.';
}
?>
<?php $pageClass = 'login-page'; include '../includes/header.php'; ?>
<div class="container mt-5"><div class="content-box text-center" style="max-width: 500px; margin: auto;"><h2>🔐 Admin Login</h2><?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?><form method="POST"><input type="text" name="username" class="form-control mb-3" placeholder="Username" required><input type="password" name="password" class="form-control mb-3" placeholder="Password" required><button type="submit" class="btn btn-primary">Login</button></form></div></div>
<?php include '../includes/footer.php'; ?>
