<?php
declare(strict_types=1);
require __DIR__ . '/auth.php';
send_security_headers();
$language = site_language();
$isEnglish = $language === 'en';

if (current_user() !== null) {
    redirect_to('/account.php');
}

$email = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_valid_csrf();
    $email = normalize_email((string) ($_POST['email'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');

    if (rate_limited('login', $email, 10, 900)) {
        $error = site_text('尝试次数过多，请 15 分钟后再试。', 'Too many attempts. Please try again in 15 minutes.');
    } else {
        $statement = database()->prepare('SELECT id, password_hash FROM users WHERE email = :email');
        $statement->execute(['email' => $email]);
        $user = $statement->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
                $rehash = database()->prepare('UPDATE users SET password_hash = :hash WHERE id = :id');
                $rehash->execute(['hash' => password_hash($password, PASSWORD_DEFAULT), 'id' => $user['id']]);
            }
            clear_login_attempts($email);
            establish_login((int) $user['id']);
            redirect_to('/account.php');
        }

        record_attempt('login', $email);
        $error = site_text('邮箱或密码不正确。', 'The email or password is incorrect.');
    }
}
?>
<!doctype html>
<html lang="<?= $isEnglish ? 'en' : 'zh-CN' ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?= escape_html(site_text('登录', 'Sign in')) ?> - <?= escape_html(site_text('米环科技（长春）有限公司', 'Mihuan Technology (Changchun) Co., Ltd.')) ?></title>
  <link rel="icon" href="/site-icon-20260917.png?v=1">
  <link rel="stylesheet" href="/auth.css?v=3">
</head>
<body>
  <header class="topbar">
    <a class="brand" href="/"><span><?= escape_html(site_text('米环科技', 'Mihuan Technology')) ?></span><span><?= escape_html(site_text('（长春）', '(Changchun)')) ?></span><span><?= escape_html(site_text('有限公司', 'Co., Ltd.')) ?></span></a>
    <nav class="language-toggle" aria-label="Language">
      <a href="<?= escape_html(site_language_href('zh')) ?>"<?= $isEnglish ? '' : ' aria-current="page"' ?>>中文</a>
      <span aria-hidden="true">/</span>
      <a href="<?= escape_html(site_language_href('en')) ?>"<?= $isEnglish ? ' aria-current="page"' : '' ?>>English</a>
    </nav>
  </header>
  <main class="auth-main">
    <section class="auth-panel" aria-labelledby="page-title">
      <h1 id="page-title"><?= escape_html(site_text('登录', 'Sign in')) ?></h1>
      <p class="lead"><?= escape_html(site_text('登录你的米环科技账户。', 'Sign in to your Mihuan Technology account.')) ?></p>
      <?php if ($error !== ''): ?><p class="error" role="alert"><?= escape_html($error) ?></p><?php endif; ?>
      <form method="post" action="/login.php">
        <input type="hidden" name="csrf_token" value="<?= escape_html(csrf_token()) ?>">
        <input type="hidden" name="lang" value="<?= escape_html($language) ?>">
        <label for="email"><?= escape_html(site_text('电子邮箱', 'Email')) ?></label>
        <input id="email" name="email" type="email" autocomplete="email" maxlength="254" required value="<?= escape_html($email) ?>">
        <label for="password"><?= escape_html(site_text('密码', 'Password')) ?></label>
        <input id="password" name="password" type="password" autocomplete="current-password" maxlength="128" required>
        <button type="submit"><?= escape_html(site_text('登录', 'Sign in')) ?></button>
      </form>
      <p class="switch"><?= escape_html(site_text('还没有账户？', 'Need an account?')) ?> <a href="/register.php?lang=<?= escape_html($language) ?>"><?= escape_html(site_text('注册', 'Create one')) ?></a></p>
    </section>
  </main>
</body>
</html>
