<?php
include("./includes/common.php");

if(!$conf['userlogin']){
    @header('Content-Type: text/html; charset=UTF-8');
	exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("未开启用户注册", {icon: 2, closeBtn: 0}, function(){ window.location.href="./"; });</script></body></html>');
}

if($islogin2==1){
    @header('Content-Type: text/html; charset=UTF-8');
	exit('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://s4.zstatic.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script></head><body><script>layer.alert("您已登录！", {icon: 1, closeBtn: 0}, function(){ window.location.href="./"; });</script></body></html>');
}

// 加载邮件验证类
$emailVerify = new \lib\EmailVerify();
$emailSender = new \lib\EmailSender();
$emailEnabled = $emailSender->isReady();

if(isset($_POST['check_username'])){
    @header('Content-Type: application/json; charset=UTF-8');
    if(!checkRefererHost())exit(json_encode(['available'=>false]));
    $username = trim($_POST['check_username']);
    if(empty($username) || !preg_match('/^[a-zA-Z0-9_]{4,20}$/', $username)){
        exit(json_encode(['available'=>false]));
    }
    $exists = $DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE username=:username", [':username'=>$username]) > 0;
    exit(json_encode(['available' => !$exists]));
}

// 处理发送验证码请求
if(isset($_POST['action']) && $_POST['action'] == 'send_code'){
    @header('Content-Type: application/json; charset=UTF-8');
    if(!checkRefererHost())exit(json_encode(['code'=>-1, 'msg'=>'请求来源非法']));
    
    // 检查邮件功能是否启用
    if(!$emailEnabled){
        exit(json_encode(['code'=>-1, 'msg'=>'邮件功能未启用']));
    }
    
    $email = trim($_POST['email']);
    
    if(empty($email)){
        exit(json_encode(['code'=>-1, 'msg'=>'请输入邮箱地址']));
    }
    
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        exit(json_encode(['code'=>-1, 'msg'=>'邮箱格式不正确']));
    }
    
    // 检查邮箱是否已被注册
    if($emailVerify->isEmailRegistered($email)){
        exit(json_encode(['code'=>-1, 'msg'=>'该邮箱已被注册']));
    }
    
    // 发送验证码
    $result = $emailVerify->sendCode($email, 'register');
    exit(json_encode($result));
}

// 处理注册请求
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    @header('Content-Type: application/json; charset=UTF-8');
    
    if(!checkRefererHost())exit(json_encode(['code'=>-1, 'msg'=>'请求来源非法']));
    
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $nickname = trim($_POST['nickname']);
    $email = trim($_POST['email']);
    $email_code = trim($_POST['email_code']);
    $csrf_token = $_POST['csrf_token'];
    
    // 验证CSRF
    if(!$csrf_token || $csrf_token != $_SESSION['csrf_token']){
        exit(json_encode(['code'=>-1, 'msg'=>'请求验证失败，请刷新页面重试']));
    }
    
    // 验证用户名
    if(empty($username)){
        exit(json_encode(['code'=>-1, 'msg'=>'请输入用户名']));
    }
    if(!preg_match('/^[a-zA-Z0-9_]{4,20}$/', $username)){
        exit(json_encode(['code'=>-1, 'msg'=>'用户名必须为4-20位字母、数字或下划线']));
    }
    
    // 验证密码
    if(empty($password)){
        exit(json_encode(['code'=>-1, 'msg'=>'请输入密码']));
    }
    if(strlen($password) < 6){
        exit(json_encode(['code'=>-1, 'msg'=>'密码长度不能少于6位']));
    }
    if($password != $confirm_password){
        exit(json_encode(['code'=>-1, 'msg'=>'两次输入的密码不一致']));
    }
    
    // 验证昵称
    if(empty($nickname)){
        $nickname = $username;
    }
    if(mb_strlen($nickname, 'UTF-8') > 20){
        exit(json_encode(['code'=>-1, 'msg'=>'昵称不能超过20个字符']));
    }
    
    // 验证邮箱（邮件功能启用时必填）
    if($emailEnabled){
        if(empty($email)){
            exit(json_encode(['code'=>-1, 'msg'=>'请输入邮箱地址']));
        }
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            exit(json_encode(['code'=>-1, 'msg'=>'邮箱格式不正确']));
        }
        
        // 检查邮箱是否已被注册
        if($emailVerify->isEmailRegistered($email)){
            exit(json_encode(['code'=>-1, 'msg'=>'该邮箱已被注册']));
        }
        
        // 验证邮箱验证码
        if(empty($email_code)){
            exit(json_encode(['code'=>-1, 'msg'=>'请输入邮箱验证码']));
        }
        
        $verifyResult = $emailVerify->verifyCode($email, $email_code, 'register');
        if($verifyResult['code'] !== 0){
            exit(json_encode(['code'=>-1, 'msg'=>'验证码错误或已过期']));
        }
    }
    
    // 检查用户名是否已存在
    if($DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE username=:username", [':username'=>$username]) > 0){
        exit(json_encode(['code'=>-1, 'msg'=>'用户名已存在']));
    }
    
    // 创建用户
    $password_hash = password_hash($password, PASSWORD_DEFAULT);
    $result = $DB->exec("INSERT INTO `pre_user` (`username`, `password`, `email`, `nickname`, `enable`, `regip`, `loginip`, `addtime`, `lasttime`) 
                          VALUES (:username, :password, :email, :nickname, 1, :regip, :regip, NOW(), NOW())", 
                          [
                              ':username' => $username,
                              ':password' => $password_hash,
                              ':email' => $email,
                              ':nickname' => $nickname,
                              ':regip' => $clientip
                          ]);
    
    if(!$result){
        exit(json_encode(['code'=>-1, 'msg'=>'注册失败：'.$DB->error()]));
    }
    
    unset($_SESSION['csrf_token']);
    exit(json_encode(['code'=>0, 'msg'=>'注册成功！即将跳转到登录页面...']));
}

