<?php

$bot_token = "7712681015:AAGbAzTvKnOn97pX0SgnGOYbfiP0O_QJuDE";
$user_token = "2f64a6fc6a67468bba5863f97dbb7484";

/* DATABASE */
$tng_conn = mysqli_connect("localhost","verrifyi_unique","verrifyi_unique","verrifyi_unique");

// ================================================================
// PAYMENT CALLBACK
// ================================================================
if(isset($_GET['payment_callback']) && isset($_GET['order_id'])){

    $order_id  = trim($_GET['order_id']);
    $esc_order = mysqli_real_escape_string($tng_conn, $order_id);

    $dup = mysqli_query($tng_conn,"SELECT id FROM wallet_transactions WHERE order_id='$esc_order'");
    if(mysqli_num_rows($dup) > 0){ echo "Already credited."; exit; }

    $ch = curl_init("https://as.findkaro.xyz/api/check-order-status/");
    curl_setopt_array($ch,[
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query(['user_token'=>$user_token,'order_id'=>$order_id]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT        => 30
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($response, true);

    if(!$result || (int)($result['status'] ?? 0) !== 1){
        $mobile = mysqli_real_escape_string($tng_conn, trim($result['customerMobile'] ?? ''));
        if($mobile){
            $tuser = mysqli_query($tng_conn,"SELECT chat_id FROM telegram_users WHERE phone='$mobile'");
            if($trow = mysqli_fetch_assoc($tuser)){
                file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id={$trow['chat_id']}&text=".urlencode("❌ Payment fail ho gayi!\n\nDobara try karne ke liye menu mein jaao."));
            }
        }
        echo "Payment failed."; exit;
    }

    $amount      = floatval($result['amount']);
    $mobile      = mysqli_real_escape_string($tng_conn, trim($result['customerMobile']));

    mysqli_query($tng_conn,"UPDATE users SET balance = balance + $amount WHERE phone='$mobile'");
    $new_bal     = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT balance FROM users WHERE phone='$mobile'"));
    $new_balance = floatval($new_bal['balance'] ?? 0);

    mysqli_query($tng_conn,"INSERT INTO wallethistory(userid,purpose,amount,balance,date) VALUES('$mobile','Wallet Recharge By Telegram $order_id','$amount','$new_balance',NOW())");
    mysqli_query($tng_conn,"INSERT INTO wallet_transactions(order_id,mobile,amount,created_at) VALUES('$esc_order','$mobile','$amount',NOW())");

    $tuser = mysqli_query($tng_conn,"SELECT chat_id FROM telegram_users WHERE phone='$mobile'");
    if($trow = mysqli_fetch_assoc($tuser)){
        $msg = "✅ Wallet Recharge Successful!\n\n"
             . "💰 Amount Added: ₹{$amount}\n"
             . "📊 New Balance: ₹{$new_balance}\n"
             . "🔖 Order ID: {$order_id}\n\n"
             . "Thank you! 🙏";
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id={$trow['chat_id']}&text=".urlencode($msg));
    }

    $admin = "7740857770";
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$admin&text=".urlencode("💳 Payment Received!\n\n📱 Mobile: {$mobile}\n💰 Amount: ₹{$amount}\n📊 New Balance: ₹{$new_balance}"));

    echo "Success"; exit;
}


$update = json_decode(file_get_contents("php://input"), true);

// ================================================================
// MESSAGE HANDLER
// ================================================================
if(isset($update["message"])){

$chat_id = $update["message"]["chat"]["id"];
$text    = $update["message"]["text"] ?? '';
$username  = $update["message"]["from"]["username"] ?? '';
$firstname = $update["message"]["from"]["first_name"] ?? '';
if($username=="") $username = $firstname;

$admin = "7740857770";

/* USER PHOTO TO ADMIN */
if($chat_id != $admin && isset($update["message"]["photo"])){
    $getUser2 = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'"));
    if($getUser2 && empty($getUser2['step'])){
        $photo_id2  = end($update["message"]["photo"])["file_id"];
        $caption2   = $update["message"]["caption"] ?? '';
        $cap_msg    = "📸 Photo From User\n\n";
        $cap_msg   .= "👤 User: {$getUser2['username']}\n";
        $cap_msg   .= "📱 Phone: {$getUser2['phone']}\n";
        $cap_msg   .= "🆔 Chat ID: $chat_id";
        if(!empty($caption2)) $cap_msg .= "\n\n💬 Caption: $caption2";
        $ph_fwd = ["chat_id"=>$admin,"photo"=>$photo_id2,"caption"=>$cap_msg];
        file_get_contents("https://api.telegram.org/bot$bot_token/sendPhoto?".http_build_query($ph_fwd));
        exit;
    }
}

/* USER MESSAGE TO ADMIN - sirf forward, koi confirm nahi */
if($chat_id != $admin && strpos($text,"/start") === false && !empty($text)){
    $getUser = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'"));
    if($getUser && empty($getUser['step'])){
        $msg  = "📩 New Message From User\n\n";
        $msg .= "👤 User: {$getUser['username']}\n";
        $msg .= "📱 Phone: {$getUser['phone']}\n";
        $msg .= "🆔 Chat ID: $chat_id\n\n";
        $msg .= "💬 Message:\n$text";
        $admin_post = ["chat_id"=>$admin,"text"=>$msg];
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($admin_post));
        exit; // User ko koi confirm nahi - bas forward karke exit
    }
}

/* ADMIN REPLY SYSTEM */
if(isset($update["message"]["reply_to_message"]) && $chat_id == $admin){
    $reply_text = $update["message"]["reply_to_message"]["text"] ?? '';
    $reply_photo = $update["message"]["reply_to_message"]["photo"] ?? null;
    // Chat ID dhundo - text ya caption mein
    $search_in = $reply_text;
    if(empty($search_in)){
        $search_in = $update["message"]["reply_to_message"]["caption"] ?? '';
    }
    preg_match('/Chat ID: ([0-9]+)/',$search_in,$match);
    if(!empty($match[1])){
        $user_chat_id = $match[1];
        $bk_reply = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
        if(isset($update["message"]["photo"])){
            // Admin ne photo reply kiya - user ko photo bhejo
            $photo_id = end($update["message"]["photo"])["file_id"];
            $caption_text = $update["message"]["caption"] ?? "📩 Admin Reply";
            $ph_post = ["chat_id"=>$user_chat_id,"photo"=>$photo_id,"caption"=>$caption_text,"reply_markup"=>json_encode($bk_reply)];
            file_get_contents("https://api.telegram.org/bot$bot_token/sendPhoto?".http_build_query($ph_post));
        } else {
            // Admin ne text reply kiya
            $reply_post = ["chat_id"=>$user_chat_id,"text"=>"📩 Admin Reply\n\n$text","reply_markup"=>json_encode($bk_reply)];
            file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($reply_post));
        }
    }
    exit;
}

// Admin ka koi bhi aur message - menu mat bhejo, bas ignore karo
if($chat_id == $admin && strpos($text,"/start") === false){
    exit;
}

/* FORGOT PASSWORD COMMAND */
if($text=="/forgotpassword"){
    $user   = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'"));
    $mobile = $user['phone'];
    $otp    = rand(100000,999999);
    mysqli_query($tng_conn,"UPDATE telegram_users SET otp='$otp', step='fp_otp' WHERE chat_id='$chat_id'");
    file_get_contents("https://as.crssorgi.xyz/api/send-text?api_key=3f00023e784e76183178&number=91$mobile&msg=".urlencode("Your OTP for password reset: $otp"));
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("📲 OTP sent to your WhatsApp number. Enter OTP"));
    exit;
}

/* OTP VERIFY */
$user = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'"));

if($user && $user['step']=="fp_otp"){
    if($text != $user['otp']){
        $try = $user['otp_try'] + 1;
        mysqli_query($tng_conn,"UPDATE telegram_users SET otp_try='$try' WHERE chat_id='$chat_id'");
        if($try >= 4){
            mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp_try=0 WHERE chat_id='$chat_id'");
            file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Too many wrong OTP attempts.\n\nReturning to Main Menu."));
        } else {
            file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Wrong OTP\n\nAttempts left: ".(4-$try)));
        }
        exit;
    }
    $newpass = rand(100000,999999);
    $hash    = password_hash($newpass, PASSWORD_DEFAULT);
    mysqli_query($tng_conn,"UPDATE users SET password='$hash' WHERE phone='".$user['phone']."'");
    file_get_contents("https://as.crssorgi.xyz/api/send-text?api_key=3f00023e784e76183178&number=91".$user['phone']."&msg=".urlencode("🔑 Your new password: $newpass"));
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("🔑 Your new password: $newpass"));
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp_try=0 WHERE chat_id='$chat_id'");
    exit;
}

