<?php
error_reporting(0);

$_GET && SafeFilter($_GET);
$_POST && SafeFilter($_POST);
$_COOKIE && SafeFilter($_COOKIE);
function SafeFilter(&$arr)
{
    $ra = array("/([\\x00-\\x08,\\x0b-\\x0c,\\x0e-\\x19])/", "/script/", "/javascript/", "/vbscript/", "/expression/", "/applet/", "/meta/", "/xml/", "/blink/", "/link/", "/style/", "/embed/", "/object/", "/frame/", "/layer/", "/title/", "/bgsound/", "/base/", "/onload/", "/onunload/", "/onchange/", "/onsubmit/", "/onreset/", "/onselect/", "/onblur/", "/onfocus/", "/onabort/", "/onkeydown/", "/onkeypress/", "/onkeyup/", "/onclick/", "/ondblclick/", "/onmousedown/", "/onmousemove/", "/onmouseout/", "/onmouseover/", "/onmouseup/", "/onunload/");
    if (is_array($arr)) {
        foreach ($arr as $key => $value) {
            if (!is_array($value)) {
                // 移除废弃的get_magic_quotes_gpc()检查，因为PHP 7.4+已经移除了magic_quotes
                $value = preg_replace($ra, '', $value);
                $arr[$key] = htmlentities(strip_tags($value));
            } else {
                SafeFilter($arr[$key]);
            }
        }
    }
}

require_once "include/core.php";
require_once "include/TelegramBot.php";
//取到提交的功能接口
$mod = isset($_GET['mod']) ? purge($_GET['mod']) : '';

define('LOG_FILE_API', __DIR__ . '/api.log');
function log_api($message, $level = 'INFO')
{
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[{$timestamp}] [{$level}] {$message}\n";
    file_put_contents(LOG_FILE_API, $logMessage, FILE_APPEND | LOCK_EX);
}



function getForwardTelegram()
{

    // 查询配置
    $config = DB::table("sys")->select();
    if (!$config) {
        return "";
    }
    foreach ($config as $value) {

        if ($value["mate_key"] == "forward_telegram") {
            return $value["mate_value"];

        }

    }
    return "";
}

function getForwardEmail()
{

    // 查询配置
    $config = DB::table("sys")->select();
    if (!$config) {
        return "";
    }
    foreach ($config as $value) {

        if ($value["mate_key"] == "forward_email") {
            return $value["mate_value"];

        }

    }
    return "";
}

