<?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'] ?? '';
        $confirm  = $_POST['confirm'] ?? '';
        $email    = trim($_POST['email'] ?? '');
        $phone    = trim($_POST['phone'] ?? '');

        if (empty($username) || empty($password) || empty($confirm)) {
            $error = '用户名和密码为必填项。';
        } elseif (strlen($username) < 3 || strlen($username) > 50) {
            $error = '用户名长度需在 3-50 个字符之间。';
        } elseif (!preg_match('/^[a-zA-Z0-9\x{4e00}-\x{9fff}_]+$/u', $username)) {
            $error = '用户名只能包含字母、数字、中文和下划线。';
        } elseif (strlen($password) < 6 || strlen($password) > 128) {
            $error = '密码长度需在 6-128 个字符之间。';
        } elseif ($password !== $confirm) {
            $error = '两次输入的密码不一致。';
        } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = '邮箱格式不正确。';
        } elseif (!empty($email) && strlen($email) > 100) {
            $error = '邮箱长度不能超过 100 个字符。';
        } elseif (!empty($phone) && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $error = '手机号格式不正确。';
        } else {
            // 检查用户名唯一性
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = '用户名已经被注册，请换一个。';
            } elseif (!empty($email)) {
                // 检查邮箱唯一性
                $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $error = '该邮箱已被注册。';
                }
            }

            if (empty($error)) {
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, phone) VALUES (?, ?, ?, ?)");
                $stmt->execute([$username, $hashed, $email, $phone]);
                header('Location: login.php?registered=1');
                exit;
            }
        }
    }
}

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

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

<main class="form-container">
    <h2>🔐 用户注册</h2>
    <?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>用户名 <span style="color:#e74c3c;">*</span></label>
            <input type="text" name="username" maxlength="50" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" placeholder="字母、数字、中文、下划线，3-50字符" required>
        </div>
        <div class="form-group">
            <label>密码 <span style="color:#e74c3c;">*</span></label>
            <input type="password" name="password" maxlength="128" placeholder="至少6个字符" required>
        </div>
        <div class="form-group">
            <label>确认密码 <span style="color:#e74c3c;">*</span></label>
            <input type="password" name="confirm" maxlength="128" placeholder="再次输入密码" required>
        </div>
        <div class="form-group">
            <label>邮箱 <span style="color:#999;">(选填)</span></label>
            <input type="email" name="email" maxlength="100" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" placeholder="用于找回密码">
        </div>
        <div class="form-group">
            <label>手机号 <span style="color:#999;">(选填)</span></label>
            <input type="tel" name="phone" maxlength="11" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>" placeholder="11位手机号">
        </div>
        <button type="submit" class="btn btn-primary">注册</button>
    </form>
    <p style="text-align:center;margin-top:15px;">已有账号？ <a href="login.php">立即登录</a></p>
</main>

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