<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\Csrf;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\RateLimiter;
use KeyLair\AuditLog;
use KeyLair\I18n;

if (Auth::check()) {
    Helpers::redirect('index.php');
}

$pdo = Database::connection();
$adminCount = (int) $pdo->query('SELECT COUNT(*) FROM admin_users')->fetchColumn();
$firstRun = $adminCount === 0;

$error = null;
$pendingTwoFactor = !empty($_SESSION['pending_2fa_admin_id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::requireValid();

    if (RateLimiter::tooManyRequests('admin_login', 10, 60)) {
        $error = I18n::t('login.error.rate_limited');
    } elseif ($firstRun && ($_POST['action'] ?? '') === 'create_master_admin') {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $passwordConfirm = $_POST['password_confirm'] ?? '';

        if (strlen($username) < 3 || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 10) {
            $error = I18n::t('login.error.invalid_master_admin_fields');
        } elseif ($password !== $passwordConfirm) {
            $error = I18n::t('login.error.passwords_dont_match');
        } else {
            $stmt = $pdo->prepare(
                'INSERT INTO admin_users (username, email, password_hash, role, is_active, created_at)
                 VALUES (:u, :e, :p, "master_admin", 1, NOW())'
            );
            $stmt->execute([
                'u' => $username,
                'e' => $email,
                'p' => password_hash($password, PASSWORD_DEFAULT),
            ]);
            $newId = (int) $pdo->lastInsertId();
            AuditLog::log($newId, 'master_admin_account_created', null);
            $result = Auth::attemptPassword($username, $password);
            Helpers::redirect('index.php');
        }
    } elseif ($pendingTwoFactor && ($_POST['action'] ?? '') === 'verify_2fa') {
        $code = trim($_POST['code'] ?? '');
        if (Auth::attemptTwoFactor($code)) {
            Helpers::redirect('index.php');
        }
        $error = I18n::t('login.error.invalid_2fa_code');
    } elseif (($_POST['action'] ?? '') === 'login') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $result = Auth::attemptPassword($username, $password);

        if ($result['status'] === 'success') {
            Helpers::redirect('index.php');
        } elseif ($result['status'] === 'needs_2fa') {
            $pendingTwoFactor = true;
        } elseif ($result['status'] === 'inactive') {
            $error = I18n::t('login.error.account_disabled');
        } else {
            $error = I18n::t('login.error.invalid_credentials');
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= Helpers::e(\KeyLair\Settings::siteName()) ?> — <?= $firstRun ? Helpers::e(I18n::t('login.title_setup')) : Helpers::e(I18n::t('login.signin_heading')) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@600;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/tokens.css?admin=1">
<?= \KeyLair\Settings::faviconTag() ?>
<style>
  body{background:var(--bg-void); color:var(--text-primary); font-family:var(--font-body); min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px;}
  .box{width:100%; max-width:380px; background:var(--bg-panel); border:1px solid var(--line); border-radius:var(--radius-lg); padding:28px 26px;}
  .brand{display:flex; align-items:center; gap:8px; margin-bottom:22px; font-family:var(--font-display); font-weight:600; font-size:15px;}
  .brand-icon{width:20px; height:20px; border-radius:5px; object-fit:contain;}
  h1{font-family:var(--font-display); font-size:18px; font-weight:600; margin:0 0 6px;}
  .sub{color:var(--text-muted); font-size:12.5px; margin:0 0 20px; line-height:1.5;}
  label{display:block; font-size:12px; font-weight:600; color:var(--text-muted); margin-bottom:6px;}
  input{width:100%; background:var(--bg-void); border:1px solid var(--line); color:var(--text-primary); font-family:var(--font-body); font-size:13.5px; padding:10px 12px; border-radius:8px; outline:none; margin-bottom:14px;}
  input:focus{border-color:var(--signal-dim);}
  button{width:100%; background:var(--signal); color:var(--bg-void); border:none; font-family:var(--font-body); font-size:13.5px; font-weight:600; padding:11px; border-radius:8px; cursor:pointer;}
  button:hover{background:#5ff0cf;}
  .error{background:rgba(232,115,95,0.12); border:1px solid var(--danger); color:var(--danger); font-size:12.5px; padding:10px 12px; border-radius:8px; margin-bottom:16px;}
  .code-input{letter-spacing:0.3em; text-align:center; font-family:var(--font-mono); font-size:18px;}
  .back{display:block; text-align:center; margin-top:16px; color:var(--text-muted); font-size:12.5px; text-decoration:none;}
  .back:hover{color:var(--signal);}
</style>
</head>
<body>
<div class="box">
  <div class="brand"><?= \KeyLair\Settings::brandIcon() ?><?= Helpers::e(\KeyLair\Settings::siteName()) ?></div>

  <?php if ($error): ?><div class="error"><?= Helpers::e($error) ?></div><?php endif; ?>

  <?php if ($firstRun): ?>
    <h1><?= Helpers::e(I18n::t('login.setup_heading')) ?></h1>
    <p class="sub"><?= sprintf(Helpers::e(I18n::t('login.setup_hint')), Helpers::e(\KeyLair\Settings::siteName())) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="action" value="create_master_admin">
      <label><?= Helpers::e(I18n::t('login.username_label')) ?></label>
      <input type="text" name="username" placeholder="admin" required autofocus>
      <label><?= Helpers::e(I18n::t('login.email_label')) ?></label>
      <input type="email" name="email" required>
      <label><?= Helpers::e(I18n::t('login.password_min_label')) ?></label>
      <input type="password" name="password" required minlength="10">
      <label><?= Helpers::e(I18n::t('login.confirm_password_label')) ?></label>
      <input type="password" name="password_confirm" required minlength="10">
      <button type="submit"><?= Helpers::e(I18n::t('login.create_account_button')) ?></button>
    </form>
  <?php elseif ($pendingTwoFactor): ?>
    <h1><?= Helpers::e(I18n::t('login.2fa_heading')) ?></h1>
    <p class="sub"><?= Helpers::e(I18n::t('login.2fa_hint')) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="action" value="verify_2fa">
      <label><?= Helpers::e(I18n::t('login.2fa_code_label')) ?></label>
      <input type="text" name="code" class="code-input" inputmode="numeric" pattern="[0-9]*" maxlength="6" required autofocus>
      <button type="submit"><?= Helpers::e(I18n::t('login.2fa_verify_button')) ?></button>
    </form>
  <?php else: ?>
    <h1><?= Helpers::e(I18n::t('login.signin_heading')) ?></h1>
    <p class="sub"><?= sprintf(Helpers::e(I18n::t('login.signin_hint')), Helpers::e(\KeyLair\Settings::siteName())) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="action" value="login">
      <label><?= Helpers::e(I18n::t('login.username_or_email_label')) ?></label>
      <input type="text" name="username" required autofocus>
      <label><?= Helpers::e(I18n::t('login.password_label')) ?></label>
      <input type="password" name="password" required>
      <button type="submit"><?= Helpers::e(I18n::t('login.signin_button')) ?></button>
    </form>
    <?php if (\KeyLair\Settings::passwordResetEnabled()): ?>
      <a class="back" href="forgot_password.php"><?= Helpers::e(I18n::t('login.forgot_password_link')) ?></a>
    <?php endif; ?>
  <?php endif; ?>
</div>
</body>
</html>