/* STEP: addbalance_amount */
if($user && $user['step'] == 'addbalance_amount'){
    $amount = intval($text);
    if($amount < 49){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Minimum ₹49 daalna zaroori hai.\n\nDobara amount daalo:"));
        exit;
    }
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='' WHERE chat_id='$chat_id'");
    $phone        = $user['phone'];
    $order_id     = $phone . '_' . time() . '_' . rand(1000,9999);
    $callback_url = "https://newunique.verrify.in/bot.php?payment_callback=1&order_id=" . urlencode($order_id);
    $gdata = [
        'customer_mobile' => $phone,
        'user_token'      => $user_token,
        'amount'          => $amount,
        'order_id'        => $order_id,
        'redirect_url'    => $callback_url,
        'remark1'         => 'WALLET',
        'remark2'         => 'ADD'
    ];
    $ch = curl_init("https://as.findkaro.xyz/api/create-order/");
    curl_setopt_array($ch,[
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($gdata),
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT        => 30
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    $r = json_decode($res, true);
    if(isset($r['status']) && strtolower($r['status'])==='success' && isset($r['result']['payment_url'])){
        $pay_url  = $r['result']['payment_url'];
        $keyboard = ["inline_keyboard"=>[[["text"=>"💳 Pay ₹{$amount} Now","url"=>$pay_url]]]];
        $post = [
            "chat_id"      => $chat_id,
            "text"         => "💳 Wallet Recharge - ₹{$amount}\n\nNeeche button dabao aur payment complete karo.\n\n⏰ Link sirf 10 min ke liye valid hai.",
            "reply_markup" => json_encode($keyboard)
        ];
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
    } else {
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Payment link nahi bana. Thodi der baad try karo."));
    }
    exit;
}

// ================================================================
// STEP: rcpdf_chiptype
// ================================================================
if($user && $user['step'] == 'rcpdf_chiptype'){
    $chip_map = ['1'=>'With Chip','2'=>'Without Chip','4'=>'New With Chip','3'=>'New Without Chip'];
    if(!array_key_exists($text, $chip_map)){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Invalid option!\n\nSirf 1, 2, 3 ya 4 type karo:\n\n1 - With Chip\n2 - Without Chip\n3 - New Without Chip\n4 - New With Chip"));
        exit;
    }
    $chip_label = $chip_map[$text];
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='rcpdf_rcno', otp='$text' WHERE chat_id='$chat_id'");
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("✅ Chip Type: $chip_label\n\nAb RC Number daalo:\nExample: MH12AB1234"));
    exit;
}

// ================================================================
// STEP: rcpdf_rcno
// ================================================================
if($user && $user['step'] == 'rcpdf_rcno'){
    $rcno     = strtoupper(trim($text));
    $chiptype = $user['otp'];
    $fee      = 25;

    mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp='' WHERE chat_id='$chat_id'");

    $urow   = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='".$user['phone']."'"));
    $wallet = floatval($urow['balance']);

    if($wallet < $fee){
        $keyboard = ["inline_keyboard"=>[[["text"=>"➕ Wallet Recharge Karo","callback_data"=>"addbalance"]]]];
        $post = [
            "chat_id"      => $chat_id,
            "text"         => "❌ Wallet Balance Low!\n\nRC PDF ke liye ₹{$fee} chahiye.\nAapka current balance: ₹{$wallet}\n\nPehle wallet recharge karo.",
            "reply_markup" => json_encode($keyboard)
        ];
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
        exit;
    }

    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("⏳ RC PDF generate ho raha hai...\n\n🚗 RC: $rcno\nPlease wait 30-60 seconds."));

    $orderid = "RC".rand(10000,99999).time();
    $api_key = "apikey";
    $api_url = "https://staging.brotool.online/api/rc_details/rc.php?api_key=$api_key&rc_number=$rcno&chiptype=$chiptype&api_orderid=$orderid";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $response = curl_exec($ch);
    curl_close($ch);

    if(!$response){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ API response nahi aaya.\n\nThodi der baad dobara try karo."));
        exit;
    }

    $res = json_decode($response, true);

    if(!isset($res['status']) || $res['status'] !== true){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ RC Verification Failed!\n\nRC Number check karo aur dobara try karo.\n\n(Balance deduct nahi hua)"));
        exit;
    }

    $pdf_base64 = str_replace('data:application/pdf;base64,', '', $res['pdf']);
    $pdf_data   = base64_decode($pdf_base64);

    $upload_dir = $_SERVER['DOCUMENT_ROOT']."/admin/uploads/rcpdf/";
    if(!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);

    $filename = "rcpdf_".$rcno."_".time().".pdf";
    $filepath = $upload_dir.$filename;
    file_put_contents($filepath, $pdf_data);

    if(filesize($filepath) < 1000){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ PDF generate nahi ho saka.\n\nDobara try karo.\n\n(Balance deduct nahi hua)"));
        exit;
    }

    $pdf_url      = "https://newunique.verrify.in/admin/uploads/rcpdf/".$filename;
    $esc_rcno     = mysqli_real_escape_string($tng_conn, $rcno);
    $esc_chiptype = mysqli_real_escape_string($tng_conn, $chiptype);
    $esc_orderid  = mysqli_real_escape_string($tng_conn, $orderid);
    $esc_pdf_path = mysqli_real_escape_string($tng_conn, "/admin/uploads/rcpdf/".$filename);
    $phone_esc    = mysqli_real_escape_string($tng_conn, $user['phone']);

    mysqli_query($tng_conn,"INSERT INTO sabprintrcpdf(userid,rcno,chiptype,orderid,pdf_url,status,fee) VALUES('$phone_esc','$esc_rcno','$esc_chiptype','$esc_orderid','$esc_pdf_path','Success','$fee')");
    mysqli_query($tng_conn,"UPDATE users SET balance=balance-$fee WHERE phone='$phone_esc'");
    $newbal = $wallet - $fee;
    mysqli_query($tng_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES('$phone_esc','$fee','$newbal','RC PDF Download By Telegram $rcno','1','Debit')");

    $chip_labels = ['1'=>'With Chip','2'=>'Without Chip','4'=>'New With Chip','3'=>'New Without Chip'];
    $chip_label  = $chip_labels[$chiptype] ?? $chiptype;

    $chip_labels = ['1'=>'With Chip','2'=>'Without Chip','4'=>'New With Chip','3'=>'New Without Chip'];
    $chip_label  = $chip_labels[$chiptype] ?? $chiptype;

    $rc_caption = "✅ RC PDF Ready!

"
               . "🚗 RC Number: $rcno
"
               . "📋 Chip Type: $chip_label
"
               . "💰 Fee Deducted: ₹{$fee}
"
               . "📊 New Balance: ₹{$newbal}";

    // User ko direct PDF bhejo
    $tmp_rc_user = tempnam(sys_get_temp_dir(), 'rc').'.pdf';
    file_put_contents($tmp_rc_user, $pdf_data);
    $ch_u = curl_init("https://api.telegram.org/bot$bot_token/sendDocument");
    curl_setopt_array($ch_u,[
        CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_POSTFIELDS=>['chat_id'=>$chat_id,'caption'=>$rc_caption,'document'=>new CURLFile($tmp_rc_user,'application/pdf',"RC_$rcno.pdf")]
    ]);
    curl_exec($ch_u); curl_close($ch_u); @unlink($tmp_rc_user);

    // Admin ko direct PDF bhejo
    $tmp_rc_admin = tempnam(sys_get_temp_dir(), 'rc').'.pdf';
    file_put_contents($tmp_rc_admin, $pdf_data);
    $ch_a = curl_init("https://api.telegram.org/bot$bot_token/sendDocument");
    curl_setopt_array($ch_a,[
        CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_POSTFIELDS=>['chat_id'=>$admin,'caption'=>"🚗 RC PDF Generated!

👤 {$urow['name']}
📱 {$user['phone']}
🔖 RC: $rcno
📋 $chip_label
💰 ₹{$fee} | 📊 ₹{$newbal}",'document'=>new CURLFile($tmp_rc_admin,'application/pdf',"RC_$rcno.pdf")]
    ]);
    curl_exec($ch_a); curl_close($ch_a); @unlink($tmp_rc_admin);

    exit;
}

// ================================================================
// STEP: agri_language
// ================================================================
if($user && $user['step'] == 'agri_language'){
    $lang_map = [
        '1'=>'hi','2'=>'bn','3'=>'ta','4'=>'te',
        '5'=>'mr','6'=>'gu','7'=>'kn','8'=>'ml',
        '9'=>'pa','10'=>'ur','11'=>'as','12'=>'or'
    ];
    if(!array_key_exists($text, $lang_map)){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Invalid option!\n\nSirf 1 se 12 ke beech number type karo:\n\n1-Hindi  2-Bengali  3-Tamil  4-Telugu\n5-Marathi  6-Gujarati  7-Kannada  8-Malayalam\n9-Punjabi  10-Urdu  11-Assamese  12-Odia"));
        exit;
    }
    $lang_code  = $lang_map[$text];
    $lang_names = [
        'hi'=>'Hindi','bn'=>'Bengali','ta'=>'Tamil','te'=>'Telugu',
        'mr'=>'Marathi','gu'=>'Gujarati','kn'=>'Kannada','ml'=>'Malayalam',
        'pa'=>'Punjabi','ur'=>'Urdu','as'=>'Assamese','or'=>'Odia'
    ];
    $lang_label = $lang_names[$lang_code];
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='agri_aadhaar', otp='$lang_code' WHERE chat_id='$chat_id'");
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("✅ Language: $lang_label\n\nAb 12-digit Aadhaar Number daalo:\nExample: 123456789012"));
    exit;
}

// ================================================================
// STEP: agri_aadhaar
// ================================================================
if($user && $user['step'] == 'agri_aadhaar'){
    $aadhaar  = trim($text);
    $language = $user['otp'];
    $fee      = 25;

    if(!preg_match('/^[0-9]{12}$/', $aadhaar)){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Invalid Aadhaar Number!\n\nSirf 12 digit ka number daalo.\nExample: 123456789012"));
        exit;
    }

    mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp='' WHERE chat_id='$chat_id'");

    $urow      = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='".$user['phone']."'"));
    $wallet    = floatval($urow['balance']);
    $phone_esc = mysqli_real_escape_string($tng_conn, $user['phone']);
    $esc_uid   = mysqli_real_escape_string($tng_conn, $aadhaar);

    if($wallet < $fee){
        $keyboard = ["inline_keyboard"=>[[["text"=>"➕ Wallet Recharge Karo","callback_data"=>"addbalance"]]]];
        $post = [
            "chat_id"      => $chat_id,
            "text"         => "❌ Wallet Balance Low!\n\nAgri PDF ke liye ₹{$fee} chahiye.\nAapka current balance: ₹{$wallet}\n\nPehle wallet recharge karo.",
            "reply_markup" => json_encode($keyboard)
        ];
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
        exit;
    }

    // Duplicate check
    $chkdup = mysqli_query($tng_conn,"SELECT id FROM sab_argi WHERE userid='$phone_esc' AND uidNumber='$esc_uid'");
    if(mysqli_num_rows($chkdup) > 0){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("⚠️ Yeh Aadhaar pehle already use ho chuka hai!\n\nIs number se dobara generate nahi ho sakta."));
        exit;
    }

    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("⏳ Agri PDF generate ho raha hai...\n\n🌾 Aadhaar: $aadhaar\nPlease wait 30-60 seconds."));

    $orderid = "ARGI".rand(10000,99999).time();
    $api_key = "apikey";
    $api_url = "https://authorized.flexsecure.in/serviceApi/FlexSecureV1/AgriStack/approvedFarmers_PDF.php?uidNumber=$aadhaar&language=$language&apiKey=$api_key";

    $ch = curl_init();
    curl_setopt_array($ch,[
        CURLOPT_URL            => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    if(!$response){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ API response nahi aaya.\n\nThodi der baad dobara try karo."));
        exit;
    }

    $res = json_decode($response, true);

    // Success check: statusCode === "100" (same as website)
    if(!isset($res['statusCode']) || $res['statusCode'] !== "100"){
        $err_msg = isset($res['error']) ? $res['error'] : (isset($res['msg']) ? $res['msg'] : 'Verification Failed');
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Agri PDF Failed!\n\n$err_msg\n\n(Balance deduct nahi hua)"));
        exit;
    }

    $pdf_raw = $res['pdf'] ?? '';
    if(empty($pdf_raw)){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ PDF data nahi mila.\n\n(Balance deduct nahi hua)"));
        exit;
    }

    // Base64 clean - prefix hata do
    $pdf_base64 = $pdf_raw;
    if(strpos($pdf_raw, 'base64,') !== false){
        $pdf_base64 = explode('base64,', $pdf_raw)[1];
    }
    $pdf_data = base64_decode(trim($pdf_base64));

    $lang_names = [
        'hi'=>'Hindi','bn'=>'Bengali','ta'=>'Tamil','te'=>'Telugu',
        'mr'=>'Marathi','gu'=>'Gujarati','kn'=>'Kannada','ml'=>'Malayalam',
        'pa'=>'Punjabi','ur'=>'Urdu','as'=>'Assamese','or'=>'Odia'
    ];
    $lang_label = $lang_names[$language] ?? $language;
    $esc_orderid  = mysqli_real_escape_string($tng_conn, $orderid);
    $esc_language = mysqli_real_escape_string($tng_conn, $language);

    // Server pe save karo
    $upload_dir = $_SERVER['DOCUMENT_ROOT']."/admin/uploads/argipdf/";
    if(!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
    $filename     = "argi_".$aadhaar."_".time().".pdf";
    $filepath     = $upload_dir.$filename;
    $bytes_written = file_put_contents($filepath, $pdf_data);
    $agri_caption = "✅ Agri PDF Ready!

"
               . "🌾 Aadhaar: $aadhaar
"
               . "🗣 Language: $lang_label
"
               . "💰 Fee Deducted: ₹{$fee}
"
               . "📊 New Balance: ₹{$newbal}";

    // DB save + wallet deduct
    $esc_pdf_path = mysqli_real_escape_string($tng_conn, "/admin/uploads/argipdf/".$filename);
    mysqli_query($tng_conn,"INSERT INTO sab_argi(userid,uidNumber,state,language,orderid,pdf_url,status,fee) VALUES('$phone_esc','$esc_uid','','$esc_language','$esc_orderid','$esc_pdf_path','Success','$fee')");
    mysqli_query($tng_conn,"UPDATE users SET balance=balance-$fee WHERE phone='$phone_esc'");
    $newbal = $wallet - $fee;
    mysqli_query($tng_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES('$phone_esc','$fee','$newbal','Agri PDF Download By Telegram $aadhaar','1','Debit')");

    // User ko direct PDF bhejo
    $tmp_agri_user = tempnam(sys_get_temp_dir(), 'agri').'.pdf';
    file_put_contents($tmp_agri_user, $pdf_data);
    $ch_au = curl_init("https://api.telegram.org/bot$bot_token/sendDocument");
    curl_setopt_array($ch_au,[
        CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_POSTFIELDS=>['chat_id'=>$chat_id,'caption'=>$agri_caption,'document'=>new CURLFile($tmp_agri_user,'application/pdf',"AgriPDF_$aadhaar.pdf")]
    ]);
    curl_exec($ch_au); curl_close($ch_au); @unlink($tmp_agri_user);

    // Admin ko direct PDF bhejo
    $tmp_agri_admin = tempnam(sys_get_temp_dir(), 'agri').'.pdf';
    file_put_contents($tmp_agri_admin, $pdf_data);
    $ch_aa = curl_init("https://api.telegram.org/bot$bot_token/sendDocument");
    curl_setopt_array($ch_aa,[
        CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_POSTFIELDS=>['chat_id'=>$admin,'caption'=>"🌾 Agri PDF Generated!

👤 {$urow['name']}
📱 {$user['phone']}
🪪 Aadhaar: $aadhaar
🗣 $lang_label
💰 ₹{$fee} | 📊 ₹{$newbal}",'document'=>new CURLFile($tmp_agri_admin,'application/pdf',"AgriPDF_$aadhaar.pdf")]
    ]);
    curl_exec($ch_aa); curl_close($ch_aa); @unlink($tmp_agri_admin);

}

// /start ya "start" aate hi step clear karo
if(strpos($text,"/start") !== false || strtolower(trim($text)) === "start"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='' WHERE chat_id='$chat_id'");
}

// ================================================================
// CONNECT TELEGRAM - EK PHONE = EK TELEGRAM ACCOUNT ONLY
// ================================================================
if(strpos($text,"/start ") !== false || preg_match('/^start\s+[0-9]{10}$/i', trim($text))){

    $phone     = trim(str_replace(["/start ","start "], "", $text));
    $esc_phone = mysqli_real_escape_string($tng_conn, $phone);

    $userCheck = mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='$esc_phone'");
    if(mysqli_num_rows($userCheck) == 0){
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Yeh number SAB FIND pe registered nahi hai.\n\nPehle website pe account banao phir Telegram connect karo."));
        exit;
    }

    $phoneCheck = mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE phone='$esc_phone'");
    if(mysqli_num_rows($phoneCheck) > 0){
        $existingUser = mysqli_fetch_assoc($phoneCheck);
        if($existingUser['chat_id'] != $chat_id){
            file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ Yeh number pehle se kisi aur Telegram account se linked hai.\n\nEk number sirf ek hi Telegram se connect ho sakta hai.\n\nApne original Telegram account se try karo."));
            exit;
        }
    } else {
        $chatCheck = mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'");
        if(mysqli_num_rows($chatCheck) > 0){
            $existingLink = mysqli_fetch_assoc($chatCheck);
            file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("⚠️ Tumhara Telegram pehle se number {$existingLink['phone']} se linked hai.\n\nEk Telegram se sirf ek number connect ho sakta hai."));
            exit;
        }

        $esc_uname = mysqli_real_escape_string($tng_conn, $username);
        mysqli_query($tng_conn,"INSERT INTO telegram_users(chat_id,username,phone) VALUES('$chat_id','$esc_uname','$esc_phone')");

        $bonus    = 10;
        $user_row = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='$esc_phone'"));
        $bonus_given = false;

        if($user_row){
            $chk = mysqli_query($tng_conn,"SELECT id FROM wallethistory WHERE userid='$esc_phone' AND purpose='Welcome Bonus - Telegram Join' LIMIT 1");
            $already_given = (mysqli_num_rows($chk) > 0);

            if(!$already_given){
                $old_bal = (float)$user_row['balance'];
                $new_bal = $old_bal + $bonus;
                mysqli_query($tng_conn,"UPDATE users SET balance='$new_bal' WHERE phone='$esc_phone'");
                mysqli_query($tng_conn,"INSERT INTO wallethistory(userid,purpose,amount,balance,date) VALUES('$esc_phone','Welcome Bonus - Telegram Join','$bonus','$new_bal',NOW())");
                $bonus_given = true;
            } else {
                $new_bal = (float)$user_row['balance'];
            }
        }

        if($bonus_given){
            $msg  = "🎉 Welcome to SAB FIND Bot!\n\n";
            $msg .= "✅ Aapka Telegram Successfully Connect Ho Gaya!\n\n";
            $msg .= "🎁 Welcome Bonus: ₹10 aapke wallet mein add kar diye gaye hain!\n\n";
            $msg .= "💰 Aapka New Balance: ₹".number_format($new_bal,2)."\n\n";
            $msg .= "📌 Ab aapko sabhi notifications milti rahengi.";
        } else {
            $msg  = "✅ Welcome to SAB FIND Bot!\n\n";
            $msg .= "✅ Aapka Telegram Successfully Connect Ho Gaya!\n\n";
            $msg .= "📌 Ab aapko sabhi notifications milti rahengi.";
        }
        file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode($msg));
    }
}

/* CHECK USER CONNECTED */
$checkUser = mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'");
if(mysqli_num_rows($checkUser)==0){
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ You are not connected with SAB FIND.\n\nPlease login to website and connect Telegram."));
    exit;
}

/* GET USER DATA */
$getPhone = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT phone FROM telegram_users WHERE chat_id='$chat_id'"));
$phone    = $getPhone['phone'];
$userData = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='$phone'"));
$name     = $userData['name'];
$balance  = $userData['balance'];

// Menu sirf /start ya "start" par aayega
if(strpos($text,"/start") === false && strtolower(trim($text)) !== "start"){
    exit; // Koi aur message - menu mat bhejo
}
// Step chal raha ho to menu mat bhejo
$_user_check = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT step FROM telegram_users WHERE chat_id='$chat_id'"));
if(!empty($_user_check['step'])){
    exit;
}

/* MAIN MENU - 2 Column Style (Photo jaisa) */
$msg = "🏠 Main Menu\n\nHi $name! 👋\nBalance: ₹$balance\n\nSelect an option below:\n🙏 Thank you for using our service!";
$keyboard = ["inline_keyboard"=>[
    [
        ["text"=>"💰 Balance Check",  "callback_data"=>"balance"],
        ["text"=>"💳 Recharge",       "callback_data"=>"addbalance"]
    ],
    [
        ["text"=>"📋 Last 20 Transactions", "callback_data"=>"history"],
        ["text"=>"📄 Today Transactions",   "callback_data"=>"today"]
    ],
    [
        ["text"=>"🚗 RC PDF",   "callback_data"=>"rcpdf"],
        ["text"=>"🌾 Agri PDF", "callback_data"=>"agripdf"]
    ],
    [
        ["text"=>"🔑 Forgot Password", "callback_data"=>"forgot"]
    ]
]];
$data = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($keyboard)];
file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($data));

} // end message


