<?php
include dirname(__DIR__) . '/includes/common.php';
if($conf['reg_type'] == 1){
    exit("<script language='javascript'>window.location.href='./reg_km.php';</script>"); 
}
if($conf['user_open'] != '1'){
    @header('Content-Type: text/html; charset=UTF-8');
    exit("<script language='javascript'>alert('暂未放开注册');window.location.href='./';</script>"); 
}
if($islogin2==1){
    @header('Content-Type: text/html; charset=UTF-8');
    exit("<script language='javascript'>alert('您已登陆！');window.location.href='./index.php';</script>");
}

function reg_json_out($code, $msg, $extra = []) {
    @header('Content-Type: application/json; charset=UTF-8');
    exit(json_encode(array_merge(['code' => (int)$code, 'msg' => (string)$msg], $extra), JSON_UNESCAPED_UNICODE));
}

$invite_code=isset($_GET['invite'])?intval($_GET['invite']):'';
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;
if($act == 'send_email'){
    if($_SERVER['REQUEST_METHOD'] !== 'POST') reg_json_out(-1, '请求方式错误');
    if(($conf['user_open'] ?? '') != '1') reg_json_out(-1, '暂未放开注册');
    if(intval($conf['reg_email_open'] ?? 0) !== 1) reg_json_out(-1, '未开启邮箱验证');
    $email = isset($_POST['email']) ? trim(daddslashes($_POST['email'])) : '';
    $key = isset($_POST['key']) ? trim(daddslashes($_POST['key'])) : '';
    if($key === '' || strlen($key) !== 32) reg_json_out(-1, '验证失败，请刷新网页');
    if(empty($_SESSION['mail_key']) || $key !== $_SESSION['mail_key']) reg_json_out(-1, '验证失败，请刷新网页');
    if($email === '') reg_json_out(-1, '请输入邮箱地址');
    if(!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)){
        reg_json_out(-1, '请输入正确的邮箱地址');
    }
    if(($conf['regcode'] ?? '') == '1' || ($conf['regphonecode'] ?? '') == '1'){
        if(!isset($_POST['verifycode'])) reg_json_out(-1, '请输入图形验证码');
        $verifycode = strtolower(trim(daddslashes((string)$_POST['verifycode'])));
        if($verifycode === '') reg_json_out(-1, '请输入图形验证码');
        if(empty($_SESSION['vc_code']) || strtolower((string)$_SESSION['vc_code']) !== $verifycode){
            reg_json_out(-1, '图形验证码错误');
        }
    }
    $ip = real_ip();
    $ipEsc = daddslashes($ip);
    $emailHourLimit = 8;
    $hourCnt = (int)$DB->getColumn("SELECT COUNT(*) FROM `pre_logs` WHERE type='reg_email_rate' AND result='{$ipEsc}' AND addtime > DATE_SUB(NOW(), INTERVAL 3600 SECOND)");
    if($hourCnt >= $emailHourLimit){
        reg_json_out(-1, '发送过于频繁，请稍后再试');
    }
    $is = $DB->getRow("SELECT * FROM `pre_logs` WHERE type='email' AND result='{$email}' ORDER BY addtime DESC LIMIT 1");
    $tmp_date = date("Y-m-d H:i:s",strtotime('-1minute'));
    if($is && $is['addtime'] > $tmp_date){
        reg_json_out(-1, '1分钟内不可以重复发送。');
    }
    $code = random(6,1);
    $content = '注册验证码：<font color="red">'.$code.'</font>，有效期30分钟。';
    $ret = \lib\MessageSend::send($email,'账号注册','账号注册',$content,'账号注册');
    if($ret == '1'){
        $DB->exec("INSERT INTO `pre_logs` (`zid`,`type`,`result`,`result2`,`result3`,`addtime`) VALUES ('1', 'email', '".$email."', '".$code."', '".$key."', NOW())");
        $DB->exec("INSERT INTO `pre_logs` (`zid`,`type`,`result`,`addtime`) VALUES ('1', 'reg_email_rate', '".$ipEsc."', NOW())");
        if(isset($_SESSION['vc_code'])) unset($_SESSION['vc_code']);
        reg_json_out(1, '验证码已发送到邮箱，请去查看!');
    }
    reg_json_out(-1, '发送失败');
}
if($act == 'send_sms'){
    if($_SERVER['REQUEST_METHOD'] !== 'POST') reg_json_out(-1, '请求方式错误');
    if(($conf['user_open'] ?? '') != '1') reg_json_out(-1, '暂未放开注册');
    if(intval($conf['regphonecode'] ?? 0) !== 1) reg_json_out(-1, '未开启手机验证');
    if(!isset($_POST['verifycode'], $_POST['phone'], $_POST['key'])) reg_json_out(-1, '参数不完整');
    $verifycode=strtolower(trim(daddslashes((string)$_POST['verifycode'])));
    $phone=daddslashes(trim((string)$_POST['phone']));
    $key=trim(daddslashes((string)$_POST['key']));
    if(strlen($phone)!=11) reg_json_out(-1, '请填写正确的手机号码！');
    if($verifycode === '') reg_json_out(-1, '请输入图形验证码');
    if(empty($_SESSION['vc_code']) || strtolower((string)$_SESSION['vc_code']) !== $verifycode) reg_json_out(-1, '验证码错误');
    if($key==='' || strlen($key)!==32) reg_json_out(-1, '秘钥不正确');
    if(empty($_SESSION["reg_key"]) || $_SESSION["reg_key"] !== $key) reg_json_out(-1, '验证失败，请刷新网页');
    if($DB->getRow("SELECT zid FROM pre_user WHERE phone='{$phone}' LIMIT 1")){
        reg_json_out(-1, '手机号码已被绑定，请换一个吧！');
    }
    $ip = real_ip();
    $is = $DB->getRow("SELECT * FROM `pre_logs` WHERE type='短信' AND result='{$ip}' ORDER BY addtime DESC LIMIT 1");
    if($is && $is['result2'] > time()){
        reg_json_out(-1, 'ip：'.$ip.'，1分钟内不可以重复发送短信。');
    }
    $code = random(6,1);
    $ret = send_sms($phone, '您的验证码为：'.$code.'，有效期5分钟。');
    if($ret['code'] == 1){
        unset($_SESSION['validate_key']);
        if(isset($_SESSION['vc_code'])) unset($_SESSION['vc_code']);
        $DB->exec("INSERT INTO `pre_logs` (`zid`,`type`,`result`,`result2`,`addtime`) VALUES ('1', '短信', '".$ip."', '".strtotime('+1minute')."', NOW()),('1', '注册验证码', '".$code."', '".$phone."', NOW())");
        $_SESSION['send_sms_time'] = strtotime('+1minute');
        $msg = '发送成功，请注意查收';
    }else{
        $msg = '发送失败：'.(isset($ret['msg']) ? strip_tags((string)$ret['msg']) : '未知错误');
    }
    reg_json_out(1, $msg);
}
if($act == 'reg'){
    if($_SERVER['REQUEST_METHOD'] !== 'POST') reg_json_out(-1, '请求方式错误');
    // 强制校验是否已阅读条款
    $agree_clause = isset($_POST['agree_clause']) ? daddslashes($_POST['agree_clause']) : '';
    $reg_clause_open = $conf['reg_clause_open'] ?? '1';
    if(($reg_clause_open == '1' || $reg_clause_open == '2') && $agree_clause != '1'){
        reg_json_out(-1, '请阅读并同意QQ账号授权使用免责条款');
    }

    if(!isset($_POST['user'], $_POST['pwd'], $_POST['qq'], $_POST['key'])){
        reg_json_out(-1, '参数不完整');
    }
    $user=daddslashes($_POST['user']);
    $pwd=daddslashes($_POST['pwd']);
    $qq=daddslashes($_POST['qq']);
    $key=trim(daddslashes($_POST['key']));
    $phone=isset($_POST['phone']) ? daddslashes($_POST['phone']) : '';
    $phonecode=isset($_POST['phonecode']) ? daddslashes($_POST['phonecode']) : '';
    $email=isset($_POST['email_user'])?daddslashes($_POST['email_user']):'';
    $email_code=isset($_POST['email_code'])?daddslashes($_POST['email_code']):'';
    $invite_code = isset($_POST['invite_code']) ? intval($_POST['invite_code']) : 0;
    $reg_timestamp=isset($_POST['reg_timestamp'])?intval($_POST['reg_timestamp']):0;
    $reg_token=isset($_POST['reg_token'])?daddslashes($_POST['reg_token']):'';
    $website_url=isset($_POST['website_url'])?daddslashes($_POST['website_url']):'';
    $browser_info=isset($_POST['browser_info'])?daddslashes($_POST['browser_info']):'';
    
    if($key==='' || strlen($key)!==32) reg_json_out(-1, '秘钥不正确');
    if(empty($_SESSION["reg_key"]) || $_SESSION["reg_key"] !== $key) reg_json_out(-1, '验证失败，请刷新网页');
    
    if($website_url != '') reg_json_out(-1, '注册失败');
    
    if($reg_timestamp == 0 || !isset($_SESSION["reg_timestamp"]) || $reg_timestamp != $_SESSION["reg_timestamp"]){
        reg_json_out(-1, '验证失败，请刷新网页');
    }
    
    if($reg_token == '' || !isset($_SESSION["reg_token"]) || $reg_token != $_SESSION["reg_token"]){
        reg_json_out(-1, '验证失败，请刷新网页');
    }
    
    if($reg_timestamp < time() - 300 || $reg_timestamp > time() + 300){
        reg_json_out(-1, '请求超时，请刷新网页');
    }

    $ip = real_ip();
    $ipEsc = daddslashes($ip);
    $regTryHourLimit = 25;
    $tryCnt = (int)$DB->getColumn("SELECT COUNT(*) FROM `pre_logs` WHERE type='reg_try' AND result='{$ipEsc}' AND addtime > DATE_SUB(NOW(), INTERVAL 3600 SECOND)");
    if($tryCnt >= $regTryHourLimit){
        reg_json_out(-1, '注册尝试过于频繁，请1小时后再试');
    }
    $DB->exec("INSERT INTO `pre_logs` (`zid`,`type`,`result`,`addtime`) VALUES ('1', 'reg_try', '".$ipEsc."', NOW())");
    
    if($browser_info != ''){
        $browser_data = json_decode($browser_info, true);
        if(isset($browser_data['userAgent'])){
            $user_agent = $browser_data['userAgent'];
            if(strpos($user_agent, 'curl') !== false || strpos($user_agent, 'wget') !== false || 
               strpos($user_agent, 'python') !== false || strpos($user_agent, 'java') !== false ||
               strpos($user_agent, 'bot') !== false || strpos($user_agent, 'spider') !== false){
                reg_json_out(-1, '注册失败');
            }
        }
    }
    
    $reg_limit_key = 'reg_limit_' . md5($ip);
    if(isset($_SESSION[$reg_limit_key]) && $_SESSION[$reg_limit_key] > 8){
        reg_json_out(-1, '注册次数过多，请稍后再试');
    }
    if(!isset($_SESSION[$reg_limit_key])){
        $_SESSION[$reg_limit_key] = 0;
    }
    $_SESSION[$reg_limit_key]++;
    
    if(($conf['regcode'] ?? '') == '1' || ($conf['regphonecode'] ?? '') == '1'){
        if(!isset($_POST['verifycode'])) reg_json_out(-1, '请输入图形验证码');
        $verifycode = strtolower(trim(daddslashes((string)$_POST['verifycode'])));
        if($verifycode === '') reg_json_out(-1, '请输入图形验证码');
        if(empty($_SESSION['vc_code'])) reg_json_out(-1, '验证码已失效，请刷新后重试');
        if(strtolower((string)$_SESSION['vc_code']) !== $verifycode) reg_json_out(-1, '验证码错误');
        unset($_SESSION['vc_code']);
    }
    if(intval($conf['regphonecode'] ?? 0) === 1){
        if(strlen($phone)!=11) reg_json_out(-1, '请填写正确的手机号码！');
        if($phonecode === '') reg_json_out(-1, '请填写短信验证码');
        $tmptime = date('Y-m-d H:i:s',strtotime('-5minute'));
        $is = $DB->getRow("SELECT * FROM `pre_logs` WHERE type='注册验证码' AND result2='{$phone}' AND addtime>'".$tmptime."' ORDER BY addtime DESC LIMIT 1");
        if(!$is) reg_json_out(-1, '短信验证码过期');
        if($is['result'] != $phonecode){
            reg_json_out(-1, '手机短信验证码错误');
        }
    } elseif (intval($conf['reg_email_open'] ?? 0) === 1) {
        if(!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)){
            reg_json_out(-1, '请输入正确的邮箱地址');
        }
        if($email_code === ''){
            reg_json_out(-1, '请填写邮箱验证码');
        }
        $is = $DB->getRow("SELECT * FROM `pre_logs` WHERE type='email' AND result='{$email}' ORDER BY addtime DESC LIMIT 1");
        if(!$is) reg_json_out(-1, '邮箱验证码不存在，请先发送邮箱验证码');
        $tmp_date = date("Y-m-d H:i:s",strtotime('-30minute'));
        if($tmp_date > $is['addtime']){
            reg_json_out(-1, '邮箱验证码已过期');
        }
        if($is['result2'] != $email_code) reg_json_out(-1, '邮箱验证码错误');
        $DB->exec("UPDATE pre_logs SET result2='' WHERE type='email' AND result='{$email}'");
    }
    if($conf['user_reg_ip'] == '2' && isset($_SESSION['reg_time']) && $_SESSION['reg_time'] > time()){
        reg_json_out(-1, '2分钟内,同一个IP不可以重复注册。');
    }elseif($conf['user_reg_ip'] == '1' && $DB->getRow("SELECT ip FROM pre_user WHERE ip=:ip LIMIT 1", [':ip'=>$ip])){
        reg_json_out(-1, 'IP已注册过账号，请换一个IP在注册哦');
    }
    if (!preg_match('/^[a-zA-Z0-9\x7f-\xff]+$/',$user)) {
        reg_json_out(-1, '用户名只能为英文、数字与汉字！');
    } elseif ($DB->getRow("SELECT zid FROM pre_user WHERE user=:user LIMIT 1", [':user'=>$user])) {
        reg_json_out(-1, '用户名已存在！');
    } elseif (strlen($pwd) < 6) {
        reg_json_out(-1, '密码不能低于6位');
    } elseif (strlen($qq) < 4 || !preg_match('/^[0-9]+$/',$qq)) {
        reg_json_out(-1, 'QQ格式不正确！');
    } elseif ($pwd == $user) {
        reg_json_out(-1, '用户名和密码不能相同！');
    }

    if($invite_code > 0){//邀请
        $invite_row = $DB->getRow("SELECT * FROM pre_user WHERE zid='{$invite_code}' LIMIT 1");
        $upzid_all = $invite_row['upzid_all']==''?$invite_row['zid']:$invite_row['upzid_all'].'_'.$invite_row['zid'];
        $upzid = $invite_row?$invite_row['zid']:1;
    }elseif($is_fenzhan && !empty($siterow)){//分站：当前域名为某用户 domain/domain2 时，新用户上级为该分站
        $upzid_all = ($siterow['upzid_all'] ?? '') === '' ? $siterow['zid'] : $siterow['upzid_all'].'_'.$siterow['zid'];
        $upzid = $siterow['zid'];
    }else{
        $upzid = '1';
        $upzid_all = '';
    }
    $user_vip = intval($conf['user_vip']);
    if($user_vip >= 1 && $user_vip <=5){
    }else{
        $user_vip = '1';
    }

    $rmb = floatval($conf['user_free']);
    $sql = "INSERT INTO `pre_user` (`email`,`upzid`,`upzid_all`,`user`,`pwd`,`qq`,`vip`,`rmb`,`addtime`,`ip`,`phone`) values ('".$email."','".$upzid."','".$upzid_all."','".$user."','".$pwd."','".$qq."','".$user_vip."','".$rmb."',NOW(),'".$ip."','".$phone."')";
    if($DB->exec($sql)){
        unset($_SESSION["reg_key"]);
        $session=md5($user.$pwd.$password_hash);
        $expiretime=time()+604800;
        $token=authcode("{$user}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
        setcookie("user_token", $token, time() + 604800, '/');
        $_SESSION['reg_time'] = strtotime('+2minute');
        reg_json_out(1, '注册成功', ['user' => $user]);
    }else{
        reg_json_out(-1, '注册失败，'.$DB->error());
    }
}
$key = md5(mt_rand(10,9999).time());
$_SESSION["reg_key"] = $key;

