<?php
// ============================================================
// COMPLETE ALL-IN-ONE TELEGRAM BOT - FULLY WORKING
// PAN + RC + DL + RATION + FARMER CARD + LL PDF + PAN TO UID
// ALL SERVICES WORKING + QR CODE + ADMIN PANEL
// ALL ADMIN COMMANDS WORKING - FIXED VERSION
// ============================================================

// ==================== CONFIGURATION ====================
$BOT_TOKEN = "8317749033:AAHZ9Njf-yiC5gfv0ChjyNlD4iiTh1pvHoI";

// ==================== WORKING APIs ====================
define('PAN_DETAILS_WORKING_API', 'https://api.satyadailynews.in/api/pan_to_details/v1/main/pan_tax.php?auth_token=25544C688632E225429EF7CFC45BE&pan=');
$PAN_API_URL = "https://ahkapi.in/api/v1/pan-find.php";
$RC_API_URL = "https://www.apizone.info/api/rc_pdf/rc.php";
$DL_API_URL = "https://www.apizone.info/api/dl_pdf/dlprint.php";
$RATION_API_URL = "https://mastmobile2.xyz/dsaosda/ration_to_uid.php";
$FARMER_API_UP = "https://mastmobile2.xyz/dompdf/up_fr.php?uid=";
$FARMER_API_BIHAR = "https://mastmobile2.xyz/dompdf/bh_fr.php?uid=";
$LL_PDF_API = "https://fast.manutrading.xyz/pariwahan/pdf/ll_pdf.php?applNum=";
define('CHECK_API', 'https://fast.manutrading.xyz/efill/chek_bot.php');
define('AADHAAR_API', 'https://fast.manutrading.xyz/efill/gen.php');

$API_KEY = "AK474548";
$ADMIN_ID = "6115049785";
$DB_FILE = 'bot_database.json';

// ==================== KEYBOARD LAYOUTS ====================
function getMainKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '🔍 PAN Search (Aadhaar)'], ['text' => '🔍 PAN Details (PAN)'], ['text' => '🔄 PAN to UID']],
            [['text' => '🚗 RC PDF'], ['text' => '🚦 DL PDF'], ['text' => '🍚 Ration UID']],
            [['text' => '🌾 Farmer Card (UP)'], ['text' => '🌾 Farmer Card (BIHAR)'], ['text' => '📄 LL PDF']],
            [['text' => '💰 Balance'], ['text' => '🛒 Buy Credits'], ['text' => '📞 Support']],
            [['text' => '🆘 Help'], ['text' => '⚙️ Admin Panel']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getAdminKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '📊 Bot Stats'], ['text' => '👥 Users List'], ['text' => '💰 Transactions']],
            [['text' => '➕ Add Balance'], ['text' => '➖ Deduct Balance'], ['text' => '👤 User Detail']],
            [['text' => '🚫 Ban User'], ['text' => '✅ Unban User'], ['text' => '📢 Broadcast']],
            [['text' => '🎯 User Price'], ['text' => '🔄 Credit Plan'], ['text' => '⚙️ Settings']],
            [['text' => '📋 All Commands'], ['text' => '🛠️ Tools']],
            [['text' => '🔙 Main Menu']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getSettingsKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '🎯 PAN Price'], ['text' => '🎯 PAN Detail Price'], ['text' => '🎯 PAN to UID Price']],
            [['text' => '🎯 RC Price'], ['text' => '🎯 DL Price'], ['text' => '🎯 Ration Price']],
            [['text' => '🎯 Farmer Price'], ['text' => '🎯 LL Price'], ['text' => '🎁 Free Credit']],
            [['text' => '📞 WhatsApp'], ['text' => '💳 UPI ID'], ['text' => '🔑 API KEY']],
            [['text' => '🔄 Bot ON/OFF'], ['text' => '📏 QR Size'], ['text' => '🔙 Admin Panel']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getUserPriceKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '🎯 User PAN Price'], ['text' => '🎯 User PAN Detail Price'], ['text' => '🎯 User PAN to UID Price']],
            [['text' => '🎯 User RC Price'], ['text' => '🎯 User DL Price'], ['text' => '🎯 User Ration Price']],
            [['text' => '🎯 User Farmer Price'], ['text' => '🎯 User LL Price'], ['text' => '🎯 Reset User Price']],
            [['text' => '👤 View User Price'], ['text' => '🔙 Admin Panel']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getCreditPlanKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '📊 View Plans'], ['text' => '➕ New Plan']],
            [['text' => '➖ Remove Plan'], ['text' => '🔢 Edit Plan']],
            [['text' => '🔙 Admin Panel']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getToolsKeyboard() {
    return json_encode([
        'keyboard' => [
            [['text' => '🔧 Export Users'], ['text' => '🔧 Export Logs']],
            [['text' => '🔧 Clear Logs'], ['text' => '🔧 Backup DB']],
            [['text' => '🔧 Reset Stats'], ['text' => '🔧 Restore DB']],
            [['text' => '🔙 Admin Panel']]
        ],
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ]);
}

function getBuyKeyboard() {
    $db = loadDB();
    $plans = $db['settings']['plans'];
    
    $keyboard = [];
    $row = [];
    $counter = 0;
    
    foreach ($plans as $credits => $price) {
        $row[] = ['text' => "$credits Credits ₹$price"];
        $counter++;
        
        if ($counter % 2 == 0) {
            $keyboard[] = $row;
            $row = [];
        }
    }
    
    if (!empty($row)) {
        $keyboard[] = $row;
    }
    
    $keyboard[] = [['text' => '🔙 Main Menu']];
    
    return json_encode([
        'keyboard' => $keyboard,
        'resize_keyboard' => true,
        'one_time_keyboard' => true
    ]);
}

// ==================== DATABASE FUNCTIONS ====================
function loadDB() {
    global $DB_FILE;
    if (!file_exists($DB_FILE)) {
        $data = [
            'users' => [],
            'settings' => [
                'pan_price' => 2, 'pan_detail_price' => 3, 'pan_to_uid_price' => 5,
                'rc_price' => 3, 'dl_price' => 4, 'ration_price' => 1,
                'farmer_price' => 20, 'll_price' => 10, 'free_credits' => 0,
                'bot_status' => 'active', 'upi_id' => 'paytmqr6omec0@ptys',
                'upi_name' => 'HARIOM BSNL', 'whatsapp_link' => 'https://wa.me/919841235815',
                'api_key' => 'AK474548', 'qr_size' => 300,
                'plans' => [10 => 10, 100 => 100, 500 => 500, 1000 => 1000],
                'banned_users' => []
            ],
            'transactions' => [], 'search_logs' => []
        ];
        file_put_contents($DB_FILE, json_encode($data, JSON_PRETTY_PRINT));
    }
    return json_decode(file_get_contents($DB_FILE), true);
}

function saveDB($data) {
    global $DB_FILE;
    file_put_contents($DB_FILE, json_encode($data, JSON_PRETTY_PRINT));
}

function getUser($chat_id) {
    $db = loadDB();
    if (in_array($chat_id, $db['settings']['banned_users'])) return false;
    return $db['users'][$chat_id] ?? null;
}

function updateUser($chat_id, $data) {
    $db = loadDB();
    if (!isset($db['users'][$chat_id])) {
        $free_credits = $db['settings']['free_credits'] ?? 0;
        $db['users'][$chat_id] = [
            'balance' => $free_credits, 'pan_searches' => 0, 'pan_detail_searches' => 0,
            'pan_to_uid_searches' => 0, 'rc_searches' => 0, 'dl_searches' => 0,
            'ration_searches' => 0, 'farmer_searches' => 0, 'll_searches' => 0,
            'joined' => date('Y-m-d H:i:s'), 'last_active' => date('Y-m-d H:i:s'),
            'custom_prices' => ['pan' => null, 'pan_detail' => null, 'pan_to_uid' => null,
                'rc' => null, 'dl' => null, 'ration' => null, 'farmer' => null, 'll' => null],
            'first_name' => '', 'username' => '', 'user_id' => $chat_id
        ];
    }
    foreach ($data as $key => $value) $db['users'][$chat_id][$key] = $value;
    $db['users'][$chat_id]['last_active'] = date('Y-m-d H:i:s');
    saveDB($db);
}

function addTransaction($chat_id, $type, $amount, $details = '') {
    $db = loadDB();
    $db['transactions'][] = ['user_id' => $chat_id, 'type' => $type, 'amount' => $amount,
        'details' => $details, 'timestamp' => date('Y-m-d H:i:s')];
    saveDB($db);
}

// ==================== TELEGRAM FUNCTIONS ====================
function botSendMessage($chat_id, $text, $keyboard = null) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/sendMessage";
    $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true];
    if ($keyboard) $data['reply_markup'] = $keyboard;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function botSendDocument($chat_id, $file_path, $caption = "") {
    global $BOT_TOKEN;
    if (!file_exists($file_path)) return false;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/sendDocument";
    $post_fields = ['chat_id' => $chat_id, 'caption' => $caption, 'parse_mode' => 'HTML',
        'document' => new CURLFile(realpath($file_path))];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    @unlink($file_path);
    return $result;
}