// ================================================================
// BUTTON CLICK
// ================================================================
if(isset($update["callback_query"])){

$chat_id = $update["callback_query"]["message"]["chat"]["id"];
$data    = $update["callback_query"]["data"];
$admin   = "7740857770";

$getPhone = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT phone FROM telegram_users WHERE chat_id='$chat_id'"));
if(!$getPhone){
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("❌ You are not connected."));
    exit;
}
$phone = $getPhone['phone'];
$user  = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='$phone'"));

// ================================================================
// MAIN MENU CALLBACK - Back to Main Menu button
// ================================================================
if($data=="mainmenu"){
    $userData2 = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM users WHERE phone='$phone'"));
    $name2    = $userData2['name'];
    $balance2 = $userData2['balance'];
    $msg = "🏠 Main Menu

Hi $name2! 👋
Balance: ₹$balance2

Select an option below:
🙏 Thank you for using our service!";
    $keyboard = ["inline_keyboard"=>[
        [
            ["text"=>"💰 Balance Check",  "callback_data"=>"balance"],
            ["text"=>"💳 Recharge",       "callback_data"=>"addbalance"]
        ],
        [
            ["text"=>"📋 Last 20 Transactions", "callback_data"=>"history"],
            ["text"=>"📄 Today Transactions",   "callback_data"=>"today"]
        ],
        [
            ["text"=>"🚗 RC PDF",   "callback_data"=>"rcpdf"],
            ["text"=>"🌾 Agri PDF", "callback_data"=>"agripdf"]
        ],
        [
            ["text"=>"🔑 Forgot Password", "callback_data"=>"forgot"]
        ]
    ]];
    $mpost = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($keyboard)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($mpost));
}

