<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';

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

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'])) {
  header('Location: /admin/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: /admin/index.php');
    exit;
  }
  $error = 'Invalid username or password.';
}
$pageTitle = 'Admin Login — Thunder Mountain Radio';
$pageClass = 'page-admin';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/nav.php';
?>
<main class="content-area">
  <div class="smurf-divider"></div>
  <div class="content-wrapper">
    <section class="content-card center-text">
      <h1 class="admin-title">🔐 Admin Login</h1>
      <?php if ($error): ?><div class="msg error"><?= smurf_h($error) ?></div><?php endif; ?>
      <?php if (isset($_GET['timeout'])): ?><div class="msg error">Session expired. Please log in again.</div><?php endif; ?>
      <form method="POST" class="form" style="max-width:520px;">
        <label>Username</label>
        <input type="text" name="username" class="input-field" required>
        <label>Password</label>
        <input type="password" name="password" class="input-field" required>
        <button type="submit" class="admin-btn primary" style="margin-top:14px;">Login</button>
      </form>
      <p style="opacity:.75;margin-top:14px;font-size:.95em;">Primary users load from <code><?= smurf_h($externalUsersFile) ?></code> with local fallback in <code><?= smurf_h($usersFile) ?></code>.</p>
    </section>
  </div>
  <div class="smurf-divider"></div>
</main>
<?php include __DIR__ . '/../includes/footer.php'; ?>
