<?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_start();
}
$_SESSION['last_activity'] = time();

$usersFile = __DIR__ . '/users.txt';
$externalUsersFile = 'C:/inetpub/Authentication/thunder/users.json';

function thunder_normalize_user_rows(array $rows): array {
  $out = [];
  foreach ($rows as $row) {
    if (!is_array($row)) continue;
    $u = trim((string)($row['u'] ?? $row['username'] ?? ''));
    $p = (string)($row['p'] ?? $row['password'] ?? '');
    $role = strtolower((string)($row['role'] ?? 'viewer'));
    $role = in_array($role, ['admin','master'], true) ? 'admin' : 'viewer';
    $perm = (string)($row['perm'] ?? $row['permissions'] ?? '');
    if ($u !== '' && $p !== '') {
      $out[$u] = ['password'=>$p,'role'=>$role,'permissions'=>$perm];
    }
  }
  return $out;
}

function thunder_load_external_users(string $path): array {
  if (!is_file($path)) return [];
  $decoded = json_decode((string)file_get_contents($path), true);
  if (!is_array($decoded)) return [];
  return thunder_normalize_user_rows($decoded['users'] ?? $decoded);
}

function thunder_load_local_users(string $path): array {
  if (!is_file($path)) return [];
  $out = [];
  $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  foreach ($lines as $line) {
    $parts = explode('|', $line);
    if (count($parts) < 4) continue;
    [$u,$p,$role,$permissions] = $parts;
    $u = trim((string)$u);
    if ($u === '' || $p === '') continue;
    $out[$u] = [
      'password'=>(string)$p,
      'role'=>(trim((string)$role)==='admin'?'admin':'viewer'),
      'permissions'=>(string)$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);
}

if (isset($_SESSION['user']) && $_SESSION['user'] !== '') {
  header('Location: index.php');
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim((string)($_POST['username'] ?? ''));
  $password = trim((string)($_POST['password'] ?? ''));
  $users = thunder_load_external_users($externalUsersFile) + thunder_load_local_users($usersFile);
  if (isset($users[$username]) && thunder_verify_password($password, (string)$users[$username]['password'])) {
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_user'] = $username;
    $_SESSION['admin_role'] = ($users[$username]['role'] ?? 'viewer') === 'admin' ? 'admin' : 'viewer';
    $_SESSION['user'] = $username;
    $_SESSION['role'] = $_SESSION['admin_role'];
    $_SESSION['permissions'] = (string)($users[$username]['permissions'] ?? '');
    $_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, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
    <?php if (isset($_GET['timeout'])): ?><div class="alert alert-danger">Session expired. Please log in again.</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'; ?>