if($data=="balance"){
    $msg  = "💰 Wallet Balance\n\nName: ".$user['name']."\nUser ID: ".$user['phone']."\nBalance: ₹".$user['balance'];
    $bk = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $bp = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($bk)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($bp));
}

if($data=="addbalance"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='addbalance_amount' WHERE chat_id='$chat_id'");
    $msg = "💳 Wallet Recharge\n\nKitna balance add karna hai?\n\n💡 Minimum amount: ₹49\n\nSirf amount type karke bhejo\nExample: 150";
    $keyboard = ["inline_keyboard"=>[[["text"=>"❌ Cancel","callback_data"=>"cancel_recharge"]]]];
    $post = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($keyboard)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
}

if($data=="cancel_recharge"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='' WHERE chat_id='$chat_id'");
    $bk_cr = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $bp_cr = ["chat_id"=>$chat_id,"text"=>"❌ Recharge cancel kar diya.","reply_markup"=>json_encode($bk_cr)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($bp_cr));
}

if($data=="rcpdf"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='rcpdf_chiptype', otp='' WHERE chat_id='$chat_id'");
    $msg = "🚗 RC PDF Download\n\n"
         . "💰 Service Fee: ₹25\n"
         . "📊 Aapka Balance: ₹".$user['balance']."\n\n"
         . "📋 Chip Type select karo - number type karke bhejo:\n\n"
         . "1️⃣ - With Chip\n"
         . "2️⃣ - Without Chip\n"
         . "3️⃣ - New Without Chip\n"
         . "4️⃣ - New With Chip";
    $keyboard = ["inline_keyboard"=>[[["text"=>"❌ Cancel","callback_data"=>"cancel_rcpdf"]]]];
    $post = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($keyboard)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
}

