<?php
// 重要：session 和 redirect 必须在任何 HTML 输出之前处理
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config.php';

// 已登录用户直接跳转
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$pageTitle = '用户登录';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
        $error = '请求无效，请重试';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($username) || empty($password)) {
            $error = '请输入用户名和密码';
        } else {
            // 支持用户名或邮箱登录
            $isEmail = (strpos($username, '@') !== false);
            if ($isEmail) {
                $stmt = $pdo->prepare("SELECT id, username, password, login_attempts, locked_until FROM users WHERE email = ?");
            } else {
                $stmt = $pdo->prepare("SELECT id, username, password, login_attempts, locked_until FROM users WHERE username = ?");
            }
            $stmt->execute([$username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            // 检查账号是否被锁定（暴力破解防护）
            if ($user && $user['locked_until'] && strtotime($user['locked_until']) > time()) {
                $remaining = ceil((strtotime($user['locked_until']) - time()) / 60);
                $error = "账号已被锁定，请 {$remaining} 分钟后再试";
            } elseif ($user && password_verify($password, $user['password'])) {
                // 登录成功，重置失败计数和解锁时间
                $stmt = $pdo->prepare("UPDATE users SET login_attempts = 0, locked_until = NULL WHERE id = ?");
                $stmt->execute([$user['id']]);

                $_SESSION['user_id']  = $user['id'];
                $_SESSION['username'] = $user['username'];
                session_regenerate_id(true);
                header('Location: index.php');
                exit;
            } else {
                // 登录失败，增加失败计数（仅当账号存在时）
                if ($user) {
                    $attempts = $user['login_attempts'] + 1;
                    $lockedUntil = null;
                    if ($attempts >= 5) {
                        $lockedUntil = date('Y-m-d H:i:s', strtotime('+15 minutes'));
                    }
                    $stmt = $pdo->prepare("UPDATE users SET login_attempts = ?, locked_until = ? WHERE id = ?");
                    $stmt->execute([$attempts, $lockedUntil, $user['id']]);
                }
                $error = '用户名或密码错误';
            }
        }
    }
}

$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// 在 redirect 逻辑全部处理完之后，才输出 HTML
require_once 'header.php';
?>

<main class="form-container">
    <h2>🔑 用户登录</h2>
    <?php if (isset($_GET['registered'])): ?>
        <p class="success-message">注册成功，请登录。</p>
    <?php endif; ?>
    <?php if ($error): ?><p class="error-message"><?php echo htmlspecialchars($error); ?></p><?php endif; ?>
    <form method="post" novalidate>
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
        <div class="form-group">
            <label>用户名 / 邮箱</label>
            <input type="text" name="username" maxlength="100" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" placeholder="输入用户名或邮箱" required>
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" name="password" maxlength="128" placeholder="输入密码" required>
        </div>
        <button type="submit" class="btn btn-primary">登录</button>
    </form>
    <p style="text-align:center;margin-top:15px;">还没有账号？ <a href="register.php">立即注册</a></p>
</main>

<?php require_once 'footer.php'; ?>