$mail_key = md5(mt_rand(11,9999).time());
$_SESSION["mail_key"] = $mail_key;

$reg_timestamp = time();
$_SESSION["reg_timestamp"] = $reg_timestamp;

$reg_token = md5($reg_timestamp . mt_rand(1000, 9999));
$_SESSION["reg_token"] = $reg_token;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>注册 - <?php echo $conf['sitename'] ?? '管理系统'; ?></title>
    <script src="../assets/js/tailwind.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="min-h-screen bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-600 flex items-center justify-center p-3 sm:p-4">
    
    <div class="w-full max-w-xs sm:max-w-sm md:max-w-md">
        <!-- Logo -->
        <div class="text-center mb-4 sm:mb-6 md:mb-8">
            <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 md:w-20 md:h-20 bg-white/20 backdrop-blur-xl rounded-xl sm:rounded-2xl mb-2 sm:mb-3 md:mb-4 shadow-lg">
                <i class="fas fa-user-plus text-xl sm:text-2xl md:text-3xl text-white"></i>
            </div>
            <h1 class="text-lg sm:text-xl md:text-2xl font-bold text-white"><?php echo $conf['sitename'] ?? '管理系统'; ?></h1>
            <p class="text-purple-200 text-xs sm:text-sm mt-0.5 sm:mt-1">安全可靠的云端管理平台</p>
        </div>
        
        <!-- 注册卡片 -->
        <div class="bg-white rounded-xl sm:rounded-2xl shadow-2xl p-3 sm:p-4 md:p-6 hover:shadow-2xl/80 transition-shadow">
            <form onsubmit="reg(this);return false;" method="post" class="space-y-2.5 sm:space-y-3 md:space-y-4">
                <input type="hidden" name="key" value="<?php echo $key?>">
                <input type="hidden" name="invite_code" value="<?php echo $invite_code?>">
                <input type="hidden" name="reg_timestamp" value="<?php echo $reg_timestamp?>">
                <input type="hidden" name="reg_token" value="<?php echo $reg_token?>">
                <input type="hidden" name="website_url" value="">
                <input type="hidden" name="browser_info" value="">
                <input type="hidden" name="agree_clause" id="agree_clause" value="0">
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">用户名</label>
                    <div class="relative">
                        <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fas fa-user text-sm"></i>
                        </span>
                        <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                               name="user" required placeholder="建议填写QQ账号">
                    </div>
                </div>
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">登录密码</label>
                    <div class="relative">
                        <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fas fa-lock text-sm"></i>
                        </span>
                        <input type="password" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                               name="pwd" required placeholder="请设置登录密码">
                    </div>
                </div>
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">QQ号</label>
                    <div class="relative">
                        <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fab fa-qq text-sm"></i>
                        </span>
                        <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                               name="qq" required placeholder="(别乱填写)如忘记密码可用于找回">
                    </div>
                </div>
                
                <?php if($conf['regcode']==1 || $conf['regphonecode']==1){?>
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">图形验证码</label>
                    <div class="flex gap-2 sm:gap-3">
                        <div class="flex-1 relative">
                            <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                <i class="fas fa-shield-alt text-sm"></i>
                            </span>
                            <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                   name="verifycode" required placeholder="请输入验证码">
                        </div>
                        <div class="flex-shrink-0">
                            <img src="./simple_code.php?r=<?php echo time();?>" height="50" class="h-9 sm:h-10 md:h-12 rounded-lg sm:rounded-xl cursor-pointer hover:opacity-90 transition-opacity"
                                 onclick="this.src='./simple_code.php?r='+Math.random();"
                                 title="点击更换验证码">
                        </div>
                    </div>
                </div>
                <?php }?>
                
                <?php if($conf['regphonecode']==1){?>
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">手机号码</label>
                    <div class="flex gap-2 sm:gap-3">
                        <div class="flex-1 relative">
                            <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                <i class="fas fa-phone text-sm"></i>
                            </span>
                            <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                   name="phone" required placeholder="请输入手机号码">
                        </div>
                        <div class="flex-shrink-0">
                            <button type="button" onclick="check_send_sms()"
                                    class="h-9 sm:h-10 md:h-12 px-3 sm:px-4 text-xs sm:text-sm bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white rounded-lg sm:rounded-xl font-medium transition-all shadow-sm hover:shadow-md">
                                发送
                            </button>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">短信验证码</label>
                    <div class="relative">
                        <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fas fa-sms text-sm"></i>
                        </span>
                        <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                               name="phonecode" required placeholder="短信验证码">
                    </div>
                </div>
                <?php }elseif($conf['reg_email_open']==1){?>
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">邮箱地址</label>
                    <div class="flex gap-2 sm:gap-3">
                        <div class="flex-1 relative">
                            <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                <i class="fas fa-envelope text-sm"></i>
                            </span>
                            <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                                   name="email_user" required placeholder="请填写邮箱地址">
                        </div>
                        <div class="flex-shrink-0">
                            <button type="button" onclick="send_email('<?php echo $mail_key?>')"
                                    class="h-9 sm:h-10 md:h-12 px-3 sm:px-4 text-xs sm:text-sm bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white rounded-lg sm:rounded-xl font-medium transition-all shadow-sm hover:shadow-md">
                                发送
                            </button>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-0.5 sm:mb-1">邮箱验证码</label>
                    <div class="relative">
                        <span class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fas fa-key text-sm"></i>
                        </span>
                        <input type="text" class="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm border border-gray-200 rounded-lg sm:rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
                               name="email_code" required placeholder="邮箱验证码">
                    </div>
                </div>
                <?php }?>

                <!-- 强制免责条款 -->
                <?php $reg_clause_open = $conf['reg_clause_open'] ?? '1'; ?>
                <?php if($reg_clause_open == '1' || $reg_clause_open == '2'){ ?>
                <div class="flex items-start gap-1.5 sm:gap-2 mt-1 sm:mt-2">
                    <input type="checkbox" id="agree_check" disabled
                           class="mt-0.5 sm:mt-1 rounded text-indigo-600 focus:ring-indigo-500 cursor-not-allowed">
                    <div class="text-xs sm:text-sm text-gray-600">
                        <label for="agree_check" class="cursor-not-allowed">
                            我已阅读并同意（点击下方蓝色字体，阅读后可勾选）
                        </label>
                        <button type="button" onclick="showForceClause()" 
                                class="text-indigo-600 hover:text-indigo-800 underline ml-1">
                            《QQ账号授权使用免责条款》
                        </button>
                    </div>
                </div>
                <?php } ?>
                
                <button type="submit" 
                        class="w-full py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm md:text-base bg-gradient-to-r from-green-600 to-teal-600 hover:from-green-700 hover:to-teal-700 text-white font-medium sm:font-semibold rounded-lg sm:rounded-xl shadow transition-all">
                    <i class="fas fa-user-plus mr-1 sm:mr-2"></i>注册账号
                </button>
            </form>
            
            <div class="mt-3 sm:mt-4 md:mt-6 text-center text-xs sm:text-sm text-gray-500 space-x-4 sm:space-x-6">
                <a href="./login.php" class="hover:text-indigo-600 transition-colors">
                    <i class="fas fa-sign-in-alt mr-0.5 sm:mr-1"></i>已有账号？去登录
                </a>
                <a href="./" class="hover:text-indigo-600 transition-colors">
                    <i class="fas fa-home mr-0.5 sm:mr-1"></i>返回首页
                </a>
            </div>
        </div>
        
        <div class="text-center mt-4 sm:mt-6 md:mt-8 text-white/70 text-xs sm:text-sm hover:text-white/90 transition-colors">
            &copy; <?php echo date('Y'); ?> <?php echo $conf['sitename'] ?? '管理系统'; ?>
        </div>
    </div>
