<?php
// 直接处理滑块验证结果
if(isset($_POST['ticket']) && isset($_POST['randstr'])){
    error_reporting(0);
    $qq = isset($_POST['qq'])?trim($_POST['qq']):null;
    $ticket = isset($_POST['ticket'])?trim($_POST['ticket']):null;
    $randstr = isset($_POST['randstr'])?trim($_POST['randstr']):null;
    $cid = isset($_POST['cid'])?trim($_POST['cid']):1;
    
    if(!$qq || !$ticket){
        echo json_encode(['code' => -1, 'msg' => '参数不能为空']);
        exit;
    }
    
    // 加载配置
    require_once '../config.php';
    require_once '../includes/robot_fun.php';
    require_once '../includes/function.php';
    
    // 获取登录接口
    $login = $DB->getRow("SELECT * FROM `pre_loginconfig` WHERE status='1' ORDER BY id LIMIT 1");
    if(!$login){
        echo json_encode(['code' => -1, 'msg' => '未找到可用的登录接口']);
        exit;
    }
    
    // 提交滑块验证
    $ret = curl_frame($login, 'submit_ticket', [
        'qq' => $qq,
        'ticket' => $ticket,
        'randstr' => $randstr
    ]);
    
    // 检查返回状态
    $final_code = $ret['code'] ?? -1;
    $final_msg = $ret['msg'] ?? '未知错误';
    
    // 处理不同的返回状态
    if($final_code == 1){
        // 登录成功，更新pre_qq表
        $qqrow = $DB->getRow("SELECT * FROM `pre_qq` WHERE qq='{$qq}' LIMIT 1");
        $c = $DB->getRow("SELECT * FROM `pre_login_class` WHERE id='{$cid}' LIMIT 1");
        if($qqrow){  	//已经存在
            $end = json_decode($qqrow['endtime_arr'],true);
            $cidstr = $c['id'].'-';
            if(stripos($c['cid'],$cidstr)==false){
                if(intval($c['free']) >= 1){ //免费体验					
                    if(!isset($end[$cid])){
                        $end[$cid] = date('Y-m-d H:i:s',strtotime(intval($c['free']).' day'));
                    }
                }
            }
            $end = json_encode($end);
            $DB->exec("UPDATE `pre_qq` SET endtime_arr='{$end}',`login_zt`='1',`cityid`='{$login['id']}',`protocol`='1',`uptime`= NOW() WHERE qq='{$qqrow['qq']}'");
        }else{
            if(intval($c['free']) >= 1){ //免费体验
                $endtime_arr[$cid] = date('Y-m-d H:i:s',strtotime(intval($c['free']).' day'));
            }else{
                $endtime_arr[$cid] = date('Y-m-d H:i:s',strtotime('+1 day'));
            }
            $DB->exec("INSERT INTO `pre_qq` (`dropline`,`login_zt`,`zid`,`qq`,`cityid`,`protocol`,`addtime`,`endtime_arr`) VALUES ('0', '1', '1', '{$qq}', '{$login['id']}', '1', NOW(), '".json_encode($endtime_arr)."')");
        }
        
        // 处理免费体验记录
        if(intval($c['free']) >= 1){ //免费体验
            $old = $DB->getRow("SELECT * FROM `pre_old_qq` WHERE qq='{$qq}'");
            $cidarr = explode('-',$old['cid']);
            if($old && !in_array($cid,$cidarr)){
                $ocid = strval($old['cid']).'-'.strval($cid);
                $DB->exec("UPDATE `pre_old_qq` SET cid='{$ocid}' WHERE qq='{$qq}'");
            }elseif(!$old){
                $DB->exec("INSERT INTO pre_old_qq (`zid`, `cid`, `qq`, `addtime`) VALUES ('1','1', '{$qq}', NOW())");
            }
        }
        
        // 初始化QQ配置
        $qqconf = $DB->getColumn("SELECT count(*) FROM `pre_frame_qqconf` WHERE qq='{$qq}'");
        if($qqconf==0){
            $DB->exec("INSERT INTO `pre_frame_qqconf` (`zid`,`qq`,`massmsg_open`,`massmsg_delay`,`addtime`) VALUES('1','{$qq}','1','2000',NOW())");
        }
        
        echo json_encode(['code' => 1, 'msg' => '登录成功']);
        exit;
    }elseif($final_code == 2 && isset($ret['ticket_url'])){
        // 还需要滑块验证
        echo json_encode([
            'code' => 20,
            'msg' => '需要执行滑块验证',
            'qq' => $qq,
            'hkurl' => $ret['ticket_url'],
            'orderno' => $qq
        ]);
        exit;
    }elseif($final_code == 10){
        // 需要短信验证码
        echo json_encode([
            'code' => 10,
            'msg' => '需要短信验证码',
            'qq' => $qq,
            'orderno' => $qq
        ]);
        exit;
    }else{
        // 其他错误
        echo json_encode(['code' => -1, 'msg' => $final_msg]);
        exit;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>滑块验证码</title>
    <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 400px;
            margin: 0 auto;
            text-align: center;
        }
        #status {
            margin: 20px 0;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>滑块验证码</h2>
        <div id="status">正在加载验证码...</div>
    </div>
    
    <script>
        // 获取URL参数
        function getUrlParam(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]);
            return null;
        }
        
        var qq = getUrlParam('qq') || '0';
        var aid = getUrlParam('aid') || '16';
        var cid = getUrlParam('cid') || '1';
        
        // 初始化腾讯滑块验证
        var captcha = new TencentCaptcha(aid, function(res) {
            var statusDiv = document.getElementById('status');
            
            if (res.ret === 0) {
                // 验证成功，提交结果
                statusDiv.innerHTML = '验证成功，正在提交...';
                statusDiv.className = 'success';
                
                // 发送请求到服务器
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'submit_ticket.php', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response.code === 1) {
                            statusDiv.innerHTML = '登录成功！';
                            // 通知父窗口
                            if (window.parent && window.parent.getticket) {
                                window.parent.getticket({
                                    randstr: res.randstr,
                                    ticket: res.ticket,
                                    orderno: qq
                                });
                            } else {
                                // 直接跳转到列表页
                                setTimeout(function() {
                                    window.location.href = './';
                                }, 1000);
                            }
                        } else {
                            statusDiv.innerHTML = '错误：' + response.msg;
                            statusDiv.className = 'error';
                        }
                    }
                };
                xhr.send('qq=' + qq + '&ticket=' + res.ticket + '&randstr=' + res.randstr + '&cid=' + cid);
            } else {
                // 验证失败
                statusDiv.innerHTML = '验证失败，请重试';
                statusDiv.className = 'error';
            }
        });
        
        // 显示验证码
        captcha.show();
        
        // 更新状态
        document.getElementById('status').innerHTML = '请完成滑块验证';
    </script>
</body>
</html>