<?php
phpinfo();
die;
/**
 * ===========================
 * Telegram 接单机器人单文件 Demo
 * ===========================
 *
 * 功能：
 * 1. 发送订单消息
 * 2. 用户点击接单按钮 → 按钮变成“已接单【昵称】”
 * 3. 自动发送接单消息回复
 * 4. 简单防止多人抢单（内存模拟，可换数据库）
 *
 * ---------------------------
 * 注意事项：
 * - 生产环境请替换 $orders 数组为数据库操作
 * - 部署到公网并设置 TG Webhook
 * - 机器人需要添加到群或个人聊天中
 */

var_dump(11111);die;
$token = "YOUR_BOT_TOKEN_HERE"; // 替换为你的Bot Token
$chat_id = "YOUR_CHAT_ID_HERE"; // 替换为TG群或个人ID

// 模拟订单存储（生产请用数据库）
$orders = []; // 格式: [order_id => ['status'=>0,'taker'=>'']]

// ----------------------
// 主逻辑
// ----------------------

// 读取 webhook 数据
$update = json_decode(file_get_contents("php://input"), true);

// 判断是否是按钮点击事件
if (isset($update['callback_query'])) {
    handleCallback($update['callback_query']);
    exit;
}

// 如果是普通消息，可根据需要处理
if (isset($update['message'])) {
    $text = $update['message']['text'] ?? '';
    // 可以监听管理员指令 /sendorder
    if (strpos($text,'/sendorder') === 0) {
        $parts = explode(' ',$text);
        $order_id = $parts[1] ?? rand(1000,9999);
        send_order($order_id);
    }
    exit;
}

// ----------------------
// 发送订单消息
// ----------------------
function send_order($order_id){
    global $token,$chat_id,$orders;

    // 初始化订单
    $orders[$order_id] = ['status'=>0,'taker'=>''];

    // 构建按钮
    $keyboard = [
        "inline_keyboard"=>[
            [
                [
                    "text"=>"接单",
                    "callback_data"=>"take_order:$order_id"
                ]
            ]
        ]
    ];

    $text = "📦 新订单\n订单号：$order_id\n金额：100 USDT";

    $params = [
        "chat_id"=>$chat_id,
        "text"=>$text,
        "reply_markup"=>json_encode($keyboard)
    ];

    file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($params));
}

// ----------------------
// 处理按钮点击事件
// ----------------------
function handleCallback($callback){
    global $token,$orders;

    $callback_id = $callback['id'];
    $message = $callback['message'];
    $chat_id = $message['chat']['id'];
    $message_id = $message['message_id'];

    $user = $callback['from'];
    $nickname = $user['first_name'] ?? '';
    $username = $user['username'] ?? '';
    $user_id = $user['id'];

    $data_str = $callback['data'];

    // 检查是否是接单按钮
    if (strpos($data_str,'take_order:') !== false){
        list($action,$order_id) = explode(":",$data_str);

        // ----------------------
        // 简单抢单逻辑
        // ----------------------
        if (!isset($orders[$order_id])){
            answerCallback($callback_id,"订单不存在");
            return;
        }

        if ($orders[$order_id]['status'] == 1){
            answerCallback($callback_id,"订单已被接");
            return;
        }

        // 标记订单已接
        $orders[$order_id]['status'] = 1;
        $orders[$order_id]['taker'] = $nickname;

        // ----------------------
        // 修改按钮
        // ----------------------
        $keyboard = [
            "inline_keyboard"=>[
                [
                    [
                        "text"=>"已接单【{$nickname}】",
                        "callback_data"=>"taken:$order_id"
                    ]
                ]
            ]
        ];

        editMessageMarkup($chat_id,$message_id,$keyboard);

        // ----------------------
        // 发送接单消息
        // ----------------------
        $replyText = "✅ @{$username} 已成功接单\n订单号：{$order_id}";
        sendMessage($chat_id,$replyText,$message_id);

        // ----------------------
        // 回调提示
        // ----------------------
        answerCallback($callback_id,"接单成功");
    }
}

// ----------------------
// 辅助函数
// ----------------------

// 编辑消息按钮
function editMessageMarkup($chat_id,$message_id,$keyboard){
    global $token;
    $params = [
        "chat_id"=>$chat_id,
        "message_id"=>$message_id,
        "reply_markup"=>json_encode($keyboard)
    ];
    file_get_contents("https://api.telegram.org/bot$token/editMessageReplyMarkup?" . http_build_query($params));
}

// 发送消息
function sendMessage($chat_id,$text,$reply_to=null){
    global $token;
    $params = [
        "chat_id"=>$chat_id,
        "text"=>$text,
    ];
    if ($reply_to) $params['reply_to_message_id'] = $reply_to;
    file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($params));
}

// 回调提示
function answerCallback($callback_id,$text){
    global $token;
    $params = [
        "callback_query_id"=>$callback_id,
        "text"=>$text
    ];
    file_get_contents("https://api.telegram.org/bot$token/answerCallbackQuery?" . http_build_query($params));
}


//设置 Webhook
//https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=https://yourdomain.com/bot.php
//发布订单
///sendorder 1001
//用户点击“接单”按钮，按钮会自动变成“已接单【昵称】”机器人会发送一条消息：
//✅ @username 已成功接单
//订单号：1001