</body>
</html>

<!-- 模态框 -->
<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 transition-opacity"></div>
    <div class="fixed inset-0 flex items-center justify-center p-3 sm:p-4">
        <div class="bg-white rounded-xl sm:rounded-2xl shadow-2xl w-full max-w-xs sm:max-w-sm md:max-w-md max-h-[85vh] flex flex-col relative transform transition-all">
            <div class="flex items-center justify-between px-3 sm:px-4 md:px-5 py-3 md:py-4 border-b border-gray-100">
                <h3 id="modalTitle" class="text-sm sm:text-base md:text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-6 h-6 sm:w-7 sm:h-7 md:w-8 md:h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times text-sm"></i>
                </button>
            </div>
            <div id="modalBody" class="px-3 sm:px-4 md:px-5 py-3 md:py-4 overflow-y-auto text-xs sm:text-sm" style="max-height: 60vh;"></div>
            <div id="modalFooter" class="px-3 sm:px-4 md:px-5 py-2 sm:py-3 border-t border-gray-100"></div>
        </div>
    </div>
</div>

<!-- Toast -->
<div id="toastWrap" class="fixed top-4 sm:top-6 left-1/2 -translate-x-1/2 z-[60] flex flex-col items-center gap-2"></div>
<div id="loadingOverlay" class="fixed inset-0 z-50 hidden bg-white/30 flex items-center justify-center">
    <div class="w-8 h-8 sm:w-10 sm:h-10 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
