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

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

// 检查是否允许注册
if (getSetting('allow_register', '1') != '1') {
    setFlashMessage('error', '本站已关闭注册');
    redirect(SITE_URL . '/index.php');
}

$error = '';
$success = '';

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

    // 验证 CSRF Token
    if (!validateCsrfToken($csrfToken)) {
        $error = '安全验证失败，请刷新页面重试';
    }
    // 验证用户名
    elseif (empty($username) || strlen($username) < 3 || strlen($username) > 20) {
        $error = '用户名长度必须在 3-20 个字符之间';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $error = '用户名只能包含字母、数字和下划线';
    }
    // 验证邮箱
    elseif (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '请输入有效的邮箱地址';
    }
    // 验证密码
    elseif (empty($password) || strlen($password) < 6) {
        $error = '密码长度至少为 6 位';
    } elseif ($password !== $passwordConfirm) {
        $error = '两次输入的密码不一致';
    } else {
        // 检查用户名是否已存在
        $existingUser = db()->queryOne("SELECT id FROM users WHERE username = ?", [$username]);
        if ($existingUser) {
            $error = '用户名已被注册';
        } else {
            // 检查邮箱是否已存在
            $existingEmail = db()->queryOne("SELECT id FROM users WHERE email = ?", [$email]);
            if ($existingEmail) {
                $error = '邮箱已被注册';
            } else {
                // 创建用户
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $userId = db()->insert(
                    "INSERT INTO users (username, email, password, status) VALUES (?, ?, ?, ?)",
                    [$username, $email, $hashedPassword, 1]
                );

                if ($userId) {
                    $success = '注册成功！正在跳转到登录页面...';
                    setFlashMessage('success', '注册成功，请登录');
                    header('Refresh: 2; URL=' . SITE_URL . '/login.php');
                } else {
                    $error = '注册失败，请稍后重试';
                }
            }
        }
    }
}

$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; ?>

        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo e($success); ?></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="3-20位字母数字下划线" value="<?php echo e($_POST['username'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" name="email" class="form-control" required
                       placeholder="your@email.com" value="<?php echo e($_POST['email'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" class="form-control" required
                       placeholder="至少6位">
            </div>

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

            <button type="submit" class="btn btn-primary btn-block btn-lg">注册</button>
        </form>

        <div class="auth-footer">
            已有账号？<a href="login.php">立即登录</a>
        </div>
    </div>
</div>

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