<?php




/* CONFIGURATION */
$BOT_TOKEN = "7679448689:AAE9LavWq8BadJkyY4ejXEUsXELkVSE042I";
$BASE_URL = "testing.win99.pp.ua/fireotp";
$GATEWAY_MIN_AMOUNT = 1000;
$PAYTM_UPI_ID= "paytm.s1xbplh@pty";
$PAYTM_MERCHANT_KEY =  "oJEkjP83475478878732";
$DEPOSIT_CHANNEL  = "@hsjsjsijss";
$OTP_CHANNEL =   "@hsjsjsijss";
$KUKUPAY_API_KEY = "s6DZn19HoOEDpvPChBM75Ldn0KwXXBhl";
$OFFICIAL_CHANNEL = "swift_otp";
$SUPPORT_USERNAME = "Swiftotpsupport";
$BOT_USR = "Swift_otp_bot";


header("Content-Type: application/json");
http_response_code(200);
echo json_encode(["ok" => true]);

// 3️⃣ FLUSH RESPONSE (VERY IMPORTANT)
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} else {
    @ob_flush();
    @flush();
}

/* ----------------------------------------*/
define('BOT_TOKEN', $BOT_TOKEN);
define('BOT_USR',$BOT_USR);
define("SUPPORT_USERNAME",$SUPPORT_USERNAME);
define('DEPOSIT_NOTIFY',$DEPOSIT_CHANNEL);
define('OTP_NOTIFY',$OTP_CHANNEL);
define('OFFICIAL_CHANNEL',$OFFICIAL_CHANNEL);
define('BASE_URL',$BASE_URL);




$raw = file_get_contents("php://input");

file_put_contents(__DIR__."/hit.log", date("H:i:s")." | RAW = ".$raw."\n", FILE_APPEND);

if (!$raw) {
    file_put_contents(__DIR__."/hit.log", date("H:i:s")." | EMPTY INPUT\n", FILE_APPEND);
    exit;
}

$update = json_decode($raw, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    file_put_contents(__DIR__."/hit.log", date("H:i:s")." | JSON ERROR = ".json_last_error_msg()."\n", FILE_APPEND);
    exit;
}
require_once __DIR__.'/refer.php';
require_once __DIR__.'/conn.php';
require_once __DIR__.'/functions.php';
/* =========================
   MESSAGE HANDLER
   ========================= */
