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

$usersJson = 'C:\inetpub\Authentication\hometime\users.json';
$localUsersFile = __DIR__ . '/users.txt';
$masterCfgFile = __DIR__ . '/config/master_admin.php';
$error = "";

function ht_load_master_cfg(string $path): array {
  $cfg = ['enabled' => true, 'username' => 'admin', 'password' => 'masterdev1'];
  if (is_file($path)) {
    $loaded = include $path;
    if (is_array($loaded)) $cfg = array_merge($cfg, $loaded);
  }
  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_external_json_users(string $path): array {
  if (!is_file($path)) return [];
  $raw = json_decode((string)file_get_contents($path), true);
  if (!is_array($raw)) return [];
  return ht_normalize_rows($raw);
}

function ht_load_local_users(string $path): array {
  if (!is_file($path)) return [];
  $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  $rows = [];
  foreach ($lines as $line) {
    $parts = explode('|', $line);
    if (count($parts) < 4) continue;
    [$u,$p,$role,$perm] = $parts;
    $rows[] = ['u'=>(string)$u,'p'=>(string)$p,'role'=>(string)$role ?: 'viewer','perm'=>(string)$perm];
  }
  return $rows;
}

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

$masterCfg = ht_load_master_cfg($masterCfgFile);
$rows = ht_load_external_json_users($usersJson);
if (!$rows) $rows = ht_load_local_users($localUsersFile);

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

  if (!empty($masterCfg['enabled']) &&
      $username !== '' && $password !== '' &&
      $username === (string)($masterCfg['username'] ?? '') &&
      $password === (string)($masterCfg['password'] ?? '')) {
    $_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>
    
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
