<?php
declare(strict_types=1);

/**
 * Sign-in.
 *
 * Deliberately tells the visitor as little as possible: one message covers a bad
 * username, a bad password and a disabled account, so the form cannot be used to
 * discover which usernames exist.
 */

if (Auth::check()) {
    redirect('dashboard');
}

$error    = null;
$username = '';

/**
 * First run: if not one account has a password yet, nobody can get in and there
 * is nothing to protect, so it is safe - and much kinder - to say so. The moment
 * a single password exists, this disappears.
 */
$needsSetup = (int) Database::scalar(
    'SELECT COUNT(*) FROM users WHERE password_hash IS NOT NULL AND is_active = 1'
) === 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Csrf::valid($_POST['csrf'] ?? null)) {
        $error = t('form_expired');
    } else {
        $username = (string) post('username', '');
        $password = (string) post('password', '');

        if ($username === '' || $password === '') {
            $error = t('login_failed');
        } elseif (Auth::isLockedOut($username)) {
            $error = t('login_locked', ['n' => LOGIN_LOCKOUT_MINUTES]);
        } elseif (Auth::attempt($username, $password)) {
            // Return the visitor to whatever page they were trying to reach.
            $next = (string) get_param('next', '');
            if ($next !== '') {
                $decoded = base64_decode($next, true);
                // A path on this host only - never absolute, scheme-relative or multiline.
                if (is_string($decoded)
                    && str_starts_with($decoded, '/')
                    && !str_starts_with($decoded, '//')
                    && !str_contains($decoded, "\n")) {
                    redirect_to($decoded);
                }
            }
            redirect('dashboard');
        } else {
            // Slow a scripted attempt without making a real person wait.
            usleep(random_int(180000, 420000));
            $error = t('login_failed');
        }
    }
}

$nextParam = (string) get_param('next', '');
?>
<!DOCTYPE html>
<html lang="<?= e(Lang::code()) ?>" dir="<?= e(Lang::dir()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<meta name="referrer" content="no-referrer">
<title><?= e(t('sign_in') . ' · ' . t('app_name')) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans+Condensed:wght@500;600;700&family=IBM+Plex+Sans+Hebrew:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= e(BASE_URL) ?>/assets/css/style.css?v=2">
</head>
<body class="login-page">

<div class="login-split">

  <!-- Identity panel. The ranging reticle is the portal's mark; the thermal
       scale beneath it is the one signal the whole system is built around. -->
  <section class="login-aside" aria-hidden="true">
    <div class="login-reticle">
      <span class="reticle-ring reticle-ring-1"></span>
      <span class="reticle-ring reticle-ring-2"></span>
      <span class="reticle-ring reticle-ring-3"></span>
      <span class="reticle-cross reticle-cross-v"></span>
      <span class="reticle-cross reticle-cross-h"></span>
      <span class="reticle-pip"></span>
    </div>

    <div class="login-aside-copy">
      <p class="login-aside-title"><?= e(t('app_name')) ?></p>
      <p class="login-aside-text"><?= e(t('login_tagline')) ?></p>
      <div class="login-aside-scale">
        <span class="thermal-scale"></span>
        <span class="login-aside-scalelabel"><?= e(t('thermal_legend')) ?></span>
      </div>
    </div>
  </section>

  <main class="login-main">
    <form class="login-card" method="post"
          action="<?= e(url('auth', 'login', $nextParam !== '' ? ['next' => $nextParam] : [])) ?>"
          data-no-lock="1">
      <?= Csrf::field() ?>

      <div class="login-brand">
        <span class="rail-mark" aria-hidden="true"></span>
        <span class="login-title"><?= e(t('app_name')) ?></span>
      </div>

      <h1 class="login-heading"><?= e(t('sign_in')) ?></h1>

      <?php foreach (Flash::take() as [$kind, $message]): ?>
        <div class="flash flash-<?= e($kind) ?>"><?= e($message) ?></div>
      <?php endforeach; ?>

      <?php if ($error !== null): ?>
        <div class="flash flash-error" role="alert"><?= e($error) ?></div>
      <?php endif; ?>

      <?php if ($needsSetup): ?>
        <div class="flash flash-warn">
          <?= e(t('login_first_run')) ?>
          <code class="login-code">php tools/set_password.php --list</code>
        </div>
      <?php endif; ?>

      <div class="field">
        <label class="label" for="username"><?= e(t('username')) ?></label>
        <input type="text" id="username" name="username" value="<?= e($username) ?>"
               autocomplete="username" autocapitalize="none" spellcheck="false"
               required autofocus>
      </div>

      <div class="field">
        <label class="label" for="password"><?= e(t('password')) ?></label>
        <div class="login-pw">
          <input type="password" id="password" name="password"
                 autocomplete="current-password" required>
          <button type="button" class="login-reveal" id="reveal"
                  aria-controls="password" aria-pressed="false"
                  title="<?= e(t('show_password')) ?>"><?= e(t('show')) ?></button>
        </div>
        <p class="hint login-caps" id="caps" hidden><?= e(t('caps_lock_on')) ?></p>
      </div>

      <button type="submit" class="btn btn-primary"><?= e(t('sign_in')) ?></button>

      <p class="login-foot">
        <a href="<?= e(url('auth', 'login', ['lang' => Lang::code() === 'he' ? 'en' : 'he'])) ?>">
          <?= Lang::code() === 'he' ? 'English' : 'עברית' ?>
        </a>
      </p>
    </form>
  </main>

</div>

<script>
(function () {
  'use strict';

  var password = document.getElementById('password');
  var caps     = document.getElementById('caps');
  var reveal   = document.getElementById('reveal');
  var labelShow = <?= json_encode(t('show'), JSON_UNESCAPED_UNICODE) ?>;
  var labelHide = <?= json_encode(t('hide'), JSON_UNESCAPED_UNICODE) ?>;

  /* Caps Lock is the commonest cause of a "wrong password" that isn't one. */
  function checkCaps(event) {
    if (!caps || typeof event.getModifierState !== 'function') { return; }
    caps.hidden = !event.getModifierState('CapsLock');
  }

  if (password) {
    password.addEventListener('keyup', checkCaps);
    password.addEventListener('keydown', checkCaps);
    password.addEventListener('blur', function () { if (caps) { caps.hidden = true; } });
  }

  /* Reveal, for long passphrases typed on a phone. */
  if (reveal && password) {
    reveal.addEventListener('click', function () {
      var showing = password.type === 'text';
      password.type = showing ? 'password' : 'text';
      reveal.setAttribute('aria-pressed', String(!showing));
      reveal.textContent = showing ? labelShow : labelHide;
      password.focus();
    });
  }
})();
</script>

</body>
</html>
