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

$usersFile = __DIR__ . '/users.txt';
$masterCfg = __DIR__ . '/config/master_admin.php';
$error = "";

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

$master = file_exists($masterCfg) ? include $masterCfg : ['enabled'=>false];

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

  // Master override (test server)
  if (!empty($master['enabled']) && $username === ($master['username'] ?? '') && $password === ($master['password'] ?? '')) {
    $_SESSION['user'] = $username;
    $_SESSION['role'] = 'admin';
    $_SESSION['permissions'] = 'all';
    $_SESSION['last_activity'] = time();
    header("Location: /admin/index.php");
    exit;
  }

  // Users file
  if (file_exists($usersFile)) {
    $lines = file($usersFile, 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;

      if ($username === $u && $password === $p) {
        $_SESSION['user'] = $u;
        $_SESSION['role'] = $role ?: 'viewer';
        $_SESSION['permissions'] = $permissions ?: '';
        $_SESSION['last_activity'] = time();
        header("Location: /admin/index.php");
        exit;
      }
    }
  }

  $error = "Invalid username or password.";
}

$pageTitle = "Admin Login — Smurfette's";
$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:.7;margin-top:14px;font-size:.95em;">
        Test server master override is controlled by <code>/admin/config/master_admin.php</code>
      </p>
    </section>
  </div>
  <div class="smurf-divider"></div>
</main>
<?php include __DIR__ . '/../includes/footer.php'; ?>
