<?php
include dirname(__DIR__) . '/includes/common.php';
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>");
}
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;

if($act == 'reg'){
    // 强制校验是否已阅读条款
    $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'){
        exit('{"code":-1,"msg":"请阅读并同意QQ账号授权使用免责条款"}');
    }

    $user=daddslashes($_POST['user']);
    $pwd=daddslashes($_POST['pwd']);
    $qq=daddslashes($_POST['qq']);
    $km=daddslashes($_POST['km']);


    if (!preg_match('/^[a-zA-Z0-9\x7f-\xff]+$/',$user)) {
        exit('{"code":-1,"msg":"用户名只能为英文、数字与汉字！"}');
    } elseif ($DB->getRow("SELECT zid FROM pre_user WHERE user=:user LIMIT 1", [':user'=>$user])) {
        exit('{"code":-1,"msg":"用户名已存在！"}');
    } elseif (strlen($pwd) < 6) {
        exit('{"code":-1,"msg":"密码不能低于6位"}');
    } elseif (strlen($qq) < 4 || !preg_match('/^[0-9]+$/',$qq)) {
        exit('{"code":-1,"msg":"QQ格式不正确！"}');
    } elseif ($pwd == $user) {
        exit('{"code":-1,"msg":"用户名和密码不能相同！"}');
    }
    $kmrow = $DB->getRow("SELECT * FROM `pre_km` WHERE km='{$km}' LIMIT 1");
    if(!$kmrow)exit('{"code":-1,"msg":"卡密不存在"}');
    if($kmrow['isuse'] == '1')exit('{"code":-1,"msg":"该卡密已经被使用"}');
    
    if($kmrow['zid'] == 1 && $kmrow['time_num'] >= 1){//主站卡密-自定义时长
        $goods['time_type'] = $kmrow['time'];//时长类型
        $goods['num'] = $kmrow['time_num'];//值
        // 自定义卡密，shopid保存的是分类ID，直接作为type使用
        $goods['type'] = $kmrow['shopid'];
    }else{
        $tmp_goods = $DB->getRow("SELECT * FROM `pre_goods` WHERE id='{$kmrow['shopid']}' LIMIT 1");
        if(!$tmp_goods)exit('{"code":-1,"msg":"该卡密关联的商品已被删除,请联系管理员进行更换新的卡密。"}');
        $goods = $tmp_goods;
    }

    if($is_fenzhan && !empty($siterow)){
        $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)){

        $id = $DB->lastInsertId();
        $qqrow = $DB->getRow("SELECT id,zid,endtime_arr FROM pre_qq WHERE qq='{$qq}' LIMIT 1");
        if($qqrow){
            $endtime_arr = edit_endtime($goods,$qqrow['endtime_arr']);
            $sql = "UPDATE `pre_qq` SET `endtime_arr`='{$endtime_arr}' WHERE qq='{$qq}'";
        }else{
            $endtime_arr = edit_endtime($goods,'{"'.$goods['type'].'":"2025-05-20 13:14:00"}');
            $sql = "INSERT INTO `pre_qq` (`zid`,`qq`,`addtime`,`endtime_arr`) VALUES ('".$id."', '".$qq."', NOW(), '".$endtime_arr."')";
        }
        if($DB->exec($sql)){
            $DB->exec("UPDATE `pre_km` SET `isuse`='1', `qq`='{$qq}', `usetime`=NOW() WHERE km='{$km}'");
            add_money_log($id,'卡密','卡密','0.00','0.00','0.00','QQ='.$qq.',km='.$km.',卡密激活['.$kmrow['name'].']');
            if($conf['kami_tc'] == 1 && $kmrow['zid'] != 1 && floatval($kmrow['tc_rmb']) > 0){
                // 使用预存的提成金额发放给上级
                $km_creator = $DB->getRow("SELECT upzid FROM pre_user WHERE zid='{$kmrow['zid']}' LIMIT 1");
                if($km_creator && $km_creator['upzid'] > 1){
                    $upzid = $km_creator['upzid'];
                    $up_user = $DB->getRow("SELECT zid, rmb_tc FROM pre_user WHERE zid='{$upzid}' LIMIT 1");
                    if($up_user){
                        $tc_rmb = floatval($kmrow['tc_rmb']);
                        $DB->exec("UPDATE pre_user SET `rmb_tc`=`rmb_tc`+'{$tc_rmb}' WHERE zid='{$upzid}'");
                        add_money_log($upzid,'佣金','提成',$tc_rmb,$up_user['rmb_tc'],($up_user['rmb_tc']+$tc_rmb),'用户='.$kmrow['zid'].',QQ='.$qq.',卡密激活['.$kmrow['name'].']');
                    }
                }
            }
        }

        $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');
        exit('{"code":1,"user":"'.$user.'","msg":"注册成功"}');
    }else{
        exit('{"code":-1,"msg":"注册失败，'.$DB->error().'"}');
    }
}
?>
<!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-key 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">
                <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="请定义一个登录账号">
                    </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="输入需要登录云端的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-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="km" required placeholder="请输入卡密">
                    </div>
                </div>
                
                <!-- 强制免责条款 -->
                <?php $reg_clause_open = $conf['reg_clause_open'] ?? '1'; ?>
                <?php if($reg_clause_open == '1' || $reg_clause_open == '2'){ ?>
                <input type="hidden" name="agree_clause" id="agree_clause" value="0">
                <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" onclick="closeModal()"></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"></div>
            <div id="modalFooter" class="px-3 sm:px-4 md:px-5 py-2 sm:py-3 border-t border-gray-100 hidden"></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>

<!-- Loading 遮罩 -->
<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 = document.getElementById('modalBody');
            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');
    });
}

