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

$usersJson = __DIR__ . '/../data/users.json';
$externalAuth = 'C:\inetpub\Authentication\hometimeradio\auth_config.php';
$error = "";

function ht_load_external_auth(string $externalAuth): array {
  $cfg = ['temp_admin_user' => '', 'temp_admin_pass' => '', 'users' => []];
  if (is_file($externalAuth)) {
    $loaded = include $externalAuth;
    if (is_array($loaded)) $cfg = array_merge($cfg, $loaded);
  }
  if (!isset($cfg['users']) || !is_array($cfg['users'])) $cfg['users'] = [];
  return $cfg;
}
function ht_normalize_rows(array $rows): array {
  $out = [];
  foreach ($rows as $key => $row) {
    if (!is_array($row)) continue;
    $u = trim((string)($row['u'] ?? $row['username'] ?? $key ?? ''));
    $p = (string)($row['p'] ?? $row['password'] ?? '');
    $roleRaw = (string)($row['role'] ?? 'viewer');
    $role = in_array($roleRaw, ['admin','dj'], true) ? $roleRaw : 'viewer';
    $perm = (string)($row['perm'] ?? $row['permissions'] ?? '');
    if ($perm === '' && isset($row['pages']) && is_array($row['pages'])) {
      $pages = $row['pages'];
      $perm = in_array('*', $pages, true) ? 'all' : implode(',', array_map(fn($v)=>basename((string)$v, '.php'), $pages));
    }
    if ($u !== '' && $p !== '') $out[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
  }
  return $out;
}
function ht_load_local_json(string $path): array {
  if (!is_file($path)) return [];
  $raw = json_decode((string)file_get_contents($path), true);
  if (!is_array($raw)) return [];
  $rows = [];
  foreach ($raw as $u => $row) {
    if (!is_array($row)) continue;
    $roleRaw = (string)($row['role'] ?? 'viewer');
    $role = in_array($roleRaw, ['admin','dj'], true) ? $roleRaw : 'viewer';
    $pages = $row['pages'] ?? [];
    if (!is_array($pages)) $pages = [];
    $perm = in_array('*', $pages, true) ? 'all' : implode(',', array_map(fn($v)=>basename((string)$v, '.php'), $pages));
    $rows[] = ['u'=>(string)$u,'p'=>(string)($row['password'] ?? ''),'role'=>$role,'perm'=>$perm];
  }
  return $rows;
}

if (isset($_SESSION['user'])) { header("Location: /admin/index.php"); exit; }

$authCfg = ht_load_external_auth($externalAuth);
$rows = ht_normalize_rows($authCfg['users'] ?? []);
if (!$rows) $rows = ht_load_local_json($usersJson);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim($_POST['username'] ?? '');
  $password = trim($_POST['password'] ?? '');

  if ($username !== '' && $password !== '' &&
      $username === (string)($authCfg['temp_admin_user'] ?? '') &&
      $password === (string)($authCfg['temp_admin_pass'] ?? '')) {
    $_SESSION['user'] = $username;
    $_SESSION['role'] = 'admin';
    $_SESSION['permissions'] = 'all';
    $_SESSION['last_activity'] = time();
    header("Location: /admin/index.php"); exit;
  }

  foreach ($rows as $row) {
    if ($username === (string)$row['u'] && $password === (string)$row['p']) {
      $_SESSION['user'] = $row['u'];
      $_SESSION['role'] = $row['role'] ?: 'viewer';
      $_SESSION['permissions'] = $row['perm'] ?: '';
      $_SESSION['last_activity'] = time();
      header("Location: /admin/index.php"); exit;
    }
  }
  $error = "Invalid username or password.";
}

$pageTitle = "Admin Login — Home Time Radio";
include __DIR__ . '/../includes/header.php';
?>
<div class="container content-box mt-5" style="max-width:760px;">
  <div class="htr-box">
    <h1>🔐 Admin Login</h1>
    <?php if ($error): ?><div class="alert alert-danger"><?= smurf_h($error) ?></div><?php endif; ?>
    <?php if (isset($_GET['timeout'])): ?><div class="alert alert-warning">Session expired. Please log in again.</div><?php endif; ?>
    <form method="POST">
      <div class="mb-3"><label class="form-label">Username</label><input type="text" name="username" class="form-control form-control-lg" required></div>
      <div class="mb-3"><label class="form-label">Password</label><input type="password" name="password" class="form-control form-control-lg" required></div>
      <button type="submit" class="btn btn-dark btn-lg">Login</button>
    </form>
    <p class="mt-3 mb-0" style="opacity:.75;">
      Reads external auth first from <code><?= smurf_h($externalAuth) ?></code> when available, then falls back to <code><?= smurf_h($usersJson) ?></code>.
    </p>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
