true])); if (!file_exists($payments_file)) file_put_contents($payments_file, json_encode([])); if (!file_exists($required_file)) file_put_contents($required_file, json_encode(new stdClass())); function getData($file) { return json_decode(file_get_contents($file), true); } function saveData($file, $data) { file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT)); } // safer save with LOCK_EX to avoid concurrent writes function saveDataLocked($file, $data) { file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT), LOCK_EX); } function logPayment($file, $entry) { $list = getData($file); if (!is_array($list)) $list = []; $list[] = $entry; saveData($file, $list); } // ========================================== // 📌 WEBHOOK (PUL TUSHGANDA AVTOMATIK ISHLOVCHI QISM) // ========================================== $_RAW_HUMO = file_get_contents('php://input'); $wh = json_decode($_RAW_HUMO, true); if ($wh && isset($wh['event']) && $wh['event'] === 'payment_confirmed') { $payload = explode("_", $wh['user_id']); $uid = (int)$payload[0]; $ad_id = $payload[1] ?? null; $amt = (float)$wh['amount']; $oid = (int)$wh['order_id']; $users = getData($users_file); $ads = getData($ads_file); if ($ad_id && isset($ads[$ad_id])) { if ($ads[$ad_id]['status'] === 'sold') { $users[$uid]['balance'] = ($users[$uid]['balance'] ?? 0) + $amt; $users[$uid]['step'] = 'start'; saveData($users_file, $users); bot('sendMessage', [ 'chat_id' => $uid, 'text' => "❌ Kechirasiz! Bu mijozni allaqachon boshqa usta sotib olib bo'ldi!\n\nO'tkazgan " . number_format($amt, 0, '.', ' ') . " so'm pulingiz bot balansingizga qaytarildi.", 'parse_mode' => 'HTML', 'reply_markup' => getMenu($uid) ]); echo json_encode(['ok' => true]); exit; } // KAYTARILMAS: BIR ODAM BIR E'LONNI FAQAT BIRINCHI MARTA SOTIB OLA OLADI if (isset($ads[$ad_id]['bought_by']) && (int)$ads[$ad_id]['bought_by'] === (int)$uid) { $users[$uid]['balance'] = ($users[$uid]['balance'] ?? 0) + $amt; $users[$uid]['step'] = 'start'; saveData($users_file, $users); bot('sendMessage', [ 'chat_id' => $uid, 'text' => "❌ Siz ushbu kontaktni avval sotib olgansiz!\n\nO'tkazgan " . number_format($amt, 0, '.', ' ') . " so'm pulingiz bot balansingizga qaytarildi.", 'parse_mode' => 'HTML', 'reply_markup' => getMenu($uid) ]); echo json_encode(['ok' => true]); exit; } $ads[$ad_id]['status'] = 'sold'; $ads[$ad_id]['bought_by'] = $uid; $ads[$ad_id]['bought_time'] = time(); saveData($ads_file, $ads); $client_id = $ads[$ad_id]['user_id']; if (isset($users[$client_id]['muted_until'])) { unset($users[$client_id]['muted_until']); } $users[$uid]['step'] = 'start'; saveData($users_file, $users); $from_chat_id = $ads[$ad_id]['from_chat_id'] ?? null; if ($from_chat_id) { bot('restrictChatMember', [ 'chat_id' => $from_chat_id, 'user_id' => $client_id, 'until_date' => 0, 'permissions' => json_encode([ 'can_send_messages' => true, 'can_send_media_messages' => true, 'can_send_polls' => true, 'can_send_other_messages' => true, 'can_add_web_page_previews' => true, 'can_change_info' => true, 'can_invite_users' => true, 'can_pin_messages' => true ]) ]); } $c_phone = $ads[$ad_id]['phone'] ?? ""; // If phone is placeholder or empty, try to extract from ad text if (empty($c_phone) || strpos($c_phone, "Guruhdan") !== false || $c_phone === "Ko'rsatilmagan") { $det = extract_phone($ads[$ad_id]['text'] ?? ''); if ($det) { $c_phone = $det; $ads[$ad_id]['phone'] = $det; saveData($ads_file, $ads); } } if (empty($c_phone)) $c_phone = "Ko'rsatilmagan"; $ads[$ad_id]['phone'] = $c_phone; sendCustomerInfoIfNeeded($ad_id, $uid, $oid, $amt); // Log purchase logPayment($payments_file, [ 'time' => time(), 'type' => 'purchase', 'buyer_id' => $uid, 'seller_id' => $client_id, 'amount' => $amt, 'order_id' => $oid, 'ad_id' => $ad_id, 'payment_method' => 'card' ]); } else { $users[$uid]['balance'] = ($users[$uid]['balance'] ?? 0) + $amt; $users[$uid]['step'] = 'start'; saveData($users_file, $users); $fmt = number_format($amt, 0, '.', ' '); $bal_fmt = number_format($users[$uid]['balance'], 0, '.', ' '); bot('sendMessage', [ 'chat_id' => $uid, 'text' => "✅ Hisobingiz to'ldirildi!\n\n💰 Summa: {$fmt} so'm\n🧾 Order: #{$oid}\n💳 Balans: {$bal_fmt} so'm", 'parse_mode' => 'HTML', 'reply_markup' => getMenu($uid) ]); // Log top-up logPayment($payments_file, [ 'time' => time(), 'type' => 'topup', 'user_id' => $uid, 'amount' => $amt, 'order_id' => $oid ]); } echo json_encode(['ok' => true]); exit; } $update = json_decode($_RAW_HUMO, true); if (!$update) { // Debug endpoint if (isset($_GET['debug'])) { echo "Debug mode. Logs:\n"; echo "BOT TOKEN: " . $bot_token . "\n"; echo "TARGET GROUP: " . $target_group . "\n"; echo "ADMIN ID: " . $admin_id . "\n"; } exit; } function bot($method, $data = []) { global $api_url; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url . $method); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $res = curl_exec($ch); curl_close($ch); return json_decode($res, true); } function sms($chat_id, $text, $reply_markup = null) { $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'HTML']; if ($reply_markup) $data['reply_markup'] = $reply_markup; return bot('sendMessage', $data); } function humo_check($order_id) { $url = AVTO_API_URL . '?action=check&order_id=' . (int)$order_id . '&shop_id=' . AVTO_SHOP_ID . '&shop_key=' . AVTO_SHOP_KEY; $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>8, CURLOPT_SSL_VERIFYPEER=>false]); $r = json_decode(curl_exec($ch), true); curl_close($ch); return $r['data'] ?? null; } // Idempotent sender: ensures contact info is delivered exactly once per ad function sendCustomerInfoIfNeeded($ad_id, $buyer_id, $order_id = null, $amount = null) { global $ads_file, $users_file, $payments_file; // ensure locks dir $locks_dir = __DIR__ . DIRECTORY_SEPARATOR . 'locks'; if (!is_dir($locks_dir)) @mkdir($locks_dir, 0755, true); $lock_fp = fopen($locks_dir . DIRECTORY_SEPARATOR . "lock_ad_{$ad_id}.lock", 'c'); if (!$lock_fp) return false; flock($lock_fp, LOCK_EX); $ads = getData($ads_file); if (!isset($ads[$ad_id])) { flock($lock_fp, LOCK_UN); fclose($lock_fp); return false; } if (!empty($ads[$ad_id]['info_sent'])) { flock($lock_fp, LOCK_UN); fclose($lock_fp); return true; } $users = getData($users_file); $client_id = $ads[$ad_id]['user_id']; $c_phone = $ads[$ad_id]['phone'] ?? ""; if (empty($c_phone) || strpos($c_phone, "Guruhdan") !== false || $c_phone === "Ko'rsatilmagan") { $det = extract_phone($ads[$ad_id]['text'] ?? ''); if ($det) { $c_phone = $det; $ads[$ad_id]['phone'] = $det; } } if (empty($c_phone)) $c_phone = "Ko'rsatilmagan"; $ads[$ad_id]['phone'] = $c_phone; $success_text = formatRevealedContactMessage($ads[$ad_id], $order_id, $amount); if ($amount === null) { $bal_fmt = number_format($users[$buyer_id]['balance'] ?? 0, 0, '.', ' '); $success_text .= "\n\n💼 Qolgan balansingiz: {$bal_fmt} so'm"; } $contact_url = getContactUrl($client_id, $ads[$ad_id]['username'] ?? null); $btn_keyboard = ['inline_keyboard' => [[['text' => "📱 Lichkasiga o'tish", 'url' => $contact_url]]]]; $res = bot('sendMessage', ['chat_id' => $buyer_id, 'text' => $success_text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($btn_keyboard)]); if (is_array($res) && isset($res['ok']) && $res['ok']) { $ads[$ad_id]['info_sent'] = 1; $ads[$ad_id]['info_sent_at'] = time(); saveDataLocked($ads_file, $ads); flock($lock_fp, LOCK_UN); fclose($lock_fp); return true; } else { // don't mark as sent; release lock and bail flock($lock_fp, LOCK_UN); fclose($lock_fp); return false; } } function normalizeAdText($text) { $text = mb_strtolower(trim((string)$text), 'UTF-8'); return preg_replace('/\s+/u', ' ', $text); } function adContentHash($user_id, $text) { return md5((string)$user_id . '|' . normalizeAdText($text)); } function isDuplicateAd($ads, $user_id, $text) { $hash = adContentHash($user_id, $text); foreach ($ads as $ad) { if (($ad['content_hash'] ?? '') === $hash && ($ad['status'] ?? 'active') === 'active') { return true; } } return false; } function buildMessageLink($chat_id, $message_id, $chat_username = null) { if ($chat_username) { return "https://t.me/" . ltrim($chat_username, '@') . "/" . (int)$message_id; } $cid = str_replace('-100', '', (string)$chat_id); return "https://t.me/c/{$cid}/" . (int)$message_id; } function getContactUrl($user_id, $username = null) { $username = ltrim(trim((string)$username), '@'); if ($username !== '') { return "https://t.me/{$username}"; } return "tg://user?id=" . (int)$user_id; } function formatNewOrderChannelMessage($text, $contact_price) { $price_fmt = number_format((int)$contact_price, 0, '.', ' '); return "📢 YANGI BUYURTMA\n\n" . "📝 Buyurtma:\n" . htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "\n\n" . "👤 Mijoz: Yashirilgan\n" . "📞 Telefon: Yashirilgan\n" . "🔗 Manba: Yashirilgan\n\n" . "💰 Kontakt narxi: {$price_fmt} so'm"; } function formatRevealedContactMessage($ad, $order_id = null, $amount = null) { global $contact_price; $client_id = (int)($ad['user_id'] ?? 0); $c_phone = $ad['phone'] ?? "Ko'rsatilmagan"; if (empty($c_phone) || strpos($c_phone, "Guruhdan") !== false || $c_phone === "Ko'rsatilmagan") { $det = extract_phone($ad['text'] ?? ''); if ($det) $c_phone = $det; } if (empty($c_phone)) $c_phone = "Ko'rsatilmagan"; $msg_link = $ad['message_link'] ?? ''; if ($msg_link === '' && !empty($ad['from_chat_id']) && !empty($ad['message_id'])) { $msg_link = buildMessageLink($ad['from_chat_id'], $ad['message_id'], $ad['group_username'] ?? null); } $msg_link_html = ($msg_link !== '' && $msg_link !== 'Mavjud emas') ? "Asl xabarga o'tish" : "Mavjud emas"; $text = "✅ To'lov muvaffaqiyatli!\n\n" . "📞 Telefon: {$c_phone}\n" . "👤 Mijoz ID: {$client_id}\n" . "🔗 Asl xabar: {$msg_link_html}\n\n" . "📝 Buyurtma:\n" . htmlspecialchars($ad['text'] ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); if ($order_id) { $text .= "\n\n🧾 Order: #{$order_id}"; } if ($amount !== null) { $text .= "\n💰 To'lov: " . number_format((float)$amount, 0, '.', ' ') . " so'm"; } return $text; } function extract_phone($text) { if (!$text) return null; // Find sequences that look like phone numbers (allow +, digits, spaces, dashes, parentheses) if (preg_match_all('/\+?\d[\d\-\s()]{6,}\d/', $text, $matches)) { foreach ($matches[0] as $m) { // keep leading + if present, then digits only $has_plus = strpos($m, '+') !== false; $num = preg_replace('/[^\d]/', '', $m); if ($num === '') continue; // normalize common Uzbekistan formats: add +998 if starts with 0 if ($has_plus) { $normalized = '+' . $num; } else { if (strlen($num) == 9) { // local number like 901234567 -> assume +998 $normalized = '+998' . $num; } elseif (strlen($num) == 10 && $num[0] === '0') { $normalized = '+998' . substr($num, 1); } elseif (strlen($num) >= 11 && substr($num, 0, 3) === '998') { $normalized = '+' . $num; } else { // fallback: return digits-only $normalized = $num; } } // basic length check $digits = preg_replace('/[^\d]/', '', $normalized); if (strlen($digits) >= 9 && strlen($digits) <= 15) return $normalized; } } return null; } function add_unique_surcharge($base_amount) { // Generate random surcharge 1-500 to make each transaction unique $surcharge = rand(1, 500); return (int)$base_amount + $surcharge; } function getMenu($user_id) { global $admin_id; $keyboard = [[["text" => "📢 E'lon berish"], ["text" => " Mening E'lonlar"]], [["text" => " 💵 Pul kiritish"]]]; if ((string)$user_id === (string)$admin_id) { $keyboard[] = [["text" => "⚙️ Admin Panel"]]; } return json_encode(['keyboard' => $keyboard, 'resize_keyboard' => true]); } // Load settings $settings = getData($settings_file); $find_clients_paid = isset($settings['find_clients_paid']) ? (bool)$settings['find_clients_paid'] : true; $ort = json_encode(['keyboard' => [[["text" => "🔙 Orqaga"]]], 'resize_keyboard' => true]); function getOrderKeywords() { return [ 'kere', 'kerek', 'kerak', 'kera', 'krk', 'kk', 'keremi', 'kerekmi', 'keree', 'kereg', 'zarur', 'usta', 'zarl', 'qilish kerak', 'qlish kere', 'qilsh kere', 'qiliw kere', 'qlsh kere', 'qlish kk', 'qilish kk', 'qivoradi', 'qivorila', 'qila oladi', 'qilaoladi', 'qivoradimi', 'bor', 'bormi', 'kim bor', 'kim qila oladi', 'topiladi', 'yordam kere', 'ish kere', 'usta kere', 'zakaz bor', 'buyurtma bor', 'tavsiya kere', 'maslahat kere', 'кере', 'керек', 'керак', 'кера', 'крк', 'кк', 'кереми', 'керекми', 'керее', 'керег', 'зарур', 'уста', 'зарл', 'қилиш керак', 'қилиш кере', 'қилш кере', 'қлиш кере', 'қилиш кк', 'қиворади', 'қиворила', 'қила олади', 'қилаолади', 'қиворадими', 'бор', 'борми', 'ким бор', 'ким қила олади', 'топилади', 'ёрдам кере', 'иш кере', 'уста кере', 'заказ бор', 'буюртма бор', 'тавсия кере', 'маслаҳат кере' ]; } function messageHasOrderKeyword($text) { if (trim((string)$text) === '') return false; $lower_text = mb_strtolower($text, 'UTF-8'); foreach (getOrderKeywords() as $word) { if (mb_strpos($lower_text, $word, 0, 'UTF-8') !== false) { return true; } } return false; } function processIncomingOrderMessage($message) { global $users_file, $ads_file, $groups_file, $required_file, $target_group, $contact_price; $chat_id = $message['chat']['id']; $chat_type = $message['chat']['type'] ?? ''; if (!in_array($chat_type, ['group', 'supergroup', 'channel'], true)) { return false; } $groups = getData($groups_file); if (!isset($groups[$chat_id])) { return false; } $text = trim((string)($message['text'] ?? $message['caption'] ?? '')); if (!messageHasOrderKeyword($text)) { return false; } $from_id = $message['from']['id'] ?? ($message['sender_chat']['id'] ?? 0); $username = $message['from']['username'] ?? ''; $first_name = $message['from']['first_name'] ?? ($message['author_signature'] ?? 'Mijoz'); $message_id = $message['message_id'] ?? 0; $group_name = $message['chat']['title'] ?? 'Noma\'lum'; $group_username = $message['chat']['username'] ?? null; if (isset($message['forward_from']) || isset($message['via_bot']) || (!empty($message['from']['is_bot']) && $message['from']['is_bot'])) { return false; } $users = getData($users_file); $ads = getData($ads_file); if ($from_id && isset($users[$from_id]['muted_until']) && time() < $users[$from_id]['muted_until']) { return false; } if ($from_id && isDuplicateAd($ads, $from_id, $text)) { return false; } $required = getData($required_file); $req = $required[$chat_id] ?? null; if ($req && $chat_type !== 'channel' && $from_id) { $ok = false; $check = bot('getChatMember', ['chat_id' => $req, 'user_id' => $from_id]); if (is_array($check) && isset($check['result']['status'])) { $s = $check['result']['status']; if (in_array($s, ['creator', 'administrator', 'member'], true)) $ok = true; } if (!$ok) { sms($chat_id, "Hurmatli {$first_name}, guruhga yozish uchun quyidagi kanal yoki guruhga obuna bo'lishingiz kerak:\n\n{$req}"); return false; } } $det_phone = extract_phone($text); $message_link = buildMessageLink($chat_id, $message_id, $group_username); $ad_id = uniqid('ad_', true); $ads[$ad_id] = [ 'user_id' => $from_id, 'name' => $first_name, 'username' => $username, 'text' => $text, 'phone' => $det_phone ?: "Ko'rsatilmagan", 'status' => 'active', 'from_chat_id' => $chat_id, 'group_name' => $group_name, 'group_username' => $group_username, 'message_id' => $message_id, 'message_link' => $message_link, 'content_hash' => adContentHash($from_id, $text), 'time' => time(), 'datetime' => date('Y-m-d H:i:s') ]; saveData($ads_file, $ads); if ($from_id) { if (!isset($users[$from_id])) { $users[$from_id] = ['step' => 'start', 'username' => $username, 'name' => $first_name, 'balance' => 0]; } else { if ($username) $users[$from_id]['username'] = $username; if ($first_name) $users[$from_id]['name'] = $first_name; } if ($chat_type !== 'channel') { $users[$from_id]['muted_until'] = time() + 3600; bot('restrictChatMember', [ 'chat_id' => $chat_id, 'user_id' => $from_id, 'permissions' => json_encode(['can_send_messages' => false, 'can_send_media_messages' => false]) ]); } saveData($users_file, $users); } $channel_msg = formatNewOrderChannelMessage($text, $contact_price); $inline_keyboard = json_encode([ 'inline_keyboard' => [[['text' => "💳 Kontaktni sotib olish", 'callback_data' => "buy_contact_{$ad_id}"]]] ]); bot('sendMessage', [ 'chat_id' => $target_group, 'text' => $channel_msg, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true, 'reply_markup' => $inline_keyboard ]); return true; } $message = $update['message'] ?? ($update['channel_post'] ?? null); $callback_query = $update['callback_query'] ?? null; $my_chat_member = $update['my_chat_member'] ?? null; // ======================================================== // 🔄 GURUXLAR RO'YXATINI YANGILASH (Bot admin bo'lganda) // ======================================================== if ($my_chat_member) { $chat_id = $my_chat_member['chat']['id']; $chat_title = $my_chat_member['chat']['title'] ?? "Guruh"; $status = $my_chat_member['new_chat_member']['status']; $groups = getData($groups_file); if ($status === 'administrator' || $status === 'creator') { $groups[$chat_id] = [ 'title' => $chat_title, 'link' => isset($my_chat_member['chat']['username']) ? "@".$my_chat_member['chat']['username'] : "Maxfiy guruh/kanal", 'type' => $my_chat_member['chat']['type'] ?? 'group' ]; } else { if (isset($groups[$chat_id])) { unset($groups[$chat_id]); } } saveData($groups_file, $groups); exit; } // ========================================== // CALLBACK QUERY HANDLING (TUGMALAR ISHLOVI) // ========================================== if ($callback_query) { $cb_id = $callback_query['id']; $from_id = $callback_query['from']['id']; $chat_id = $callback_query['message']['chat']['id']; $msg_id = $callback_query['message']['message_id']; $cb_data = $callback_query['data']; $users = getData($users_file); $ads = getData($ads_file); $groups = getData($groups_file); if ((string)$from_id === (string)$admin_id) { if ($cb_data == "admin_stats") { $total_users = count($users); $total_ads = count($ads); bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); bot('sendMessage', [ 'chat_id' => $chat_id, 'text' => "📊 Bot Statistikasi:\n\n👥 Umumiy foydalanuvchilar: {$total_users} ta\n📢 Umumiy e'lonlar: {$total_ads} ta", 'parse_mode' => 'HTML' ]); exit; } if ($cb_data == "admin_add_bal") { $users[$from_id]['step'] = 'admin_wait_uid'; saveData($users_file, $users); bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); sms($chat_id, "👤 Pul qo'shmoqchi bo'lgan foydalanuvchining ID raqamini yozib yuboring:", $ort); exit; } if ($cb_data == "admin_reports") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); sms($chat_id, "📋 Tizim hisoboti va resurslar:\n\nTarget Kanal/Guruh: {$target_group}\nKontakt narxi: {$contact_price} so'm\nTo'lov tizimi: HUMO Avto"); exit; } if ($cb_data == "admin_users") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $users[$from_id]['step'] = 'admin_wait_manage_uid'; saveData($users_file, $users); sms($chat_id, "👥 Foydalanuvchi boshqaruvi: Iltimos boshqariladigan foydalanuvchining ID raqamini yuboring:", $ort); exit; } if ($cb_data == "admin_required") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $groups = getData($groups_file); if (empty($groups)) { sms($chat_id, "⚠️ Bot hozircha hech qanday guruhda admin emas.", getMenu($chat_id)); exit; } $keyboard = ['inline_keyboard' => []]; foreach ($groups as $gid => $info) { $keyboard['inline_keyboard'][] = [[ 'text' => "Set obuna: {$info['title']}", 'callback_data' => "admin_setreq_{$gid}" ]]; } bot('sendMessage', ['chat_id' => $chat_id, 'text' => "🔐 Guruh uchun obuna shartini belgilang:", 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]); exit; } if (strpos($cb_data, 'admin_setreq_') === 0) { $group_id = str_replace('admin_setreq_', '', $cb_data); $users[$from_id]['step'] = 'admin_wait_req_' . $group_id; saveData($users_file, $users); sms($chat_id, "📎 Guruh (ID: {$group_id}) uchun obuna bo'lishi kerak bo'lgan kanal yoki guruhning username yoki linkini yuboring (masalan: @kanal yoki https://t.me/kanal):", $ort); exit; } if (strpos($cb_data, 'admin_editbal_') === 0) { $target = (int)str_replace('admin_editbal_', '', $cb_data); $users[$from_id]['step'] = 'admin_wait_setbal_' . $target; saveData($users_file, $users); sms($chat_id, "💰 {$target} uchun yangi balans summasini kiriting (musbat yoki manfiy):", $ort); exit; } if (strpos($cb_data, 'admin_payments_') === 0) { $target = (int)str_replace('admin_payments_', '', $cb_data); $payments = getData($payments_file); $lines = []; foreach ($payments as $p) { if ((int)($p['user_id'] ?? 0) === $target) { $t = date('Y-m-d H:i', $p['time'] ?? time()); $lines[] = "[{$t}] {$p['type']} — " . ($p['amount'] ?? 0) . " so'm (order:" . ($p['order_id'] ?? '-') . ")"; } } $txt = empty($lines) ? "📭 To'lovlar topilmadi." : implode("\n", $lines); bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "📜 {$target} to'lov tarixi:\n\n" . $txt, 'parse_mode' => 'HTML']); exit; } if ($cb_data == "admin_settings") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $status = $find_clients_paid ? "✅ Pullik (Kontakt sotib olinadi)" : "✅ Tekin (Lichkaga yozish)"; $txt = "⚙️ Bot Sozlamalari:\n\nKontakt rejimi: {$status}\n\nEslatma: Pullik rejimda guruhdan olingan e'lonlarda \"Kontaktni sotib olish\" tugmasi paydo bo'ladi."; $kbd = ['inline_keyboard' => [[['text' => ($find_clients_paid ? '🔁 Pullikni o‘chirish' : '🔁 Pullikni yoqish'), 'callback_data' => 'admin_toggle_paid']]]]; bot('sendMessage', ['chat_id' => $chat_id, 'text' => $txt, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($kbd)]); exit; } if ($cb_data == 'admin_toggle_paid') { // toggle and save $settings = getData($settings_file); $settings['find_clients_paid'] = empty($settings['find_clients_paid']) ? true : false; saveData($settings_file, $settings); $find_clients_paid = (bool)$settings['find_clients_paid']; bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => '✅ Sozlama yangilandi.', 'show_alert' => false]); $status = $find_clients_paid ? "✅ Pullik (Kontakt sotib olinadi)" : "✅ Tekin (Lichkaga yozish)"; sms($chat_id, "⚙️ Sozlama saqlandi. Hozirgi holat: {$status}", getMenu($chat_id)); exit; } // 🏦 ADMIN UCHUN GURUHLAR RO'YXATINI KO'RSATISH if ($cb_data == "admin_groups") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); if (empty($groups)) { $gr_txt = "⚠️ Bot hozircha biror guruhda admin emas!\nBotni guruhlarga qo'shib admin huquqini bering."; } else { $gr_txt = "🏰 Bot admin bo'lgan guruhlar ro'yxati:\n\n"; $i = 1; foreach ($groups as $id => $info) { $gr_txt .= "{$i}. {$info['title']} ({$id}) — {$info['link']}\n"; $i++; } } bot('sendMessage', ['chat_id' => $chat_id, 'text' => $gr_txt, 'parse_mode' => 'HTML']); exit; } // 🚫 BLOKLANGAN FOYDALANUVCHILAR RO'YXATI if ($cb_data == "admin_blocked") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $blocked_users = []; $now = time(); foreach ($users as $uid => $user) { if (isset($user['muted_until']) && $user['muted_until'] > $now) { $remaining = $user['muted_until'] - $now; $minutes = floor($remaining / 60); $blocked_users[] = ['id' => $uid, 'remaining' => $minutes, 'name' => $user['name'] ?? 'Nomalum']; } } if (empty($blocked_users)) { $bl_txt = "✅ Bloklangan foydalanuvchilar yo'q!"; bot('sendMessage', ['chat_id' => $chat_id, 'text' => $bl_txt, 'parse_mode' => 'HTML']); } else { $bl_txt = "🚫 Bloklangan foydalanuvchilar:\n\n"; $keyboard = ['inline_keyboard' => []]; foreach ($blocked_users as $idx => $u) { $bl_txt .= "" . ($idx+1) . ". {$u['name']} (ID: {$u['id']}) — {$u['remaining']} daqiqa qoldi\n"; $keyboard['inline_keyboard'][] = [['text' => "🔓 {$u['name']} ni ochish", 'callback_data' => "admin_unblock_{$u['id']}"]]; } bot('sendMessage', ['chat_id' => $chat_id, 'text' => $bl_txt, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]); } exit; } // 🔓 FOYDALANUVCHINI BLOKDAN CHIQARISH if (strpos($cb_data, 'admin_unblock_') === 0) { $unblock_uid = (int)str_replace('admin_unblock_', '', $cb_data); if (isset($users[$unblock_uid])) { unset($users[$unblock_uid]['muted_until']); saveData($users_file, $users); bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "✅ Foydalanuvchi blokdan chiqarildi!", 'show_alert' => true]); bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => "✅ Foydalanuvchi (ID: {$unblock_uid}) blokdan chiqarildi!\n\nU endi guruhlarda yoza oladi.", 'parse_mode' => 'HTML' ]); } else { bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "⚠️ Foydalanuvchi topilmadi!", 'show_alert' => true]); } exit; } // 💎 TEKIN TARIF FOYDALANUVCHILAR RO'YXATI if ($cb_data == "admin_free_users") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $free_users = getData($free_users_file); if (empty($free_users)) { $free_txt = "✅ Tekin tarif foydalanuvchilar yo'q!"; $keyboard = ['inline_keyboard' => [[['text' => "➕ Qo'shish", 'callback_data' => "admin_add_free_user"]]]]; bot('sendMessage', ['chat_id' => $chat_id, 'text' => $free_txt, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]); } else { $free_txt = "💎 Tekin tarif foydalanuvchilar:\n\n"; $keyboard = ['inline_keyboard' => []]; foreach ($free_users as $idx => $uid) { $user_name = $users[$uid]['name'] ?? 'Noma\'lum'; $free_txt .= "" . ($idx+1) . ". {$user_name} (ID: {$uid})\n"; $keyboard['inline_keyboard'][] = [['text' => "❌ {$user_name} ni olib tashla", 'callback_data' => "admin_remove_free_{$uid}"]]; } $keyboard['inline_keyboard'][] = [['text' => "➕ Yangi foydalanuvchi qo'shish", 'callback_data' => "admin_add_free_user"]]; bot('sendMessage', ['chat_id' => $chat_id, 'text' => $free_txt, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]); } exit; } // ➕ TEKIN FOYDALANUVCHI QOSH if ($cb_data == "admin_add_free_user") { bot('answerCallbackQuery', ['callback_query_id' => $cb_id]); $users[$from_id]['step'] = 'admin_wait_free_uid'; saveData($users_file, $users); sms($chat_id, "👤 Tekin tarif ga qo'shmoqchi bo'lgan foydalanuvchining ID raqamini yozib yuboring:", $ort); exit; } // ❌ TEKIN FOYDALANUVCHINI OLIB TASHLA if (strpos($cb_data, 'admin_remove_free_') === 0) { $remove_uid = (int)str_replace('admin_remove_free_', '', $cb_data); $free_users = getData($free_users_file); $free_users = array_filter($free_users, function($uid) use ($remove_uid) { return $uid != $remove_uid; }); $free_users = array_values($free_users); saveData($free_users_file, $free_users); bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "✅ Foydalanuvchi olib tashlandi!", 'show_alert' => true]); bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => "✅ Foydalanuvchi (ID: {$remove_uid}) tekin tarifdan olib tashlandi!", 'parse_mode' => 'HTML' ]); exit; } } if (strpos($cb_data, 'buy_contact_') === 0) { $ad_id = str_replace('buy_contact_', '', $cb_data); if (!isset($ads[$ad_id])) { bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "⚠️ E'lon topilmadi!", 'show_alert' => true]); exit; } // KAYTARILMAS XATOLI: AD ALLAQACHON SOTILGAN if ($ads[$ad_id]['status'] === 'sold') { bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "❌ Kechirasiz, bu mijozni boshqa usta sotib olib bo'ldi!", 'show_alert' => true]); bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => "❌ Bu buyurtma allaqachon sotilgan!", 'parse_mode' => 'HTML' ]); exit; } // KAYTARILMAS XATOLI: BIR ODAM FAQAT BIR ANNOUNCEMENT SOTIB OLA OLADI if (isset($ads[$ad_id]['bought_by']) && (int)$ads[$ad_id]['bought_by'] === (int)$from_id) { bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "Siz ushbu kontaktni avval sotib olgansiz", 'show_alert' => true]); exit; } $free_users = getData($free_users_file); $is_free_user = in_array($from_id, $free_users); $user_bal = $users[$from_id]['balance'] ?? 0; // TEKIN TARIF YOKI BALANS YO'Q - BEVOSITA KONTAKT OLIB BERISH if ($is_free_user || $user_bal >= $contact_price) { if (!$is_free_user) { $users[$from_id]['balance'] -= $contact_price; } $ads[$ad_id]['status'] = 'sold'; $ads[$ad_id]['bought_by'] = $from_id; $ads[$ad_id]['bought_time'] = time(); saveData($ads_file, $ads); $client_id = $ads[$ad_id]['user_id']; if (isset($users[$client_id]['muted_until'])) { unset($users[$client_id]['muted_until']); } saveData($users_file, $users); $from_chat_id = $ads[$ad_id]['from_chat_id'] ?? null; if ($from_chat_id) { bot('restrictChatMember', [ 'chat_id' => $from_chat_id, 'user_id' => $client_id, 'until_date' => 0, 'permissions' => json_encode([ 'can_send_messages' => true, 'can_send_media_messages' => true, 'can_send_polls' => true, 'can_send_other_messages' => true, 'can_add_web_page_previews' => true, 'can_change_info' => true, 'can_invite_users' => true, 'can_pin_messages' => true ]) ]); } $c_phone = $ads[$ad_id]['phone'] ?? ""; if (empty($c_phone) || strpos($c_phone, "Guruhdan") !== false || $c_phone === "Ko'rsatilmagan") { $det = extract_phone($ads[$ad_id]['text'] ?? ''); if ($det) { $c_phone = $det; $ads[$ad_id]['phone'] = $det; saveData($ads_file, $ads); } } if (empty($c_phone)) $c_phone = "Ko'rsatilmagan"; $ads[$ad_id]['phone'] = $c_phone; saveData($ads_file, $ads); sendCustomerInfoIfNeeded($ad_id, $from_id, null, $is_free_user ? 0 : $contact_price); bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "Mijoz muvaffaqiyatli sotib olindi!"]); bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => formatNewOrderChannelMessage($ads[$ad_id]['text'], $contact_price) . "\n\n✅ Bu buyurtma sotib olindi.", 'parse_mode' => 'HTML', 'reply_markup' => json_encode(['inline_keyboard' => []]) ]); // LOG PURCHASE KO'RSATISH logPayment($payments_file, [ 'time' => time(), 'type' => 'direct_purchase', 'buyer_id' => $from_id, 'seller_id' => $client_id, 'amount' => $contact_price, 'ad_id' => $ad_id, 'payment_method' => $is_free_user ? 'free_tier' : 'balance' ]); exit; } else { bot('answerCallbackQuery', ['callback_query_id' => $cb_id, 'text' => "⏳ Avto to'lov cheki yaratilmoqda...", 'show_alert' => false]); $custom_payload = (string)$from_id . "_" . $ad_id; $amount_with_surcharge = add_unique_surcharge($contact_price); $body = json_encode([ 'shop_id' => AVTO_SHOP_ID, 'shop_key' => AVTO_SHOP_KEY, 'amount' => (float)$amount_with_surcharge, 'user_id' => $custom_payload, 'webhook_url' => $webhook_url ]); $ch = curl_init(AVTO_API_URL . '?action=create_order'); curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>$body, CURLOPT_HTTPHEADER=>['Content-Type: application/json'], CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10, CURLOPT_SSL_VERIFYPEER=>false]); $result = json_decode(curl_exec($ch), true); curl_close($ch); if (!$result || !isset($result['ok']) || !$result['ok']) { bot('sendMessage', ['chat_id' => $chat_id, 'text' => "❌ To'lov tizimida uzilish bo'ldi. Qayta urinib ko'ring."]); exit; } $d = $result['data']; $order_id = $d['order_id']; $final = (int)$d['amount']; $card = $d['card_number']; $ttl_sec = (int)($d['ttl_minutes'] ?? 5) * 60; $expire = date('H:i', time() + $ttl_sec); $users[$from_id]['step'] = "humo_wait-$order_id"; saveData($users_file, $users); $extra_note = ""; if ((int)($d['extra_sum'] ?? 0) > 0) { $extra_note = "\n\n⚠️ Nima uchun summa o'zgardi?\n" . "Farqlash uchun +" . $d['extra_sum'] . " so'm qo'shildi — bu ham hisobingizga o'tadi."; } $pay_msg = "💳 HUMO Avto To'lov (Kontakt sotib olish)\n\n" . "💰 To'lov summasi: " . number_format($final, 0, '.', ' ') . " so'm\n" . "🏦 Karta raqami: {$card}\n\n" . "⏳ Muddat: 5 daqiqa ({$expire} gacha)" . $extra_note; bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => $pay_msg, 'parse_mode' => 'HTML', 'reply_markup' => json_encode(['inline_keyboard' => [ [['text' => "📋 Karta raqamidan nusxa", 'copy_text' => ['text' => str_replace(' ', '', $card)]]], [['text' => "💰 Summadan nusxa", 'copy_text' => ['text' => (string)$final]]], [['text' => "✅ To'lov qildim", 'callback_data' => "humo_check-{$order_id}"]], [['text' => "❌ Bekor qilish", 'callback_data' => "humo_cancel-{$order_id}"]] ]]) ]); } exit; } $res = str_replace("menu=", "", $cb_data); if($res == "HUMO") { bot('deleteMessage', ['chat_id'=>$chat_id, 'message_id'=>$msg_id]); $user_bal = $users[$chat_id]['balance'] ?? 0; sms($chat_id, "💳 HUMO Avto To'lov\n\n💰 Hisobingiz: " . number_format($user_bal, 0, '.', ' ') . " so'm\n\n📝 Qancha kiritmoqchisiz?\n(Min: 1 000 | Max: 10 000 000)", $ort); $users[$chat_id]['step'] = "humo_amount"; saveData($users_file, $users); exit; } if (mb_stripos($cb_data, "humo_check-") !== false) { $order_id = (int)explode("-", $cb_data)[1]; $d = humo_check($order_id); if (!$d) { bot('answerCallbackQuery', ['callback_query_id'=>$cb_id, 'text'=>"⚠️ Server javob bermadi. Qaytadan bosing.", 'show_alert'=>true]); exit; } $status = $d['status'] ?? 'unknown'; $secs = (int)($d['seconds_left'] ?? 0); if ($status === 'paid') { bot('answerCallbackQuery', ['callback_query_id'=>$cb_id, 'text'=>"✅ To'lovingiz tasdiqlandi!", 'show_alert'=>true]); // Try to get payload (buyer_ad) from order data and reveal contact similar to webhook $payload = isset($d['user_id']) ? explode("_", $d['user_id']) : []; $buyer_id = (int)($payload[0] ?? $from_id); $ad_id = $payload[1] ?? null; $ads = getData($ads_file); $users = getData($users_file); if ($ad_id && isset($ads[$ad_id])) { // If already sold to someone else, refund to buyer balance if ($ads[$ad_id]['status'] === 'sold' && (int)($ads[$ad_id]['bought_by'] ?? 0) !== $buyer_id) { $users[$buyer_id]['balance'] = ($users[$buyer_id]['balance'] ?? 0) + (float)($d['amount'] ?? 0); $users[$buyer_id]['step'] = 'start'; saveData($users_file, $users); bot('sendMessage', ['chat_id' => $buyer_id, 'text' => "❌ Kechirasiz! Bu mijozni allaqachon boshqa usta sotib olib bo'ldi!\n\nO'tkazgan pulingiz bot balansingizga qaytarildi.", 'parse_mode'=>'HTML', 'reply_markup'=>getMenu($buyer_id)]); } else { // mark sold and reveal contact $ads[$ad_id]['status'] = 'sold'; $ads[$ad_id]['bought_by'] = $buyer_id; $ads[$ad_id]['bought_time'] = time(); saveData($ads_file, $ads); $client_id = $ads[$ad_id]['user_id']; if (isset($users[$client_id]['muted_until'])) unset($users[$client_id]['muted_until']); $users[$buyer_id]['step'] = 'start'; saveData($users_file, $users); $from_chat_id = $ads[$ad_id]['from_chat_id'] ?? null; if ($from_chat_id) { bot('restrictChatMember', [ 'chat_id' => $from_chat_id, 'user_id' => $client_id, 'until_date' => 0, 'permissions' => json_encode([ 'can_send_messages' => true, 'can_send_media_messages' => true, 'can_send_polls' => true, 'can_send_other_messages' => true, 'can_add_web_page_previews' => true, 'can_change_info' => true, 'can_invite_users' => true, 'can_pin_messages' => true ]) ]); } $c_phone = $ads[$ad_id]['phone'] ?? ""; if (empty($c_phone) || strpos($c_phone, "Guruhdan") !== false || $c_phone === "Ko'rsatilmagan") { $det = extract_phone($ads[$ad_id]['text'] ?? ''); if ($det) { $c_phone = $det; $ads[$ad_id]['phone'] = $det; saveData($ads_file, $ads); } } if (empty($c_phone)) $c_phone = "Ko'rsatilmagan"; bot('deleteMessage', ['chat_id'=>$chat_id, 'message_id'=>$msg_id]); sendCustomerInfoIfNeeded($ad_id, $buyer_id, $order_id, (float)($d['amount'] ?? 0)); logPayment($payments_file, [ 'time' => time(), 'type' => 'purchase', 'buyer_id' => $buyer_id, 'seller_id' => $client_id, 'amount' => (float)($d['amount'] ?? 0), 'order_id' => $order_id, 'ad_id' => $ad_id, 'payment_method' => 'card' ]); } } else { // No ad payload: treat as top-up $users[$buyer_id]['balance'] = ($users[$buyer_id]['balance'] ?? 0) + (float)($d['amount'] ?? 0); $users[$buyer_id]['step'] = 'start'; saveData($users_file, $users); $fmt = number_format((float)($d['amount'] ?? 0), 0, '.', ' '); $bal_fmt = number_format($users[$buyer_id]['balance'], 0, '.', ' '); bot('deleteMessage', ['chat_id'=>$chat_id, 'message_id'=>$msg_id]); bot('sendMessage', ['chat_id' => $buyer_id, 'text' => "✅ Hisobingiz to'ldirildi!\n\n💰 Summa: {$fmt} so'm\n🧾 Order: #{$order_id}\n💳 Balans: {$bal_fmt} so'm", 'parse_mode' => 'HTML', 'reply_markup' => getMenu($buyer_id)]); logPayment($payments_file, ['time'=>time(),'type'=>'topup','user_id'=>$buyer_id,'amount'=>(float)($d['amount'] ?? 0),'order_id'=>$order_id]); } } elseif ($status === 'expired' || $secs <= 0) { bot('answerCallbackQuery', ['callback_query_id'=>$cb_id, 'text'=>"⏰ Muddat tugadi.", 'show_alert'=>true]); bot('editMessageText', [ 'chat_id' => $chat_id, 'message_id' => $msg_id, 'text' => "⏰ To'lov muddati tugadi.\n\nQaytadan urinib ko'ring.", 'parse_mode' => 'HTML' ]); $users[$chat_id]['step'] = "start"; saveData($users_file, $users); } else { $min = floor($secs / 60); $sec = $secs % 60; $t = $min > 0 ? "{$min} daqiqa {$sec} soniya" : "{$sec} soniya"; bot('answerCallbackQuery', [ 'callback_query_id' => $cb_id, 'text' => "⏳ Hali tasdiqlanmadi. Taxminan {$t} vaqt qoldi.", 'show_alert' => true ]); } exit; } if (mb_stripos($cb_data, "humo_cancel-") !== false) { bot('deleteMessage', ['chat_id'=>$chat_id, 'message_id'=>$msg_id]); $users[$chat_id]['step'] = "start"; saveData($users_file, $users); sms($chat_id, "❌ To'lov bekor qilindi.", getMenu($chat_id)); exit; } } // ========================================== // MESSAGE HANDLING (XABARLAR KELGANDA) // ========================================== if ($message) { $chat_id = $message['chat']['id']; $chat_type = $message['chat']['type']; $text = $message['text'] ?? ''; $from_id = $message['from']['id']; $username = $message['from']['username'] ?? ''; $first_name = $message['from']['first_name'] ?? 'Mijoz'; $users = getData($users_file); $ads = getData($ads_file); $step = $users[$from_id]['step'] ?? 'start'; if (isset($users[$from_id]['muted_until']) && time() > $users[$from_id]['muted_until']) { unset($users[$from_id]['muted_until']); saveData($users_file, $users); } if (($chat_type == 'group' || $chat_type == 'supergroup') && isset($users[$from_id]['muted_until'])) { if (time() < $users[$from_id]['muted_until']) { bot('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message['message_id']]); exit; } } // ======================================================== // 🔎 GURUX/KANAL XABARLARIDAN ZAKAZ YIG'ISH // ======================================================== if ($chat_type == 'group' || $chat_type == 'supergroup' || $chat_type == 'channel') { if (processIncomingOrderMessage($message)) { exit; } } // LICHKA MANTIQLARI if ($chat_type == 'private') { if (!isset($users[$from_id])) { $users[$from_id] = ['step' => 'start', 'username' => $username, 'name' => $first_name, 'balance' => 0]; saveData($users_file, $users); } if ($text == '/start' || ($text == "🔙 Orqaga" && $step == 'start')) { $users[$from_id]['step'] = 'start'; // Foydalanuvchining username'ni saqlash if ($username) { $users[$from_id]['username'] = $username; } saveData($users_file, $users); error_log('USER START - ID: ' . $from_id . ', Username: ' . $username); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Ustalar platformasi botiga xush kelibsiz!", 'reply_markup' => getMenu($chat_id)]); exit; } // Admin buyruqlari if ((string)$from_id === (string)$admin_id) { if ($text == "/admin" || $text == "⚙️ Admin Panel") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); $admin_keyboard = ['inline_keyboard' => [ [['text' => "📊 Statistika", 'callback_data' => "admin_stats"]], [['text' => "🏰 Admin Guruhlar", 'callback_data' => "admin_groups"]], [['text' => "🚫 Bloklangan Foydalanuvchilar", 'callback_data' => "admin_blocked"]], [['text' => " Tekin Tarif Foydalanuvchilar", 'callback_data' => "admin_free_users"]], [['text' => " 💰 Balans Qo'shish", 'callback_data' => "admin_add_bal"]], [['text' => "📋 Tizim Sozlamalari", 'callback_data' => "admin_reports"]], [['text' => "⚙️ Sozlamalar", 'callback_data' => "admin_settings"]], [['text' => "👥 Foydalanuvchi boshqaruvi", 'callback_data' => "admin_users"]], [['text' => "🔐 Obuna sharti (Guruhlar)", 'callback_data' => "admin_required"]] ]]; bot('sendMessage', [ 'chat_id' => $chat_id, 'text' => "💻 Xush kelibsiz Admin! O'zingizga kerakli funksiyani tanlang:", 'parse_mode' => 'HTML', 'reply_markup' => json_encode($admin_keyboard) ]); exit; } if ($step == 'admin_wait_uid') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); sms($chat_id, "❌ Pul qo'shish jarayoni bekor qilindi.", getMenu($chat_id)); exit; } if (isset($users[$text])) { $users[$from_id]['temp_admin_uid'] = $text; $users[$from_id]['step'] = 'admin_wait_amount'; saveData($users_file, $users); sms($chat_id, "💰 Foydalanuvchi topildi. Balansiga qancha pul qo'shmoqchisiz (faqat raqam)?", $ort); } else { sms($chat_id, "❌ Bunday ID ga ega foydalanuvchi bot bazasida topilmadi. Qayta kiriting:", $ort); } exit; } if ($step == 'admin_wait_amount') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; unset($users[$from_id]['temp_admin_uid']); saveData($users_file, $users); sms($chat_id, "❌ Pul qo'shish jarayoni bekor qilindi.", getMenu($chat_id)); exit; } $amount = (float)str_replace([" ", ","], "", $text); if (is_numeric($amount) && $amount > 0) { $target_uid = $users[$from_id]['temp_admin_uid']; $users[$target_uid]['balance'] = ($users[$target_uid]['balance'] ?? 0) + $amount; $users[$from_id]['step'] = 'start'; unset($users[$from_id]['temp_admin_uid']); saveData($users_file, $users); sms($chat_id, "✅ Foydalanuvchi (ID: {$target_uid}) balansiga " . number_format($amount, 0, '.', ' ') . " so'm muvaffaqiyatli qo'shildi!", getMenu($chat_id)); sms($target_uid, "💰 Admin tomonidan hisobingizga " . number_format($amount, 0, '.', ' ') . " so'm qo'shildi!\n💼 Joriy balansingiz: " . number_format($users[$target_uid]['balance'], 0, '.', ' ') . " so'm"); } else { sms($chat_id, "⚠️ Noto'g'ri summa kiritildi. Qayta kiriting:", $ort); } exit; } if ($step == 'admin_wait_free_uid') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); sms($chat_id, "❌ Jarayon bekor qilindi.", getMenu($chat_id)); exit; } $target_id = (int)$text; if (isset($users[$target_id])) { $free_users = getData($free_users_file); if (!in_array($target_id, $free_users)) { $free_users[] = $target_id; saveData($free_users_file, $free_users); $target_name = $users[$target_id]['name'] ?? 'Noma\'lum'; sms($chat_id, "✅ {$target_name} (ID: {$target_id}) tekin tarifga muvaffaqiyatli qo'shildi!\n\nU endi barcha mijozlarni tekin olishi mumkin.", getMenu($chat_id)); } else { sms($chat_id, "⚠️ Bu foydalanuvchi allaqachon tekin tarifda!", getMenu($chat_id)); } } else { sms($chat_id, "❌ Bunday ID ga ega foydalanuvchi bot bazasida topilmadi. Qayta kiriting:", $ort); } $users[$from_id]['step'] = 'start'; saveData($users_file, $users); exit; } if ($step == 'admin_wait_manage_uid') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); sms($chat_id, "❌ Jarayon bekor qilindi.", getMenu($chat_id)); exit; } $target = (int)$text; if (!isset($users[$target])) { sms($chat_id, "⚠️ Bunday ID mavjud emas. Qayta kiriting:", $ort); exit; } $u = $users[$target]; $bal = $u['balance'] ?? 0; $kbd = ['inline_keyboard' => [[['text' => "⚖️ Balansni o'zgartirish", 'callback_data' => "admin_editbal_{$target}"],[ 'text' => "📜 To'lovlar", 'callback_data' => "admin_payments_{$target}" ]]]]; sms($chat_id, "👤 Foydalanuvchi: {$u['name']} (ID: {$target})\nBalans: " . number_format($bal,0,'.',' ') . " so'm", json_encode($kbd)); $users[$from_id]['step'] = 'start'; saveData($users_file, $users); exit; } if (mb_stripos($step, 'admin_wait_setbal_') === 0) { $target = (int)explode('_', $step)[3]; $amount = (float)str_replace([" ", ","], "", $text); if (!is_numeric($amount)) { sms($chat_id, "⚠️ Noto'g'ri summa. Qayta kiriting:", $ort); exit; } $users[$target]['balance'] = ($users[$target]['balance'] ?? 0) + $amount; saveData($users_file, $users); sms($chat_id, "✅ Balans yangilandi. \nYangi balans: " . number_format($users[$target]['balance'],0,'.',' ') . " so'm", getMenu($chat_id)); // log admin adjustment logPayment($payments_file, ['time'=>time(),'type'=>'admin_adjust','user_id'=>$target,'amount'=>$amount,'by'=>$from_id]); $users[$from_id]['step'] = 'start'; saveData($users_file, $users); exit; } if (mb_stripos($step, 'admin_wait_req_') === 0) { $parts = explode('_', $step); $groupid = $parts[3] ?? null; if (!$groupid) { sms($chat_id, "⚠️ Guruh ID topilmadi.", $ort); exit; } $reqs = getData($required_file); $reqs[$groupid] = $text; saveData($required_file, $reqs); sms($chat_id, "✅ Obuna talabi saqlandi: {$text}", getMenu($chat_id)); $users[$from_id]['step'] = 'start'; saveData($users_file, $users); exit; } } // Start havolalari (Sotib olish havolasi orqali kelganda) if (strpos($text, '/start buy_') === 0) { $ad_id = str_replace('/start buy_', '', $text); if (isset($ads[$ad_id])) { if ($ads[$ad_id]['status'] === 'sold') { sms($chat_id, "❌ Kechirasiz, bu buyurtma allaqachon sotilgan!", getMenu($chat_id)); exit; } $c_text = $ads[$ad_id]['text']; $confirm_msg = "📋 Siz tanlagan buyurtma:\n\n\"{$c_text}\"\n\n" . "💰 Kontaktni ochish narxi: " . number_format($contact_price, 0, '.', ' ') . " so'm\n" . "Sotib olishni tasdiqlaysizmi?"; $confirm_btn = ['inline_keyboard' => [ [['text' => "💳 Kontaktni sotib olish", 'callback_data' => "buy_contact_{$ad_id}"]], [['text' => "❌ Bekor qilish", 'callback_data' => "humo_cancel-0"]] ]]; sms($chat_id, $confirm_msg, json_encode($confirm_btn)); } else { sms($chat_id, "⚠️ E'lon topilmadi yoki muddati o'tgan.", getMenu($chat_id)); } exit; } if ($text == "📢 E'lon berish") { $users[$from_id]['step'] = 'waiting_text_private'; saveData($users_file, $users); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Qanday usta kerakligi haqida to'liq yozib yuboring:", 'reply_markup' => $ort]); exit; } if ($text == "📋 Mening E'lonlar") { // Show user's own ads $my_ads = []; foreach ($ads as $ad_id => $ad) { if ((int)$ad['user_id'] === (int)$from_id) { $my_ads[$ad_id] = $ad; } } if (empty($my_ads)) { sms($chat_id, "📭 Sizning e'lonlaringiz yo'q.", getMenu($chat_id)); exit; } $msg = "📋 Sizning E'lonlar:\\n\\n"; foreach ($my_ads as $ad_id => $ad) { $status = $ad['status'] === 'sold' ? "✅ Sotilgan" : "🔴 Faol"; $phone = $ad['phone'] ?? "Ko'rsatilmagan"; $msg .= "{$status} - {$ad['text']}\\n📱: {$phone}\\n---\\n"; } sms($chat_id, $msg, getMenu($chat_id)); exit; } if ($step == 'waiting_text_private') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Bosh sahifaga qaytdingiz.", 'reply_markup' => getMenu($chat_id)]); exit; } $users[$from_id]['temp_text'] = $text; $users[$from_id]['step'] = 'waiting_phone_private'; saveData($users_file, $users); $phone_btn = json_encode(['keyboard' => [[['text' => "📱 Telefon raqamni yuborish", 'request_contact' => true]], [["text" => "🔙 Orqaga"]]], 'resize_keyboard' => true]); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Ustalar siz bilan bog'lanishi uchun pastdagi tugmani bosib telefon raqamingizni yuboring:", 'reply_markup' => $phone_btn]); exit; } if ($step == 'waiting_phone_private') { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'waiting_text_private'; saveData($users_file, $users); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Usta kerakligi haqida e'lon matnini to'liq yozib yuboring:", 'reply_markup' => $ort]); exit; } $phone = isset($message['contact']) ? $message['contact']['phone_number'] : $text; $ad_text = $users[$from_id]['temp_text']; $ad_id = uniqid('ad_', true); $message_link = buildMessageLink($chat_id, 0, null); $ads[$ad_id] = [ 'user_id' => $from_id, 'name' => $first_name, 'username' => $username, 'text' => $ad_text, 'phone' => $phone, 'status' => 'active', 'from_chat_id' => $chat_id, 'group_name' => 'Bot orqali', 'message_id' => 0, 'message_link' => '', 'content_hash' => adContentHash($from_id, $ad_text), 'time' => time(), 'datetime' => date('Y-m-d H:i:s') ]; saveData($ads_file, $ads); $users[$from_id]['step'] = 'start'; unset($users[$from_id]['temp_text']); saveData($users_file, $users); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "✅ E'loningiz qabul qilindi!", 'reply_markup' => getMenu($chat_id)]); $group_msg = formatNewOrderChannelMessage($ad_text, $contact_price); $inline_keyboard = json_encode(['inline_keyboard' => [[['text' => "💳 Kontaktni sotib olish", 'callback_data' => "buy_contact_{$ad_id}"]]]]); bot('sendMessage', ['chat_id' => $target_group, 'text' => $group_msg, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true, 'reply_markup' => $inline_keyboard]); exit; } if ($text == "💵 Pul kiritish") { $keyboard2 = [[['text' => "🏦 HUMO Avto To'lov", 'callback_data' => "menu=HUMO"]]]; $user_bal = $users[$from_id]['balance'] ?? 0; bot('sendMessage', ['chat_id' => $chat_id, 'text' => "💳 HUMO Avto To'lov\n\n💰 Hisobingiz: " . number_format($user_bal, 0, '.', ' ') . " so'm\n\nHisobni to'ldirish turini tanlang:", 'parse_mode' => 'HTML', 'reply_markup' => json_encode(['inline_keyboard' => $keyboard2])]); exit; } if ($step == "humo_amount") { if ($text == "🔙 Orqaga") { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); bot('sendMessage', ['chat_id' => $chat_id, 'text' => "Bosh sahifaga qaytdingiz.", 'reply_markup' => getMenu($chat_id)]); exit; } $amount = str_replace([" ", ","], "", $text); if (!is_numeric($amount) || $amount < 1000 || $amount > 10000000) { sms($chat_id, "⚠️ Noto'g'ri summa!\n\nMinimal: 1 000 so'm\nMaksimal: 10 000 000 so'm", $ort); exit; } $amount_with_surcharge = add_unique_surcharge((int)$amount); $body = json_encode(['shop_id' => AVTO_SHOP_ID, 'shop_key' => AVTO_SHOP_KEY, 'amount' => (float)$amount_with_surcharge, 'user_id' => (string)$chat_id, 'webhook_url' => $webhook_url]); $ch = curl_init(AVTO_API_URL . '?action=create_order'); curl_setopt_array($ch, [CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>$body, CURLOPT_HTTPHEADER=>['Content-Type: application/json'], CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>10, CURLOPT_SSL_VERIFYPEER=>false]); $result = json_decode(curl_exec($ch), true); curl_close($ch); if (!$result || !isset($result['ok']) || !$result['ok']) { sms($chat_id, "❌ To'lov tizimida xatolik yuz berdi.", getMenu($chat_id)); exit; } $d = $result['data']; $order_id = $d['order_id']; $final = (int)$d['amount']; $card = $d['card_number']; $ttl_sec = (int)($d['ttl_minutes'] ?? 5) * 60; $expire = date('H:i', time() + $ttl_sec); $users[$from_id]['step'] = "humo_wait-$order_id"; saveData($users_file, $users); $extra_note = ""; if ((int)($d['extra_sum'] ?? 0) > 0) { $extra_note = "\n\n⚠️ Nima uchun summa o'zgardi?\n" . "Farqlash uchun +" . $d['extra_sum'] . " so'm qo'shildi — bu ham hisobingizga o'tadi."; } sms($chat_id, "💳 HUMO Avto To'lov Cheki\n\n" . "💰 Summa: " . number_format($final, 0, '.', ' ') . " so'm\n" . "🏦 Karta: {$card}\n\n" . "⏳ Muddat: 5 daqiqa ({$expire} gacha)" . $extra_note, json_encode(['inline_keyboard' => [ [['text' => "📋 Karta raqamidan nusxa", 'copy_text' => ['text' => str_replace(' ', '', $card)]]], [['text' => "💰 Summadan nusxa", 'copy_text' => ['text' => (string)$final]]], [['text' => "✅ To'lov qildim", 'callback_data' => "humo_check-{$order_id}"]], [['text' => "❌ Bekor qilish", 'callback_data' => "humo_cancel-{$order_id}"]] ]]) ); exit; } if (mb_stripos($step, "humo_wait-") !== false) { $order_id = (int)explode("-", $step)[1]; $d = humo_check($order_id); $st = $d['status'] ?? ''; $sec = (int)($d['seconds_left'] ?? 0); if ($st === 'paid') { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); } elseif ($st === 'expired' || $sec <= 0) { $users[$from_id]['step'] = 'start'; saveData($users_file, $users); sms($chat_id, "⏰ To'lov muddati tugadi.\n\n«💵 Pul kiritish» tugmasini bosib qaytadan urinib ko'ring.", getMenu($chat_id)); exit; } } } } ?>