if ($mod == "push") {
    log_api("接收到推送请求");
    // 获取IP
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    if (!ip2long($ip)) {
        $ip = '未知';
    }
    // 应用ID
    $appId = isset($_GET['appId']) ? purge($_GET['appId']) : '';
    if (!$appId) {
        log_api("校验应用失败");
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 查询应用
    $app = DB::table("app")->where(["id" => $appId])->find();
    if (!$app) {
        log_api("校验应用失败2");
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "应用不存在";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 校验数据签名
    $sign = isset($_GET['sign']) ? purge($_GET['sign']) : '';
    if (!$sign) {
        log_api("校验数据签名失败");
        $result["code"] = "0";
        $result["msg"] = "签名数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $timestamp = isset($_GET['timestamp']) ? purge($_GET['timestamp']) : '';
    if (!$sign) {
        log_api("校验数据签名失败2");
        $result["code"] = "0";
        $result["msg"] = "时间戳校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $data = file_get_contents("php://input");
    $md5 = md5($data . $timestamp . $app["commKey"]);
    if ($md5 != $sign) {
        log_api("校验数据签名失败3");
        $result["code"] = "0";
        $result["msg"] = "签名校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 解密数据
    $decryptData = json_decode(mi_rc4($data, $app["commKey"], 1), true);
    $user = DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->find();

    if (!$user) {
        log_api("校验用户失败");
        $result["code"] = "0";
        $result["msg"] = "账号或密码错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    //log_api("开始解析数据");
    // 解析数据入库
    $order = $decryptData["order"];

    // 解析消息类型
    $notice_type = $decryptData["type"];
    $app = $decryptData["app"];
    //log_api("消息类型".$notice_type);
    // 解析收信账户
    $notice_account = $decryptData["account"];
    //log_api("收信账户".$notice_account);
    // 邮箱
    if (filter_var($notice_account, FILTER_VALIDATE_EMAIL)) {
        //log_api("邮箱用户".$notice_account);
        // 邮件内容
        if ($notice_type == "test_push") {
            //log_api("当前账号:".$decryptData["username"]);

            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n内容:信息接收测试, 接收到本消息则表明测试正常.";



            //log_api("发送消息:".$msg);
            //$bot->sendMessage($chat_id, $msg);
        }
        // 读取注单
        if ($notice_type == "read_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\r\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            //log_api(json_encode($order));
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:读取注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\r\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n盘口:" . $order["ORDER_CON"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\r\n开赛时间:" . $order["G_TIME"];




            $find_cache = DB::table("orders")->where(["TID" => $order["TID"]])->find();
            if (!$find_cache) {
                $database_order["TID"] = $order["TID"];
                $database_order["USERNAME"] = $decryptData["username"];
                $database_order["DATETIME"] = $order["DATETIME"];
                $database_order["NAME0"] = $order["NAME0"];
                $database_order["GT"] = $order["GT"];
                $database_order["WAGERS_TYPE"] = $order["WAGERS_TYPE"];
                $database_order["LEAGUE"] = $order["LEAGUE"];
                $database_order["TEAM_H"] = $order["TEAM_H"];
                $database_order["TEAM_C"] = $order["TEAM_C"];
                $database_order["ORDER_TYPE"] = $order["ORDER_TYPE"];
                $database_order["ORDER_CON"] = $order["ORDER_CON"];
                $database_order["SCORE"] = $order["SCORE"];
                $database_order["IORATIO"] = $order["IORATIO"];
                $database_order["GOLD"] = $order["GOLD"];
                $database_order["SRV_IP"] = $order["SRV_IP"];
                $database_order["SESSION"] = $order["SESSION"];
                $database_order["STAGE"] = $order["STAGE"];
                $database_order["G_TIME"] = $order["G_TIME"];
                $database_order["NUM_C"] = $order["NUM_C"];
                $database_order["NUM_H"] = $order["NUM_H"];
                DB::table("orders")->add($database_order);
                //log_api($user["forward"]);
                if ($user["forward"] == 1) {
                    //log_api("邮箱转发");
                    $forward_email = getForwardEmail();
                    if (filter_var($forward_email, FILTER_VALIDATE_EMAIL)) {
                        sendemail("金运来消息推送", $msg, $forward_email, $back);
                    }
                }
            }




            //$bot->sendMessage($chat_id, $msg);
        }
        // 接收注单
        if ($notice_type == "accept_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:接收注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n盘口:" . $order["ORDER_CON"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"];
            //$bot->sendMessage($chat_id, $msg);
        }
        // 筛选注单
        if ($notice_type == "screen_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:筛选注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n最新比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"] . "\n过滤原因:" . $order["REASON"];
            //$bot->sendMessage($chat_id, $msg);
        }
        // 跟单成功
        if ($notice_type == "bet_order_success") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:跟单成功\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n最新比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO_NEW"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"];
            // $bot->sendMessage($chat_id, $msg);
        }
        // 跟单失败
        if ($notice_type == "bet_order_failed") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:跟单失败\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO_NEW"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"] . "\n失败原因:" . $order["REASON"];
            // $bot->sendMessage($chat_id, $msg);
        }
        // 账户掉线
        if ($notice_type == "account_dissconnected") {
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:账户掉线";
            //$bot->sendMessage($chat_id, $msg);
        }
        // 账户重连
        if ($notice_type == "account_reconnected") {
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:账户重连";
            //$bot->sendMessage($chat_id, $msg);
            //$bot->sendMessage($chat_id, "账户重连");
        }



        if (!sendemail("金运来消息推送", $msg, $notice_account, $back)) {
            $result["code"] = "0";
            $result["msg"] = "推送失败";
            $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
            //log_api("推送失败结果:".$back);
            die(json_encode($result));
            //die("请求超时或返回的数据解析失败：" . $back);
        } else {

            $result["code"] = "1";
            $result["msg"] = "推送成功";
            $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
            die(json_encode($result));
            //die("邮件已发送至您开通授权时候设置的站长邮箱，请检查收件箱和垃圾箱是否已收到文件");
        }


    } else {
        //log_api("机器人初始化".$notice_account);
        $bot = new TelegramBot();
        // log_api("机器人初始化完成".$notice_account);
        // 先找send_id(群聊)
        $telegram_account = DB::table("telegram")->where(["chat_id" => $notice_account])->find();
        if (!$telegram_account) {
            // 找TG号
            $telegram_account = DB::table("telegram")->where(["account" => $notice_account])->find();
        }
        // 机器人发信
        $chat_id = $telegram_account["chat_id"];
        // log_api("收信账户chat_id".$chat_id);
        // 测试通信
        $msg = "";
        if ($notice_type == "test_push") {
            //log_api("当前账号:".$decryptData["username"]);

            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n内容:信息接收测试, 接收到本消息则表明测试正常.";
            //log_api("发送消息:".$msg);

            // $database_order["TID"] = "22855900875";
            // $database_order["DATETIME"] = "2025-10-24 18:03:29";
            // $database_order["NAME0"] = "dtt8user1";
            // $database_order["GT"] = "足球";
            // $database_order["WAGERS_TYPE"] = "(滚球) 大 / 小-上半场";
            // $database_order["LEAGUE"] = "巴西乙组联赛";
            // $database_order["TEAM_H"] = "甘美奥诺瓦里桑蒂诺SP";
            // $database_order["TEAM_C"] = "博塔福格SP";
            // $database_order["ORDER_TYPE"] ="大";
            // $database_order["ORDER_CON"] = "0.5 / 1";
            // $database_order["SCORE"] = "0:0";
            // $database_order["IORATIO"] = "0.73";
            // $database_order["GOLD"] = "50";
            // $database_order["SRV_IP"] = "手机";
            // $database_order["SESSION"] = "滚球";
            // $database_order["STAGE"] = "上半场";
            // $database_order["G_TIME"] = "10-24-2025 18:00:00";
            // $database_order["NUM_C"] = "11111";
            // $database_order["NUM_H"] = "222222";
            // DB::table("orders")->add($database_order);




            $bot->sendMessage($chat_id, $msg);
        }
        // 读取注单
        if ($notice_type == "read_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\r\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            //log_api(json_encode($order));
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:读取注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\r\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n盘口:" . $order["ORDER_CON"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\r\n开赛时间:" . $order["G_TIME"];
           // log_api("开始入库");
            $find_cache = DB::table("orders")->where(["TID" => $order["TID"]])->find();
            if (!$find_cache) {
                $database_order["TID"] = $order["TID"];
                $database_order["USERNAME"] = $decryptData["username"];
                $database_order["DATETIME"] = $order["DATETIME"];
                $database_order["NAME0"] = $order["NAME0"];
                $database_order["GT"] = $order["GT"];
                $database_order["WAGERS_TYPE"] = $order["WAGERS_TYPE"];
                $database_order["LEAGUE"] = $order["LEAGUE"];
                $database_order["TEAM_H"] = $order["TEAM_H"];
                $database_order["TEAM_C"] = $order["TEAM_C"];
                $database_order["ORDER_TYPE"] = $order["ORDER_TYPE"];
                $database_order["ORDER_CON"] = $order["ORDER_CON"];
                $database_order["SCORE"] = $order["SCORE"];
                $database_order["IORATIO"] = $order["IORATIO"];
                $database_order["GOLD"] = $order["GOLD"];
                $database_order["SRV_IP"] = $order["SRV_IP"];
                $database_order["SESSION"] = $order["SESSION"];
                $database_order["STAGE"] = $order["STAGE"];
                $database_order["G_TIME"] = $order["G_TIME"];
                $database_order["NUM_C"] = $order["NUM_C"];
                $database_order["NUM_H"] = $order["NUM_H"];
                DB::table("orders")->add($database_order);
                //log_api($user["forward"]);
                if ($user["forward"] == 1) {
                    //log_api("TG转发");
                    $forward_tg = getForwardTelegram();
                    //log_api("TG转发:".$forward_tg);
                    if ($forward_tg != "") {
                        $forward_telegram_account = DB::table("telegram")->where(["chat_id" => $forward_tg])->find();
                        if (!$forward_telegram_account) {
                            // 找TG号
                            $forward_telegram_account = DB::table("telegram")->where(["account" => $forward_tg])->find();
                        }
                        if ($forward_telegram_account["chat_id"] != "") {
                            $bot->sendMessage($forward_telegram_account["chat_id"], $msg);
                        }
                    }
                }
            }
            //log_api("结束入库");


            if($chat_id!="")
            {
                $bot->sendMessage($chat_id, $msg);
            }
            


        }
        // 接收注单
        if ($notice_type == "accept_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:接收注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n盘口:" . $order["ORDER_CON"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"];
            $bot->sendMessage($chat_id, $msg);
        }
        // 筛选注单
        if ($notice_type == "screen_order") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:筛选注单\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n最新比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"] . "\n过滤原因:" . $order["REASON"];
            $bot->sendMessage($chat_id, $msg);
        }
        // 跟单成功
        if ($notice_type == "bet_order_success") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:跟单成功\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n最新比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO_NEW"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"];
            $bot->sendMessage($chat_id, $msg);
        }
        // 跟单失败
        if ($notice_type == "bet_order_failed") {
            if ($order["SRV_IP"] == "手机") {
                $order["SRV_IP"] = "\n手机";
            }
            // $msg = $decryptData["order"]["TID"]."AAA";
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:跟单失败\n" . "单号: " . $order["TID"] . "\n时间:" . $order["DATETIME"] . "\n会员:" . $order["NAME0"] . "\n球种:" . $order["GT"] . "\n赛段:" . $order["SESSION"] . "\n玩法:" . $order["WAGERS_TYPE"] . $order["SRV_IP"] . "\n联盟:" . $order["LEAGUE"] . "\n队伍:" . $order["TEAM_H"] . " : " . $order["TEAM_C"] . "\n比分:" . $order["SCORE"] . "\n比分:" . $order["SCORE_NEW"] . "\n盘口:" . $order["ORDER_CON"] . "\n最新盘口:" . $order["ORDER_CON_NEW"] . "\n下注:" . $order["ORDER_TYPE"] . "\n赔率:" . $order["IORATIO"] . "\n最新赔率:" . $order["IORATIO_NEW"] . "\n金额:" . $order["GOLD"] . "\n开赛时间:" . $order["G_TIME"] . "\n失败原因:" . $order["REASON"];
            $bot->sendMessage($chat_id, $msg);
        }
        // 账户掉线
        if ($notice_type == "account_dissconnected") {
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:账户掉线";
            $bot->sendMessage($chat_id, $msg);
        }
        // 账户重连
        if ($notice_type == "account_reconnected") {
            $msg = "用户:" . $decryptData["username"] . "\n程序:" . $app . "\n类型:账户重连";
            $bot->sendMessage($chat_id, $msg);
            //$bot->sendMessage($chat_id, "账户重连");
        }

    }

    // 未到期
    $result["code"] = "1";
    $result["msg"] = "推送成功";
    $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
    $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
    die(json_encode($result));
}

