<?php
/**
 * 用户登录页面
 */
require_once __DIR__ . '/includes/functions.php';

// 如果已登录，跳转到首页
if (isLoggedIn()) {
    redirect(SITE_URL . '/index.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);
    $csrfToken = $_POST['csrf_token'] ?? '';

    // 验证 CSRF Token
    if (!validateCsrfToken($csrfToken)) {
        $error = '安全验证失败，请刷新页面重试';
    } elseif (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        // 先查询用户（包括被禁用的）
        $user = db()->queryOne(
            "SELECT * FROM users WHERE username = ? OR email = ?",
            [$username, $username]
        );

        if (!$user) {
            $error = '用户名或密码错误';
        } elseif ($user['status'] == 0) {
            // 用户被禁用
            $error = '您的账号已被封禁，请联系管理员';
        } elseif (!password_verify($password, $user['password'])) {
            $error = '用户名或密码错误';
        } else {
            // 登录成功
            $_SESSION['user_id'] = $user['id'];

            // 更新最后登录时间
            db()->execute(
                "UPDATE users SET last_login_at = NOW() WHERE id = ?",
                [$user['id']]
            );

            // 管理员也需要满足条件才能解锁勋章，不再自动解锁
            // 检查是否有可解锁的勋章并发送通知
            try {
                checkAndNotifyMedalUnlock($user['id']);
            } catch (Exception $e) {
                error_log('检查勋章失败: ' . $e->getMessage());
            }

            // 如果选择了记住我，设置 Cookie（这里简化处理，实际应该使用更安全的 token 机制）
            if ($remember) {
                $token = bin2hex(random_bytes(32));
                // 这里可以将 token 存入数据库，并设置 cookie
            }

            setFlashMessage('success', '欢迎回来，' . $user['username'] . '！');
            redirect(SITE_URL . '/index.php');
        }
    }
}

$pageTitle = '用户登录';
include __DIR__ . '/templates/header.php';
?>

<div class="auth-container">
    <div class="auth-card">
        <h2>用户登录</h2>

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

        <form method="POST" action="">
            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">

            <div class="form-group">
                <label for="username">用户名或邮箱</label>
                <input type="text" id="username" name="username" class="form-control" required
                       placeholder="请输入用户名或邮箱" value="<?php echo e($_POST['username'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" class="form-control" required
                       placeholder="请输入密码">
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                    <input type="checkbox" name="remember" value="1">
                    <span>记住我</span>
                </label>
            </div>

            <button type="submit" class="btn btn-primary btn-block btn-lg">登录</button>
        </form>

        <div class="auth-footer">
            还没有账号？<a href="register.php">立即注册</a>
        </div>
    </div>
</div>

<?php include __DIR__ . '/templates/footer.php'; ?>