</div>

<script src="../assets/js/jquery.min.js"></script>
<script type="text/javascript">
var regGonggao = <?php echo json_encode(html_entity_decode($conf['reg_gg'] ?? '')); ?>;
var regClauseOpen = <?php echo json_encode($conf['reg_clause_open'] ?? '1'); ?>;

// 免责条款
var clauseContent = <?php echo json_encode(html_entity_decode($conf['reg_clause_content'] ?? '')); ?>;

var canCloseClause = false;
var countdown = 5;

function showForceClause() {
    var isLargeScreen = window.innerWidth >= 1024;
    var needCountdown = regClauseOpen == '2';
    canCloseClause = isLargeScreen || !needCountdown;
    countdown = 5;
    $('#agree_check').prop('disabled', true).prop('checked', false);
    $('#agree_clause').val('0');

    var btnText = needCountdown ? `请阅读完整条款（${countdown}秒）` : '我已阅读并同意';
    var btnDisabled = needCountdown ? 'disabled' : '';
    var btnClass = needCountdown ? 'bg-gray-400' : 'bg-indigo-600 hover:bg-indigo-700';

    openModal('QQ账号授权使用免责条款', clauseContent, function() {
        return `<button id="clauseConfirmBtn" ${btnDisabled} class="w-full py-2 text-sm ${btnClass} text-white rounded-lg font-medium">${btnText}</button>`;
    });

    if (needCountdown) {
        var timer = setInterval(function() {
            countdown--;
            if (countdown <= 0) {
                clearInterval(timer);
                $('#clauseConfirmBtn').removeClass('bg-gray-400').addClass('bg-indigo-600 hover:bg-indigo-700').removeAttr('disabled').text('我已阅读并同意');
            } else {
                $('#clauseConfirmBtn').text(`请阅读完整条款（${countdown}秒）`);
            }
        }, 1000);
    }

    if (!isLargeScreen && needCountdown) {
        var checkScroll = function() {
            var el = $('#modalBody')[0];
            if (!el) return;
            if (el.scrollHeight <= el.clientHeight + 5) {
                canCloseClause = true;
            } else if (el.scrollTop + el.clientHeight >= el.scrollHeight - 5) {
                canCloseClause = true;
            }
        };
        $('#modalBody').on('scroll', checkScroll);
        setTimeout(checkScroll, 100);
    }

    $(document).off('click', '#clauseConfirmBtn').on('click', '#clauseConfirmBtn', function() {
        if (!canCloseClause) {
            showToast('请滑动到条款最底部再确认', 'error');
            return;
        }
        $('#agree_check').prop('disabled', false).prop('checked', true);
        $('#agree_clause').val('1');
        closeModal();
        showToast('已同意条款，可注册', 'success');
    });
}

