<?php

declare(strict_types=1);

/**
 * Console login (SPEC §11): level 255 only, same 5-per-15-min throttle as
 * the matrix (shared Users::authenticate), CSRF even here, and one generic
 * refusal string; the login page confirms nothing about what exists.
 */

require __DIR__ . '/_lib.php';

if (admin_user() !== null) {
    admin_redirect('index.php');
}

$error = null;
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    admin_verify_csrf();
    $handle = trim((string)($_POST['handle'] ?? ''));
    $pass = (string)($_POST['pass'] ?? '');
    $r = \Atdt\Users::authenticate(atdt_db(), $handle, $pass, client_ip());
    $user = $r['user'];
    if ($r['code'] === 'throttled') {
        $error = 'Too many tries. The console is locked for 15 minutes.';
    } elseif ($r['code'] === 'ok' && (int)$user['level'] === 255) {
        session_regenerate_id(true);
        $_SESSION['admin_uid'] = (int)$user['id'];
        atdt_log_event('admin', 'console:' . $user['handle'], 'SysOp logged into the console');
        admin_redirect('index.php');
    } else {
        if ($r['code'] === 'ok') {
            atdt_log_event('security', 'admin:' . client_ip(), 'Non-SysOp "' . mb_substr($handle, 0, 40) . '" tried the console');
        }
        $error = 'That did not open the door.';
    }
}

$board = (string)atdt_settings()->get('board_name', 'ATDT');
header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Console login - <?= h($board) ?></title>
<link rel="stylesheet" href="../assets/admin.css">
</head>
<body>
<main class="login">
  <h1>SysOp console <span class="step"><?= h($board) ?></span></h1>
  <?php if ($error !== null): ?><p class="bad"><?= h($error) ?></p><?php endif; ?>
  <form method="post" action="login.php">
    <?= csrf_field() ?>
    <label>Handle <input type="text" name="handle" autofocus autocomplete="username"></label>
    <label>Password <input type="password" name="pass" autocomplete="current-password"></label>
    <button class="btn" type="submit">Open the console</button>
  </form>
  <p class="hint">Level 255 only. The <a href="../">caller terminal</a> is around front.</p>
</main>
</body>
</html>