if($data=="cancel_rcpdf"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp='' WHERE chat_id='$chat_id'");
    $bk_rcc = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $bp_rcc = ["chat_id"=>$chat_id,"text"=>"❌ RC PDF cancel kar diya.","reply_markup"=>json_encode($bk_rcc)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($bp_rcc));
}

if($data=="agripdf"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='agri_language', otp='' WHERE chat_id='$chat_id'");
    $msg = "🌾 Agri PDF Download\n\n"
         . "💰 Service Fee: ₹25\n"
         . "📊 Aapka Balance: ₹".$user['balance']."\n\n"
         . "🗣 Language select karo - number type karke bhejo:\n\n"
         . "1️⃣ - Hindi\n"
         . "2️⃣ - Bengali\n"
         . "3️⃣ - Tamil\n"
         . "4️⃣ - Telugu\n"
         . "5️⃣ - Marathi\n"
         . "6️⃣ - Gujarati\n"
         . "7️⃣ - Kannada\n"
         . "8️⃣ - Malayalam\n"
         . "9️⃣ - Punjabi\n"
         . "🔟 - Urdu\n"
         . "11 - Assamese\n"
         . "12 - Odia";
    $keyboard = ["inline_keyboard"=>[[["text"=>"❌ Cancel","callback_data"=>"cancel_agripdf"]]]];
    $post = ["chat_id"=>$chat_id,"text"=>$msg,"reply_markup"=>json_encode($keyboard)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($post));
}