function botSendPhoto($chat_id, $photo_url, $caption = "", $keyboard = null) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/sendPhoto";
    $post_fields = ['chat_id' => $chat_id, 'caption' => $caption, 'parse_mode' => 'HTML', 'photo' => $photo_url];
    if ($keyboard) $post_fields['reply_markup'] = $keyboard;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

// ==================== PRICE MANAGEMENT ====================
function getUserPrice($chat_id, $service) {
    $db = loadDB();
    if (isset($db['users'][$chat_id]['custom_prices'][$service]) && $db['users'][$chat_id]['custom_prices'][$service] !== null) {
        return $db['users'][$chat_id]['custom_prices'][$service];
    }
    return $db['settings'][$service . '_price'];
}

function setUserPrice($user_id, $service, $price) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found: <code>$user_id</code>";
    $db['users'][$user_id]['custom_prices'][$service] = $price;
    saveDB($db);
    return "✅ User price set!\nUser: <code>$user_id</code>\nService: " . strtoupper($service) . "\nNew Price: $price credits";
}

function resetUserPrice($user_id, $service = null) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found: <code>$user_id</code>";
    if ($service === null) {
        $db['users'][$user_id]['custom_prices'] = ['pan' => null, 'pan_detail' => null, 'pan_to_uid' => null,
            'rc' => null, 'dl' => null, 'ration' => null, 'farmer' => null, 'll' => null];
        return "✅ All user prices reset!\nUser: <code>$user_id</code>";
    } else {
        $db['users'][$user_id]['custom_prices'][$service] = null;
        return "✅ User price reset!\nUser: <code>$user_id</code>\nService: " . strtoupper($service);
    }
}

function showUserPrice($chat_id, $user_id) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found: <code>$user_id</code>";
    $user = $db['users'][$user_id];
    $s = $db['settings'];
    $msg = "🎯 <b>User Price Details</b>\n\nUser ID: <code>$user_id</code>\n\n";
    $msg .= "🔹 PAN (Aadhaar): " . ($user['custom_prices']['pan'] ?? $s['pan_price']) . " credits\n";
    $msg .= "🔹 PAN Details: " . ($user['custom_prices']['pan_detail'] ?? $s['pan_detail_price']) . " credits\n";
    $msg .= "🔹 PAN to UID: " . ($user['custom_prices']['pan_to_uid'] ?? $s['pan_to_uid_price']) . " credits\n";
    $msg .= "🔹 RC: " . ($user['custom_prices']['rc'] ?? $s['rc_price']) . " credits\n";
    $msg .= "🔹 DL: " . ($user['custom_prices']['dl'] ?? $s['dl_price']) . " credits\n";
    $msg .= "🔹 Ration: " . ($user['custom_prices']['ration'] ?? $s['ration_price']) . " credits\n";
    $msg .= "🔹 Farmer: " . ($user['custom_prices']['farmer'] ?? $s['farmer_price']) . " credits\n";
    $msg .= "🔹 LL PDF: " . ($user['custom_prices']['ll'] ?? $s['ll_price']) . " credits";
    return $msg;
}

// ==================== CREDIT PLAN FUNCTIONS ====================
function showCreditPlans($chat_id) {
    $db = loadDB();
    $plans = $db['settings']['plans'];
    if (empty($plans)) {
        botSendMessage($chat_id, "❌ No Plans Available!\nCreate new plan using button below.", getCreditPlanKeyboard());
        return;
    }
    $msg = "🔄 Credit Plans List\n\nTotal Plans: " . count($plans) . "\n\n";
    $c = 1;
    foreach ($plans as $credits => $price) $msg .= "$c. $credits Credits = ₹$price\n";
    botSendMessage($chat_id, $msg, getCreditPlanKeyboard());
}

function addCreditPlan($credits, $price) {
    $db = loadDB();
    if ($credits <= 0 || $price <= 0) return "❌ Invalid values!";
    if (isset($db['settings']['plans'][$credits])) return "❌ Plan already exists!";
    $db['settings']['plans'][$credits] = $price;
    ksort($db['settings']['plans']);
    saveDB($db);
    return "✅ New plan added!\nCredits: $credits\nPrice: ₹$price";
}

function removeCreditPlan($credits) {
    $db = loadDB();
    if (!isset($db['settings']['plans'][$credits])) return "❌ Plan not found!";
    unset($db['settings']['plans'][$credits]);
    saveDB($db);
    return "✅ Plan removed!\nCredits: $credits";
}

function editCreditPlan($credits, $new_price) {
    $db = loadDB();
    if ($new_price <= 0) return "❌ Invalid price!";
    if (!isset($db['settings']['plans'][$credits])) return "❌ Plan not found!";
    $db['settings']['plans'][$credits] = $new_price;
    saveDB($db);
    return "✅ Plan updated!\nCredits: $credits\nNew Price: ₹$new_price";
}

// ==================== QR CODE FUNCTION ====================
function sendQRCode($chat_id, $upi_id, $amount, $credits) {
    $db = loadDB();
    $qr_size = $db['settings']['qr_size'] ?? 300;
    $upi_string = "upi://pay?pa=" . urlencode($upi_id) . "&pn=Credits%20Payment&am=" . $amount . "&tn=" . urlencode($credits . " Credits Payment") . "&cu=INR";
    $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=" . $qr_size . "x" . $qr_size . "&data=" . urlencode($upi_string);
    $caption = "💳 UPI Payment QR Code\n\n━━━━━━━━━━━━━━━━━━━━\n📋 Payment Details\n━━━━━━━━━━━━━━━━━━━━\n📦 Plan: $credits Credits\n💰 Amount: ₹$amount\nUPI ID: $upi_id\n━━━━━━━━━━━━━━━━━━━━\n\nScan QR code or pay manually to $upi_id";
    botSendPhoto($chat_id, $qr_url, $caption);
    return true;
}