if ($mod == "version") {
    // 获取IP
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    if (!ip2long($ip)) {
        $ip = '未知';
    }
    // 应用ID
    $appId = isset($_GET['appId']) ? purge($_GET['appId']) : '';
    if (!$appId) {
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 查询应用
    $app = DB::table("app")->where(["id" => $appId])->find();
    if (!$app) {
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "应用不存在";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 校验数据签名
    $sign = isset($_GET['sign']) ? purge($_GET['sign']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "签名数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $timestamp = isset($_GET['timestamp']) ? purge($_GET['timestamp']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "时间戳校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $data = file_get_contents("php://input");
    $md5 = md5($data . $timestamp . $app["commKey"]);
    if ($md5 != $sign) {
        $result["code"] = "0";
        $result["msg"] = "签名校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 未到期
    $result["code"] = "1";
    $result["msg"] = "获取成功";
    $result["data"]["version"] = $app["version"];
    $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
    $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
    die(json_encode($result));

}


if ($mod == "heartbeat") {
    // 获取IP
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    if (!ip2long($ip)) {
        $ip = '未知';
    }
    // 应用ID
    $appId = isset($_GET['appId']) ? purge($_GET['appId']) : '';
    if (!$appId) {
        $result["code"] = "0";
        $result["msg"] = "数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 查询应用
    $app = DB::table("app")->where(["id" => $appId])->find();
    if (!$app) {
        $result["code"] = "0";
        $result["msg"] = "应用不存在";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 校验数据签名
    $sign = isset($_GET['sign']) ? purge($_GET['sign']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "签名数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $timestamp = isset($_GET['timestamp']) ? purge($_GET['timestamp']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "时间戳校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $data = file_get_contents("php://input");
    $md5 = md5($data . $timestamp . $app["commKey"]);
    if ($md5 != $sign) {
        $result["code"] = "0";
        $result["msg"] = "签名校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 解密数据
    $decryptData = json_decode(mi_rc4($data, $app["commKey"], 1), true);
    $user = DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->find();
    
    if (!$user) {
        // if($decryptData["username"] == "hh6888")
        // {
        //     log_api("gg1");
        // }
        $result["code"] = "0";
        $result["msg"] = "账号或密码错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 计时收费
    if ($app["billingType"] == "1") {
        //        if($decryptData["username"] == "hh6888")
        // {
        //     log_api("gg2");
        // }
        // 判断到期
        if (strtotime($user["expireTime"]) - time() < 0) {
        //            if($decryptData["username"] == "hh6888")
        // {
        //     log_api("gg3");
        // }
            $result["code"] = "0";
            $result["msg"] = "用户已到期";
            $result["data"] = "";
            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
            die(json_encode($result));
        }

        // 绑定机器
        if ($app["bindType"] == "1") {
            if ($decryptData["hardwareCode"] != $user["hardwareCode"]) {
                $result["code"] = "0";
                $result["msg"] = "非绑定机器";
                $result["data"] = "";
                $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                die(json_encode($result));
            }
        }
        // 绑定IP
        if ($app["bindType"] == "2") {
            if ($decryptData["ip"] != $user["ip"]) {
                $result["code"] = "0";
                $result["msg"] = "非绑定IP";
                $result["data"] = "";
                $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                die(json_encode($result));
            }
        }
    }

    // 判断是否存活
    if (time() - strtotime($user["heartbeatTime"]) > $app["heartbeatInterval"]) {
               if($decryptData["username"] == "hh6888")
        {
            log_api("心跳失败 原始时间".strtotime($user["heartbeatTime"])."当前".time()."周期".$app["heartbeatInterval"]);
        }
        $result["code"] = "0";
        $result["msg"] = "心跳超时";
        $result["data"]["expireTime"] = $user["expireTime"];
        $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

       if($decryptData["username"] == "hh6888")
        {
            log_api("ssss");
        }
    // 更新心跳时间
    $currentTime = date("Y-m-d H:i:s", time());
    DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['heartbeatTime' => $currentTime]);

    $result["code"] = "1";
    $result["msg"] = "心跳成功";
    $result["data"]["expireTime"] = $user["expireTime"];
    $result["data"]["heartbeatTime"] = $currentTime;  // 添加心跳时间到返回数据
    $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
    $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
    die(json_encode($result));

}

if ($mod == "login") {
    // 获取IP
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    if (!ip2long($ip)) {
        $ip = '未知';
    }
    // 应用ID
    $appId = isset($_GET['appId']) ? purge($_GET['appId']) : '';
    if (!$appId) {
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 查询应用
    $app = DB::table("app")->where(["id" => $appId])->find();
    if (!$app) {
        $result["timestamp"] = time();
        $result["code"] = "0";
        $result["msg"] = "应用不存在";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    // 校验数据签名
    $sign = isset($_GET['sign']) ? purge($_GET['sign']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "签名数据错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $timestamp = isset($_GET['timestamp']) ? purge($_GET['timestamp']) : '';
    if (!$sign) {
        $result["code"] = "0";
        $result["msg"] = "时间戳校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }
    $data = file_get_contents("php://input");
    $md5 = md5($data . $timestamp . $app["commKey"]);
    if ($md5 != $sign) {
        $result["code"] = "0";
        $result["msg"] = "签名校验失败";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 解密数据
    $decryptData = json_decode(mi_rc4($data, $app["commKey"], 1), true);
    $user = DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->find();
    if (!$user) {
        $result["code"] = "0";
        $result["msg"] = "账号或密码错误";
        $result["data"] = "";
        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
        die(json_encode($result));
    }

    // 计时收费
    if ($app["billingType"] == "1") {
        // 判断到期
        if (strtotime($user["expireTime"]) - time() < 0) {
            $result["code"] = "0";
            $result["msg"] = "用户已到期";
            $result["data"] = "";
            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
            die(json_encode($result));
        }

        // 绑定机器
        if ($app["bindType"] == "1") {
            // 只有当用户已经绑定了机器码时，才进行验证
            if ($user["hardwareCode"] && $user["hardwareCode"] != '') {
                if ($decryptData["hardwareCode"] != $user["hardwareCode"]) {
                    // 禁止解绑
                    if ($app["unbindType"] == "0") {
                        $result["code"] = "0";
                        $result["msg"] = "非绑定机器，禁止解绑";
                        $result["data"] = "";
                        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                        die(json_encode($result));
                    }
                    // 免费解绑
                    if ($app["unbindType"] == "1") {
                        // 更新机器码
                        DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['hardwareCode' => $decryptData["hardwareCode"]]);
                    }
                    // 收费解绑
                    if ($app["unbindType"] == "2") {
                        // 判断余额
                        if (strtotime($user["expireTime"]) - $app["unbindDeduct"] < 0) {
                            $result["code"] = "0";
                            $result["msg"] = "解绑余额不足";
                            $result["data"] = "";
                            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                            die(json_encode($result));
                        }
                        // 收费
                        DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['expireTime' => date("Y-m-d H:i:s", strtotime($user["expireTime"]) - $app["unbindDeduct"])]);
                        // 更新机器码
                        DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['hardwareCode' => $decryptData["hardwareCode"]]);
                    }
                }
            } else {
                // 用户没有绑定机器码，直接绑定当前机器码
                DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['hardwareCode' => $decryptData["hardwareCode"]]);
            }
        }
        // 绑定IP
        if ($app["bindType"] == "2") {
            // 只有当用户已经绑定了IP时，才进行验证
            if ($user["ip"] && $user["ip"] != '') {
                if ($decryptData["ip"] != $user["ip"]) {
                    // 禁止解绑
                    if ($app["unbindType"] == "0") {
                        $result["code"] = "0";
                        $result["msg"] = "非绑定IP，禁止解绑";
                        $result["data"] = "";
                        $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                        die(json_encode($result));
                    }
                    // 免费解绑
                    if ($app["unbindType"] == "1") {
                        DB::table('user')->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['ip' => $ip]);
                    }
                    // 收费解绑
                    if ($app["unbindType"] == "2") {
                        // 判断余额
                        if (strtotime($user["expireTime"]) - $app["unbindDeduct"] < 0) {
                            $result["code"] = "0";
                            $result["msg"] = "解绑余额不足";
                            $result["data"] = "";
                            $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
                            die(json_encode($result));
                        }
                        // 收费
                        DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['expireTime' => date("Y-m-d H:i:s", strtotime($user["expireTime"]) - $app["unbindDeduct"])]);
                        // 更新ip
                        DB::table('user')->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['ip' => $ip]);
                    }
                }
            } else {
                // 用户没有绑定IP，直接绑定当前IP
                DB::table('user')->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['ip' => $ip]);
            }
        }
    }


    // 更新登录时间
    $currentTime = date("Y-m-d H:i:s", time());
    DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['loginTime' => $currentTime]);
    // 更新心跳时间
    DB::table("user")->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['heartbeatTime' => $currentTime]);
    // 更新IP地址
    DB::table('user')->where(["username" => $decryptData["username"], "password" => $decryptData["password"]])->update(['ip' => $ip]);
    // 未到期
    $result["code"] = "1";
    $result["msg"] = "登录成功";
    $result["data"]["expireTime"] = $user["expireTime"];
    $result["data"] = mi_rc4(json_encode($result["data"]), $app["commKey"], 0);
    $result["sign"] = md5($result["code"] . $result["msg"] . $result["data"]);
    die(json_encode($result));
}


function decode($str, $pwd)
{
    $TempUndata = hexToStrBytes($str);
    $count = count($TempUndata) - 1;
    $xor = getRigthBytes($TempUndata, 1);
    $UnHashData = ByteXor($TempUndata, $xor);
    $RValue = getMidBytes($UnHashData, $count - 2, 3);
    $md5 = bytesToMd5($RValue, $xor, integerToBytes(crc32($pwd)));
    $last = bytesToShort(getMidBytes($UnHashData, $count - 4, 2), 0);
    $HashData = getLeftBytes($UnHashData, $count - 5);
    $len = count($HashData);
    $n = mb_strlen($md5);
    $error = 0;

    $offset = 1;
    $_last = $last;

    foreach ($HashData as $key => $value) {

        if ($len < $_last) {
            $error = 1;
            break;
        }
        if ($offset > $n) {
            $offset = 1;
        }

        if ($last - $offset < 0) {
            $last = $n;
            $offset = 1;
        }
        $Location = hexdec(mb_substr($md5, $last - $offset, 1)) + 3;


        $offset++;
        if ($Location > $len) {
            continue;
        }

        // 问题修复 +1 解决
        LocationExchange($len - $len + $key, $Location - 1, $HashData);
    }

    $tCrc32 = bytesToInteger(getRigthBytes($HashData, 4));
    $HashData = getLeftBytes($HashData, $len - 4);
    $nCrc32 = crc32(toStr($HashData));
    //调试输出("解密",$tCrc32,toStr($HashData),$nCrc32);
    if ($error == 1) {
        return '';
    }
    if ($nCrc32 == $tCrc32) {
        return toStr($HashData);
    }
    return '';
}

function encode($string, $pwd)
{
    $crc32 = integerToBytes(crc32($string));// 正确
    $Tempdata = array_merge_recursive(getBytes($string), $crc32);// 正确
    $Xor = getBytes(chr(mt_rand(1, 255)));// 正确
    $aaaa = mt_rand(1, 255);
    $bbbb = mt_rand(1, 255);
    $cccc = mt_rand(1, 255);
    $RValue = [chr($aaaa), chr($bbbb), chr($cccc)]; // 修复成功 如果使用 getByTes 那么可能会识别成两个

    $md5 = bytesToMd5($RValue, $Xor, integerToBytes(crc32($pwd)));// 正确

    $n = mb_strlen($md5);// 正确
    $len = count($Tempdata);// 正确
    $offset = 1;

    foreach ($Tempdata as $key => $value) {
        if ($offset > $n) {
            $offset = 1;
        }
        $Location = hexdec(mb_substr($md5, $offset - 1, 1)) + 3;

        $offset++;
        if ($Location > $len) {
            continue;
        }

        LocationExchange($len - $key - 1, $Location - 1, $Tempdata);
    }

    $Tempdata = array_merge_recursive($Tempdata, shortToBytes($offset - 1), $RValue);
    return bytesToHex(array_merge_recursive(ByteXor($Tempdata, $Xor), $Xor));
}
function LocationExchange($LocalA, $LocalB, &$ByteData)
{

    $TempA = $ByteData[$LocalA];
    $TempB = $ByteData[$LocalB];



    $ByteData[$LocalA] = $TempB;
    $ByteData[$LocalB] = $TempA;
}

function 调试输出()//简易调试输出
{
    $args = func_get_args();
    foreach ($args as $value) {
        if (is_array($value)) {
            print_r('字节集:' . count($value) . '{' . join($value, ',') . '}');
            echo "\t<br/>\r\n";
        } else {
            print_r($value . "\t");
        }
    }
    echo "\t<br/>\r\n";
}

function bytesToMd5()//字节集到md5
{
    $args = func_get_args();
    $bytes = [];
    foreach ($args as $value) {
        if (is_array($value)) {
            $bytes = array_merge_recursive($bytes, $value);
        }
    }
    $md5 = md5(toStr($bytes));
    $md5 = strtoupper($md5);
    return $md5;
}
function bytesToInteger($bytes, $position = 0)//取整数
{
    $val = 0;
    $val = @$bytes[$position + 3] & 0xff;
    $val <<= 8;
    $val |= @$bytes[$position + 2] & 0xff;
    $val <<= 8;
    $val |= $bytes[$position + 1] & 0xff;
    $val <<= 8;
    $val |= $bytes[$position] & 0xff;
    return $val;
}
function bytesToShort($bytes, $position)//取短整数
{
    $val = 0;
    $val = $bytes[$position + 1] & 0xFF;
    $val = $val << 8;
    $val |= $bytes[$position] & 0xFF;
    return $val;
}
function getMidBytes($bytes, $start, $num)//取字节集中间
{
    $mBytes = [];
    for ($i = 0; $i < $num; $i++) {
        $mBytes[] = $bytes[$start - 1 + $i];
    }
    return $mBytes;
}

function getLeftBytes($bytes, $num)//取字节集左边
{
    $lBytes = [];
    for ($i = 0; $i < $num; $i++) {
        $lBytes[] = $bytes[$i];
    }
    return $lBytes;
}
function getRigthBytes($bytes, $num)//取字节集右边
{
    $count = count($bytes) - $num;
    $rBytes = [];
    for ($i = 0; $i < $num; $i++) {
        $rBytes[] = $bytes[$count + $i];
    }
    return $rBytes;
}

function hexToStrBytes($hex)//十六进制到字节集
{
    $bytes = array();
    for ($i = 0; $i < mb_strlen($hex) - 1; $i += 2) {
        $bytes[] = ord(chr(hexdec($hex[$i] . $hex[$i + 1])));
    }
    return $bytes;
}

function ByteXor($bytes, $xor)
{
    $_bytes = [];
    foreach ($bytes as $val) {
        $_bytes[] = $val ^ $xor[0];
    }
    return $_bytes;
}

function bytesToHex($bytes)//字节集转十六进制
{
    $hex = "";
    foreach ($bytes as $value) {
        $hex .= sprintf("%02X", $value);
    }
    return $hex;
}

function strToHex($string)//字符串转十六进制
{
    $hex = "";
    for ($i = 0; $i < strlen($string); $i++)
        $hex .= dechex(ord($string[$i]));
    $hex = strtoupper($hex);
    return $hex;
}
function hexToStr($hex)//十六进制转字符串
{
    $string = "";
    for ($i = 0; $i < strlen($hex) - 1; $i += 2)
        $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
    return $string;
}

function toStr($bytes)//到文本
{
    $str = '';
    foreach ($bytes as $ch) {
        $str .= chr($ch);
    }
    return $str;
}
function getBytes($string)//到字节集
{
    $bytes = array();
    for ($i = 0; $i < mb_strlen($string); $i++) {
        $bytes[] = ord($string[$i]);
    }
    return $bytes;
}

function integerToBytes($val)//整数到字节集
{
    $byt = array();
    $byt[0] = ($val & 0xff);
    $byt[1] = ($val >> 8 & 0xff);
    $byt[2] = ($val >> 16 & 0xff);
    $byt[3] = ($val >> 24 & 0xff);
    return $byt;
}

function shortToBytes($val)//短整数到字节集
{
    $byt = array();
    $byt[0] = ($val & 0xff);
    $byt[1] = ($val >> 8 & 0xff);
    return $byt;
}


?>