<?php

/* CONFIGURATION */
$BOT_TOKEN = "7679448689:AAFhMiusY2SSgkCokM32b4BEW7N6AnQOGUw";
$BASE_URL = "otpking.in/fireotp";
$GATEWAY_MIN_AMOUNT = 100;
$PAYTM_UPI_ID= "paytm.s1fygm3@pty";
$PAYTM_MERCHANT_KEY =  "uQQLfW22173024367709";
$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);


$update = json_decode(file_get_contents("php://input"), true);
if (!$update) exit;
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 create / get
    $user = get_or_create_user($pdo, strval($chat_id), $name);

    // ban filter
    ban_filter($user, $chat_id);

    switch ($text) {

        case '/start':
            start($pdo,$chat_id,$name);
            break;

        case '➕ Deposit':
            send_deposit_menu($chat_id,$name);
            break;
        case '👤 Profile':
            send_profile($chat_id,$name,$user);
            break;
        case '🆘 Support':
            send_support($chat_id);
            break;
        case "⭐ Favourite":
            send_favourites($pdo,$chat_id,$chat_id);
            break;
        case "📲 Get OTP":
            send_unique_services($pdo,$chat_id);
          
            break;
        default:
            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;
            }elseif ($user['admin'] === "YES") {

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

    if($cmd == "/admin"){
        generate_admin_token($chat_id,$BASE_URL);
        exit;
    }
    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,"ok");

    // 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,
        "💰 *Deposit Credited*\n\nAmount: ₹{$amount}\nBy: Admin",
        null,
        "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_balance($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 '/buy':
            sendMessage($chat_id, "Buying OTP: $data2");
            break;
        case "SEARCH":
            if(!$data2 ||  !$data3){
                 sendAlert('Something Went Wrong',$cid);
                 exit;
            }
            search_services($pdo,$chat_id,$data3,$data2);
            sendAlert('',$cid);
            break;
        case 'DEPOSIT_UPI':
            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":
            send_otp_history($pdo,$chat_id,$chat_id);
            sendAlert('',$cid);
            break;
        case "SERVICES":
          
            send_unique_services($pdo,$chat_id,$data2);
            sendAlert('',$cid);
            break;
        case "CANCEL":
            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":
            send_deposit_history($pdo,$chat_id,$chat_id);
            sendAlert('',$cid);
            break;
        case 'DEPOSIT_PAID':
            handle_deposit_paid($pdo,$chat_id,$data2,$PAYTM_MERCHANT_KEY,$cid,$message_id);
            break;
      case 'GET_OTP':
    // $data2 = order_id
    handle_get_otp(
        $pdo,
        $chat_id,
        $data2,
        $cq['message']['message_id'],$cid
    );
    break;
    case 'NEW_OTP':
    handle_new_otp(
        $pdo,
        $chat_id,
        $data2,
        $cq['message']['message_id'],$cid
    );
    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 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 <= 99) {
        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%20FAST%20OTP"
            . "&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,
        "*💳 Payment Link Created*\n\n".
        "💰 *Amount:* ₹{$amount}\n".
        "🧾 *Order ID:* `{$orderId}`\n\n".
        "👉 [Click here to Pay]({$payUrl})\n\n".
        "⏳ After payment, balance will be added automatically.",
        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,
        "*👋 Hey!* [$name](tg://user?id=$chat_id)\n\n".
        "*💰 Deposit Information*\n\n".
        "• Minimum UPI Deposit: *₹100.00*\n".
        "• No extra charges up to *₹100*\n\n".
        "⚠️ *Note: Once deposit is successful, funds are non-withdrawable.*",
        [
            "inline_keyboard" => [
                [
                    [
                        "text" => "💠 Deposit via 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;
}