// ==================== HELPER FUNCTIONS ====================
function makeRequest($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

function formatDob($dob) {
    if(empty($dob)) return '';
    $date = date_create($dob);
    if($date) return date_format($date, 'd/m/Y');
    return $dob;
}

// ==================== SERVICE FUNCTIONS ====================
function searchPAN($chat_id, $aadhaar) {
    global $PAN_API_URL, $API_KEY;
    $db = loadDB();
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'pan');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nPAN search: $price credits\nYour balance: {$user['balance']} credits\nBuy credits: /buy", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'pan_searches' => $user['pan_searches'] + 1]);
    addTransaction($chat_id, 'pan_search', $price, "Aadhaar: $aadhaar");
    botSendMessage($chat_id, "🔍 PAN search started...\nAadhaar: $aadhaar\nCost: $price credits\n⏳ Please wait...", getMainKeyboard());
    
    // FIXED: Correct API URL format
    $url = $PAN_API_URL . "?api_key=" . $API_KEY . "&aadhaar_no=" . urlencode($aadhaar);
    $response = makeRequest($url);
    
    if ($response) {
        $data = json_decode($response, true);
        // FIXED: Handle the actual API response format
        if ($data && isset($data['status']) && $data['status'] === true && isset($data['data']['pan_no'])) {
            $new_balance = getUser($chat_id)['balance'];
            $message = "✅ PAN found!\n\n━━━━━━━━━━━━━━━━━━━━\n📋 Result\n━━━━━━━━━━━━━━━━━━━━\n🆔 Aadhaar: " . ($data['data']['aadhaar_no'] ?? $aadhaar) . "\n📇 PAN: " . $data['data']['pan_no'] . "\n";
            if (isset($data['data']['application_no'])) $message .= "📄 Application No: " . $data['data']['application_no'] . "\n";
            $message .= "━━━━━━━━━━━━━━━━━━━━\n💰 Balance\n━━━━━━━━━━━━━━━━━━━━\nCost: $price credits\nRemaining: $new_balance credits";
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ PAN not found\n\nAadhaar: $aadhaar\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ API Error\n\nTry again later\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchPANDetails($chat_id, $pan_number) {
    $db = loadDB();
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'pan_detail');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nPAN Details: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'pan_detail_searches' => ($user['pan_detail_searches'] ?? 0) + 1]);
    addTransaction($chat_id, 'pan_detail_search', $price, "PAN: $pan_number");
    botSendMessage($chat_id, "🔍 PAN Details search started...\nPAN: $pan_number\nCost: $price credits", getMainKeyboard());
    $url = PAN_DETAILS_WORKING_API . urlencode($pan_number);
    $response = makeRequest($url);
    if ($response) {
        $data = json_decode($response, true);
        if ($data && isset($data['status']) && $data['status'] == 'success') {
            $new_balance = getUser($chat_id)['balance'];
            $full_name = $data['full_name'] ?? 'N/A';
            $father_name = $data['father_name'] ?? $data['fathername'] ?? 'N/A';
            $dob = formatDob($data['date_of_birth'] ?? '');
            $message = "✅ PAN DETAILS FOUND\n\n━━━━━━━━━━━━━━━━━━━━\n📋 PAN Details\n━━━━━━━━━━━━━━━━━━━━\n📇 PAN: $pan_number\n👤 Name: $full_name\n👨 Father: $father_name\n📅 DOB: $dob\n━━━━━━━━━━━━━━━━━━━━\n💰 Balance\n━━━━━━━━━━━━━━━━━━━━\nCost: $price credits\nRemaining: $new_balance credits";
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ PAN DETAILS NOT FOUND\n\n📇 PAN: $pan_number\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ API Error\n\nTry again later\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchPanToUID($chat_id, $pan_number) {
    $db = loadDB();
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'pan_to_uid');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nPAN to UID: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'pan_to_uid_searches' => ($user['pan_to_uid_searches'] ?? 0) + 1]);
    addTransaction($chat_id, 'pan_to_uid_search', $price, "PAN: $pan_number");
    botSendMessage($chat_id, "🔄 PAN to UID search started...\nPAN: $pan_number\nCost: $price credits", getMainKeyboard());
    $details_url = PAN_DETAILS_WORKING_API . urlencode($pan_number);
    $details_response = makeRequest($details_url);
    $pan_details = json_decode($details_response, true);
    if (!$pan_details || !isset($pan_details['status']) || $pan_details['status'] != 'success') {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "🔍 PAN TO UID RESULT\n\n━━━━━━━━━━━━━━━━━━━━\n📇 PAN: $pan_number\n\n❌ Aadhaar Details Not Found\n━━━━━━━━━━━━━━━━━━━━\n💰 Balance\n━━━━━━━━━━━━━━━━━━━━\nCost: $price credits\nRemaining: {$user['balance']} credits";
        botSendMessage($chat_id, $message, getMainKeyboard());
        return;
    }
    $full_name = $pan_details['full_name'] ?? '';
    $dob = formatDob($pan_details['date_of_birth'] ?? '');
    $check_url = CHECK_API . '?userId=' . urlencode($pan_number);
    $check_response = makeRequest($check_url);
    $status_result = json_decode($check_response, true);
    $status_message = isset($status_result['message']) ? $status_result['message'] : 'Pan Is Eligible To Find Aadhaar';
    $aadhaar_url = AADHAAR_API . '?userId=' . urlencode($pan_number) . '&name=' . urlencode($full_name) . '&dob=' . urlencode($dob) . '&userGender=M';
    $aadhaar_response = makeRequest($aadhaar_url);
    $aadhaar_result = json_decode($aadhaar_response, true);
    $new_balance = getUser($chat_id)['balance'];
    $aadhaar_no = '';
    if (isset($aadhaar_result['status_code']) && $aadhaar_result['status_code'] == 200) $aadhaar_no = $aadhaar_result['data']['aadhaar_number'] ?? '';
    elseif (isset($aadhaar_result['aadhaar'])) $aadhaar_no = $aadhaar_result['aadhaar'];
    elseif (isset($aadhaar_result['uid'])) $aadhaar_no = $aadhaar_result['uid'];
    $message = "🔍 PAN TO UID RESULT\n\n━━━━━━━━━━━━━━━━━━━━\n📇 PAN: $pan_number\n\n📝 Link Status: $status_message\n\n";
    if (!empty($aadhaar_no)) {
        $message .= "🆔 Aadhaar No: $aadhaar_no\n👤 Name: $full_name\n📅 DOB: $dob";
    } else {
        $message .= "❌ Aadhaar Details Not Found\nThe PAN is eligible but data could not be retrieved.";
    }
    $message .= "\n\n━━━━━━━━━━━━━━━━━━━━\n💰 Balance\n━━━━━━━━━━━━━━━━━━━━\nCost: $price credits\nRemaining: $new_balance credits\n━━━━━━━━━━━━━━━━━━━━\n🤖 Powered By HARIOM Bot";
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchRC($chat_id, $rc_number) {
    $db = loadDB();
    $api_key = $db['settings']['api_key'];
    global $RC_API_URL;
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $rc_number = strtoupper(trim($rc_number));
    $price = getUserPrice($chat_id, 'rc');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nRC PDF: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'rc_searches' => $user['rc_searches'] + 1]);
    addTransaction($chat_id, 'rc_search', $price, "RC: $rc_number");
    botSendMessage($chat_id, "🚗 RC PDF downloading...\nRC: $rc_number\nCost: $price credits", getMainKeyboard());
    $url = "$RC_API_URL?api_key=$api_key&rcno=" . urlencode($rc_number);
    $response = makeRequest($url);
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['status']) && $data['status'] == '200' && !empty($data['pdf'])) {
            $pdf_base64 = str_replace('data:application/pdf;base64,', '', $data['pdf']);
            $pdf_data = base64_decode($pdf_base64);
            if ($pdf_data) {
                $temp_file = sys_get_temp_dir() . '/RC_' . $rc_number . '_' . time() . '.pdf';
                file_put_contents($temp_file, $pdf_data);
                $new_balance = getUser($chat_id)['balance'];
                $caption = "📄 RC PDF\nNumber: $rc_number\nName: {$data['name']}\nCost: $price credits\nRemaining: $new_balance";
                botSendDocument($chat_id, $temp_file, $caption);
                $message = "✅ RC PDF downloaded!\nRC: $rc_number\nName: {$data['name']}\nCost: $price credits\n💰 Remaining: $new_balance";
            } else {
                updateUser($chat_id, ['balance' => $user['balance']]);
                $message = "❌ PDF process error\n\n💰 Credits refunded";
            }
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ RC PDF not found\nRC: $rc_number\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ API connection error\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchDL($chat_id, $dlno, $dob) {
    $db = loadDB();
    $api_key = $db['settings']['api_key'];
    global $DL_API_URL;
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $dlno = strtoupper(trim($dlno));
    $price = getUserPrice($chat_id, 'dl');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nDL PDF: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'dl_searches' => $user['dl_searches'] + 1]);
    addTransaction($chat_id, 'dl_search', $price, "DL: $dlno, DOB: $dob");
    botSendMessage($chat_id, "🚦 DL PDF generating...\nDL: $dlno\nDOB: $dob\nCost: $price credits", getMainKeyboard());
    $url = "$DL_API_URL?api_key=$api_key&dlno=" . urlencode($dlno) . "&dob=" . urlencode($dob);
    $response = makeRequest($url);
    if ($response) {
        $data = json_decode($response, true);
        if ($data && isset($data['status']) && $data['status'] == '200' && isset($data['pdf'])) {
            $pdf_data = $data['pdf'];
            if (strpos($pdf_data, 'base64,') !== false) $pdf_data = substr($pdf_data, strpos($pdf_data, 'base64,') + 7);
            $pdf_content = base64_decode($pdf_data);
            if ($pdf_content && strlen($pdf_content) > 100) {
                $temp_file = sys_get_temp_dir() . '/DL_' . $dlno . '_' . time() . '.pdf';
                file_put_contents($temp_file, $pdf_content);
                $new_balance = getUser($chat_id)['balance'];
                $caption = "📄 DL PDF\nNumber: $dlno\nDOB: $dob\nCost: $price credits\nRemaining: $new_balance";
                if (isset($data['application_no'])) $caption .= "\nApp No: " . $data['application_no'];
                botSendDocument($chat_id, $temp_file, $caption);
                $message = "✅ DL PDF generated!\nDL: $dlno\nDOB: $dob\nCost: $price credits\n💰 Remaining: $new_balance";
            } else {
                updateUser($chat_id, ['balance' => $user['balance']]);
                $message = "❌ PDF data invalid\n\n💰 Credits refunded";
            }
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ DL PDF not found\nDL: $dlno\nDOB: $dob\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ API connection error\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchRationUID($chat_id, $ration_number) {
    $db = loadDB();
    global $RATION_API_URL;
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'ration');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nRation UID: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'ration_searches' => ($user['ration_searches'] ?? 0) + 1]);
    addTransaction($chat_id, 'ration_search', $price, "Ration: $ration_number");
    botSendMessage($chat_id, "🍚 Ration UID search started...\nRation No: $ration_number\nCost: $price credits", getMainKeyboard());
    $url = "$RATION_API_URL?Id=" . urlencode($ration_number);
    $response = makeRequest($url);
    if ($response) {
        $data = json_decode($response, true);
        if ($data && isset($data['status']) && $data['status'] === "success") {
            $new_balance = getUser($chat_id)['balance'];
            $message = "✅ RATION CARD DETAILS FOUND\n\n━━━━━━━━━━━━━━━━━━━━\nRation No: {$data['ration_no']}\n━━━━━━━━━━━━━━━━━━━━\n\n";
            foreach ($data['data'] as $member) {
                $message .= "👤 {$member['Nameof_Family_Member_EN']}\nGender: {$member['Gender']}\nFather: {$member['Father_Name_EN']}\nRelation: {$member['RELATION']}\nDOB: {$member['DOB']}\nUID: {$member['UIDNo']}\n\n━━━━━━━━━━━━━━━━━━━━\n";
            }
            $message .= "💰 Balance\nCost: $price credits\nRemaining: $new_balance credits";
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ RATION CARD NOT FOUND\nRation No: $ration_number\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ API Error\n\nTry again later\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

function searchFarmerCard($chat_id, $state, $uid) {
    global $FARMER_API_UP, $FARMER_API_BIHAR;
    $db = loadDB();
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'farmer');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nFarmer Card: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'farmer_searches' => ($user['farmer_searches'] ?? 0) + 1]);
    addTransaction($chat_id, 'farmer_search', $price, "State: $state, UID: $uid");
    botSendMessage($chat_id, "🌾 Farmer Card PDF generating...\nState: " . strtoupper($state) . "\nUID: $uid\nCost: $price credits", getMainKeyboard());
    $api_url = ($state == 'up') ? $FARMER_API_UP . $uid : $FARMER_API_BIHAR . $uid;
    $response = makeRequest($api_url);
    if (!$response) {
        updateUser($chat_id, ['balance' => $user['balance']]);
        botSendMessage($chat_id, "⚠️ API Connection Error\n\n💰 Credits refunded", getMainKeyboard());
        return;
    }
    if (!is_dir("pdf")) mkdir("pdf", 0777, true);
    $pdf_url = "";
    $json_data = json_decode($response, true);
    if ($json_data) { if (isset($json_data['pdf'])) $pdf_url = $json_data['pdf']; if (isset($json_data['pdf_url'])) $pdf_url = $json_data['pdf_url']; }
    if (!$pdf_url && filter_var(trim($response), FILTER_VALIDATE_URL)) $pdf_url = trim($response);
    if (!$pdf_url) { preg_match('/https?:\/\/[^ ]+\.pdf/i', $response, $match); if (isset($match[0])) $pdf_url = $match[0]; }
    if (!$pdf_url) {
        updateUser($chat_id, ['balance' => $user['balance']]);
        botSendMessage($chat_id, "❌ Farmer Card Not Found\nState: " . strtoupper($state) . "\nUID: $uid\n\n💰 Credits refunded", getMainKeyboard());
        return;
    }
    $pdf_file = "pdf/farmer_{$uid}_{$state}_" . time() . ".pdf";
    $pdf_data = file_get_contents($pdf_url);
    if (!$pdf_data || strlen($pdf_data) < 100) {
        updateUser($chat_id, ['balance' => $user['balance']]);
        botSendMessage($chat_id, "❌ PDF Download Failed\n\n💰 Credits refunded", getMainKeyboard());
        return;
    }
    file_put_contents($pdf_file, $pdf_data);
    $new_balance = getUser($chat_id)['balance'];
    $caption = "✅ Farmer Card PDF Generated\n\n🌾 State: " . strtoupper($state) . "\n🆔 UID: $uid\n💰 Cost: $price credits\n💎 Remaining: $new_balance credits";
    botSendDocument($chat_id, $pdf_file, $caption);
    @unlink($pdf_file);
}

