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

$usersFile = __DIR__ . '/users.txt';
$externalAuth = 'C:\inetpub\Authentication\smurfettescountrydelights\auth_config.php';
$error = "";

function smurf_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 smurf_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 = ((string)($row['role'] ?? 'viewer') === 'admin') ? 'admin' : 'viewer';
    $perm = (string)($row['perm'] ?? $row['permissions'] ?? '');
    if ($u !== '' && $p !== '') {
      $out[] = ['u'=>$u,'p'=>$p,'role'=>$role,'perm'=>$perm];
    }
  }
  return $out;
}

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

$authCfg = smurf_load_external_auth($externalAuth);
$externalUsers = smurf_normalize_user_rows($authCfg['users'] ?? []);

// local users fallback
$localUsers = [];
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;
    $localUsers[] = ['u'=>$u,'p'=>$p,'role'=>$role ?: 'viewer','perm'=>$permissions ?: ''];
  }
}

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

  // Secure temp admin from external auth file outside web root
  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;
  }

  // External managed users (auth_config.php)
  foreach ($externalUsers 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;
    }
  }

  // Local users fallback
  foreach ($localUsers 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 — 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;">
        Temporary admin login now loads from <code><?= smurf_h($externalAuth) ?></code><br>
        Managed users are read from that same file first, then <code><?= smurf_h($usersFile) ?></code> as fallback.
      </p>
    </section>
  </div>
  <div class="smurf-divider"></div>
</main>
<?php include __DIR__ . '/../includes/footer.php'; ?>