if($data=="cancel_agripdf"){
    mysqli_query($tng_conn,"UPDATE telegram_users SET step='', otp='' WHERE chat_id='$chat_id'");
    $bk_agc = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $bp_agc = ["chat_id"=>$chat_id,"text"=>"❌ Agri PDF cancel kar diya.","reply_markup"=>json_encode($bk_agc)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($bp_agc));
}

if($data=="forgot"){
    $fuser  = mysqli_fetch_assoc(mysqli_query($tng_conn,"SELECT * FROM telegram_users WHERE chat_id='$chat_id'"));
    $mobile = $fuser['phone'];
    $otp    = rand(100000,999999);
    mysqli_query($tng_conn,"UPDATE telegram_users SET otp='$otp', step='fp_otp' WHERE chat_id='$chat_id'");
    file_get_contents("https://as.crssorgi.xyz/api/send-text?api_key=3f00023e784e76183178&number=91$mobile&msg=".urlencode("Your OTP for password reset: $otp"));
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode("📲 OTP sent to your WhatsApp number. Enter OTP"));
}

if($data=="today"){
    $q   = mysqli_query($tng_conn,"SELECT * FROM wallethistory WHERE userid='$phone' AND DATE(date)=CURDATE() ORDER BY id DESC LIMIT 20");
    $msg = "Today's Transactions:\n\nNo | Type | Amount | Closing | Time\n------------------------------------\n\n";
    $i   = 1;
    while($row=mysqli_fetch_assoc($q)){
        $msg .= $i." | ".$row['purpose']." | ".$row['amount']." | ".$row['balance']." | ".$row['date']."\n\n";
        $i++;
    }
    $bk_td = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $td_post = ["chat_id"=>$chat_id,"text"=>"```\n".$msg."\n```","parse_mode"=>"Markdown","reply_markup"=>json_encode($bk_td)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($td_post));
}

