<?php 
// 引入数据库配置文件 
require './config.php'; 

if (!isset($conn)) { 
    die("连接失败：数据库连接地址未定义"); 
} 

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    $username = $_POST['username']; 
    $email = $_POST['email']; 
    $password = $_POST['password']; 
    $confirm_password = $_POST['confirm-password']; 
    // 获取新增字段
    $organization = $_POST['organization'] ?? '';
    $development_field = $_POST['development_field'] ?? '';
    $skill_tags = $_POST['skill_tags'] ?? '';
    $register_time = date('Y-m-d H:i:s');

    // 输入验证逻辑 
    if (empty($email)) { 
        echo "邮箱不能为空，请填写邮箱地址。"; 
        exit(); 
    } 

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
        echo "邮箱格式不正确，请输入有效的邮箱地址。"; 
        exit(); 
    } 

    if ($password !== $confirm_password) { 
        echo "密码不一致，请重新输入。"; 
        exit(); 
    } 

    // 密码必须包含大小写字母 
    if (!preg_match('/[a-z]/', $password) || !preg_match('/[A-Z]/', $password)) { 
        echo "密码必须包含大小写字母。"; 
        exit(); 
    } 

    // 检查用户名是否已存在 
    $stmt = $conn->prepare("SELECT username FROM users WHERE username = ?"); 
    $stmt->bind_param("s", $username); 
    $stmt->execute(); 
    $stmt->store_result(); 

    if ($stmt->num_rows > 0) { 
        echo "用户名已存在，请选择其他用户名。"; 
        exit(); 
    } 

    // 检查邮箱是否已存在 
    $stmt = $conn->prepare("SELECT email FROM users WHERE email = ?"); 
    $stmt->bind_param("s", $email); 
    $stmt->execute(); 
    $stmt->store_result(); 

    if ($stmt->num_rows > 0) { 
        echo "邮箱已被注册，请使用其他邮箱。"; 
        exit(); 
    } 

    // 密码散列 
    $hashed_password = password_hash($password, PASSWORD_DEFAULT); 

    // 设置默认等级和积分 
    $level = 1; 
    $points = 100; 

    // 修改插入语句，添加新字段
    $stmt = $conn->prepare("INSERT INTO users (username, email, password, level, points, register_time, organization, development_field, skill_tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); 
    $stmt->bind_param("sssisssss", $username, $email, $hashed_password, $level, $points, $register_time, $organization, $development_field, $skill_tags); 
    if ($stmt->execute()) { 
        echo "注册成功！请登录。"; 
    } else { 
        echo "本地数据库创建用户失败: " . $stmt->error; 
    } 

    $stmt->close(); 
} 
$conn->close(); 
?>