if (isset($update['message'])) {

    $chat_id = $update['message']['chat']['id'];
    $text    = trim($update['message']['text'] ?? '');
    $name    = $update['message']['from']['first_name'] ?? 'User';

    $user = get_or_create_user($pdo, strval($chat_id), $name);

    /* ================= BAN FILTER ================= */

    if ($user['status'] == 'BANNED') return;

    /* =====================================================
       😈🔥🔥🔥 STATE LOCK MUST COME FIRST
    ===================================================== */

    $state = getUserState($chat_id);

    if ($state) {

        debug_log("STATE_ACTIVE: ".$state);

        switch ($state) {

            case "WAITING_COUPON":

                debug_log("COUPON_LOCKED");

                apply_referral_code($pdo, $chat_id, strval($chat_id), $text);

                clearUserState($chat_id);

                return;  // ⛔ STOP EVERYTHING 😎🔥
        }
    }

    /* ================= /START ================= */

    if (strpos($text, '/start') === 0) {
 file_put_contents(__DIR__."/user_lock_$chat_id.txt", "REFERRAL");
        if (!$user['refer_by']) {
            ask_coupon_question($chat_id);
        } else {
            start($pdo, $chat_id, $name);
        }

        return;
    }


    switch ($text) {
        
 case '📩 𝐒𝐌𝐒 𝐂𝐇𝐄𝐂𝐊𝐄𝐑':
    file_put_contents(__DIR__."/user_lock_$chat_id.txt", "SMS");
    sendMessage(
        $chat_id,
        "📩 *Mᴀɪ Sᴍs Cʜᴇᴄᴋᴇʀ Hᴜ*\n\n".
        "👉 Bᴀs Pᴜʀᴀ OTP Wᴀʟᴀ SMS Bʜᴇᴊᴏ.\n\n".
        "⏱️ *Mᴀɪ 2 Sᴇᴄᴏɴᴅ Mᴇ Bᴀᴛᴀ Dᴜɴɢᴀ Kɪ Kɪs Sᴇʀᴠɪᴄᴇ Pᴀʀ OTP Aᴀʏᴀ Hᴀɪ Aᴜʀ Kᴏɴ Sᴀ Sᴇʀᴠᴇʀ Usᴇ Kᴀʀɴᴀ Hᴀɪ.*\n\n".
        "⚡ Iᴛɴᴇ Dᴇʀ Sᴏᴄʜ Kʏᴀ Rᴀʜᴇ Hᴏ? Fᴏʀᴍᴀᴛ Bʜᴇᴊᴏ, Bʜᴜᴛ Kᴀᴀᴍ Hᴀɪ Mᴜᴊʜᴇ 😎",
        null,
        "Markdown"
    );
    break;

case '🔥 𝐌𝐎𝐑𝐄':

   sendMessage(
    $chat_id,
    "✨ *Mᴏʀᴇ Oᴘᴛɪᴏɴs Mᴇ Aᴀᴘᴋᴀ Sᴡᴀɢᴀᴛ Hᴀɪ 😎🔥*\n\n".
    "😂 *Hᴀᴍ Fᴇᴀᴛᴜʀᴇs Tᴏ Bʜᴀʀ Bʜᴀʀ Kᴇ Lᴀɴᴀ Cʜᴀʜᴛᴇ Tʜᴇ…*\n".
    "🔘 *Lᴇᴋɪɴ Bᴜᴛᴛᴏɴs Nᴇ Hᴀᴛʜ Kʜᴀᴅᴇ Kᴀʀ Dɪʏᴇ 😭*\n\n".
    "🔥 *Isʟɪʏᴇ Mᴀᴊʙᴜʀɪ Mᴇ 🔥 Mᴏʀᴇ Bᴀɴᴀɴᴀ Pᴀᴅᴀ 😈😂*\n\n".
    "⚡ *Cʜᴀʟᴏ Aʙ Dᴇᴋʜᴛᴇ Jᴀᴏ — Aɢʟᴇ Uᴘᴅᴀᴛᴇ Mᴇ Aᴜʀ Dʜᴀᴍᴀᴋᴀ Hᴏɢᴀ 😎🔥*",
    more_keyboard(),
    "Markdown"
);


    break;


case '🔙 𝐁𝐀𝐂𝐊':

  sendMessage(
    $chat_id,
    
    "😂 *Aᴀᴊᴀᴏ Aᴀᴊᴀᴏ — Vᴀᴘs Aᴀ Gʏᴇ Fᴀᴛᴀᴋ Sᴇ 😈⚡*",
    main_keyboard(),
    "Markdown"
);


    break;

    case '🎁 𝐏𝐑𝐎𝐌𝐎𝐂𝐎𝐃𝐄':
        file_put_contents(__DIR__."/user_lock_$chat_id.txt", "PROMO");
        sendMessage(
            $chat_id,
            "🎁 *Eɴᴛᴇʀ Pʀᴏᴍᴏ Cᴏᴅᴇ*",
            null,
            "Markdown"
        );
        break;
case '🎁 𝐑𝐄𝐅𝐄𝐑 & 𝐄𝐀𝐑𝐍':
    show_referral_dashboard($pdo, $chat_id);
    break;
    case '🎁 𝐑𝐄𝐅𝐄𝐑 𝐁𝐎𝐍𝐔𝐒':
          file_put_contents(__DIR__."/user_lock_$chat_id.txt", "REFERRAL");

    sendMessage(
        $chat_id,
        "🎁 *Rᴇғᴇʀʀᴀʟ Bᴏɴᴜs*\n\n".
        "🔑 Aᴘɴᴀ Rᴇғᴇʀʀᴀʟ Cᴏᴅᴇ Dᴀʟᴏ 😎\n\n".
        "💰 Rᴇғᴇʀ Kᴀʀᴏ → 10% Bᴏɴᴜs Pᴀᴏ 😈🔥",
        null,
        "Markdown"
    );

    break;
        case '🎡 𝐒𝐏𝐈𝐍 & 𝐖𝐈𝐍':
    handle_spin_check($pdo, $chat_id, $cid);
    break;



     case '💎 𝗥𝗘𝗔𝗗𝗬𝗠𝗔𝗗𝗘 𝗔𝗖𝗖𝗢𝗨𝗡𝗧':
    show_account_servers($pdo, $chat_id);
    break;

        case '💰 𝐃𝐄𝐏𝐎𝐒𝐈𝐓':
            send_deposit_menu($chat_id,$name);
            break;
        case '👤 𝐏𝐑𝐎𝐅𝐈𝐋𝐄':
            send_profile($chat_id,$name,$user);
            break;
        case '🎧 𝐒𝐔𝐏𝐏𝐎𝐑𝐓':
            send_support($chat_id);
            break;
        case "❤️ 𝐅𝐀𝐕𝐎𝐔𝐑𝐈𝐓𝐄":
            send_favourites($pdo,$chat_id,$chat_id);
            break;
        case "🛒 𝐆𝐄𝐓 𝐎𝐓𝐏":
            send_unique_services($pdo,$chat_id);
          
            break;
        default:
             $lockFile = __DIR__."/user_lock_$chat_id.txt";

    if (file_exists($lockFile)) {

        $mode = trim(file_get_contents($lockFile));
        unlink($lockFile);

        if ($mode === 'PROMO') {
            redeem_promocode($pdo, $chat_id, $text);
            return;
        }

        if ($mode === 'SMS') {
            sendMessage($chat_id, "⏳ Bᴀs 2 Sᴇᴄ Rᴜᴋᴏ, Nɪᴄʜᴇ Bʜᴇᴊ Rᴀʜᴀ Hᴜ… 😎");
            $result = autoCheckSms($text);
            sendMessage($chat_id, $result);
            return;
        }
         if ($mode === 'REFERRAL') {

        apply_referral_code($pdo, $chat_id, strval($chat_id), $text);

        return;
    }

        if ($mode === 'RESELLER') {

    if (!is_numeric($text) || $text <= 0) {
        sendMessage($chat_id, "❌ Invalid amount. Number bhejo.");
        return;
    }

    $code = substr(md5(uniqid()), 0, 8);

    $pdo->prepare("
        INSERT INTO reseller_links (reseller_id, code, margin)
        VALUES (?,?,?)
    ")->execute([$chat_id, $code, $text]);

  sendMessage(
    $chat_id,
    "🔗* Rᴇsᴇʟʟᴇʀ Lɪɴᴋ Cʀᴇᴀᴛᴇᴅ*\n\n".
    "💰 Pᴇʀ Nᴜᴍʙᴇʀ Tᴜᴍᴋᴏ Mɪʟᴇɢᴀ: ₹{$text}\n\n".
    "👇* Yᴇ Lᴏ Lɪɴᴋ — Dᴏsᴛᴏ Kᴏ Bʜᴇᴊᴏ Aᴜʀ Dᴀʙᴀᴋᴇ Fᴀʏᴅᴀ Lᴏ* 😎🔥\n\n".
    "https://t.me/swift_otp_bot?start=ref{$code}",
    null,
    null   // 🔥 parse OFF
);


    return;

}

        return;
    }

 

            if(file_exists("answer/$chat_id.txt")){
            $answer = file_get_contents("answer/$chat_id.txt");
            unlink("answer/$chat_id.txt");
            if($answer == "paytm"){
                handle_deposit_upi($chat_id,$text);
                exit;
            }
            }elseif(strpos($text,"/buy") !== false){
                handle_buy_command($pdo,$chat_id,$text);
                exit;
            }elseif(strpos($text,"/fav") !== false){
                  $key = str_replace('/fav_', '', $text);
            
            $match_name = strtolower(str_replace(' ', '', $key));


  $stmt = $pdo->prepare(
    "INSERT IGNORE INTO favourites (user_id, service_code, service_name)
     SELECT 
        ?, 
        UPPER(REPLACE(service_name, ' ', '')) AS service_code,
        service_name
     FROM services
     WHERE REPLACE(LOWER(service_name), ' ', '') = ?
     LIMIT 1"
);

$stmt->execute([$chat_id, $match_name]);


    sendMessage($chat_id, "⭐ Added to favourites.");
exit;

}elseif(strpos($text,"/rem_") !== false){
    handle_remove_favourite($pdo,$chat_id,$text);
    exit;
}

// ---- commands parsing ----
$parts = explode(' ', trim($text));
$cmd   = strtolower($parts[0] ?? '');

// /depost sab ke liye
if($cmd == "/depost"){
    depost($chat_id,$BASE_URL);
    exit;
}

// sirf admin ke liye
if ($user['admin'] === "YES") {

    if($cmd == "/admin"){
        generate_admin_token($chat_id,$BASE_URL);
        exit;
    }
 if ($cmd === '/bal' && count($parts) === 3) {

    $target_user = (int)$parts[1];
    $amount = floatval($parts[2]);

    if ($amount <= 0) {
        sendMessage($chat_id, "❌ Invalid amount");
        return;
    }

 // add balance
    add_bal($pdo, $target_user, $amount);
    // add deposit history
    add_deposit($pdo, $target_user, $amount,"ADMIN_".strval(mt_rand(1938,988304)),"SUCCESS");
    
    
     // notify admin
    sendMessage(
        $chat_id,
        "✅ *Balance Aincrease dded*\n\nUser: `{$target_user}`\nAmount: ₹{$amount}",
        null,
        "Markdown"
    );

    return;


}

    if ($cmd === '/user' && count($parts) === 2) {
        $target_user = (int)$parts[1];
         send_profile($chat_id,"Customer",get_or_create_user($pdo,$target_user,"Customer"));
         send_deposit_history($pdo,$chat_id,$target_user);
          send_otp_history($pdo,$chat_id,$target_user);
    return;}
    if ($cmd === '/add' && count($parts) === 3) {

    $target_user = (int)$parts[1];
    $amount = floatval($parts[2]);

    if ($amount <= 0) {
        sendMessage($chat_id, "❌ Invalid amount");
        return;
    }

    // add balance
    add_balance($pdo, $target_user, $amount);

    // add deposit history
    add_deposit($pdo, $target_user, $amount,"ADMIN_".strval(mt_rand(1938,988304)),"SUCCESS");

    // notify admin
    sendMessage(
        $chat_id,
        "✅ *Balance Added*\n\nUser: `{$target_user}`\nAmount: ₹{$amount}",
        null,
        "Markdown"
    );
    
     // notify user
    sendMessage(
    $target_user,
    "💰 *Iᴅʜᴀʀ Dᴇᴋʜᴏ, Pᴀɪsᴇ Aᴀ Gᴀʏᴇ*\n\n".
    "💵 *Aᴍᴏᴜɴᴛ:* ₹{$amount}\n".
    "👑 *Mᴀʟɪᴋ Nᴇ Kʜᴜᴅ Aᴅᴅ Kɪʏᴀ Hᴀɪ*",
    null,
    "Markdown"
);

    return;


function send_main_menu($chat_id){
    sendMessage(
        $chat_id,
        "*👋 Oʜ Hᴏ Dᴇᴋʜᴏ Dᴇᴋʜᴏ Kᴏɴ Aᴀʏᴀ — 😎 Aᴀᴏ Aᴀᴏ!*\n\n".

        "⚡ Aᴀʏᴀ Nᴀ? Dᴇʀ Kʏᴜɴ Lᴀɢɪ — Hᴀᴍ OTP Mᴇ Bɪᴊʟɪ Sᴇ Bʜɪ Tᴇᴊ Hᴀɪ 😎\n\n".
        "🛒 *Jᴏ Cʜᴀʜɪʏᴇ, Nɪᴄʜᴇ Sᴇ Cʜᴜɴᴏ — Bᴀᴀᴋɪ Sᴀʙ Hᴀᴍ Sᴀᴍʙʜᴀᴀʟ Lᴇɴɢᴇ *👇",
        main_keyboard(),
        "Markdown"
    );
}

    return;
}


    // /cut user_id amount
    
       if ($cmd === '/cut' && count($parts) === 3) {

    $target_user = (int)$parts[1];
    $amount = floatval($parts[2]);

    if ($amount <= 0) {
        sendMessage($chat_id, "❌ Invalid amount");
        return;
    }

    if (!cut_balances($pdo, $target_user, $amount)) {
        sendMessage($chat_id, "❌ Insufficient balance");
        return;
    }

    // log deduction in deposit history (negative)
    add_deposit($pdo, $target_user, -$amount, "ADMIN_CUT_" . time(),"SUCCESS");

    // notify admin
    sendMessage(
        $chat_id,
        "✅ *Balance Deducted*\n\nUser: `{$target_user}`\nAmount: ₹{$amount}",
        null,
        "Markdown"
    );

    // notify user
    sendMessage(
        $target_user,
        "⚠️ *Balance Deducted*\n\nAmount: ₹{$amount}\nBy: Admin",
        null,
        "Markdown"
    );
    return;

    }
    
    if ($cmd === '/ban' && count($parts) === 2) {

        $target_user = $parts[1];
        ban($pdo, $target_user);

        // notify admin
        sendMessage(
            $chat_id,
            "🚫 *User Banned*\n\nUser: `{$target_user}`",
            null,
            "Markdown"
        );

        // notify user
        sendMessage(
            $target_user,
            "🚫 *Your account has been banned by admin.*\n\nContact support if you think this is a mistake.",
            null,
            "Markdown"
        );
        return;
    }

    /* =======================
       UNBAN USER
       /unban user_id
       ======================= */
    if ($cmd === '/unban' && count($parts) === 2) {

        $target_user = $parts[1];
        unban($pdo, $target_user);

        // notify admin
        sendMessage(
            $chat_id,
            "✅ *User Unbanned*\n\nUser: `{$target_user}`",
            null,
            "Markdown"
        );

        // notify user
        sendMessage(
            $target_user,
            "✅ *Your account has been unbanned.*\n\nYou can use the bot again.",
            null,
            "Markdown"
        );
        return;
    }
}

              search_services($pdo,$chat_id,$text);;
            break;
    }
}elseif (isset($update['callback_query'])) {

    $cq        = $update['callback_query'];
    $chat_id  = $cq['message']['chat']['id'];
    $name    = $cq['from']['first_name'] ?? 'User';
    
    $data     = trim($cq['data']);

    // user fetch
    $user =  get_or_create_user($pdo, strval($chat_id), $name);

    ban_filter($user, $chat_id);

    $parts = explode(' ', $data, 5);

    $data1 = $parts[0] ?? null;
    $data2 = $parts[1] ?? null;
    $data3 = $parts[2] ?? null;
    $data4 = $parts[3] ?? null;
    $data5 = $parts[4] ?? null;
    $cid =$cq["id"];
     $message_id = $cq["message"]["message_id"];
    switch ($data1) {
        
         case 'RESELLER_DASHBOARD':
        send_reseller_dashboard($pdo, $chat_id);
        break;

    /* ================= CREATE LINK ================= */
   case 'RESELLER_CREATE':

    // lock set
    file_put_contents(__DIR__."/user_lock_$chat_id.txt", "RESELLER");

    sendAlert(
        "Aᴘɴᴇ Dᴏsᴛ Kᴏ Kɪᴛɴᴇ Rᴜᴘᴇᴇ Eᴋsᴛʀᴀ Mᴇ Sᴇʀᴠɪᴄᴇ Sᴇʟʟ Kᴀʀᴏɢᴇ 💰",
        $cid
    );

    sendMessage(
        $chat_id,
        "💸 *Pᴇʀ OTP Kɪᴛɴᴀ Eᴋsᴛʀᴀ Cʜᴀʀɢᴇ?*\n\n".
        "👉 *Jɪᴛɴᴇ Rᴜᴘᴇᴇ Aᴀᴘ Lɪᴋʜᴏɢᴇ, Uᴛɴᴀ Pʀɪᴄᴇ Iɴᴄʀᴇᴀsᴇ Hᴏ Jᴀʏᴇɢᴀ.*\n".
        "👀 *Yᴇʜ Pʀɪᴄᴇ Tᴜᴍʜᴀʀᴇ Dᴏsᴛ Kᴏ Dɪᴋʜᴇɢᴀ Aᴜʀ Tᴜᴍ Pᴇʀ Nᴜᴍʙᴇʀ Uᴛɴᴀ Rᴜᴘᴇᴇ Kᴀᴍᴀᴏɢᴇ.*\n\n".
        "😎 *Mᴀsᴛ Tᴀʀɪᴋᴀ Hᴀɪ — Dᴀʙʙᴀ Kᴇ Dᴏsᴛᴏ Kᴏ Fᴀʏᴅᴀ Lᴏ!*",
        null,
        "Markdown"
    );
    break;

case 'RESELLER_WITHDRAW':

    // get reseller balance
    $stmt = $pdo->prepare("
        SELECT balance 
        FROM resellers 
        WHERE user_id=?
    ");
    $stmt->execute([$chat_id]);
    $rbalance = floatval($stmt->fetchColumn());

    if ($rbalance <= 0) {
        sendAlert("❌ 😅 Bʜᴀɪ Tᴜᴍ Gᴀʀᴇᴇʙ Hᴏ, Kᴏɪ Pᴀɪsᴇ Nᴀʜɪ Hᴀɪw", $cid);
        break;
    }

    // transaction safe
    $pdo->beginTransaction();

    // add to main wallet
    $pdo->prepare("
        UPDATE user_data 
        SET balance = balance + ?
        WHERE user_id=?
    ")->execute([$rbalance, $chat_id]);

    // reset reseller balance
    $pdo->prepare("
        UPDATE resellers 
        SET balance = 0 
        WHERE user_id=?
    ")->execute([$chat_id]);

    $pdo->commit();

    sendMessage(
        $chat_id,
        "✅ Withdraw Successful\n💰 Amount Credited: ₹{$rbalance}",
        null,
        null
    );

    break;

    /* ================= MY LINKS ================= */
    case 'RESELLER_LINKS':
 stop_all_auto_clickers($pdo, $chat_id);
        $stmt = $pdo->prepare("SELECT * FROM reseller_links WHERE reseller_id=?");
        $stmt->execute([$chat_id]);
        $links = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$links) {
            sendAlert("No links found", $cid);
            break;
        }

        $msg = "📂 *Your Reseller Links*\n\n";
        foreach ($links as $l) {
            $msg .= "🔗 https://t.me/YOUR_BOT_USERNAME?start=ref{$l['code']}\n";
            $msg .= "💰 Margin: ₹{$l['margin']}\n\n";
        }

        sendMessage($chat_id, $msg, null, "Markdown");
        break;
case 'ACC_SERVERS':
    show_account_servers($pdo, $chat_id);
    break;
case 'GEN_REFER':
    generate_user_referral_code($pdo, $chat_id);
    break;

case 'REF_WITHDRAW':
    referral_withdraw_request($pdo, $chat_id);
    break;
case 'REF_TERMS':
    show_referral_terms($chat_id);
    break;
case 'MY_REFER_USERS':
    show_my_referrals($pdo, $chat_id);
    break;
case 'ACC_VIEW':
    show_account_detail($pdo, $chat_id, (int)$data2);
    break;

case 'ACC_CONFIRM':
    confirm_account_buy($pdo, $chat_id, (int)$data2);
    break;

case 'ACC_BUY':
    buy_log("ROUTER ACC_BUY | data={$data2} | msg={$message_id}");
    process_account_buy($pdo, $chat_id, (int)$data2, $message_id, $cid);
    break;


        case '/buy':
            sendMessage($chat_id, "Buying OTP: $data2");
             stop_all_auto_clickers($pdo, $chat_id);
            break;
           case 'BUY':
    handle_buy_callback($pdo, $chat_id, $data, $cid);
    handle_auto_try_once($pdo, $chat_id, $data2, $message_id, $cid);
    break;
  case 'AUTO_RETRY':
    handle_auto_try_once($pdo, $chat_id, $data2, $message_id, $cid);
    break;
case 'SPIN_DO':
    handle_spin($pdo, $chat_id, $cid);
    break;
case 'AUTO_STOP':
    stop_all_auto_clickers($pdo, $chat_id);
    sendAlert("🛑 Auto stoppedd.", $cid);
    break;

case 'AUTO_SELECT':
    show_auto_server_list($pdo, $chat_id, $data2, $cid);
    break;

case 'AUTO_START':
error_log("⚡😎 Bᴀs Aᴜᴛᴏ Sᴛᴀʀᴛ Kᴀᴀᴍ Kᴀʀɴᴇ Jᴀ Rᴀʜᴀ Hᴀɪ… 🚀🔥: data2=" . $data2);
sendAlert("⚡😎 Bᴀs Aᴜᴛᴏ Sᴛᴀʀᴛ Kᴀᴀᴍ Kᴀʀɴᴇ Jᴀ Rᴀʜᴀ Hᴀɪ… 🚀🔥", $cid);

    $msg = sendMessage(
        $chat_id,
        "⚡ Auto clicker starting...\n\nPlease wait",
        null,
        "Markdown"
    );

    $message_id = json_decode($msg, true)['result']['message_id'] ?? null;

    if (!$message_id) {
        sendAlert("❌ Failed to start auto clicker.", $cid);
        return;
    }

    start_auto_clicker(
        $pdo,
        $chat_id,
        $data2,      // service_code_apiid
        $message_id,
        $cid
    );
    break;


            case 'AUTO_BUY':
    handle_auto_buy(
        $pdo,
        $chat_id,
        $data2,   // service_code
        $cid
    );
    break;
    
    
case 'AUTO_TOGGLE':
    handle_auto_toggle($pdo, $chat_id, $data2, $cid);
    handle_auto_try_once($pdo, $chat_id, $data2, $message_id, $cid);
    break;


case 'TG_SESSION':
    handle_telegram_session_buy($pdo, $chat_id, $cid);
    break;
case 'TG_BUY':

list($server_id, $qty) = explode('|', $data2);

handle_telegram_session_buy(
    $pdo,
    $chat_id,
    (int)$server_id,
    (int)$qty,
    $cid
);

break;

case 'TG_CONFIRM':

    $server_id = (int)$data2;

    $s = $pdo->query("
        SELECT * FROM account_servers WHERE id={$server_id}
    ")->fetch(PDO::FETCH_ASSOC);

    $bal = $pdo->prepare("SELECT balance FROM user_data WHERE user_id=?");
    $bal->execute([$chat_id]);

    $balance = $bal->fetchColumn();

    sendMessage(
        $chat_id,
        "⚠️ *Confirm Telegram Session Purchase*\n\n".
        "Service: {$s['name']}\n".
        "Price: ₹{$s['price']}\n".
        "Balance: ₹{$balance}",
        [
            "inline_keyboard" => [
                [
                    ["text" => "✅ Yes Buy", "callback_data" => "TG_BUY {$server_id}"],
                    ["text" => "❌ Cancel", "callback_data" => "ACC_SERVERS"]
                ]
            ]
        ],
        "Markdown"
    );

break;

            
        case "SEARCH":
             stop_all_auto_clickers($pdo, $chat_id);
            if(!$data2 ||  !$data3){
                 sendAlert('Something Went Wrong',$cid);
                 exit;
            }
            search_services($pdo,$chat_id,$data3,$data2);
            sendAlert('',$cid);
            break;
            
            
        case 'DEPOSIT_UPI':
             stop_all_auto_clickers($pdo, $chat_id);
            if(!$data2){
             file_put_contents("answer/$chat_id.txt","paytm");
             ask_deposit_amount($chat_id);
             deleteMessage($chat_id,$message_id);
            }else{
               handle_deposit_upi($chat_id,$data2);
               sendAlert('',$cid);
            }
             break;
        case "OTP_HISTORY":
             stop_all_auto_clickers($pdo, $chat_id);
            send_otp_history($pdo,$chat_id,$chat_id);
            sendAlert('',$cid);
            break;
        case "SERVICES":
           stop_all_auto_clickers($pdo, $chat_id);
            send_unique_services($pdo,$chat_id,$data2);
            sendAlert('',$cid);
            break;
            case 'DELETE_MSG':

    $message_id = $update['callback_query']['message']['message_id'];

    deleteMessage($chat_id, $message_id);

    break;

        case "CANCEL":
             stop_all_auto_clickers($pdo, $chat_id);
            if(!$data2){
                sendAlert("❌ Order ID not found. Kindly try again later.",$cid);
                exit;
            }
            handle_cancel_order($pdo,$chat_id,$data2,$message_id,$cid);
            break;
        case "DEPOSIT_HISTORY":
             stop_all_auto_clickers($pdo, $chat_id);
            send_deposit_history($pdo,$chat_id,$chat_id);
            sendAlert('',$cid);
            break;
        case 'ACCOUNT_BUY_HISTORY':
    buy_log("ROUTER ACCOUNT_BUY_HISTORY | user={$chat_id}");
    send_account_buy_history($pdo, $chat_id);
    break;


        case 'DEPOSIT_PAID':
             stop_all_auto_clickers($pdo, $chat_id);
            handle_deposit_paid($pdo,$chat_id,$data2,$PAYTM_MERCHANT_KEY,$cid,$message_id);
            break;
      case 'GET_OTP':
           stop_all_auto_clickers($pdo, $chat_id);
    // $data2 = order_id
    handle_get_otp(
        $pdo,
        $chat_id,
        $data2,
        $cq['message']['message_id'],$cid
    );
    break;
    case 'TG_CONFIRM':
    show_telegram_confirm($pdo, $chat_id, $cid);
    break;
    
    case 'NEW_OTP':
    handle_new_otp(
        $pdo,
        $chat_id,
        $data2,
        $cq['message']['message_id'],$cid
    );
    break;
case 'OTP_PAGE':
    send_history_page($pdo, $chat_id, $user_id, 'otp', (int)$data2);
    break;

case 'DEPOSIT_PAGE':
    send_history_page($pdo, $chat_id, $user_id, 'deposit', (int)$data2);
    break;
case 'HAS_COUPON':

            

            ask_coupon_code($chat_id);
            break;

        case 'NO_COUPON':

           

            start($pdo, $chat_id, "User");
            break;
    

        case 'JOINED':
            // example: CANCEL order_id
            handle_joined($pdo,$chat_id,$name,$cid,$message_id);
            break;
        case "BUY":
            handle_buy_callback($pdo,$chat_id,$data,$cid);
            sendAlert('',$cid);
            break;
        default:
            
            sendMessage($chat_id, "Invalid action");
    }
}
function sendDocument($chat_id, $file, $caption = '')
{
    global $BOT_TOKEN;

    $url = "https://api.telegram.org/bot{$BOT_TOKEN}/sendDocument";

    $post = [
        'chat_id'  => $chat_id,
        'document' => $file,
        'caption'  => $caption
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);

    buy_log("TELEGRAM RESPONSE = " . $result);

    if (curl_errno($ch)) {
        buy_log("CURL ERROR = " . curl_error($ch));
    }

    curl_close($ch);

    return $result;
}


function send_account_buy_history(PDO $pdo, string $chat_id)
{
    buy_log("ENTER send_account_buy_history | user={$chat_id}");

    $stmt = $pdo->prepare("
        SELECT 
            s.name AS service_name,
            a.username,
            a.password,
            a.used_at
        FROM accounts_stock a
        JOIN account_servers s ON s.id = a.server_id
        WHERE a.used_by = ?
          AND a.is_used = 1
        ORDER BY a.used_at DESC
        LIMIT 10
    ");
    $stmt->execute([(string)$chat_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    buy_log("HISTORY ROWS COUNT=" . count($rows));

    if (!$rows || count($rows) === 0) {
        sendMessage(
            $chat_id,
            "ℹ️ No account purchases found yet."
        );
        return;
    }

  $msg = "🧾 *Bᴜʏ Hɪsᴛᴏʀʏ (Lᴀsᴛ 10)* 😎🔥\n\n";

$i = 1;
foreach ($rows as $r) {
    $time = date('d M Y H:i', strtotime($r['used_at']));

    $msg .=
        "{$i}. 🚀 *{$r['service_name']}*\n".
        "👤 *Usᴇʀɴᴀᴍᴇ:* `{$r['username']}`\n".
        "🔑 *Pᴀssᴡᴏʀᴅ:* `{$r['password']}`\n".
        "⏱ *Tɪᴍᴇ:* {$time}\n\n";

    $i++;
}


    // 🔥 Plain text only (safe)
    sendMessage($chat_id, $msg);
}

function handle_deposit_upi(string $chat_id,  $amount)
{
    global $GATEWAY_MIN_AMOUNT, $PAYTM_UPI_ID,$pdo,$KUKUPAY_API_KEY;

    // basic validation
    $amount = intval($amount) ?? 0;
    if ($amount <= 9) {
        sendMessage($chat_id, "❌ Invalid amount.");
        return;
    }

    // generate unique txn id
    $rnd = "TXN" . time() . rand(100, 999);

    // ===== CASE 1: Amount < Gateway Min → Manual UPI =====
    if ($amount < $GATEWAY_MIN_AMOUNT) {

        /* ================= BUILD UPI ================= */
        $upi_link = "upi://pay"
            . "?pa={$PAYTM_UPI_ID}"
            . "&pn=Paytm%20Merchant"
            . "&tn=PAYING%20TO%20t%20"
            . "&tr={$rnd}"
            . "&am={$amount}";

        $qr_lib = "https://api.qrserver.com/v1/create-qr-code/?data="
            . urlencode($upi_link)
            . "&margin=35";

        /* ================= TELEGRAM SEND ================= */
        $caption =
            "🔎 *Scan this QR and send INR (₹{$amount})*\n\n"
            . "🧾 *Txn ID:* `{$rnd}`\n\n"
            . "After payment, click ➜ *PAID* ✅";

        $reply_markup = [
            "inline_keyboard" => [
                [
                    [
                        "text" => "✅ PAID",
                        "callback_data" => "DEPOSIT_PAID {$rnd}"
                    ]
                ],
                [
                    [
                        "text" => "🔄 Regenerate QR",
                        "callback_data" => "DEPOSIT_UPI {$amount}"
                    ]
                ]
            ]
        ];

        sendPhoto($chat_id, $qr_lib, $caption, $reply_markup);
        add_deposit($pdo,$chat_id,$amount,$rnd);
        return;
    }

    // ===== CASE 2: Amount >= Gateway Min (future use) =====
  
// ===== CASE 2: Amount >= Gateway Min =====

$payload = [
    "api_key"      => $KUKUPAY_API_KEY,
    "amount"       => intval($amount),
    "phone"        => $chat_id,
    "webhook_url"  => "https://" . BASE_URL . "/webhook_kukupay.php",
    "return_url"   => "https://t.me/" . BOT_USR,
    "order_id"     => $rnd
];

$headers = [
    "Content-Type: application/json"
];

$url = base64_decode("aHR0cHM6Ly9rdWt1cGF5LnByby9wYXkvY3JlYXRl");

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_HTTPHEADER     => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 20
]);

$response = curl_exec($ch);

if ($response === false) {
    sendMessage($chat_id, "❌ Gateway not responding. Try again later.");
    curl_close($ch);
    return;
}

curl_close($ch);

// decode response
$data = json_decode($response, true);

if (!is_array($data)) {
    sendMessage($chat_id, "❌ Invalid gateway response.");
    return;
}

/* ================= SUCCESS ================= */
if (isset($data['status']) && (int)$data['status'] === 200) {

    $payUrl = $data['data']['payment_url'] ?? null;
    $orderId = $data['data']['order_id'] ?? $rnd;

    if (!$payUrl) {
        sendMessage($chat_id, "❌ Payment URL not found.");
        return;
    }

    // save pending deposit
    add_deposit($pdo, $chat_id, $amount, $orderId);

  sendMessage(
    $chat_id,
    "*💳 Pᴀʏᴍᴇɴᴛ Lɪɴᴋ Cʀᴇᴀᴛᴇᴅ*\n\n".
    "💰 *Aᴍᴏᴜɴᴛ:* ₹{$amount}\n".
    "🧾 *Oʀᴅᴇʀ ID:* `{$orderId}`\n\n".
    "👉 [Cʟɪᴄᴋ Hᴇʀᴇ ᴛᴏ Pᴀʏ]({$payUrl})\n\n".
    "✅ *Pᴀʏᴍᴇɴᴛ Aᴜᴛᴏᴍᴀᴛɪᴄ Aᴅᴅ Hᴏ Jᴀʏᴇɢᴀ. Aɢᴀʀ Aᴅᴅ Nᴀʜɪ Hᴜᴀ ᴛᴏ Sᴜᴘᴘᴏʀᴛ Pᴀʀ Mᴇssᴀɢᴇ Kᴀʀᴏ, Aᴅᴅ Hᴏ Jᴀʏᴇɢᴀ.*",
    null,
    "Markdown"
);


    return;
}

/* ================= ERROR ================= */
$errorMsg = $data['message'] ?? 'Payment gateway error';

sendMessage(
    $chat_id,
    "❌ *Payment Failed*\n\n{$errorMsg}",
    null,
    "Markdown"
);
return;

}
function sendPhoto(string $chat_id, string $photo, string $caption, array $inline = null)
{
    $url = "https://api.telegram.org/bot" . BOT_TOKEN . "/sendPhoto";

    $params = [
        "chat_id" => $chat_id,
        "photo" => $photo,
        "caption" => $caption,
        "parse_mode" => "Markdown"
    ];

    if (!empty($inline)) {
        $params["reply_markup"] = json_encode($inline, JSON_UNESCAPED_UNICODE);
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10
    ]);

    curl_exec($ch);
    curl_close($ch);
}

function ban_filter(array $user, int $chat_id) {
    if ($user['status'] === 'BANNED') {
       sendMessage($chat_id,"🚫 You are banned."
        );
        exit;
    }
}

function send_deposit_menu(string $chat_id, string $name)
{
    sendMessage(
        $chat_id,
        "*👋 Hᴇʏ!* [$name](tg://user?id=$chat_id)\n\n".
        "*💰 Dᴇᴘᴏsɪᴛ Iɴғᴏʀᴍᴀᴛɪᴏɴ*\n\n".
        "• Mɪɴɪᴍᴜᴍ Dᴇᴘᴏsɪᴛ : *₹10*\n\n".
        "⚠️ *Nᴏᴛᴇ :- Aɢᴀʀ ᴀᴀᴘɴᴇ Dᴇᴘᴏsɪᴛ ᴋᴀʀ ʟɪʏᴀ ᴛᴏ Wɪᴛʜᴅʀᴀᴡᴀʟ ɴᴀʜɪ ʜᴏɢᴀ. Aᴀᴘ ᴜs Rᴀsʜɪ sᴇ Hᴀᴍᴀʀɪ Sᴇʀᴠɪᴄᴇ ᴜsᴇ ᴋᴀʀ sᴀᴋᴛᴇ ʜᴏ. Sᴇʀᴠɪᴄᴇ ᴀᴠᴀɪʟᴀʙʟᴇ ᴋᴀʀᴀɴᴇ ᴋɪ Jɪᴍᴍᴇᴅᴀʀɪ Hᴀᴍᴀʀɪ ʜᴀɪ.*\n\n".
        "👇 *Nɪᴄʜᴇ Dᴇᴘᴏsɪᴛ Bᴜᴛᴛᴏɴ Dᴀʙᴀᴏ*",
        [
            "inline_keyboard" => [
                [
                    [
                        "text" => "💠 Dᴇᴘᴏsɪᴛ ᴠɪᴀ UPI",
                        "callback_data" => "DEPOSIT_UPI"
                    ]
                ]
            ]
        ],
        "Markdown"
    );
}


function deleteMessage(string $chat_id, int $message_id): bool
{
    $url = "https://api.telegram.org/bot" . BOT_TOKEN . "/deleteMessage";

    $params = [
        'chat_id' => $chat_id,
        'message_id' => $message_id
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 5
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) {
        return false;
    }

    $data = json_decode($response, true);
    return isset($data['ok']) && $data['ok'] === true;
}
function is_user_joined(string $user_id, string $channel): bool
{
    $channel = ltrim($channel, '@');

    $url = "https://api.telegram.org/bot" . BOT_TOKEN . "/getChatMember";

    $params = [
        'chat_id' => '@' . $channel,
        'user_id' => $user_id
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 5
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) {
        return false;
    }

    $data = json_decode($response, true);

    if (!isset($data['ok']) || $data['ok'] !== true) {
        return false;
    }

    $status = $data['result']['status'] ?? '';

    // valid joined statuses
    return in_array($status, ['member', 'administrator', 'creator'], true);
}
function sendAlert($text, $id)
{
    $url ="https://api.telegram.org/bot" .BOT_TOKEN ."/answerCallbackQuery?callback_query_id={$id}&text=" .
        urlencode($text) .
        "&show_alert=true";
    $ch = curl_init($url);
    

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function sendMessage($chat_id, $text, $inline = null, $parse = "Markdown")
{
    $params = [
        "chat_id" => $chat_id,
        "text" => $text,
        "disable_web_page_preview" => true
    ];

    if (!empty($inline)) {
        $params["reply_markup"] = json_encode($inline, JSON_UNESCAPED_UNICODE);
    }

    if (!empty($parse)) {
        $params["parse_mode"] = $parse; // HTML or MarkdownV2
    }

    $url = "https://api.telegram.org/bot" .BOT_TOKEN . "/sendMessage";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 10
    ]);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log("Telegram CURL Error: " . curl_error($ch));
    }

    curl_close($ch);
    return $result;
}

function editMessage($chat_id,$msgID, $text, $inline = null, $parse = "Markdown")
{
    $params = [
        "chat_id" => $chat_id,
        "text" => $text,
        "disable_web_page_preview" => true,
        "message_id"=>$msgID
    ];

    if (!empty($inline)) {
        $params["reply_markup"] = json_encode($inline, JSON_UNESCAPED_UNICODE);
    }

    if (!empty($parse)) {
        $params["parse_mode"] = $parse; // HTML or MarkdownV2
    }

    $url = "https://api.telegram.org/bot" .BOT_TOKEN . "/editMessageText";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 10
    ]);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log("Telegram CURL Error: " . curl_error($ch));
    }

    curl_close($ch);
    return $result;
}