if($data=="history"){
    $q   = mysqli_query($tng_conn,"SELECT * FROM wallethistory WHERE userid='$phone' ORDER BY id DESC LIMIT 20");
    $msg = "Transaction History\n\nNo | Type | Amount | Closing | Time\n------------------------------------\n\n";
    $i   = 1;
    while($row=mysqli_fetch_assoc($q)){
        $msg .= $i." | ".$row['purpose']." | ".$row['amount']." | ".$row['balance']." | ".$row['date']."\n\n";
        $i++;
    }
    $bk_hs = ["inline_keyboard"=>[[["text"=>"🏠 Back to Main Menu","callback_data"=>"mainmenu"]]]];
    $hs_post = ["chat_id"=>$chat_id,"text"=>"```\n".$msg."\n```","parse_mode"=>"Markdown","reply_markup"=>json_encode($bk_hs)];
    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?".http_build_query($hs_post));
}

if($chat_id == $admin && strpos($data,"deletebroadcast") === 0){
    $bc_id = '';
    if(strpos($data,'deletebroadcast_') === 0){
        $bc_id = substr($data, strlen('deletebroadcast_'));
    }

    $esc_bcid = mysqli_real_escape_string($tng_conn, $bc_id);

    if($bc_id !== ''){
        $q = mysqli_query($tng_conn,"SELECT * FROM telegram_messages WHERE broadcast_id='$esc_bcid'");
    } else {
        $q = mysqli_query($tng_conn,"SELECT * FROM telegram_messages");
    }

    $deleted = 0;
    while($row=mysqli_fetch_assoc($q)){
        $del_url = "https://api.telegram.org/bot$bot_token/deleteMessage?chat_id={$row['chat_id']}&message_id={$row['message_id']}";
        @file_get_contents($del_url);
        $deleted++;
    }

    if($bc_id !== ''){
        mysqli_query($tng_conn,"DELETE FROM telegram_messages WHERE broadcast_id='$esc_bcid'");
    } else {
        mysqli_query($tng_conn,"DELETE FROM telegram_messages");
    }

    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$admin&text=".urlencode("🗑 Broadcast Deleted! $deleted messages removed."));
}

} // end callback

?>
