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

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

// 检查是否允许注册
if (getSetting('allow_register', '1') != '1') {
    setFlashMessage('error', '本站已关闭注册');
    redirect(SITE_URL . '/mobile/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 . '/mobile/login.php');
                } else {
                    $error = '注册失败，请稍后重试';
                }
            }
        }
    }
}

$pageTitle = '用户注册';
include __DIR__ . '/includes/header.php';
?>

<!-- 返回按钮 -->
<div class="mobile-back-bar">
    <a href="javascript:history.back();" class="mobile-back-btn">
        <i class="fas fa-arrow-left"></i> 返回
    </a>
</div>

<div class="mobile-section">
    <div class="mobile-section-title">
        <i class="fas fa-user-plus" style="color: var(--primary-color);"></i>
        <span>注册新账号</span>
    </div>
    
    <?php if ($error): ?>
    <div class="mobile-alert mobile-alert-error">
        <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
    </div>
    <?php endif; ?>
    
    <?php if ($success): ?>
    <div class="mobile-alert mobile-alert-success">
        <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
    </div>
    <?php endif; ?>
    
    <form method="POST" action="" class="mobile-form">
        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
        
        <div class="mobile-form-group">
            <label class="mobile-form-label">用户名</label>
            <input type="text" name="username" class="mobile-form-control" required
                   placeholder="3-20位字母数字下划线" value="<?php echo e($_POST['username'] ?? ''); ?>">
        </div>
        
        <div class="mobile-form-group">
            <label class="mobile-form-label">邮箱</label>
            <input type="email" name="email" class="mobile-form-control" required
                   placeholder="your@email.com" value="<?php echo e($_POST['email'] ?? ''); ?>">
        </div>
        
        <div class="mobile-form-group">
            <label class="mobile-form-label">密码</label>
            <input type="password" name="password" class="mobile-form-control" required
                   placeholder="至少6位">
        </div>
        
        <div class="mobile-form-group">
            <label class="mobile-form-label">确认密码</label>
            <input type="password" name="password_confirm" class="mobile-form-control" required
                   placeholder="再次输入密码">
        </div>
        
        <button type="submit" class="mobile-btn mobile-btn-primary mobile-btn-block">
            <i class="fas fa-user-plus"></i> 注册
        </button>
    </form>
    
    <div style="text-align: center; margin-top: 20px; color: #666; font-size: 14px;">
        已有账号？<a href="<?php echo SITE_URL; ?>/mobile/login.php" style="color: var(--primary-color);">立即登录</a>
    </div>
</div>

<style>
.mobile-back-bar {
    background: #fff;
    padding: 10px 15px;
    border-bottom: 1px solid #f0f0f0;
}
.mobile-back-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: #666;
    font-size: 14px;
    text-decoration: none;
}
.mobile-back-btn i {
    font-size: 12px;
}
.mobile-alert {
    padding: 12px 15px;
    margin: 10px;
    border-radius: 8px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.mobile-alert-error {
    background: #ffebee;
    color: #c62828;
}
.mobile-alert-success {
    background: #e8f5e9;
    color: #2e7d32;
}
.mobile-form {
    padding: 15px;
}
.mobile-form-group {
    margin-bottom: 15px;
}
.mobile-form-label {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 6px;
    font-weight: 500;
}
.mobile-form-control {
    width: 100%;
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
    font-family: inherit;
    box-sizing: border-box;
}
.mobile-form-control:focus {
    outline: none;
    border-color: var(--primary-color);
}
.mobile-btn {
    padding: 12px 20px;
    border-radius: 8px;
    font-size: 15px;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}
.mobile-btn-primary {
    background: var(--primary-color);
    color: white;
}
.mobile-btn-block {
    width: 100%;
}
</style>

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