<?php
/**
 * 秒赞扫码登录节点入口（无需数据库，解压即用）
 * 仅负责向 QQ 拉取二维码和扫码结果，主站负责写库。部署后将该地址填到主站后台「节点设置」即可。
 */
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
date_default_timezone_set('Asia/Shanghai');
header('Content-Type: application/json; charset=UTF-8');

$lib = __DIR__ . '/lib/QzoneLoginService.php';
if (!is_file($lib)) {
    exit(json_encode(['code' => -1, 'msg' => '缺少 lib/QzoneLoginService.php，请使用完整压缩包部署']));
}
require_once $lib;

$act = isset($_GET['act']) ? trim((string)$_GET['act']) : '';

if ($act === 'get_qrcode') {
    $login = new QzoneLoginService();
    $result = $login->getqrpic();
    if (isset($result['saveOK']) && $result['saveOK'] == 0) {
        exit(json_encode(['code' => 0, 'qrsig' => $result['qrsig'], 'image' => $result['image']]));
    }
    exit(json_encode(['code' => -1, 'msg' => $result['msg'] ?? '获取二维码失败']));
}

if ($act === 'check_qrlogin') {
    $qrsig = isset($_POST['qrsig']) ? trim((string)$_POST['qrsig']) : '';
    if ($qrsig === '') {
        exit(json_encode(['code' => -1, 'msg' => '参数错误']));
    }
    $login = new QzoneLoginService();
    $result = $login->qrlogin($qrsig);

    if (isset($result['saveOK']) && $result['saveOK'] == 0) {
        $uin = $result['uin'] ?? '';
        $skey = $result['skey'] ?? '';
        $pskey = $result['pskey'] ?? '';
        $superkey = $result['superkey'] ?? '';
        $nickname = $result['nickname'] ?? '';
        if (empty($uin) || !is_numeric($uin) || $uin == '0') {
            exit(json_encode(['code' => -1, 'msg' => 'QQ号无效']));
        }
        exit(json_encode([
            'code' => 0,
            'msg' => '登录成功',
            'uin' => $uin,
            'skey' => $skey,
            'pskey' => $pskey,
            'superkey' => $superkey,
            'nickname' => $nickname
        ]));
    }
    if (isset($result['saveOK']) && $result['saveOK'] == 1) exit(json_encode(['code' => 1, 'msg' => '二维码已过期']));
    if (isset($result['saveOK']) && $result['saveOK'] == 2) exit(json_encode(['code' => 2, 'msg' => '等待扫码']));
    if (isset($result['saveOK']) && $result['saveOK'] == 3) exit(json_encode(['code' => 3, 'msg' => '等待确认']));
    exit(json_encode(['code' => -1, 'msg' => $result['msg'] ?? '登录失败']));
}

exit(json_encode(['code' => -1, 'msg' => '无效操作']));