function searchLLPDF($chat_id, $application_number) {
    global $LL_PDF_API;
    $db = loadDB();
    $user = getUser($chat_id);
    if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!", getMainKeyboard()); return; }
    $price = getUserPrice($chat_id, 'll');
    if ($user['balance'] < $price) {
        botSendMessage($chat_id, "❌ Insufficient balance!\nLL PDF: $price credits\nBalance: {$user['balance']} credits", getMainKeyboard());
        return;
    }
    updateUser($chat_id, ['balance' => $user['balance'] - $price, 'll_searches' => ($user['ll_searches'] ?? 0) + 1]);
    addTransaction($chat_id, 'll_search', $price, "Application No: $application_number");
    botSendMessage($chat_id, "📄 LL PDF generating...\nApplication No: $application_number\nCost: $price credits", getMainKeyboard());
    $api_url = $LL_PDF_API . urlencode($application_number);
    $response = makeRequest($api_url);
    if ($response) {
        $json = json_decode($response, true);
        if (isset($json["status"]) && $json["status"] == "success" && isset($json["data"]["pdf"])) {
            $temp_file = sys_get_temp_dir() . '/LL_' . $application_number . '_' . time() . '.pdf';
            file_put_contents($temp_file, base64_decode($json["data"]["pdf"]));
            $new_balance = getUser($chat_id)['balance'];
            $caption = "📄 LL PDF Generated\n\n📋 Application No: $application_number\n💰 Cost: $price credits\n💎 Remaining: $new_balance credits";
            botSendDocument($chat_id, $temp_file, $caption);
            $message = "✅ LL PDF Generated!\nApplication No: $application_number\nCost: $price credits\n💰 Remaining: $new_balance";
        } elseif (substr($response, 0, 4) == "%PDF") {
            $temp_file = sys_get_temp_dir() . '/LL_' . $application_number . '_' . time() . '.pdf';
            file_put_contents($temp_file, $response);
            $new_balance = getUser($chat_id)['balance'];
            $caption = "📄 LL PDF Generated\n\n📋 Application No: $application_number\n💰 Cost: $price credits\n💎 Remaining: $new_balance credits";
            botSendDocument($chat_id, $temp_file, $caption);
            $message = "✅ LL PDF Generated!\nApplication No: $application_number\nCost: $price credits\n💰 Remaining: $new_balance";
        } else {
            updateUser($chat_id, ['balance' => $user['balance']]);
            $message = "❌ LL PDF Not Found\nApplication No: $application_number\n\n💰 Credits refunded";
        }
    } else {
        updateUser($chat_id, ['balance' => $user['balance']]);
        $message = "⚠️ Server Error\n\n💰 Credits refunded";
    }
    botSendMessage($chat_id, $message, getMainKeyboard());
}