$title = '用户注册 - ' . $conf['title'];
include SYSTEM_ROOT.'header.php';

// 生成CSRF Token
$csrf_token = md5(mt_rand(0,999).time());
$_SESSION['csrf_token'] = $csrf_token;
?>
<link rel="stylesheet" href="./assets/css/register.css">

<div class="register-wrapper">
    <div class="register-card">
        <div class="register-header">
            <div class="logo-icon">
                <i class="fa fa-user-plus"></i>
            </div>
            <h2>创建账户</h2>
            <p>注册一个新账户开始使用</p>
        </div>
        
        <div class="register-body">
            <form id="registerForm" method="post">
                <div class="register-input-group">
                    <i class="fa fa-user input-icon"></i>
                    <input type="text" name="username" placeholder="请输入用户名" required maxlength="20">
                    <div id="usernameHint" class="help-text">4-20位字母、数字或下划线</div>
                </div>
                
                <div class="register-input-group">
                    <i class="fa fa-lock input-icon"></i>
                    <input type="password" name="password" placeholder="请输入密码" required>
                    <div class="help-text">密码长度不少于6位</div>
                </div>
                
                <div class="register-input-group">
                    <i class="fa fa-lock input-icon"></i>
                    <input type="password" name="confirm_password" placeholder="请再次输入密码" required>
                    <div class="help-text">请再次输入密码确认</div>
                </div>
                
                <?php if($emailEnabled): ?>
                <div class="register-input-group">
                    <i class="fa fa-envelope input-icon"></i>
                    <input type="email" name="email" placeholder="请输入邮箱地址（必填）" required>
                    <div class="help-text">用于账号验证和找回密码</div>
                </div>
                
                <div class="register-input-group">
                    <i class="fa fa-shield input-icon"></i>
                    <input type="text" name="email_code" class="code-input" placeholder="请输入邮箱验证码" required maxlength="6">
                    <button type="button" class="btn-send-code" id="btnSendCode" onclick="sendRegisterCode()">获取验证码</button>
                </div>
                <?php else: ?>
                <input type="hidden" name="email" value="">
                <input type="hidden" name="email_code" value="">
                <?php endif; ?>
                
                <div class="register-input-group">
                    <i class="fa fa-id-card input-icon"></i>
                    <input type="text" name="nickname" placeholder="昵称（可选）" maxlength="20">
                    <div class="help-text">不填写则默认使用用户名</div>
                </div>
                
                <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                
                <button type="submit" class="btn-register">立即注册</button>
            </form>
            
            <div class="register-footer">
                <p>已有账号？ <a href="./login.php">立即登录</a></p>
            </div>
        </div>
    </div>
</div>

<script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script>
<script>var emailEnabled = <?php echo $emailEnabled ? 'true' : 'false'; ?>;</script>
<script src="./assets/js/register.js"></script>
<?php include SYSTEM_ROOT.'footer.php'; ?>