<?php
include dirname(__DIR__) . '/includes/common.php';
$time = $_SESSION['oauth_arr']['time'];
if(time() > $time)exit("cookie失效，请重新使用快捷登录");
$data = $_SESSION['oauth_arr']['data'];
if(!is_array($data))exit("快捷登录失效");
$openid = $data['social_uid'];
if($_GET['act'] == 'oauth'){
    $user=daddslashes($_POST['user']);
    $pwd=daddslashes($_POST['pwd']);
    $qq=daddslashes($_POST['qq']);
    $openid_type = $data['type'];
    $row = $DB->getRow("SELECT * FROM pre_user WHERE user='{$user}' limit 1");
    if($row){
        if($row['pwd'] != $pwd)exit('{"code":-1,"msg":"密码错误"}');

        $DB->exec("UPDATE `pre_user` SET openid_".$openid_type."='{$openid}' WHERE zid='{$row['zid']}'");
        $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, '/');
        exit('{"code":1,"msg":"绑定成功"}');
    }else{

        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":"用户名和密码不能相同！"}');
        }

        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']);
        $openid_field = 'openid_' . $openid_type;
        $sql = "INSERT INTO `pre_user` (`upzid`,`upzid_all`,`user`,`pwd`,`qq`,`vip`,`rmb`,`{$openid_field}`,`addtime`) values ('".$upzid."','".$upzid_all."','".$user."','".$pwd."','".$qq."','".$user_vip."','".$rmb."','".$openid."',NOW())";
        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, '/');
            exit('{"code":1,"user":"'.$user.'","msg":"注册成功"}');
        }else{
            exit('{"code":-1,"msg":"注册失败，'.$DB->error().'"}');
        }
    }

}elseif($_GET['act'] == 'check_user'){
    $user=daddslashes($_POST['user']);
    $row = $DB->getRow("SELECT * FROM pre_user WHERE user='{$user}' limit 1");
    if($row){
        exit('{"code":1,"qq":"'.$row['qq'].'"}');
    }else{
        exit('{"code":-1}');
    }
}
?>
<!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-link 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">openID</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-fingerprint 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 bg-gray-50"
                               name="openid" value="<?php echo $openid?>" disabled="disabled">
                    </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-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"
                               id="user" 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 id="showqq" style="display: none;">
                    <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"
                               id="qq" name="qq" placeholder="如忘记密码可用于找回">
                    </div>
                </div>
                
                <button type="submit" id="sub"
                        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-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-medium sm:font-semibold rounded-lg sm:rounded-xl shadow transition-all">
                    <i class="fas fa-link 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>
    
    <!-- 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>
</body>
</html>
<script src="../assets/js/jquery.min.js"></script>
<script type="text/javascript">
    function debounce(fn, delay) {
        let that = this
        let timer = null
        return function () {
            let args = arguments
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(that, args)
            }, delay)
        }
    }
    let debounceTest = debounce(check_qq,600);
    document.querySelector('#user').addEventListener('input', (e) => {
        debounceTest(e.target.value)
    })
    function check_qq(e){
        $.ajax({
            type : 'POST',
            url : '?act=check_user',
            data : {user:$('#user').val()},
            dataType : 'json',
            success : function(data){
                if(data.code == 1){
                    $('#qq').removeAttr('required');
                    $('#sub').html('<i class="fas fa-link mr-1 sm:mr-2"></i>绑定');
                    $('#showqq').hide();
                }else{
                    $('#qq').attr('required',"true");
                    $('#sub').html('<i class="fas fa-user-plus mr-1 sm:mr-2"></i>注册账号');
                    $('#showqq').show();
                }
            }
        });
    }
    function reg(obj){
        showLoading();
        $.ajax({
            type : 'POST',
            url : '?act=oauth',
            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');
            }
        });     
    }
    
    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);
    }
    
    function showLoading() {
        document.getElementById('loadingOverlay').classList.remove('hidden');
    }
    
    function hideLoading() {
        document.getElementById('loadingOverlay').classList.add('hidden');
    }
</script>