// ==================== PAYMENT FUNCTIONS ====================
function showBuyCredits($chat_id) {
    $db = loadDB();
    $plans = $db['settings']['plans'];
    $msg = "🛒 Buy Credits\n\nSelect a plan:\n\n";
    foreach ($plans as $credits => $price) $msg .= "• $credits Credits = ₹$price\n";
    $msg .= "\n📱 UPI: " . $db['settings']['upi_id'] . "\n📞 Support: " . $db['settings']['whatsapp_link'];
    botSendMessage($chat_id, $msg, getBuyKeyboard());
}

function processPayment($chat_id, $plan_text) {
    $db = loadDB();
    preg_match('/(\d+)\s+Credits\s+₹(\d+)/', $plan_text, $matches);
    if (count($matches) < 3) { botSendMessage($chat_id, "❌ Could not identify plan!", getMainKeyboard()); return; }
    $credits = (int)$matches[1];
    $amount = (int)$matches[2];
    if (!isset($db['settings']['plans'][$credits]) || $db['settings']['plans'][$credits] != $amount) {
        botSendMessage($chat_id, "❌ Invalid plan!", getMainKeyboard());
        return;
    }
    sendQRCode($chat_id, $db['settings']['upi_id'], $amount, $credits);
    botSendMessage($chat_id, "💰 Payment Details\n\n🎯 Plan: $credits Credits\n💰 Amount: ₹$amount\n📱 UPI: " . $db['settings']['upi_id'] . "\n\nAfter payment, send screenshot on WhatsApp: " . $db['settings']['whatsapp_link'], getMainKeyboard());
}

// ==================== ADMIN PANEL FUNCTIONS ====================
function showAdminPanel($chat_id) {
    $db = loadDB();
    botSendMessage($chat_id, "⚡ ADMIN CONTROL PANEL\n\n📊 Users: " . count($db['users']) . "\n🟢 Bot Status: " . $db['settings']['bot_status'] . "\n👑 Admin ID: $chat_id\n\nUse below buttons:", getAdminKeyboard());
}

function adminStats($chat_id) {
    $db = loadDB();
    $total_users = count($db['users']);
    $total_balance = $total_pan = $total_pan_detail = $total_pan_to_uid = $total_rc = $total_dl = $total_ration = $total_farmer = $total_ll = 0;
    foreach ($db['users'] as $user) {
        $total_balance += $user['balance'];
        $total_pan += $user['pan_searches'];
        $total_pan_detail += ($user['pan_detail_searches'] ?? 0);
        $total_pan_to_uid += ($user['pan_to_uid_searches'] ?? 0);
        $total_rc += $user['rc_searches'];
        $total_dl += $user['dl_searches'];
        $total_ration += ($user['ration_searches'] ?? 0);
        $total_farmer += ($user['farmer_searches'] ?? 0);
        $total_ll += ($user['ll_searches'] ?? 0);
    }
    $msg = "📊 Bot Statistics\n\n👥 Users: $total_users\n💰 Total Balance: $total_balance credits\n\n🔍 Search Stats:\n• PAN (Aadhaar): $total_pan\n• PAN Details: $total_pan_detail\n• PAN to UID: $total_pan_to_uid\n• RC: $total_rc\n• DL: $total_dl\n• Ration: $total_ration\n• Farmer: $total_farmer\n• LL PDF: $total_ll";
    botSendMessage($chat_id, $msg);
}

function adminAddBalance($admin_id, $user_id, $amount) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found!";
    $db['users'][$user_id]['balance'] += $amount;
    saveDB($db);
    @botSendMessage($user_id, "💰 Admin added $amount credits to your account!");
    return "✅ Added $amount credits to $user_id";
}

function adminDeductBalance($admin_id, $user_id, $amount) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found!";
    if ($db['users'][$user_id]['balance'] < $amount) return "❌ Insufficient balance!";
    $db['users'][$user_id]['balance'] -= $amount;
    saveDB($db);
    @botSendMessage($user_id, "💰 Admin deducted $amount credits from your account!");
    return "✅ Deducted $amount credits from $user_id";
}

function getUserDetails($chat_id, $user_id) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found!";
    $user = $db['users'][$user_id];
    $msg = "👤 USER DETAILS\n\n🆔 ID: $user_id\n👤 Name: {$user['first_name']}\n📱 Username: @" . ($user['username'] ?? 'N/A') . "\n💰 Balance: {$user['balance']} credits\n📅 Joined: {$user['joined']}\n\n📊 Stats:\n• PAN: {$user['pan_searches']}\n• PAN Details: " . ($user['pan_detail_searches'] ?? 0) . "\n• PAN to UID: " . ($user['pan_to_uid_searches'] ?? 0) . "\n• RC: {$user['rc_searches']}\n• DL: {$user['dl_searches']}\n• Ration: " . ($user['ration_searches'] ?? 0) . "\n• Farmer: " . ($user['farmer_searches'] ?? 0) . "\n• LL PDF: " . ($user['ll_searches'] ?? 0);
    return $msg;
}

function showUsersList($chat_id) {
    $db = loadDB();
    $users = $db['users'];
    if (empty($users)) { botSendMessage($chat_id, "❌ No users found!"); return; }
    $msg = "👥 USERS LIST\n\nTotal: " . count($users) . " users\n\n";
    $c = 1;
    foreach ($users as $user_id => $user) {
        $msg .= "$c. $user_id - {$user['first_name']} - {$user['balance']} credits\n";
        $c++;
        if ($c > 20) break;
    }
    botSendMessage($chat_id, $msg);
}

function showSettingsPanel($chat_id) {
    $db = loadDB();
    $s = $db['settings'];
    $msg = "⚙️ SETTINGS\n\n🎯 PAN Price: {$s['pan_price']} credits\n🎯 PAN Detail: {$s['pan_detail_price']} credits\n🎯 PAN to UID: {$s['pan_to_uid_price']} credits\n🎯 RC: {$s['rc_price']} credits\n🎯 DL: {$s['dl_price']} credits\n🎯 Ration: {$s['ration_price']} credits\n🎯 Farmer: {$s['farmer_price']} credits\n🎯 LL PDF: {$s['ll_price']} credits\n\n🎁 Free Credits: {$s['free_credits']}\n📞 WhatsApp: {$s['whatsapp_link']}\n💳 UPI: {$s['upi_id']}\n🟢 Bot Status: {$s['bot_status']}";
    botSendMessage($chat_id, $msg, getSettingsKeyboard());
}

function banUser($admin_id, $user_id, $reason) {
    $db = loadDB();
    if (!isset($db['users'][$user_id])) return "❌ User not found!";
    if (in_array($user_id, $db['settings']['banned_users'])) return "❌ User already banned!";
    $db['settings']['banned_users'][] = $user_id;
    saveDB($db);
    @botSendMessage($user_id, "🚫 Account Banned!\nReason: $reason");
    return "✅ User banned!";
}

function unbanUser($admin_id, $user_id) {
    $db = loadDB();
    if (!in_array($user_id, $db['settings']['banned_users'])) return "❌ User is not banned!";
    $key = array_search($user_id, $db['settings']['banned_users']);
    unset($db['settings']['banned_users'][$key]);
    $db['settings']['banned_users'] = array_values($db['settings']['banned_users']);
    saveDB($db);
    @botSendMessage($user_id, "✅ Account Unbanned!");
    return "✅ User unbanned!";
}

function broadcastMessage($admin_id, $message) {
    $db = loadDB();
    $sent = 0;
    foreach ($db['users'] as $user_id => $user) {
        if (!in_array($user_id, $db['settings']['banned_users'])) {
            @botSendMessage($user_id, "📢 Message from Admin\n\n$message");
            $sent++;
            usleep(50000);
        }
    }
    return "✅ Broadcast sent to $sent users!";
}

