<?php
header('Content-Type: application/json; charset=UTF-8');
ini_set('default_charset', 'UTF-8');

// 配置区
define('AES_KEY', 'qqqqtgviqqqqtgvi');
define('AES_IV', 'tgviqqqqtgviqqqq');
define('LOG_FILE', __DIR__ . '/telegram_log.txt');

// 日志开关
define('IsOutputLogs', true);

// 统一封装日志
function writeLog($content) {
    if (!IsOutputLogs) return;
    $time = date('Y-m-d H:i:s');
    $logStr = "[$time] " . print_r($content, true) . "\n----------------------------------------\n";
    file_put_contents(LOG_FILE, $logStr, FILE_APPEND | LOCK_EX);
}

// 接收原始请求
$rawInput = file_get_contents('php://input');
writeLog('【原始请求数据】：' . $rawInput);

$params = json_decode($rawInput, true);

// 参数校验
if (empty($params['token']) || empty($params['chatid']) || empty($params['text']) || empty($params['parse_mode'])) {
    $msg = '参数缺失：token/chatid/text/parse_mode 不能为空';
    writeLog('【错误】' . $msg);
    http_response_code(400);
    echo json_encode(['code' => 400, 'msg' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

// 异步响应
ignore_user_abort(true);
set_time_limit(30);
ob_start();
echo json_encode(['code' => 200, 'msg' => '已接收，后台异步发送'], JSON_UNESCAPED_UNICODE);
$size = ob_get_length();
header("Connection: close");
header("Content-Length: $size");
ob_end_flush();
flush();

// 解密函数
function aesDecryptFromHex($encryptedHex, $key, $iv) {
    try {
        $encrypted = hex2bin($encryptedHex);
        if ($encrypted === false) return false;

        $keyByte = mb_convert_encoding($key, 'ASCII', 'auto');
        $ivByte  = mb_convert_encoding($iv, 'ASCII', 'auto');

        $decrypted = openssl_decrypt(
            $encrypted,
            'aes-128-cbc',
            $keyByte,
            OPENSSL_RAW_DATA,
            $ivByte
        );
        return $decrypted !== false ? trim($decrypted) : false;
    } catch (Exception $e) {
        return false;
    }
}

// 解密
$decrypted = [
    'token'     => aesDecryptFromHex($params['token'], AES_KEY, AES_IV),
    'chatid'    => aesDecryptFromHex($params['chatid'], AES_KEY, AES_IV),
    'text'      => aesDecryptFromHex($params['text'], AES_KEY, AES_IV),
    'parse_mode'=> aesDecryptFromHex($params['parse_mode'], AES_KEY, AES_IV),
];

writeLog('【解密后数据】：' . print_r($decrypted, true));

if (in_array(false, $decrypted, true)) {
    writeLog('【错误】AES 解密失败');
    exit;
}

// 发送 Telegram（已删除 curl_close）
function sendTelegramMessage($token, $chatId, $text, $parseMode) {
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $postData = [
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => $parseMode
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    
    // 关闭SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    writeLog([
        'API地址' => $url,
        '参数'    => $postData,
        'HTTP'    => $httpCode,
        '错误'    => $curlError ?: '无',
        '返回'    => $response
    ]);

    return $response;
}

sendTelegramMessage(
    $decrypted['token'],
    $decrypted['chatid'],
    $decrypted['text'],
    $decrypted['parse_mode']
);

writeLog('【流程结束】消息发送完成');
?>