// 通用弹窗
function openModal(title, content, footerCallback) {
    $('#modalTitle').text(title);
    $('#modalBody').html(content);
    $('#modalFooter').html(footerCallback()).show();
    $('#appModal').removeClass('hidden');
    $('body').css('overflow', 'hidden');
}

function closeModal() {
    $('#appModal').addClass('hidden');
    $('body').css('overflow', '');
}

// Toast
function showToast(message, type = 'info', duration = 2000) {
    const t = $('<div class="bg-' + (type==='success'?'green-600':type==='error'?'red-600':'gray-800') + ' text-white px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm rounded-lg shadow-lg opacity-0 translate-y-[-10px] transition-all">' + message + '</div>');
    $('#toastWrap').append(t);
    setTimeout(() => t.removeClass('opacity-0 translate-y-[-10px]'), 10);
    setTimeout(() => { t.addClass('opacity-0 translate-y-[-10px]'); setTimeout(() => t.remove(), 300); }, duration);
}

function showLoading(){$('#loadingOverlay').removeClass('hidden');}
function hideLoading(){$('#loadingOverlay').addClass('hidden');}

// 注册提交
function reg(obj){
    if((regClauseOpen == '1' || regClauseOpen == '2') && $('#agree_clause').val() != '1'){
        showToast('请先阅读并同意免责条款', 'error');
        return false;
    }
    showLoading();
    var browserInfo = {userAgent:navigator.userAgent,language:navigator.language,platform:navigator.platform,screen:screen.width+'x'+screen.height};
    $('input[name="browser_info"]').val(JSON.stringify(browserInfo));
    $.ajax({
        type:'POST', url:'reg.php?act=reg', data:$(obj).serialize(), dataType:'json',
        success:function(data){
            hideLoading();
            data.code==1 ? openModal('成功',data.msg,()=>'<button onclick="window.location.href=\'./\'" class="w-full py-2 text-sm bg-indigo-600 text-white rounded-lg">进入后台</button>') : showToast(data.msg,'error');
        },error:function(){hideLoading();showToast('请求失败','error');}
    });
}

// 短信/邮箱
function check_send_sms(){
    var p=$('input[name="phone"]').val(),c=$('input[name="verifycode"]').val(),k=$('input[name="key"]').val();
    if(!c||!p||p.length!=11){showToast('请正确填写手机号与验证码','error');return;}
    showLoading();
    $.post('reg.php?act=send_sms',{phone:p,verifycode:c,key:k},function(d){hideLoading();showToast(d.msg,d.code==1?'success':'error');},'json');
}
function send_email(key){
    var e=$('input[name="email_user"]').val();
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){showToast('邮箱格式错误','error');return;}
    var data = {email:e,key:key};
    var $vc = $('input[name="verifycode"]');
    if($vc.length){ data.verifycode = ($vc.val()||'').trim(); }
    showLoading();
    $.post('reg.php?act=send_email', data, function(d){hideLoading();showToast(d.msg,d.code==1?'success':'error');},'json');
}

// 页面加载完成后显示注册公告
$(document).ready(function(){
    if(regGonggao && regGonggao.trim() !== ''){
        openModal('公告', regGonggao, function(){
            return '<button onclick="closeModal()" class="w-full py-2 text-sm bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium">我知道了</button>';
        });
    }
});
</script>