function showAllCommands($chat_id) {
    $msg = "🛠️ ADMIN COMMANDS LIST\n\n";
    $msg .= "👤 USER MANAGEMENT:\n";
    $msg .= "<code>add [user_id] [amount]</code> - Add balance\n";
    $msg .= "<code>deduct [user_id] [amount]</code> - Deduct balance\n";
    $msg .= "<code>userinfo [user_id]</code> - User details\n";
    $msg .= "<code>ban [user_id] [reason]</code> - Ban user\n";
    $msg .= "<code>unban [user_id]</code> - Unban user\n\n";
    $msg .= "🎯 PRICE MANAGEMENT:\n";
    $msg .= "<code>price [service] [amount]</code> - Set price\n";
    $msg .= "<code>freecredits [amount]</code> - Set free credits\n";
    $msg .= "<code>userprice set [id] [service] [price]</code> - Set user price\n";
    $msg .= "<code>userprice reset [id] [service]</code> - Reset user price\n";
    $msg .= "<code>userprice view [id]</code> - View user price\n\n";
    $msg .= "🔄 CREDIT PLANS:\n";
    $msg .= "<code>plan add [credits] [price]</code> - Add plan\n";
    $msg .= "<code>plan remove [credits]</code> - Remove plan\n";
    $msg .= "<code>plan edit [credits] [price]</code> - Edit plan\n\n";
    $msg .= "⚙️ SETTINGS:\n";
    $msg .= "<code>whatsapp [number]</code> - Set WhatsApp\n";
    $msg .= "<code>upi [id] [name]</code> - Set UPI\n";
    $msg .= "<code>apikey [key]</code> - Set API key\n";
    $msg .= "<code>qrsize [size]</code> - Set QR size\n";
    $msg .= "<code>botstatus [active/inactive]</code> - Bot status\n\n";
    $msg .= "📢 BROADCAST:\n";
    $msg .= "<code>broadcast [message]</code> - Send to all\n\n";
    $msg .= "🔧 TOOLS:\n";
    $msg .= "<code>export users</code> - Export users\n";
    $msg .= "<code>export transactions</code> - Export transactions\n";
    $msg .= "<code>clearlogs</code> - Clear logs\n";
    $msg .= "<code>resetstats</code> - Reset stats\n";
    $msg .= "<code>backup</code> - Backup DB\n";
    $msg .= "<code>commands</code> - This list\n\n";
    $msg .= "💡 Example: <code>add 6115049785 100</code>";
    botSendMessage($chat_id, $msg);
}

// ==================== MAIN BOT LOGIC ====================
$update = json_decode(file_get_contents('php://input'), true);
if (!$update) $update = $_POST ?: $_GET;