// Toast 提示函数
function showToast(message, type = 'info', duration = 2000) {
    const toastWrap = document.getElementById('toastWrap');
    const toast = document.createElement('div');
    
    let bgClass = 'bg-gray-800';
    if (type === 'success') bgClass = 'bg-green-600';
    if (type === 'error') bgClass = 'bg-red-600';
    if (type === 'warning') bgClass = 'bg-yellow-600';
    
    toast.className = `${bgClass} text-white px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm rounded-lg shadow-lg flex items-center gap-1.5 transform transition-all duration-300 ease-in-out opacity-0 translate-y-[-10px]`;
    toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'exclamation' : type === 'warning' ? 'exclamation-triangle' : 'info'}"></i><span>${message}</span>`;
    
    toastWrap.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.remove('opacity-0', 'translate-y-[-10px]');
    }, 10);
    
    setTimeout(() => {
        toast.classList.add('opacity-0', 'translate-y-[-10px]');
        setTimeout(() => {
            toastWrap.removeChild(toast);
        }, 300);
    }, duration);
}

// Loading 遮罩函数
function showLoading() {
    document.getElementById('loadingOverlay').classList.remove('hidden');
}

function hideLoading() {
    document.getElementById('loadingOverlay').classList.add('hidden');
}

// 模态框相关函数
function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

// 显示注册弹窗公告
$(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 transition-colors">我知道了</button>';
        });
    }
});

// 注册提交
function reg(obj){
    if((regClauseOpen == '1' || regClauseOpen == '2') && $('#agree_clause').val() != '1'){
        showToast('请先阅读并同意免责条款', 'error');
        return false;
    }
    showLoading();
    $.ajax({
        type : 'POST',
        url : 'reg_km.php?act=reg',
        data : $(obj).serialize(),
        dataType : 'json',
        success : function(data) {
            hideLoading();
            if(data.code == '1'){
                showToast(data.msg, 'success');
                setTimeout(function() {
                    window.location.href='./';
                }, 1500);
            }else{
                showToast(data.msg, 'error');
            }
        },
        error:function(data){
            hideLoading();
            showToast('请求超时', 'error');
        }
    });     
}
</script>