if (isset($update['message'])) {
    $message = $update['message'];
    $chat_id = $message['chat']['id'];
    $text = trim($message['text'] ?? '');
    $first_name = $message['from']['first_name'] ?? 'User';
    $username = $message['from']['username'] ?? '';
    $is_admin = ($chat_id == $ADMIN_ID);
    
    if (!is_dir("pdf")) mkdir("pdf", 0777, true);
    if (!is_dir("json_data")) mkdir("json_data", 0777, true);
    
    $db = loadDB();
    if (!isset($db['users'][$chat_id])) updateUser($chat_id, ['first_name' => $first_name, 'username' => $username]);
    
    // ========== ADMIN COMMANDS HANDLER (TEXT COMMANDS) ==========
    if ($is_admin && !empty($text) && $text[0] != '/') {
        $parts = explode(' ', $text, 5);
        $cmd = strtolower($parts[0]);
        
        if ($cmd == 'add' && count($parts) >= 3) {
            botSendMessage($chat_id, adminAddBalance($chat_id, $parts[1], (int)$parts[2]));
            exit;
        }
        if ($cmd == 'deduct' && count($parts) >= 3) {
            botSendMessage($chat_id, adminDeductBalance($chat_id, $parts[1], (int)$parts[2]));
            exit;
        }
        if ($cmd == 'userinfo' && count($parts) >= 2) {
            botSendMessage($chat_id, getUserDetails($chat_id, $parts[1]));
            exit;
        }
        if ($cmd == 'ban' && count($parts) >= 3) {
            botSendMessage($chat_id, banUser($chat_id, $parts[1], $parts[2]));
            exit;
        }
        if ($cmd == 'unban' && count($parts) >= 2) {
            botSendMessage($chat_id, unbanUser($chat_id, $parts[1]));
            exit;
        }
        if ($cmd == 'broadcast' && count($parts) >= 2) {
            botSendMessage($chat_id, broadcastMessage($chat_id, implode(' ', array_slice($parts, 1))));
            exit;
        }
        if ($cmd == 'price' && count($parts) >= 3) {
            $service = $parts[1];
            $amount = (int)$parts[2];
            $valid = ['pan', 'pan_detail', 'pan_to_uid', 'rc', 'dl', 'ration', 'farmer', 'll'];
            if (in_array($service, $valid)) {
                $db = loadDB();
                $db['settings'][$service . '_price'] = $amount;
                saveDB($db);
                botSendMessage($chat_id, "✅ $service price updated to $amount credits");
            } else {
                botSendMessage($chat_id, "❌ Invalid service! Use: pan, pan_detail, pan_to_uid, rc, dl, ration, farmer, ll");
            }
            exit;
        }
        if ($cmd == 'freecredits' && count($parts) >= 2) {
            $db = loadDB();
            $db['settings']['free_credits'] = (int)$parts[1];
            saveDB($db);
            botSendMessage($chat_id, "✅ Free credits updated to " . $parts[1]);
            exit;
        }
        if ($cmd == 'whatsapp' && count($parts) >= 2) {
            $db = loadDB();
            $db['settings']['whatsapp_link'] = "https://wa.me/" . $parts[1];
            saveDB($db);
            botSendMessage($chat_id, "✅ WhatsApp updated");
            exit;
        }
        if ($cmd == 'upi' && count($parts) >= 3) {
            $db = loadDB();
            $db['settings']['upi_id'] = $parts[1];
            $db['settings']['upi_name'] = $parts[2];
            saveDB($db);
            botSendMessage($chat_id, "✅ UPI updated");
            exit;
        }
        if ($cmd == 'apikey' && count($parts) >= 2) {
            $db = loadDB();
            $db['settings']['api_key'] = $parts[1];
            saveDB($db);
            botSendMessage($chat_id, "✅ API Key updated");
            exit;
        }
        if ($cmd == 'qrsize' && count($parts) >= 2) {
            $size = (int)$parts[1];
            if ($size < 100 || $size > 1000) {
                botSendMessage($chat_id, "❌ QR size must be between 100 and 1000px");
            } else {
                $db = loadDB();
                $db['settings']['qr_size'] = $size;
                saveDB($db);
                botSendMessage($chat_id, "✅ QR size updated to {$size}px");
            }
            exit;
        }
        if ($cmd == 'botstatus' && count($parts) >= 2) {
            $status = strtolower($parts[1]);
            if (in_array($status, ['active', 'inactive'])) {
                $db = loadDB();
                $db['settings']['bot_status'] = $status;
                saveDB($db);
                botSendMessage($chat_id, "✅ Bot status: $status");
            } else {
                botSendMessage($chat_id, "❌ Use: active or inactive");
            }
            exit;
        }
        if ($cmd == 'userprice' && count($parts) >= 3) {
            $subcmd = strtolower($parts[1]);
            if ($subcmd == 'set' && count($parts) >= 5) {
                botSendMessage($chat_id, setUserPrice($parts[2], $parts[3], (int)$parts[4]));
            } elseif ($subcmd == 'reset' && count($parts) >= 3) {
                $service = count($parts) >= 4 ? $parts[3] : null;
                botSendMessage($chat_id, resetUserPrice($parts[2], $service));
            } elseif ($subcmd == 'view' && count($parts) >= 3) {
                botSendMessage($chat_id, showUserPrice($chat_id, $parts[2]));
            } else {
                botSendMessage($chat_id, "❌ Use: userprice set [id] [service] [price] OR userprice reset [id] [service] OR userprice view [id]");
            }
            exit;
        }
        if ($cmd == 'plan' && count($parts) >= 3) {
            $subcmd = strtolower($parts[1]);
            if ($subcmd == 'add' && count($parts) >= 4) {
                botSendMessage($chat_id, addCreditPlan((int)$parts[2], (int)$parts[3]));
            } elseif ($subcmd == 'remove' && count($parts) >= 3) {
                botSendMessage($chat_id, removeCreditPlan((int)$parts[2]));
            } elseif ($subcmd == 'edit' && count($parts) >= 4) {
                botSendMessage($chat_id, editCreditPlan((int)$parts[2], (int)$parts[3]));
            } else {
                botSendMessage($chat_id, "❌ Use: plan add [credits] [price] OR plan remove [credits] OR plan edit [credits] [price]");
            }
            exit;
        }
        if ($cmd == 'export' && count($parts) >= 2) {
            $type = strtolower($parts[1]);
            if ($type == 'users') {
                $db = loadDB();
                $data = json_encode($db['users'], JSON_PRETTY_PRINT);
                $file = sys_get_temp_dir() . '/users_' . time() . '.json';
                file_put_contents($file, $data);
                botSendDocument($chat_id, $file, "📊 Users Export");
            } elseif ($type == 'transactions') {
                $db = loadDB();
                $data = json_encode($db['transactions'], JSON_PRETTY_PRINT);
                $file = sys_get_temp_dir() . '/transactions_' . time() . '.json';
                file_put_contents($file, $data);
                botSendDocument($chat_id, $file, "💰 Transactions Export");
            } else {
                botSendMessage($chat_id, "❌ Use: export users OR export transactions");
            }
            exit;
        }
        if ($cmd == 'clearlogs') {
            $db = loadDB();
            $db['transactions'] = [];
            saveDB($db);
            botSendMessage($chat_id, "✅ Transaction logs cleared!");
            exit;
        }
        if ($cmd == 'resetstats') {
            $db = loadDB();
            foreach ($db['users'] as $uid => $user) {
                $db['users'][$uid]['pan_searches'] = 0;
                $db['users'][$uid]['pan_detail_searches'] = 0;
                $db['users'][$uid]['pan_to_uid_searches'] = 0;
                $db['users'][$uid]['rc_searches'] = 0;
                $db['users'][$uid]['dl_searches'] = 0;
                $db['users'][$uid]['ration_searches'] = 0;
                $db['users'][$uid]['farmer_searches'] = 0;
                $db['users'][$uid]['ll_searches'] = 0;
            }
            saveDB($db);
            botSendMessage($chat_id, "✅ All stats reset to zero!");
            exit;
        }
        if ($cmd == 'backup') {
            $db = loadDB();
            $data = json_encode($db, JSON_PRETTY_PRINT);
            $file = sys_get_temp_dir() . '/backup_' . date('Y-m-d_H-i-s') . '.json';
            file_put_contents($file, $data);
            botSendDocument($chat_id, $file, "💾 Database Backup");
            exit;
        }
        if ($cmd == 'commands') {
            showAllCommands($chat_id);
            exit;
        }
    }
    
    // Check bot status
    $db = loadDB();
    if ($db['settings']['bot_status'] == 'inactive' && !$is_admin) {
        botSendMessage($chat_id, "❌ Bot is currently inactive.");
        exit;
    }
    
    // Handle /start
    if ($text === '/start') {
        $user = getUser($chat_id);
        if (!$user) { botSendMessage($chat_id, "❌ Your account is banned!"); exit; }
        $welcome = "👋 Hello $first_name!\n\n🔍🚗🚦🍚🌾📄🔄 Welcome to ALL-IN-ONE Bot!\n\n💰 Your Balance: {$user['balance']} credits\n\n📌 How to use:\n• 12 digit Aadhaar → PAN by Aadhaar (2 credits)\n• 10 digit PAN → PAN Details (3 credits)\n• UID 10digitPAN → PAN to UID (5 credits)\n• RC number → RC PDF (3 credits)\n• DL# DD-MM-YYYY → DL PDF (4 credits)\n• RUID 12digitno → Ration UID (1 credit)\n• UP/BIHAR buttons → Farmer Card (20 credits)\n• Application No → LL PDF (10 credits)\n\n📱 Select service using buttons below:";
        botSendMessage($chat_id, $welcome, getMainKeyboard());
        exit;
    }
    
    // Handle button clicks
    switch ($text) {
        case '🔍 PAN Search (Aadhaar)':
            botSendMessage($chat_id, "🔍 Send 12 digit Aadhaar number:", getMainKeyboard());
            exit;
        case '🔍 PAN Details (PAN)':
            botSendMessage($chat_id, "🔍 Send 10 digit PAN number for details:", getMainKeyboard());
            exit;
        case '🔄 PAN to UID':
            botSendMessage($chat_id, "🔄 Send: UID AFAP07844R", getMainKeyboard());
            exit;
        case '🚗 RC PDF':
            botSendMessage($chat_id, "🚗 Send RC number:", getMainKeyboard());
            exit;
        case '🚦 DL PDF':
            botSendMessage($chat_id, "🚦 Send: DL# DD-MM-YYYY", getMainKeyboard());
            exit;
        case '🍚 Ration UID':
            botSendMessage($chat_id, "🍚 Send: RUID 12digitno", getMainKeyboard());
            exit;
        case '🌾 Farmer Card (UP)':
            botSendMessage($chat_id, "🌾 Send 12 digit Aadhaar number for UP Farmer Card:", getMainKeyboard());
            $db = loadDB();
            $db['users'][$chat_id]['temp_state'] = 'up';
            saveDB($db);
            exit;
        case '🌾 Farmer Card (BIHAR)':
            botSendMessage($chat_id, "🌾 Send 12 digit Aadhaar number for BIHAR Farmer Card:", getMainKeyboard());
            $db = loadDB();
            $db['users'][$chat_id]['temp_state'] = 'bihar';
            saveDB($db);
            exit;
        case '📄 LL PDF':
            botSendMessage($chat_id, "📄 Send Learning License Application Number:", getMainKeyboard());
            exit;
        case '💰 Balance':
            $user = getUser($chat_id);
            $msg = "💰 Your Balance: " . ($user ? $user['balance'] : 0) . " credits\n\n📊 Your Stats:\n• PAN: " . ($user['pan_searches'] ?? 0) . "\n• PAN Details: " . ($user['pan_detail_searches'] ?? 0) . "\n• PAN to UID: " . ($user['pan_to_uid_searches'] ?? 0) . "\n• RC: " . ($user['rc_searches'] ?? 0) . "\n• DL: " . ($user['dl_searches'] ?? 0) . "\n• Ration: " . ($user['ration_searches'] ?? 0) . "\n• Farmer: " . ($user['farmer_searches'] ?? 0) . "\n• LL PDF: " . ($user['ll_searches'] ?? 0);
            botSendMessage($chat_id, $msg, getMainKeyboard());
            exit;
        case '🛒 Buy Credits':
            showBuyCredits($chat_id);
            exit;
        case '📞 Support':
            $db = loadDB();
            botSendMessage($chat_id, "📞 WhatsApp Support: " . $db['settings']['whatsapp_link'], getMainKeyboard());
            exit;
        case '🆘 Help':
            $msg = "🆘 Help Center\n\n📌 Commands:\n• 12 digit Aadhaar → PAN (2 credits)\n• 10 digit PAN → PAN Details (3 credits)\n• UID 10digitPAN → PAN to UID (5 credits)\n• RC number → RC PDF (3 credits)\n• DL# DD-MM-YYYY → DL PDF (4 credits)\n• RUID 12digitno → Ration UID (1 credit)\n• UP/BIHAR buttons → Farmer Card (20 credits)\n• Application No → LL PDF (10 credits)\n\n💰 Buy credits: Press '🛒 Buy Credits' button";
            botSendMessage($chat_id, $msg, getMainKeyboard());
            exit;
        case '⚙️ Admin Panel':
            if ($is_admin) showAdminPanel($chat_id);
            else botSendMessage($chat_id, "❌ Admin only!");
            exit;
        case '🔙 Main Menu':
            botSendMessage($chat_id, "👋 Main Menu", getMainKeyboard());
            exit;
        case '🔙 Admin Panel':
            if ($is_admin) showAdminPanel($chat_id);
            exit;
        case '📊 Bot Stats':
            if ($is_admin) adminStats($chat_id);
            exit;
        case '👥 Users List':
            if ($is_admin) showUsersList($chat_id);
            exit;
        case '💰 Transactions':
            if ($is_admin) {
                $db = loadDB();
                $transactions = array_slice($db['transactions'], -20);
                $msg = "💰 Recent Transactions\n\n";
                foreach ($transactions as $t) $msg .= "User: {$t['user_id']}\nType: {$t['type']}\nAmount: {$t['amount']}\nTime: {$t['timestamp']}\n━━━━━━━━━━━━\n";
                botSendMessage($chat_id, $msg ?: "No transactions yet!");
            }
            exit;
        case '➕ Add Balance':
            if ($is_admin) botSendMessage($chat_id, "➕ Add Balance\n\nFormat: add [user_id] [amount]\nExample: add 123456789 50");
            exit;
        case '➖ Deduct Balance':
            if ($is_admin) botSendMessage($chat_id, "➖ Deduct Balance\n\nFormat: deduct [user_id] [amount]\nExample: deduct 123456789 10");
            exit;
        case '👤 User Detail':
            if ($is_admin) botSendMessage($chat_id, "👤 View User Detail\n\nFormat: userinfo [user_id]\nExample: userinfo 123456789");
            exit;
        case '🚫 Ban User':
            if ($is_admin) botSendMessage($chat_id, "🚫 Ban User\n\nFormat: ban [user_id] [reason]\nExample: ban 123456789 Fraud");
            exit;
        case '✅ Unban User':
            if ($is_admin) botSendMessage($chat_id, "✅ Unban User\n\nFormat: unban [user_id]\nExample: unban 123456789");
            exit;
        case '📢 Broadcast':
            if ($is_admin) botSendMessage($chat_id, "📢 Broadcast Message\n\nFormat: broadcast [message]\nExample: broadcast Hello Users!");
            exit;
        case '🎯 User Price':
            if ($is_admin) botSendMessage($chat_id, "🎯 User Price Management\n\nSelect option:", getUserPriceKeyboard());
            exit;
        case '🔄 Credit Plan':
            if ($is_admin) showCreditPlans($chat_id);
            exit;
        case '⚙️ Settings':
            if ($is_admin) showSettingsPanel($chat_id);
            exit;
        case '📋 All Commands':
            if ($is_admin) showAllCommands($chat_id);
            else botSendMessage($chat_id, "❌ Admin only!");
            exit;
        case '🛠️ Tools':
            if ($is_admin) botSendMessage($chat_id, "🛠️ Admin Tools\n\nSelect a tool:", getToolsKeyboard());
            exit;
        case '🔧 Export Users':
            if ($is_admin) {
                $db = loadDB();
                $data = json_encode($db['users'], JSON_PRETTY_PRINT);
                $file = sys_get_temp_dir() . '/users_' . time() . '.json';
                file_put_contents($file, $data);
                botSendDocument($chat_id, $file, "📊 Users Export");
            }
            exit;
        case '🔧 Export Logs':
            if ($is_admin) {
                $db = loadDB();
                $data = json_encode($db['transactions'], JSON_PRETTY_PRINT);
                $file = sys_get_temp_dir() . '/transactions_' . time() . '.json';
                file_put_contents($file, $data);
                botSendDocument($chat_id, $file, "💰 Transactions Export");
            }
            exit;
        case '🔧 Clear Logs':
            if ($is_admin) {
                $db = loadDB();
                $count = count($db['transactions']);
                $db['transactions'] = [];
                saveDB($db);
                botSendMessage($chat_id, "✅ Transaction logs cleared! Removed $count transactions");
            }
            exit;
        case '🔧 Backup DB':
            if ($is_admin) {
                $db = loadDB();
                $data = json_encode($db, JSON_PRETTY_PRINT);
                $file = sys_get_temp_dir() . '/backup_' . date('Y-m-d_H-i-s') . '.json';
                file_put_contents($file, $data);
                botSendDocument($chat_id, $file, "💾 Database Backup");
            }
            exit;
        case '🔧 Reset Stats':
            if ($is_admin) {
                $db = loadDB();
                foreach ($db['users'] as $uid => $user) {
                    $db['users'][$uid]['pan_searches'] = 0;
                    $db['users'][$uid]['pan_detail_searches'] = 0;
                    $db['users'][$uid]['pan_to_uid_searches'] = 0;
                    $db['users'][$uid]['rc_searches'] = 0;
                    $db['users'][$uid]['dl_searches'] = 0;
                    $db['users'][$uid]['ration_searches'] = 0;
                    $db['users'][$uid]['farmer_searches'] = 0;
                    $db['users'][$uid]['ll_searches'] = 0;
                }
                saveDB($db);
                botSendMessage($chat_id, "✅ All user search statistics reset to zero!");
            }
            exit;
        case '🔧 Restore DB':
            if ($is_admin) botSendMessage($chat_id, "⚠️ Database Restore\n\nSend database backup file to restore.\n\nWarning: This will replace current database!");
            exit;
        default:
            // Handle payment plans
            if (preg_match('/(\d+)\s+Credits\s+₹(\d+)/', $text)) {
                processPayment($chat_id, $text);
                exit;
            }
            
            // Handle PAN to UID with UID prefix
            if (preg_match('/^UID\s+([A-Z]{5}[0-9]{4}[A-Z]{1})$/i', $text, $matches)) {
                searchPanToUID($chat_id, strtoupper($matches[1]));
                exit;
            }
            
            // Handle Farmer Card based on stored state
            $db = loadDB();
            if (isset($db['users'][$chat_id]['temp_state']) && preg_match('/^\d{12}$/', $text)) {
                $state = $db['users'][$chat_id]['temp_state'];
                unset($db['users'][$chat_id]['temp_state']);
                saveDB($db);
                searchFarmerCard($chat_id, $state, $text);
                exit;
            }
            
            // Handle PAN Details (10 digit PAN)
            if (preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i', $text)) {
                searchPANDetails($chat_id, strtoupper($text));
                exit;
            }
            
            // Handle PAN by Aadhaar (12 digit)
            if (preg_match('/^\d{12}$/', $text)) {
                searchPAN($chat_id, $text);
                exit;
            }
            
            // Handle RC search
            if (preg_match('/^[A-Z]{2}[0-9A-Z]+$/i', $text) && strlen($text) >= 5) {
                searchRC($chat_id, $text);
                exit;
            }
            
            // Handle DL search
            if (preg_match('/^[A-Z0-9]+\s+\d{2}-\d{2}-\d{4}$/i', $text)) {
                $parts = explode(' ', $text, 2);
                searchDL($chat_id, $parts[0], $parts[1]);
                exit;
            }
            
            // Handle Ration UID
            if (preg_match('/^RUID\s+(\d{12})$/i', $text, $matches)) {
                searchRationUID($chat_id, $matches[1]);
                exit;
            }
            
            // Handle LL PDF
            if (strlen($text) >= 10 && preg_match('/^[A-Z0-9]+$/i', $text)) {
                searchLLPDF($chat_id, $text);
                exit;
            }
            
            // Handle /buy command
            if ($text === '/buy') {
                showBuyCredits($chat_id);
                exit;
            }
            
            // Default response for unknown messages
            if (!empty($text)) {
                botSendMessage($chat_id, "❌ Invalid format!\n\n📌 Correct formats:\n• 12 digit Aadhaar → PAN\n• 10 digit PAN → PAN Details\n• UID 10digitPAN → PAN to UID\n• RC number → RC PDF\n• DL# DOB → DL PDF\n• RUID number → Ration\n• Use Farmer Card buttons for Farmer PDF\n• App No → LL PDF", getMainKeyboard());
            }
            break;
    }
}

// Handle document upload for database restore (admin only)
if (isset($update['message']['document']) && $update['message']['chat']['id'] == $ADMIN_ID) {
    $chat_id = $update['message']['chat']['id'];
    $file_id = $update['message']['document']['file_id'];
    $url = "https://api.telegram.org/bot$BOT_TOKEN/getFile?file_id=$file_id";
    $result = json_decode(file_get_contents($url), true);
    if ($result['ok']) {
        $file_url = "https://api.telegram.org/file/bot$BOT_TOKEN/" . $result['result']['file_path'];
        $backup_data = file_get_contents($file_url);
        if ($backup_data) {
            $restored_data = json_decode($backup_data, true);
            if ($restored_data) {
                saveDB($restored_data);
                botSendMessage($chat_id, "✅ Database restored successfully!");
            } else {
                botSendMessage($chat_id, "❌ Invalid backup file!");
            }
        }
    }
    exit;
}

echo "OK";
?>