<?php
    
    //-------------------------------------- ip checker
    error_log(">>>> webhook called: " . time());
 
    // $telegram_ip_ranges = [
    
    // ['lower' => '149.154.160.0', 'upper' => '149.154.175.255'], // literally 149.154.160.0/20
    
    // ['lower' => '91.108.4.0', 'upper' => '91.108.7.255'], // literally 91.108.4.0/22
    
    // ];
    
    // $ip_dec = (float) sprintf("%u", ip2long($_SERVER['REMOTE_ADDR']));
    
    // $ok=false;
    
    // foreach ($telegram_ip_ranges as $telegram_ip_range) if (!$ok) {
    
    // $lower_dec = (float) sprintf("%u", ip2long($telegram_ip_range['lower']));
    
    // $upper_dec = (float) sprintf("%u", ip2long($telegram_ip_range['upper']));
    
    // if ($ip_dec >= $lower_dec and $ip_dec <= $upper_dec) $ok=true;
    
    // }
    
    // if (!$ok) die("Are You Okay ?");
    

    //-------------------------------------- times and data
    
    //$est_time = ini_set('date.timezone', 'US/Eastern');         //set time zoon   ini_set('date.timezone', 'Asia/Tehran');
    
    $time_h_i       = date('H:i');
    $date       = date('y-m-d');
    
    //--------------------------------------adv text
    
    $ad_text = "\n\nAd: " . file_get_contents(__DIR__ . "/../ad.txt");         //"\n\nad.[SOLANA Price](t.me/SOLPriceX)"; //\n\n*🕛 Time EST : $time_h_i*           🕛 Time now *(UTC +0)* : $time_h_i\n\n 
    
    //--------------------------------------reply texts
    
    $feedback_record = "You are sending feedback to support.\n\nPlease enter your feedback (in the form of text or text with image or video or gif)";
    $ad_record  = "Hey my owner.\n\nPlease send your Ad text(MarkDown format). Im waiting...";
    
    //--------------------------------------
    
    $bot_url      = "https://tapi.bale.ai/bot33636894:nSY5zfmwCzwokO6WzDevMEu1hK5r4Gp9cnM";
    
    //--------------------------------------Cron job Process
    
    // $connection = connect_to_db();
        
    //     $result = $connection -> query("SELECT * FROM message_chek WHERE channel_id = 'cronjob AiPrice'  ");
        
    //     while($row = $result -> fetch_assoc()) {
         
    //         $Active_test_db   = $row['send_chek'];
            
    //     }
        
    //     if ($Active_test_db == "Active") { show_cronjob(); }
        
    // $connection -> close();
     
    //--------------------------------------
    
    $update = file_get_contents("php://input");
    
    // http_response_code(200); 
    
    $update_array = json_decode($update, true);
    
    
    // $url = $bot_url."/sendMessage";
    // $post_params = [    
    //                     'chat_id' => "698468282" ,
    //                     'text' => $update,
    //                 ];
    // send_reply($url, $post_params);
    
    //--------------------------------------  cronjob
    
    if (isset($update_array["message"]["chat"]["type"])) {
        
        $media_group_id     = $update_array["message"]["media_group_id"];
        $channel_chat_id    = $update_array["message"]["chat"]["id"];
        $channel_chat_title = $update_array["message"]["chat"]["title"];
        $entities           = $update_array['message']['entities'];
        $caption_entities   = $update_array['message']['caption_entities'];
        $telegram_msg_id = $update_array["message"]["message_id"];
        $reply_to_msg_id = $update_array["message"]["reply_to_message"]["message_id"] ?? null;
        
        if (isset($update_array['message']['pinned_message'])) {
            // یعنی این آپدیت مربوط به پین شدن پیامه — کاری نکن
            exit;
        }
        
        $connection = connect_to_db();
            
            $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot WHERE channel_id = $channel_chat_id");
        
            if ($row = $result->fetch_assoc()) {
                
                $telegram_id        = $row["telegram_id"];
                $eitatoken          = $row["eitatoken"];
                $eita_channel       = $row["eita_channel"];
                $bale_channel       = $row["bale_channel"];
                $rubika_channel     = $row["rubika_channel"];
                $tg_channel_title   = $row["tg_channel_title"];
                $end_subscription   = $row["end_subscription"];
                $url_mode_in_eitaa  = $row["url_mode_in_eitaa"];
                
                $rules = json_decode($row['replace_rules'], true);
                
                
                $baletoken  = "1875200944:l93TlxZY3yEJtThgGH4ND8RtSJwxMOrG4H89vIyb";
                $rubikatoken = "BGFDI0JRZGFVFKSLENWJRFOXZGTXNSECSFANJELXKSSUSCDDUSMZGZTNYRJIXNOS";
                
                $now = time();
                
                
                if (strtotime($end_subscription) > $now) {
                    
                    $reply_to_msg_id = $update_array["message"]["reply_to_message"]["message_id"] ?? null;
                    $reply_to_bale   = null;
                    $reply_to_eitaa  = null;
                    $reply_to_rubika = null;
                    
                    if ($reply_to_msg_id) {
                        $resultMap = $connection -> query("
                            SELECT * FROM eitaayarbot_message_map 
                            WHERE telegram_id = '$channel_chat_id' 
                            AND telegram_msg_id = '$reply_to_msg_id'
                        ");
                        if ($mapRow = $resultMap -> fetch_assoc()) {
                            $reply_to_bale   = $mapRow['bale_msg_id'];
                            $reply_to_eitaa  = $mapRow['eitaa_msg_id'];
                            $reply_to_rubika = $mapRow['rubika_msg_id'];
                        }
                    }
                    
                    $caption = $update_array['message']['caption'] ?? ""; // توضیحات (در صورت وجود)
                    // $caption = convertTelegramEntitiesToMarkdownBale($update_array['message']['caption'] ?? "", $caption_entities); //با فرمت متنی
                    
                    if (isset($update_array['message']['photo'])) {
                        $file_id = end($update_array['message']['photo'])['file_id'];
                        $file_type = "photo";
                        
                    } elseif (isset($update_array['message']['video'])) {
                        $file_id = $update_array['message']['video']['file_id'];
                        $file_type = "video";
                        
                    } elseif (isset($update_array['message']['audio'])) {
                        $file_id = $update_array['message']['audio']['file_id'];
                        $file_type = "audio";
                        
                    } elseif (isset($update_array['message']['voice'])) {
                        $file_id = $update_array['message']['voice']['file_id'];
                        $file_type = "voice";
                    
                    } elseif (isset($update_array['message']['video_note'])) {
                        $file_id = $update_array['message']['video_note']['file_id'];
                        // $file_type = "video_note";
                        $file_type = "video";
                        
                    
                    } elseif (isset($update_array['message']['document'])) {
                        $file_id = $update_array['message']['document']['file_id'];
                        $file_type = "document";
                        
                    } elseif (isset($update_array['message']['animation'])) {
                        $file_id = $update_array['message']['animation']['file_id'];
                        $file_type = "animation";
                        
                    } elseif (isset($update_array['message']['sticker'])) {
                        $file_id = $update_array['message']['sticker']['thumbnail']['file_id'];
                        $file_type = "sticker";
                        
                    } else {
                        $text = $update_array['message']['text'];
                        // $text = convertTelegramEntitiesToMarkdownBale($update_array['message']['text'], $entities);
                        
                        if (!empty($eitatoken) && !empty($eita_channel)) {
                            
                            $text_to_send_eitaa = applyRules($text, $rules, 'eitaa');
                            
                            if($url_mode_in_eitaa == 1) {
                                $text_to_send_eitaa = convertTelegramEntitiesToMarkdownEitaa($text_to_send_eitaa, $entities);
                            }
                            
                            $response = sendToEitaa($text_to_send_eitaa, $eitatoken, $eita_channel, $reply_to_eitaa);
                            
                            if ($response === false) {
                                
                                error_log("ارسال به ایتا با مشکل مواجه شد: chat_id = $eita_channel");
                                
                            } else {
                                
                                $response = json_decode($response, true);
                                $eitaa_msg_id = $response['result']['message_id'];
                                saveMessageMap($telegram_msg_id, $eitaa_msg_id, 'eitaa', $channel_chat_id);
                                
                            }
                        }
                        
                        if (!empty($baletoken) && !empty($bale_channel)) {
                            
                            $text_to_send_bale = applyRules($text, $rules, 'bale');
                            
                            if($entities) {
                                $text_to_send_bale = convertTelegramEntitiesToMarkdownBale($text_to_send_bale, $entities);
                            }
                            
                            $response = sendToBale($text_to_send_bale, $baletoken, $bale_channel, $reply_to_bale);
                            
                            $response = json_decode($response, true);
                            $bale_msg_id = $response['result']['message_id'];
                            saveMessageMap($telegram_msg_id, $bale_msg_id, 'bale', $channel_chat_id);
                            
                            if (isset($response['ok']) && $response['ok'] === false) {
                                if (isset($response['error_code']) && $response['error_code'] == 403) {
                                    $reply = "ربات هنوز در کانال بله ادمین نشده!";
                                }
                                // else {
                                //     $reply = "خطای دیگری رخ داده: " . ($response['description'] ?? 'نامشخص');
                                // }
                                
                                $url = $GLOBALS['bot_url']."/sendMessage";
                                $post_params = [    
                                                    'chat_id' => "$telegram_id" ,
                                                    'text' => $reply ,
                                                    'parse_mode' => 'HTML'
                                                ];
                                send_reply($url, $post_params);
                            }
                            // else {
                            //     $reply = "پیام با موفقیت ارسال شد.";
                            // }
                            
                        }
                        
                        if (!empty($rubikatoken) && !empty($rubika_channel)) {
                            
                            $text_to_send_rubika = applyRules($text, $rules, 'rubika');
                            
                            $response = sendToRubika($text_to_send_rubika, $rubikatoken, $rubika_channel, $reply_to_rubika);
                            
                            // $response = json_decode($response, true);
                            // $rubika_msg_id = $response['result']['message_id'];
                            
                            if ($response['status'] === 'OK') {
                                $rubika_msg_id = $response['message_id'];
                                saveMessageMap($telegram_msg_id, $rubika_msg_id, 'rubika', $channel_chat_id);
                                
                            } else {
                                error_log( "❌ ارسال ناموفق: " . $response['message']);
                            }
                            
                        }
                        
                        if (empty($eita_channel) && empty($bale_channel) && empty($rubika_channel)) {
                            
                            $reply  = "🌸 کاربر عزیز\n\n"; 
                            $reply .= "✅ کانال تلگرام <b>$tg_channel_title</b> را متصل کرده‌اید،\n\n"; 
                            $reply .= "اما هنوز هیچ کانالی برای<b>ایتا</b>، <b>بله</b> یا <b>روبیکا</b> متصل نکرده‌اید.\n\n\n"; 
                            $reply .= "📌 لطفاً یکی از این شبکه‌ها را متصل کنید یا ربات را از کانال تلگرام خود حذف نمایید.";
                            
                            $url = $GLOBALS['bot_url']."/sendMessage";
                            $post_params = [    
                                                'chat_id' => "$telegram_id" ,
                                                'text' => $reply ,
                                                'parse_mode' => 'HTML'
                                            ];
                            send_reply($url, $post_params);
                            
                        }
                        
                        // $connection->close();
                        return;
                    }
                    
                    if (isset($media_group_id) && in_array($file_type, ['photo', 'video'])) {
                        
                        if (!empty($baletoken) && !empty($bale_channel)) {
                            
                            $caption_to_send_bale = applyRules($caption, $rules, 'bale');
                            
                            $caption_to_send_bale = convertTelegramEntitiesToMarkdownBale($caption_to_send_bale, $caption_entities); //با فرمت متنی
                        }
                        
                        if (!empty($rubikatoken) && !empty($rubika_channel)) {
                            
                            $caption_to_send_rubika = applyRules($caption, $rules, 'rubika');
                            
                            // $response = sendFileToRubika($fileUrl, $caption_to_send_rubika, $file_type, $rubikatoken, $rubika_channel, $reply_to_rubika);
                            
                            // if ($response['status'] === 'OK' && isset($response['response']['data']['message_id'])) {
                                
                            //     $rubika_msg_id = $response['response']['data']['message_id'];
                            //     saveMessageMap($telegram_msg_id, $rubika_msg_id, 'rubika', $channel_chat_id);
                                
                            // } else {
                            //     $rubika_msg_id = null;
                            //     error_log("❌ Rubika sendFile failed or no message_id found: " . print_r($response, true));
                            // }
                        }
                        
                        
                        handleTelegramAlbum($media_group_id, $file_type, $file_id, $caption_to_send_bale, $bale_channel, $channel_chat_id, $telegram_msg_id, $caption_to_send_rubika, $rubika_channel);
                        
                        
                        $fileUrl = getTelegramFileURL($file_id);
                        
                        if ($fileUrl === false) {
                            
                            // $connection->close();
                            return; // هیچی نفرست
                        }
                        
                        if ($fileUrl) {
                            if (!empty($eitatoken) && !empty($eita_channel)) {
                                
                                $caption_to_send_eitaa = applyRules($caption, $rules, 'eitaa');
                                
                                if($url_mode_in_eitaa == 1) {
                                    $caption_to_send_eitaa = convertTelegramEntitiesToMarkdownEitaa($caption_to_send_eitaa, $caption_entities);
                                }
                                
                                $response = sendFileToEitaa($fileUrl, $caption_to_send_eitaa, $eitatoken, $eita_channel, $reply_to_eitaa);
                                
                                if ($response === false) {
                                    
                                    error_log("❌ ارسال به ایتا با مشکل مواجه شد: chat_id = $eita_channel");
                                    
                                } elseif (isset($response['result']['message_id'])) {
                                    
                                    $eitaa_msg_id = $response['result']['message_id'];
                                    saveMessageMap($telegram_msg_id, $eitaa_msg_id, 'eitaa', $channel_chat_id);
                                    
                                } else {
                                    
                                    error_log("⚠️ پاسخ نامعتبر از API ایتا: " . print_r($response, true));
                                }
                            }
                        }
                        
                        // $connection->close();
                        return;
                        
                    } else {
                        
                        // دریافت لینک فایل از تلگرام
                        $fileUrl = getTelegramFileURL($file_id);
                        
                        if ($fileUrl === false) {
                            
                            // $connection->close();
                            return; // هیچی نفرست
                        }
                        
                        if ($fileUrl) {
                            
                            if (!empty($eitatoken) && !empty($eita_channel)) {
                                
                                $caption_to_send_eitaa = applyRules($caption, $rules, 'eitaa');
                                
                                if($url_mode_in_eitaa == 1) {
                                    $caption_to_send_eitaa = convertTelegramEntitiesToMarkdownEitaa($caption_to_send_eitaa, $caption_entities);
                                }
                                
                                $response = sendFileToEitaa($fileUrl, $caption_to_send_eitaa, $eitatoken, $eita_channel, $reply_to_eitaa);
                                
                                if ($response === false) {
                                    
                                    error_log("❌ ارسال به ایتا با مشکل مواجه شد: chat_id = $eita_channel");
                                    
                                } elseif (isset($response['result']['message_id'])) {
                                    
                                    $eitaa_msg_id = $response['result']['message_id'];
                                    saveMessageMap($telegram_msg_id, $eitaa_msg_id, 'eitaa', $channel_chat_id);
                                    
                                } else {
                                    
                                    error_log("⚠️ پاسخ نامعتبر از API ایتا: " . print_r($response, true));
                                }
                            }
                            
                            if (!empty($baletoken) && !empty($bale_channel)) {
                                
                                $caption_to_send_bale = applyRules($caption, $rules, 'bale');
                                
                                $caption_to_send_bale = convertTelegramEntitiesToMarkdownBale($caption_to_send_bale, $caption_entities); //با فرمت متنی
                                
                                $response = sendFileToBale($fileUrl, $caption_to_send_bale, $file_type, $baletoken, $bale_channel, $reply_to_bale);
                                
                                $response = json_decode($response, true);
                                $bale_msg_id = $response['result']['message_id'];
                                saveMessageMap($telegram_msg_id, $bale_msg_id, 'bale', $channel_chat_id);
                                
                                
                                if (isset($response['ok']) && $response['ok'] === false) {
                                    if (isset($response['error_code']) && $response['error_code'] == 403) {
                                        $reply = "ربات هنوز در کانال بله ادمین نشده!";
                                    } else {
                                        $reply = "خطای دیگری رخ داده: " . ($response['description'] ?? 'نامشخص');
                                    }
                                }
                                // else {
                                //     $reply = "پیام با موفقیت ارسال شد.";
                                // }
                                
                                $url = $GLOBALS['bot_url']."/sendMessage";
                                $post_params = [    
                                                    'chat_id' => "$telegram_id" ,
                                                    'text' => $reply , 
                                                    // 'parse_mode' => 'HTML'
                                                ];
                                send_reply($url, $post_params);
                            }
                            
                            if (!empty($rubikatoken) && !empty($rubika_channel)) {
                                
                                $caption_to_send_rubika = applyRules($caption, $rules, 'rubika');
                                
                                // $response = sendFileToRubika($fileUrl, $caption_to_send_rubika, $file_type, $rubikatoken, $rubika_channel, $reply_to_rubika); 
                                $response = sendFileToRubika($fileUrl, $caption_to_send_rubika, $file_type, $rubikatoken, $rubika_channel, $reply_to_rubika = null);
                                
                                if ($response['status'] === 'OK' && isset($response['response']['data']['message_id'])) {
                                    
                                    $rubika_msg_id = $response['response']['data']['message_id'];
                                    saveMessageMap($telegram_msg_id, $rubika_msg_id, 'rubika', $channel_chat_id);
                                    
                                } else {
                                    $rubika_msg_id = null;
                                    error_log("❌ Rubika sendFile failed or no message_id found: " . print_r($response, true));
                                }
                            }
                            
                            if (empty($eita_channel) && empty($bale_channel) && empty($rubika_channel)) {
                                
                                $reply  = "🌸 کاربر عزیز\n\n"; 
                                $reply .= "✅ کانال تلگرام <b>$tg_channel_title</b> را متصل کرده‌اید،\n\n"; 
                                $reply .= "اما هنوز هیچ کانالی برای<b>ایتا</b>، <b>بله</b> یا <b>روبیکا</b> متصل نکرده‌اید.\n\n\n"; 
                                $reply .= "📌 لطفاً یکی از این شبکه‌ها را متصل کنید یا ربات را از کانال تلگرام خود حذف نمایید.";
                                
                                $url = $GLOBALS['bot_url']."/sendMessage";
                                $post_params = [    
                                                    'chat_id' => "$telegram_id" ,
                                                    'text' => $reply ,
                                                    'parse_mode' => 'HTML'
                                                ];
                                send_reply($url, $post_params);
                                
                            }
                            
                            // $connection->close();
                            
                            return;
                        }
                    }
                } else {
                    
                    
                    $telegram_id = $row["telegram_id"];
                    
                    $reply  = "⚠️ <b>مشترک گرامی</b>\n\n";
                    $reply .= "⏳ مدت اشتراک شما به پایان رسیده است و پیام از کانال <b>$channel_chat_title</b> به ایتا ارسال نشد.\n\n\n";
                    $reply .= "🌿 برای تمدید، به بخش <b>وضعیت اشتراک</b> مراجعه کنید.\n\n\n";
                    $reply .= "💬 در صورت نیاز به راهنمایی می‌توانید با <a href='https://t.me/Yar36'><b>پشتیبانی پرداخت</b></a> در ارتباط باشید.";
                    
                    $url = $GLOBALS['bot_url']."/sendMessage";
                    $post_params = [    
                                        'chat_id' => "$telegram_id" ,
                                        'text' => $reply ,
                                        'parse_mode' => 'HTML',
                                        'disable_web_page_preview' => true
                                    ];
                    send_reply($url, $post_params);
                    
                    return;
                    
                    // اگر اشتراک تموم شده از الان شروع کن
                    // $new_end = date("Y-m-d H:i:s", strtotime("+3 months", $now));
                    
                }
            }
        // $connection->close();
    }
    
    if (isset($update_array["edited_message"])) {
        
        $channel_chat_id    = $update_array["edited_message"]["chat"]["id"];
        $telegram_msg_id    = $update_array["edited_message"]["message_id"];
        $entities           = $update_array["edited_message"]["entities"] ?? null;
        $caption_entities   = $update_array["edited_message"]["caption_entities"] ?? null;
        
        
        $new_text    = $update_array["edited_message"]["text"] ?? null;
        $new_caption = $update_array["edited_message"]["caption"] ?? null;
        
        
        $connection = connect_to_db();
            
            $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot WHERE channel_id = $channel_chat_id");
        
            if ($row = $result->fetch_assoc()) {
                
                $telegram_id        = $row["telegram_id"];
                $eitatoken          = $row["eitatoken"];
                $eita_channel       = $row["eita_channel"];
                $bale_channel       = $row["bale_channel"];
                $rubika_channel     = $row["rubika_channel"];
                $tg_channel_title   = $row["tg_channel_title"];
                $end_subscription   = $row["end_subscription"];
                $url_mode_in_eitaa  = $row["url_mode_in_eitaa"];
                
                $rules = json_decode($row['replace_rules'], true);
            }
            
            $baletoken   = "1875200944:l93TlxZY3yEJtThgGH4ND8RtSJwxMOrG4H89vIyb";
            $rubikatoken = "BGFDI0JRZGFVFKSLENWJRFOXZGTXNSECSFANJELXKSSUSCDDUSMZGZTNYRJIXNOS";
            
            
            $now = time();
            
            
            if (strtotime($end_subscription) > $now) {
                
                $resultMap = $connection -> query("
                    SELECT * FROM eitaayarbot_message_map 
                    WHERE telegram_id = '$channel_chat_id' 
                    AND telegram_msg_id = '$telegram_msg_id'
                ");
                if ($mapRow = $resultMap -> fetch_assoc()) {
                    $bale_msg_id   = $mapRow['bale_msg_id'];
                    $eitaa_msg_id  = $mapRow['eitaa_msg_id'];
                    $rubika_msg_id = $mapRow['rubika_msg_id'];
                }
            }
            
            if ($new_text) {
                
                if (!empty($baletoken) && !empty($bale_channel)) {
                    
                    $text_to_send_bale = applyRules($new_text, $rules, 'bale');
                    
                    if ($entities) {
                        $text_to_send_bale = convertTelegramEntitiesToMarkdownBale($text_to_send_bale, $entities);
                    }
                    
                    editBaleMessage($baletoken, $bale_channel, $bale_msg_id, $text_to_send_bale, null);
                    
                }
                
                if (!empty($rubikatoken) && !empty($rubika_channel)) {
                    
                    $text_to_send_rubika = applyRules($new_text, $rules, 'rubika');
                    
                    // if ($entities) {
                    //     $text_to_send_rubika = convertTelegramEntitiesToMarkdownBale($text_to_send_rubika, $entities);
                    // }
                    
                    editRubikaMessage($rubikatoken, $rubika_channel, $rubika_msg_id, $text_to_send_rubika, null);
                    
                }
                
            } elseif ($new_caption) {
                
                if (!empty($baletoken) && !empty($bale_channel)) {
                    
                    $caption_to_send_bale = applyRules($new_caption, $rules, 'bale');
                    
                    if ($caption_entities) {
                        $caption_to_send_bale = convertTelegramEntitiesToMarkdownBale($caption_to_send_bale, $caption_entities);
                    }
                    
                    editBaleMessage($baletoken, $bale_channel, $bale_msg_id, null, $caption_to_send_bale);
                    
                }
                
                if (!empty($rubikatoken) && !empty($rubika_channel)) {
                    
                    $caption_to_send_rubika = applyRules($new_caption, $rules, 'rubika');
                    
                    // if ($caption_entities) {
                    //     $caption_to_send_rubika = convertTelegramEntitiesToMarkdownBale($caption_to_send_rubika, $caption_entities);
                    // }
                    
                    editRubikaMessage($rubikatoken, $rubika_channel, $rubika_msg_id, null, $caption_to_send_rubika);
                    
                }
                
            }
            
        // $connection->close();
    }

    //------------------------- check started - cicked and save to db
    
    // $reply = "$update";
    // $url = $GLOBALS['bot_url']."/sendMessage";
    // $post_params = [    
    //                     'chat_id' => "698468282" ,
    //                     'text' => $reply ,
    //                 ];
    // send_reply($url, $post_params);
    
    //---------------------
    
    $keyt  = '🟦 وضعیت کانال تلگرام 🟦';
    $keye  = '🟧 وضعیت کانال ایتا 🟧';
    $keyb  = '🟩 وضعیت کانال بله 🟩';
    $keyr  = '⬜ وضعیت کانال روبیکا ⬜';
    $abzar_key = "🛠 ابزارها";
    $key3  = 'وضعیت توکن ایتایار';
    $skey  = "وضعیت اشتراک";
 
    $startkeys = [
                    'keyboard'          => [
                                                [$keyt , $keye] ,
                                                [$keyb , $keyr] ,
                                                [$skey , $key3] ,
                                                [$re_key],
                                            ] ,
                    'resize_keyboard'   => true ,
                    'one_time_keyboard' => false ,
                ];
    $startMarkup = json_encode($startkeys);
    
    
    $connection = connect_to_db();
        
        if(isset($update_array['message']['new_chat_members'])) {
            
            $new_member = $update_array['message']['new_chat_members'][0];
            $new_status = $new_member['id'];
            
            $chat_id            = $update_array['message']['chat']['id'];
            $chat_title         = $update_array['message']['chat']['title'];
            $chat_type          = $update_array['message']['chat']['type'];
            
            $from_id            = $update_array['message']['from']['id'] ?? 0;
            $from_first_name    = $update_array['message']['from']['first_name'] ?? '';
            $from_last_name     = $update_array['message']['from']['last_name'] ?? '';
            $from_username      = $update_array['message']['from']['username'] ?? '';
            
            $date = $update_array['message']['date'];
            
            if ($new_status == 33636894) {
                
                // دریافت اطلاعات کاربر از دیتابیس
                $result = $connection->query("SELECT eitatoken FROM baleapp_eitaayarbot WHERE telegram_id = $from_id");
            
                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    $token = $row['eitatoken'];
            
                    if (empty($token)) {
                        
                        $reply  = "🌸 <b>اتصال با موفقیت انجام شد!</b> ✅\n\n";
                        $reply .= "ربات با موفقیت به کانال <b>$chat_title</b> متصل گردید. 🌿\n\n";
                        $reply .= "💎 لطفاً از طریق سایت <a href='https://eitaayar.ir'><b>eitaayar.ir</b></a>، توکن ایتایار خود را دریافت کرده و در اینجا ارسال نمایید. 🌺";
                        
                        $waiting = 1;
                        
                    } else {
                        
                        $reply  = "🌸 <b>اتصال موفقیت‌آمیز!</b> ✅\n\n";
                        $reply .= "ربات با موفقیت به کانال جدید <b>$chat_title</b> متصل شد. 🌿\n\n";
                        $reply .= "🍃 اگر کانال تلگرام را تغییر داده‌اید، ربات را از کانال قبلی حذف کنید؛ در غیر این صورت نیازی به اقدام دیگری نیست. 🌺";
                        
                        $waiting = 0;
                        
                    }
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET channel_id = '$chat_id', tg_channel_title = '$chat_title', waiting = '$waiting' WHERE telegram_id = $from_id");
                    
                }
                
                $url = $GLOBALS['bot_url'] . "/sendMessage";
                $post_params = [
                    'chat_id' => $from_id,
                    'text' => $reply,
                    // 'reply_markup' => $startMarkup,
                    'parse_mode' => 'HTML'
                ];
                send_reply($url, $post_params);
                
            } 
            elseif ($new_status === 'left') {
                
                // اطلاعات کاربر حذف‌کننده
                
                $fullName = trim($from_first_name . ' ' . $from_last_name);
                $usernameTag = $from_username ? "@" . $from_username : "ندارد";
                
                // پیدا کردن صاحب اصلی کانال (کسی که ربات رو به کانال اضافه کرده)
                $result = $connection->query("SELECT telegram_id FROM baleapp_eitaayarbot WHERE channel_id  = $chat_id");
                
                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    $ownerTelegramID = $row['telegram_id'];
                    
                    if($ownerTelegramID == $from_id or $from_username == "Channel_Bot") {
                        // پیام به شخصی که حذف کرده (همون کدی که قبلا بود)
                        
                        $reply  = "⚠️ <b>ربات از کانال <b>$chat_title</b> حذف شد.</b> ❌\n\n";
                        $reply .= "🌿 اگر به اشتباه ربات را از کانال حذف کرده‌اید، لطفاً آن را دوباره اضافه کنید تا اتصال با ایتا برقرار شود. 💫\n\n";
                        $reply .= "➕ <a href='http://t.me/baleapp_eitaayarbot?startchannel=addtochannel'>افزودن ربات به ادمین‌های کانال</a>";
                        
                        
                        $url = $GLOBALS['bot_url'] . "/sendMessage";
                        $post_params = [
                            'chat_id' => $ownerTelegramID,
                            'text' => $reply,
                            'parse_mode' => 'HTML'
                        ];
                        send_reply($url, $post_params);
                    } else {
                        
                        // پیام به صاحب اصلی کانال
                        $textToOwner  = "⚠️ <b>هشدار:</b> ربات از کانال <b>$chat_title</b> حذف شد! ❌\n\n";
                        $textToOwner .= "👤 <b>اطلاعات کاربری که ربات را حذف کرده است:</b>\n\n";
                        $textToOwner .= "▫️ نام کامل: <b>$fullName</b>\n";
                        $textToOwner .= "▫️ یوزرنیم: <b>$usernameTag</b>\n";
                        $textToOwner .= "▫️ آیدی عددی: <b>$from_id</b>\n\n";
                        $textToOwner .= "🌿 برای افزودن مجدد، از لینک زیر استفاده کنید:\n\n";
                        $textToOwner .= "<a href='http://t.me/baleapp_eitaayarbot?startchannel=addtochannel'>➕ افزودن ربات به ادمین‌های کانال</a>";
                        
                        $url = $GLOBALS['bot_url'] . "/sendMessage";
                        $post_params = [
                            'chat_id' => $ownerTelegramID,
                            'text' => $textToOwner,
                            'parse_mode' => 'HTML'
                        ];
                        send_reply($url, $post_params);
                        
                    }
                }
            
                // حذف channel_id وقتی ربات از کانال حذف شده
                $connection->query("UPDATE baleapp_eitaayarbot SET channel_id = NULL WHERE channel_id = $chat_id");
            }
            
        } else{ 
            
            $new_status = "member";
            
            $chat_id    = $update_array["message"]['chat']['id'];
            $chat_title = $update_array["message"]['chat']['first_name'];
            $last_name  = $update_array["message"]['chat']['last_name'];
            $username   = $update_array["message"]['chat']['username'];
            
        }
        
        if ($new_status === "member") {
            
            if (!empty($chat_id) && $chat_id > 0) {
                
                $result = $connection->query("SELECT telegram_id FROM baleapp_eitaayarbot WHERE telegram_id = $chat_id");
                
                if ($result->num_rows == 0) {
                    
                    // کاربر جدید - insert کن
                    $end_subscription = date("Y-m-d H:i:s", strtotime("+7 days"));
                    
                    $connection->query("INSERT INTO baleapp_eitaayarbot (telegram_id, first_name, last_name, username, end_subscription,status) VALUES ('$chat_id', '$chat_title', '$last_name', '$username', '$end_subscription','$new_status')");
                } else {
                    
                    // کاربر قدیمی - update کن
                    $connection->query("UPDATE baleapp_eitaayarbot SET first_name = '$chat_title', last_name = '$last_name', username = '$username', status = '$new_status' WHERE telegram_id = $chat_id");
                }
            }
        }
        
    // $connection -> close();
    
    //--------------------
    
    if(isset($update_array["callback_query"])) {
        
        $callback_id= $update_array["callback_query"]["id"];
        $data       = $update_array["callback_query"]["data"];
        $chat_id    = $update_array["callback_query"]["message"]["chat"]["id"];
        $first_name = $update_array["callback_query"]["message"]["chat"]["first_name"];
        $last_name  = $update_array["callback_query"]["message"]["chat"]["last_name"];
        $message_id = $update_array["callback_query"]["message"]["message_id"];
        
        detect_callback_received_and_reply();
    }
    
    else if(isset($update_array["message"])) {
        
        $text           = $update_array["message"]["text"];
        $chat_id        = $update_array["message"]["chat"]["id"];
        $chat_title     = $update_array["message"]["chat"]["title"];
        $new_chat_parti = $update_array["message"]["new_chat_participant"]["username"];
        $message_id     = $update_array["message"]["message_id"];
        $thread_id      = $update_array["message"]["message_thread_id"];
        $from_id        = $update_array["message"]["from"]["id"];
        $language_code  = $update_array["message"]["from"]["language_code"];
        $first_name     = $update_array["message"]["from"]["first_name"];
        $last_name      = $update_array["message"]["from"]["last_name"];
        $username       = $update_array["message"]["from"]["username"];
        
        //--------------------------------------
        
        // $message = $update_array['message'];
        // $from_id = $message['from']['id'];
        // $text = trim($message['text'] ?? '');
        
        //--------------------------------------
        
        // $reply = "$text \n\n" . $update;
        // $url = $GLOBALS['bot_url']."/sendMessage";
        // $post_params = [    
        //                     'chat_id' => "698468282" ,
        //                     'text' => $reply ,
                            
        //                 ];
        // send_reply($url, $post_params);
        
        //--------------------
        
        if($new_chat_parti == "eitaayarbot") {
            
            $reply = "Thanks for adding me to your channel!";
            $url = $GLOBALS['bot_url']."/sendMessage";
            $post_params = [    
                                'chat_id' => "$chat_id" ,
                                'text' => $reply ,
                            ];
            send_reply($url, $post_params);
            
        }
        
        if (isset($update_array["message"]["reply_to_message"])) {
            
            $text_replied       = $update_array["message"]["reply_to_message"]["text"];
            $chat_id_replied    = $update_array["message"]["reply_to_message"]["id"];
            $message_id_replied = $update_array["message"]["reply_to_message"]["message_id"];
            
        }
        
        if ($chat_id == '698468282') {
            
            admin_settings();
            return;
        }
        
        detect_text_received_and_reply();
        
    }

    else if (isset($update_array["inline_query"])) {
        
        $inline_query    = $update_array["inline_query"]["query"];
        $inline_query_id = $update_array["inline_query"]["id"];
        
        
        detect_inline_query_received_and_reply_1();
        
    }
    //-------------------------------------
    
    function createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chatId, $desc) {
        
        $callback_url = $callback_url . "?chat_id=$chatId&desc=$desc";
    
        $data = [
            "merchant_id" => $merchant_id,
            "amount" => $amount,
            "callback_url" => $callback_url,
            "description" => $desc,
            "metadata" => [
                "order_id" => strval($chatId),
                // "mobile" => $mobile,
                // "email" => $email
            ]
        ];
    
        $ch = curl_init("https://payment.zarinpal.com/pg/v4/payment/request.json");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    
        $response = curl_exec($ch);
    
        // لاگ خطای cURL
        if(curl_errno($ch)){
            error_log('cURL error: ' . curl_error($ch));
        }
    
        curl_close($ch);
    
        // لاگ پاسخ زرین پال برای دیباگ داخلی
        error_log('Zarinpal request response: ' . $response);
    
        $result = json_decode($response, true);
    
        if (isset($result['data']['code']) && $result['data']['code'] == 100) {
            $authority = $result['data']['authority'];
            return "https://payment.zarinpal.com/pg/StartPay/" . $authority;
        }
    
        return false;
    }

    
    // function createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chatId, $desc = 'پرداخت از ربات') {
    //     $data = [
    //         "merchant_id" => $merchant_id,
    //         "amount" => $amount,
    //         "callback_url" => $callback_url,
    //         "description" => $desc,
    //         "metadata" => [
    //             "order_id" => $chatId
    //         ]
    //     ];
    
    //     $ch = curl_init("https://payment.zarinpal.com/pg/v4/payment/request.json");
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($ch, CURLOPT_HTTPHEADER, [
    //         'Content-Type: application/json',
    //         'Accept: application/json'
    //     ]);
    //     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    //     $response = curl_exec($ch);
    //     curl_close($ch);
    
    //     $result = json_decode($response, true);
    
    //     if (isset($result['data']['code']) && $result['data']['code'] == 100) {
    //         $authority = $result['data']['authority'];
    //         return "https://payment.zarinpal.com/pg/StartPay/" . $authority;
    //     }
    
    //     return false;
    // }
/*
    function createZarinpalPaymentLink($merchant_id, $callback_url, $currency, $chatId, $amount, $desc = 'pay from telegram', $mobile = '', $email = '') {
        
        $params = [
            "merchant_id"  => $merchant_id,
            "amount"       => $amount,
            "currency"     => $currency,
            "callback_url" => $callback_url,
            "description"  => $desc,
            "metadata"     => [
                "mobile"   => $mobile,
                "email"    => $email,
                "order_id" => (string)$chatId
            ]
        ];
    
        $ch = curl_init('https://payment.zarinpal.com/pg/v4/payment/request.json');
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json'
            ],
            CURLOPT_TIMEOUT        => 20,
        ]);
    
        $result = curl_exec($ch);
        curl_close($ch);
    
        $response = json_decode($result, true);
    
        if (isset($response['data']['code']) && $response['data']['code'] == 100) {
            return 'https://payment.zarinpal.com/pg/StartPay/' . $response['data']['authority'];
        }
    
        return false;
    }
*/
    //-------------------------------------
    
    // گرفتن متن/لینک جایگزین
    function getRules($chat_id) {
        $connection = connect_to_db();
        $res = $connection->query("SELECT replace_rules FROM baleapp_eitaayarbot WHERE telegram_id = " . intval($chat_id) . " LIMIT 1");
        $row = $res->fetch_assoc();
        // $connection->close();
    
        $base = [
            "meta"   => ["pending" => null],
            "eitaa"  => [],
            "bale"   => [],
            "rubika" => []
        ];
    
        if (!$row || !$row['replace_rules']) return $base;
    
        $rules = json_decode($row['replace_rules'], true);
        if (!is_array($rules)) return $base;
    
        foreach (["meta","eitaa","bale","rubika"] as $k) {
            if (!array_key_exists($k, $rules)) {
                $rules[$k] = ($k === "meta") ? ["pending" => null] : [];
            }
        }
        if (!isset($rules["meta"]["pending"])) $rules["meta"]["pending"] = null;
    
        // $connection->close();
        return $rules;
    }
    
    // ذخیره قوانین در دیتابیس
    function saveRules($chat_id, $rules) {
        $connection = connect_to_db();
        $json = $connection->real_escape_string(json_encode($rules, JSON_UNESCAPED_UNICODE));
        $connection->query("UPDATE baleapp_eitaayarbot SET replace_rules = '{$json}' WHERE telegram_id = " . intval($chat_id));
        // $connection->close();
    }
    
    // ساخت ID یکتا برای هر قانون
    function generateRuleId() {
        return 'r_' . bin2hex(random_bytes(5));
    }
    
    // مرحله ۱: شروع پیش‌نویس
    function startDraft($chat_id, $platform) {
        if (!in_array($platform, ['eitaa','bale','rubika'])) {
            return false;
        }
    
        $rules = getRules($chat_id);
    
        // اگر پیش‌نویس قبلی بود حذفش کن
        if (!empty($rules['meta']['pending'])) {
            $pending = $rules['meta']['pending'];
            $p = $pending['platform'];
            $rid = $pending['rule_id'];
            $rules[$p] = array_values(array_filter($rules[$p], function($r) use ($rid) {
                return ($r['id'] ?? null) !== $rid;
            }));
            $rules['meta']['pending'] = null;
        }
    
        $rid = generateRuleId();
        $draft = [
            "id"         => $rid,
            "source"     => null,
            "target"     => null,
            "status"     => "draft",
            "created_at" => time()
        ];
    
        $rules[$platform][] = $draft;
        $rules['meta']['pending'] = ["rule_id" => $rid, "platform" => $platform];
    
        saveRules($chat_id, $rules);
        return $rid;
    }
    
    // مرحله ۲: ثبت متن اصلی (source)
    function setDraftSource($chat_id, $source) {
        $rules = getRules($chat_id);
        $pending = $rules['meta']['pending'] ?? null;
        if (!$pending) return false;
    
        $p = $pending['platform'];
        $rid = $pending['rule_id'];
    
        foreach ($rules[$p] as &$r) {
            if (($r['id'] ?? null) === $rid) {
                $r['source'] = $source;
                break;
            }
        }
    
        saveRules($chat_id, $rules);
        return true;
    }
    
    // مرحله ۳: ثبت متن جایگزین (target) و نهایی کردن
    function finalizeDraft($chat_id, $target) {
        $rules = getRules($chat_id);
        $pending = $rules['meta']['pending'] ?? null;
        if (!$pending) return false;
    
        $p = $pending['platform'];
        $rid = $pending['rule_id'];
    
        foreach ($rules[$p] as &$r) {
            if (($r['id'] ?? null) === $rid) {
                $r['target'] = $target;
                if (strlen(trim($r['source'])) && strlen(trim($r['target']))) {
                    $r['status'] = "active";
                }
                break;
            }
        }
    
        $rules['meta']['pending'] = null;
        saveRules($chat_id, $rules);
        return true;
    }
    
    //-------------------------------------
    
    function applyRules($text, $rules, $platform) {
        
        if (empty($rules[$platform])) return $text;
    
        foreach ($rules[$platform] as $rule) {
            if (($rule['status'] ?? '') === 'active' && !empty($rule['source'])) {
                $source = $rule['source'];
                $target = $rule['target'] ?? '';
                // جایگزینی ساده
                $text = str_replace($source, $target, $text);
            }
        }
        return $text;
    }
    
    //-------------------------------------
    
    //channels add - remove هنوز استفاده نشده
    
    function get_channels($chat_id) {
        
        $connection = connect_to_db();
        
        $res = $connection->query("SELECT channels FROM baleapp_eitaayarbot WHERE telegram_id='$chat_id'");
        $channels = ["channels" => []];
        
        if ($res && $row = $res->fetch_assoc()) {
            $channels = json_decode($row['channels'], true) ?: ["channels" => []];
        }
        
        // $connection->close();
        return $channels;
    }
    
    function save_channels($chat_id, $channels) {
        
        $connection = connect_to_db();
        
        $json = $connection->real_escape_string(json_encode($channels, JSON_UNESCAPED_UNICODE));
        $connection->query("UPDATE baleapp_eitaayarbot SET channels='$json' WHERE telegram_id='$chat_id'");
        
        // $connection->close();
    }
    
    function add_channel($chat_id, $new_channel) {
        
        $channels = get_channels($chat_id);
        
        $new_channel['id'] = "c_" . bin2hex(random_bytes(4));
        $new_channel['status'] = "active";
        $new_channel['created_at'] = time();
        
        $channels["channels"][] = $new_channel;
        
        save_channels($chat_id, $channels);
        return $new_channel['id'];
    }
    
    function remove_channel($chat_id, $channel_id) {
        
        $channels = get_channels($chat_id);
        
        $channels["channels"] = array_values(array_filter($channels["channels"], function($c) use ($channel_id) {
            return ($c['id'] ?? '') !== $channel_id;
        }));
        
        save_channels($chat_id, $channels);
    }
    
    function set_channel_status($chat_id, $channel_id, $status) {
        
        $channels = get_channels($chat_id);
        
        foreach ($channels["channels"] as &$c) {
            if (($c['id'] ?? '') === $channel_id) {
                $c['status'] = $status;
            }
        }
        
        save_channels($chat_id, $channels);
    }
    
    //-------------------------------------
    
    function getTelegramFileURL($file_id) {
        
        $bot_url  = $GLOBALS['bot_url'];
        $bot_token = "bot33636894:nSY5zfmwCzwokO6WzDevMEu1hK5r4Gp9cnM";
        
        // حداکثر دو بار تلاش
        for ($i = 0; $i < 2; $i++) {
            $fileInfo = @file_get_contents("$bot_url/getFile?file_id=$file_id");
            if ($fileInfo === false) {
                // کمی صبر قبل از تلاش بعدی
                sleep(0.5); // 0.5 ثانیه
                continue;
            }
            
            $fileInfoArray = json_decode($fileInfo, true);
            
            if (isset($fileInfoArray['result']['file_path'])) {
                $file_path = $fileInfoArray['result']['file_path'];
                return "https://tapi.bale.ai/file/$bot_token/$file_path";
            }
        }
        
        // اگر هر دو بار شکست خورد
        return false;
    }

    
    // function getTelegramFileURL($file_id) {
        
    //     $bot_url = $GLOBALS['bot_url'];
        
    //     sleep(0.5);
        
    //     $fileInfo = file_get_contents("$bot_url/getFile?file_id=$file_id");
    //     $fileInfoArray = json_decode($fileInfo, true);
        
    //     if (!isset($fileInfoArray['result']['file_path'])) {
    //         return false;
    //     }
    
    //     $file_path = $fileInfoArray['result']['file_path'];
        
    //     return "https://tapi.bale.ai/file/bot33636894:nSY5zfmwCzwokO6WzDevMEu1hK5r4Gp9cnM/$file_path";
    // }
    
    //-------------------------------------
    
    function convertTelegramEntitiesToHTML($text, $entities) {
        
        if (!is_array($entities)) {
            return htmlspecialchars($text); // اگر entity نداشت، فقط encode کن
        }
    
        $replacements = [];
    
        foreach (array_reverse($entities) as $entity) {
            $offset = $entity['offset'];
            $length = $entity['length'];
            $type = $entity['type'];
    
            $part = mb_substr($text, $offset, $length, 'UTF-8');
    
            switch ($type) {
                case 'bold':
                    $replace = "<b>$part</b>";
                    break;
                case 'italic':
                    $replace = "<i>$part</i>";
                    break;
                case 'underline':
                    $replace = "<u>$part</u>";
                    break;
                case 'strikethrough':
                    $replace = "<s>$part</s>";
                    break;
                case 'code':
                    $replace = "<code>$part</code>";
                    break;
                case 'pre':
                    $replace = "<pre>$part</pre>";
                    break;
                case 'text_link':
                    $url = $entity['url'];
                    $replace = "<a href=\"$url\">$part</a>";
                    break;
                case 'text_mention':
                    $user = $entity['user'];
                    $url = "tg://user?id=" . $user['id'];
                    $replace = "<a href=\"$url\">$part</a>";
                    break;
                default:
                    $replace = $part;
            }
    
            // جایگزینی در متن اصلی
            $text = mb_substr($text, 0, $offset, 'UTF-8') . $replace . mb_substr($text, $offset + $length, null, 'UTF-8');
        }
    
        return $text;
    }
    
    // function convertTelegramEntitiesToMarkdownEitaa($text, $entities) {
        
    //     if (!is_array($entities) || empty($entities)) {
    //         return $text;
    //     }
        
    //     $offsetShift = 0;
    //     $links = [];
        
    //     foreach ($entities as $entity) {
    //         $offset = $entity['offset'] + $offsetShift;
    //         $length = $entity['length'];
    //         $type = $entity['type'];
            
    //         $before = mb_substr($text, 0, $offset, 'UTF-8');
    //         $target = mb_substr($text, $offset, $length, 'UTF-8');
    //         $after = mb_substr($text, $offset + $length, null, 'UTF-8');
            
    //         switch ($type) {
    //             case 'bold':
    //                 $replacement = "$target";
    //                 break;
    //             case 'italic':
    //                 $replacement = "$target";
    //                 break;
    //             case 'code':
    //                 $replacement = "$target";
    //                 break;
    //             case 'pre':
    //                 $replacement = "$target";
    //                 break;
    //             case 'text_link':
                    
    //                 $replacement = $target;
                    
    //                 $links[] = "\n" . $entity['url'];
    //                 break;
    //             case 'underline': 
    //             case 'strikethrough': 
    //                 $replacement = $target;
    //                 break;
    //             default:
    //                 $replacement = $target;
    //         }
            
    //         $text = $before . $replacement . $after;
    //         $offsetShift += mb_strlen($replacement, 'UTF-8') - $length;
    //     }
        
        
    //     if (!empty($links)) {
    //         $text .= "\n\n" . implode("\n", $links);
    //     }
        
    //     return $text;
    // }

    function convertTelegramEntitiesToMarkdownEitaa($text, $entities) {
        
        if (!is_array($entities) || empty($entities)) {
            return $text;
        }
    
        $offsetShift = 0;
    
        foreach ($entities as $entity) {
            $offset = $entity['offset'] + $offsetShift;
            $length = $entity['length'];
            $type = $entity['type'];
    
            $before = mb_substr($text, 0, $offset, 'UTF-8');
            $target = mb_substr($text, $offset, $length, 'UTF-8');
            $after  = mb_substr($text, $offset + $length, null, 'UTF-8');
    
            switch ($type) {
                case 'bold':
                case 'italic':
                case 'code':
                case 'pre':
                case 'underline': 
                case 'strikethrough': 
                    $replacement = $target;
                    break;
    
                case 'text_link':
                    $replacement = $target;
    
                    // پیدا کردن انتهای پاراگراف
                    $nextNewlinePos = mb_strpos($after, "\n", 0, 'UTF-8');
                    if ($nextNewlinePos === false) {
                        // آخر متن
                        $insertionPoint = mb_strlen($after, 'UTF-8');
                    } else {
                        // تا قبل از اولین \n
                        $insertionPoint = $nextNewlinePos;
                    }
    
                    // متن تا انتهای همون پاراگراف
                    $parAfter  = mb_substr($after, 0, $insertionPoint, 'UTF-8');
                    $restAfter = mb_substr($after, $insertionPoint, null, 'UTF-8');
    
                    // اضافه کردن لینک بعد از پاراگراف
                    $parAfter .= "\n" . $entity['url'];
    
                    // بازسازی after
                    $after = $parAfter . $restAfter;
    
                    break;
    
                default:
                    $replacement = $target;
            }
    
            $text = $before . $replacement . $after;
            $offsetShift += mb_strlen($replacement, 'UTF-8') - $length;
        }
    
        return $text;
    }
    
    

function convertTelegramEntitiesToMarkdownBale($text, $entities) {
    if (!is_array($entities) || empty($entities)) {
        return $text;
    }

    // مرتب‌سازی entities از انتها به ابتدا
    usort($entities, function($a, $b) {
        return $b['offset'] - $a['offset'];
    });

    foreach ($entities as $entity) {
        $offset = $entity['offset'];
        $length = $entity['length'];
        $type   = $entity['type'];
        $url    = $entity['url'] ?? '';

        // تقسیم متن به قبل، هدف و بعد با رعایت UTF-16
        list($before, $target, $after) = utf16_substr_full($text, $offset, $length);

        switch ($type) {
            case 'bold':
            case 'messageEntityBold':
                $replacement = " *$target* ";  // space قبل و بعد ستاره
                break;
            case 'italic':
            case 'messageEntityItalic':
                $replacement = "_ $target _"; // space قبل و بعد آندرلاین
                break;
            case 'code':
            case 'messageEntityCode':
                $replacement = "`$target`";
                break;
            case 'pre':
            case 'messageEntityPre':
                $replacement = "\n$target\n";
                break;
            case 'text_link':
            case 'messageEntityTextUrl':
                $replacement = "[$target]($url)";
                break;
            case 'underline':
            case 'strikethrough':
            case 'custom_emoji':
                $replacement = $target; // بدون تغییر
                break;
            default:
                $replacement = $target;
        }

        $text = $before . $replacement . $after;
    }

    return $text;
}

// تابع کمکی برای تقسیم متن بر اساس UTF-16 code units
function utf16_substr_full($text, $offset, $length) {
    $before = '';
    $target = '';
    $after  = '';

    $utf16count = 0;
    $len = mb_strlen($text, 'UTF-8');

    for ($i = 0; $i < $len; $i++) {
        $char = mb_substr($text, $i, 1, 'UTF-8');
        $codepoint = mb_ord($char, 'UTF-8');
        $unit = ($codepoint > 0xFFFF) ? 2 : 1; // surrogate pair = 2

        if ($utf16count < $offset) {
            $before .= $char;
        } elseif ($utf16count >= $offset && $utf16count < $offset + $length) {
            $target .= $char;
        } else {
            $after .= $char;
        }

        $utf16count += $unit;
    }

    return [$before, $target, $after];
}

    //-------------------------------------
    
    function testEitaToken($token) {
        
        $url = "https://eitaayar.ir/api/$token/getMe";
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $response = curl_exec($ch);
    
        if(curl_errno($ch)) {
            curl_close($ch);
            return ['ok' => false, 'username' => null];
        }
        curl_close($ch);
    
        $res = json_decode($response, true);
    
        $ok = isset($res['ok']) && $res['ok'] === true;
        $username = $ok && isset($res['result']['username']) ? $res['result']['username'] : null;
    
        return ['ok' => $ok, 'username' => $username];
    }
    
    //-------------------------------------
    
    function testEitaChannel($token, $channel_id) {
        
        $url = "https://eitaayar.ir/api/$token/sendMessage";
    
        $post_fields = [
            'chat_id' => $channel_id,
            'text' => '✅'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $response = curl_exec($ch);
    
        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        }
    
        curl_close($ch);
        $res = json_decode($response, true);
        return isset($res['ok']) && $res['ok'] === true;
    }
    
    
    // function sendFileToEitaa($fileUrl, $caption = "", $eitatoken, $eita_channel = "", $reply_to_message_id = null) {
        
    //     $token = "$eitatoken";
    //     $chat_id = $eita_channel;
    //     $caption = "$caption";
    //     $title = 'send file by api';
    
    //     sleep(2); // اختیاری
    
    //     $request = curl_init("https://eitaayar.ir/api/$token/sendFile");
        
    //     $postFields = [
    //         'file' => new CURLFile($fileUrl),
    //         'chat_id' => $chat_id,
    //         'title' => $title,
    //         'caption' => $caption,
    //     ];
        
    //     // اگه ریپلای وجود داشت اضافه کن
    //     if (!empty($reply_to_message_id)) {
    //         $postFields['reply_to_message_id'] = $reply_to_message_id;
    //     }
        
    //     curl_setopt($request, CURLOPT_POST, true);
    //     curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 0);
    //     curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
    //     curl_setopt($request, CURLOPT_POSTFIELDS, $postFields);
    //     curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($request, CURLOPT_TIMEOUT, 60);
    //     curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 15);
    
    //     $response = curl_exec($request);
    //     $http_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
    
    //     if (curl_errno($request)) {
    //         error_log("Curl error in baleapp_eitaayarbot_copy -> sendFileToEitaa\n\nchat_id: $chat_id\n\nResponse: " . curl_error($request));
            
    //         curl_close($request);
    //         return false;
            
    //     } elseif ($http_code !== 200) {
    //         error_log("HTTP $http_code in baleapp_eitaayarbot_copy -> sendFileToEitaa \n\nchat_id: $chat_id\n\nResponse: $response");
            
    //         curl_close($request);
    //         return false;
    //     }
    
    //     curl_close($request);
    //     return $response;
    // }

    // function sendFileToEitaa($fileUrl, $caption = "", $eitatoken, $eita_channel = "", $reply_to_message_id = null) {
    //     $token = "$eitatoken";
    //     $chat_id = $eita_channel;
    //     $caption = "$caption";
    //     $title = 'send file by api';
    //     $url = "https://eitaayar.ir/api/$token/sendFile";
    
    
    //     $tmpFile = sys_get_temp_dir() . "/" . basename($fileUrl);
    //     $fileContent = @file_get_contents($fileUrl);
    //     if ($fileContent === false) {
    //         error_log("Failed to download file from $fileUrl");
    //         return false;
    //     }
    //     file_put_contents($tmpFile, $fileContent);
    
    //     $postFields = [
    //         'file' => new CURLFile($tmpFile),
    //         'chat_id' => $chat_id,
    //         'title' => $title,
    //         'caption' => $caption,
    //     ];
    //     if (!empty($reply_to_message_id)) {
    //         $postFields['reply_to_message_id'] = $reply_to_message_id;
    //     }
    
    //     $maxTries = 3;
    //     $tries = 0;
    //     $response = false;
    
    //     do {
    //         $request = curl_init($url);
    //         curl_setopt($request, CURLOPT_POST, true);
    //         curl_setopt($request, CURLOPT_POSTFIELDS, $postFields);
    //         curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    //         curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 0);
    //         curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
    //         curl_setopt($request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    //         curl_setopt($request, CURLOPT_TIMEOUT, 120);
    //         curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 15);
    
    //         $response = curl_exec($request);
    //         $errno = curl_errno($request);
    //         $http_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
    
    //         if ($errno) {
    //             error_log("Curl error ($errno) in sendFileToEitaa [try $tries]: " . curl_error($request));
    //         } elseif ($http_code !== 200) {
    //             error_log("HTTP $http_code in sendFileToEitaa [try $tries]: $response");
    //         } else {
    //             $decoded = json_decode($response, true);
    //             if ($decoded && isset($decoded['ok']) && $decoded['ok'] === true) {
    //                 curl_close($request);
    //                 unlink($tmpFile); // پاک کردن فایل موقت
    //                 return $response;
    //             } else {
    //                 error_log("Invalid response in sendFileToEitaa [try $tries]: $response");
    //             }
    //         }
    
    //         curl_close($request);
    //         $tries++;
    
    //         // 2️⃣ retry روی connection reset (56) و timeout (28)
    //         if (in_array($errno, [56, 28])) {
    //             sleep(2);
    //         }
    
    //     } while (in_array($errno, [56, 28]) && $tries < $maxTries);
    
    //     // پاک کردن فایل موقت در صورت fail
    //     if (file_exists($tmpFile)) {
    //         unlink($tmpFile);
    //     }
    
    //     return false;
    // }

    function sendFileToEitaa($fileUrl, $caption = "", $eitatoken, $eita_channel = "", $reply_to_message_id = null) {
        
        $token = $eitatoken;
        $chat_id = $eita_channel;
        $title = 'send file by api';
        $url = "https://eitaayar.ir/api/$token/sendFile";
    
        $postFieldsBase = [
            'chat_id' => $chat_id,
            'title'   => $title,
            'caption' => $caption,
        ];
        if (!empty($reply_to_message_id)) {
            $postFieldsBase['reply_to_message_id'] = $reply_to_message_id;
        }
    
        // ✅ مرحله اول: تلاش برای ارسال مستقیم فایل (بدون دانلود)
        $directSuccess = false;
        $response = null;
        $http_code = null;
    
        if (file_exists($fileUrl)) {
            $postFields = $postFieldsBase;
            $postFields['file'] = new CURLFile($fileUrl);
    
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_POSTFIELDS => $postFields,
                CURLOPT_TIMEOUT => 12,  //60
            ]);
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $errno = curl_errno($ch);
            curl_close($ch);
    
            if (!$errno && $http_code === 200) {
                $decoded = json_decode($response, true);
                if ($decoded && isset($decoded['ok']) && $decoded['ok'] === true) {
                    $directSuccess = true;
                }
            }
        }
    
        // ✅ اگر ارسال مستقیم موفق نشد، روش دوم (دانلود و آپلود موقت)
        if (!$directSuccess) {
            $tmpFile = sys_get_temp_dir() . "/" . uniqid("eitaa_") . '.' . pathinfo($fileUrl, PATHINFO_EXTENSION);
            $fileData = @file_get_contents($fileUrl);
            if ($fileData === false) {
                error_log("❌ Failed to download file from: $fileUrl");
                return false;
            }
            file_put_contents($tmpFile, $fileData);
    
            $postFields = $postFieldsBase;
            $postFields['file'] = new CURLFile($tmpFile);
    
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_POSTFIELDS => $postFields,
                CURLOPT_TIMEOUT => 12, //90
            ]);
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $errno = curl_errno($ch);
            curl_close($ch);
    
            // حذف فایل موقت بعد از آپلود
            if (file_exists($tmpFile)) {
                unlink($tmpFile);
            }
    
            if ($errno) {
                error_log("❌ Curl error in sendFileToEitaa (download mode): " . curl_error($ch));
                return false;
            }
    
            if ($http_code !== 200 || empty($response)) {
                error_log("❌ HTTP $http_code in sendFileToEitaa (download mode): $response");
                return false;
            }
        }
    
        // ✅ بررسی پاسخ نهایی
        $decoded = json_decode($response, true);
        if (isset($decoded['ok']) && $decoded['ok'] === true) {
            return $decoded;
        } else {
            error_log("⚠️ Eitaa API invalid response: " . $response);
            return false;
        }
    }
    
    function sendToEitaa($text, $eitatoken, $eita_channel = "", $reply_to_message_id = null) {
        $token = "$eitatoken";
        $chat_id = $eita_channel;
        $text = "$text";
        $url = "https://eitaayar.ir/api/$token/sendMessage";
    
        $postFields = [
            'chat_id' => $chat_id,
            'text' => $text,
        ];
        if (!empty($reply_to_message_id)) {
            $postFields['reply_to_message_id'] = $reply_to_message_id;
        }
    
        $sendRequest = function($postFields, $use_http_build = false) use ($url) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    
            if ($use_http_build) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
    
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err = curl_errno($ch) ? curl_error($ch) : null;
            curl_close($ch);
    
            return [
                'response' => $response,
                'http_code' => $http_code,
                'error' => $err
            ];
        };
    
        // 🔹 روش ۱: ارسال با http_build_query (x-www-form-urlencoded)
        $r1 = $sendRequest($postFields, true);
    
        $sent = false;
        $needs_retry = false;
    
        // 🎯 تحلیل پاسخ اول
        if ($r1['error']) {
            error_log("Eitaa send error (method1 curl): " . $r1['error']);
            $needs_retry = true;
        } elseif ($r1['http_code'] !== 200) {
            error_log("Eitaa send error (method1 HTTP {$r1['http_code']}): " . $r1['response']);
            $needs_retry = true;
        } else {
            $json = json_decode($r1['response'], true);
            if (isset($json['ok']) && $json['ok'] === true) {
                $sent = true;
            } elseif (isset($json['result']['message_id'])) {
                // اگر پیام واقعاً ارسال شده باشه ولی ok=false برگرده
                $sent = true;
                error_log("Eitaa warning (method1 ok=false but message_id found): " . $r1['response']);
            } else {
                // پاسخ غیرمنتظره (نه ok=true و نه message_id)
                error_log("Eitaa warning (method1 unknown response): " . $r1['response']);
                $needs_retry = false; // چون احتمال ارسال وجود داره، دوباره نمی‌فرستیم
            }
        }
    
        // 🔹 روش ۲: فقط اگر ارتباط واقعی قطع بود
        if (!$sent && $needs_retry) {
            $r2 = $sendRequest($postFields, false);
    
            if ($r2['error']) {
                error_log("Eitaa send error (method2 curl): " . $r2['error']);
                return false;
            } elseif ($r2['http_code'] !== 200) {
                error_log("Eitaa send error (method2 HTTP {$r2['http_code']}): " . $r2['response']);
                return false;
            } else {
                $json2 = json_decode($r2['response'], true);
                if (isset($json2['ok']) && $json2['ok'] === true) {
                    return $r2['response'];
                } else {
                    error_log("Eitaa warning (method2 unknown response): " . $r2['response']);
                    return false;
                }
            }
        }
    
        return $r1['response'];
    }
    /*
    function sendToEitaa($text, $eitatoken, $eita_channel = "", $reply_to_message_id = null) {
        $token = "$eitatoken";
        $chat_id = $eita_channel;
        $text = "$text";
        $title = 'send file by api';
    
        sleep(1); // اختیاری
    
        $request = curl_init("https://eitaayar.ir/api/$token/sendMessage");
        
        $postFields = [
            'chat_id' => $chat_id,
            'title' => $title,
            'text' => $text,
        ];
    
        // اگه ریپلای وجود داشت اضافه کن
        if (!empty($reply_to_message_id)) {
            $postFields['reply_to_message_id'] = $reply_to_message_id;
        }
        
        curl_setopt($request, CURLOPT_POST, true);
        curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($request, CURLOPT_POSTFIELDS, http_build_query($postFields));            //curl_setopt($request, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    
        $response = curl_exec($request);
        $http_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
    
        if (curl_errno($request)) {
            error_log("Curl error in baleapp_eitaayarbot_copy -> sendToEitaa\n\nchat_id: $chat_id\n\nResponse: " . curl_error($request));
            
            curl_close($request);
            return false;
            
        } elseif ($http_code !== 200) {
            error_log("HTTP $http_code in baleapp_eitaayarbot_copy -> sendToEitaa \n\nchat_id: $chat_id\n\nResponse: $response");
            
            curl_close($request);
            return false;
            
        }
    
        curl_close($request);
        return $response;
    }
    */
    //-------------------------------------
    
    function testBaleChannel($token, $channel_id) {
        
        $url = "https://tapi.bale.ai/bot$token/sendMessage";
    
        $post_fields = [
            'chat_id' => $channel_id,
            'text' => '✅' // پیام تست
        ];
    
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:application/x-www-form-urlencoded"]);
        curl_setopt($ch, CURLOPT_URL, $url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        
        $response = curl_exec($ch);
    
        // $reply = $response;
        // $url = $GLOBALS['bot_url']."/sendMessage";
        // $post_params = [    
        //                     'chat_id' => "698468282" ,
        //                     'text' => $reply ,
                            
        //                 ];
        // send_reply($url, $post_params);
        
        if (curl_errno($ch)) {
            curl_close($ch);
            return false; // خطای اتصال
        }
    
        curl_close($ch);
        $res = json_decode($response, true);
        return isset($res['ok']) && $res['ok'] === true;
    }
    
    
    function sendToBale($text, $bale_token, $bale_chat_id = "", $reply_to_message_id = null) {
        $token = "$bale_token";
        $chat_id = $bale_chat_id;
        $text = "$text";
    
        sleep(1); // اختیاری
    
        $url = "https://tapi.bale.ai/bot$token/sendMessage";
        
        $postFields = [
            'chat_id' => $chat_id,
            'text' => $text,
        ];
    
        // اگه ریپلای وجود داشت اضافه کن
        if (!empty($reply_to_message_id)) {
            $postFields['reply_to_message_id'] = $reply_to_message_id;
        }
        
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:application/x-www-form-urlencoded"]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
    
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        if (curl_errno($ch)) {
            error_log("Curl error in baleapp_eitaayarbot_copy -> sendToBale\n\nchat_id: $chat_id\n\nResponse: " . curl_error($ch));
            
            // $reply = "Curl error in baleapp_eitaayarbot_copy -> sendToBale\n\nchat_id: $chat_id\n\nResponse: " . curl_error($ch);
            // $url = $GLOBALS['bot_url']."/sendMessage";
            // $post_params = [    
            //                     'chat_id' => "698468282" ,
            //                     'text' => $reply,
            //                 ];
            // send_reply($url, $post_params);
            
        } elseif ($http_code !== 200) {
            error_log("HTTP $http_code in baleapp_eitaayarbot_copy -> sendToBale \n\nchat_id: $chat_id\n\nResponse: $response");
            
            // $reply = "HTTP $http_code in baleapp_eitaayarbot_copy -> sendToBale \n\nchat_id: $chat_id\n\nResponse: $response";
            // $url = $GLOBALS['bot_url']."/sendMessage";
            // $post_params = [    
            //                     'chat_id' => "698468282" ,
            //                     'text' => $reply,
            //                 ];
            // send_reply($url, $post_params);
        }
    
        curl_close($ch);
        return $response;
    }
    
    function sendFileToBale($fileUrl, $caption = "", $file_type, $bale_token, $bale_chat_id = "", $reply_to_message_id = null) {
        $token = "$bale_token";
        $chat_id = $bale_chat_id;
        $caption = "$caption";
    
        sleep(1); // اختیاری
    
        $url = "https://tapi.bale.ai/bot$token/send$file_type";
        
        $postFields = [
            'chat_id' => $chat_id,
            'caption' => $caption,
            "$file_type" => new CURLFile($fileUrl),
        ];
    
        // اگه ریپلای وجود داشت اضافه کن
        if (!empty($reply_to_message_id)) {
            $postFields['reply_to_message_id'] = $reply_to_message_id;
        }
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        if (curl_errno($ch)) {
            error_log("Curl error in baleapp_eitaayarbot_copy -> sendFileToBale\n\nchat_id: $chat_id\n\nResponse: " . curl_error($ch) . "\n\n\n");
            
            // $reply = "Curl error in baleapp_eitaayarbot_copy -> sendFileToBale\n\nchat_id: $chat_id\n\nResponse: " . curl_error($ch);
            // $url = $GLOBALS['bot_url']."/sendMessage";
            // $post_params = [    
            //                     'chat_id' => "698468282" ,
            //                     'text' => $reply,
            //                 ];
            // send_reply($url, $post_params);
            
        } elseif ($http_code !== 200) {
            error_log("HTTP $http_code in baleapp_eitaayarbot_copy -> sendFileToBale \n\nchat_id: $chat_id\n\nResponse: $response\n\n\n");
            
            // $reply = "HTTP $http_code in baleapp_eitaayarbot_copy -> sendFileToBale \n\nchat_id: $chat_id\n\nResponse: $response";
            // $url = $GLOBALS['bot_url']."/sendMessage";
            // $post_params = [    
            //                     'chat_id' => "698468282" ,
            //                     'text' => $reply,
            //                 ];
            // send_reply($url, $post_params);
            
        }
    
        curl_close($ch);
        return $response;
    }
    
    function editBaleMessage($bale_token, $bale_chat_id, $bale_msg_id, $new_text = null, $new_caption = null) {
        
        if (!empty($new_text)) {
            
            $url = "https://tapi.bale.ai/bot{$bale_token}/editMessageText";
            $postFields = [
                'chat_id'    => $bale_chat_id,
                'message_id' => $bale_msg_id,
                'text'       => $new_text,
            ];
        } elseif (!empty($new_caption)) {
            
            $url = "https://tapi.bale.ai/bot{$bale_token}/editMessageCaption";
            $postFields = [
                'chat_id'    => $bale_chat_id,
                'message_id' => $bale_msg_id,
                'caption'    => $new_caption,
            ];
        } else {
            return false; // چیزی برای ادیت وجود نداره
        }
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:application/x-www-form-urlencoded"]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            error_log("Curl error in editBaleMessage -> " . curl_error($ch));
        } elseif ($http_code !== 200) {
            error_log("HTTP $http_code in editBaleMessage -> Response: $response");
        }
        
        curl_close($ch);
        return $response;
    }
    
    //-------------------------------------
    
    function testRubikaChannel($token, $rubika_channel) {
        
        $url = "https://botapi.rubika.ir/v3/$token/sendMessage";
    
        $data = [
            "text"    => "✅",
            "chat_id" => $rubika_channel
        ];
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $response  = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        if (curl_errno($ch)) {
            curl_close($ch);
            return false; // خطای اتصال
        }
    
        curl_close($ch);
    
        $res = json_decode($response, true);
        
        return ($http_code === 200 && isset($res['status']) && $res['status'] === 'OK');
    }
    
    // function sendToRubika($text, $token, $rubika_channel, $reply_to_message_id = null) {
        
    //     $url = "https://botapi.rubika.ir/v3/$token/sendMessage";
    
    //     $postFields = [
    //         "text"    => $text,
    //         "chat_id" => $rubika_channel,
    //     ];
    
    //     if (!empty($reply_to_message_id)) {
    //         $postFields['reply_to_message_id'] = $reply_to_message_id;
    //     }
    
    //     $ch = curl_init($url);
    //     curl_setopt_array($ch, [
    //         CURLOPT_POST => true,
    //         CURLOPT_SSL_VERIFYHOST => 0,
    //         CURLOPT_SSL_VERIFYPEER => false,
    //         CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
    //         CURLOPT_POSTFIELDS => json_encode($postFields),
    //         CURLOPT_RETURNTRANSFER => true,
    //     ]);
    
    //     $response = curl_exec($ch);
    //     $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    //     if (curl_errno($ch)) {
    //         error_log("Curl error in sendToRubika: " . curl_error($ch));
    //         curl_close($ch);
    //         return ['status' => 'ERROR', 'message' => 'Curl error'];
    //     }
    
    //     curl_close($ch);
    
    //     if ($http_code !== 200 || empty($response)) {
    //         error_log("HTTP $http_code in sendToRubika. Response: $response");
    //         return ['status' => 'ERROR', 'message' => "HTTP $http_code"];
    //     }
    
    //     $res = json_decode($response, true);
    
    //     // بررسی پاسخ معتبر
    //     if (isset($res['status']) && $res['status'] === 'OK' && isset($res['data']['message_id'])) {
    //         return [
    //             'status' => 'OK',
    //             'message_id' => $res['data']['message_id'],
    //             'response' => $res,
    //         ];
    //     } else {
    //         error_log("Rubika API error. Response: " . $response);
    //         return [
    //             'status' => 'ERROR',
    //             'message' => 'Rubika API error',
    //             'response' => $res,
    //         ];
    //     }
    // }
    
    function sendToRubika($text, $token, $rubika_channel, $reply_to_message_id = null) {
        
        $url = "https://botapi.rubika.ir/v3/$token/sendMessage";
    
        $postFields = [
            "text"    => $text,
            "chat_id" => $rubika_channel,
        ];
    
        if (!empty($reply_to_message_id)) {
            $postFields['reply_to_message_id'] = $reply_to_message_id;
        }
    
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
            CURLOPT_POSTFIELDS => json_encode($postFields),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10, // جلوگیری از گیر کردن درخواست
        ]);
    
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $timestamp = date('Y-m-d H:i:s');
    
        // بررسی خطای CURL
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            error_log("[$timestamp] ❌ Curl error: $error");
            return [
                'status' => 'ERROR',
                'message' => "Curl error: $error",
            ];
        }
    
        curl_close($ch);
    
        // بررسی وضعیت HTTP
        if ($http_code !== 200 || empty($response)) {
            error_log("[$timestamp] ❌ HTTP Error $http_code. Response: $response");
            return [
                'status' => 'ERROR',
                'message' => "HTTP error $http_code",
            ];
        }
    
        $res = json_decode($response, true);
    
        // بررسی پاسخ Rubika API
        if (isset($res['status']) && $res['status'] === 'OK' && isset($res['data']['message_id'])) {
            error_log("[$timestamp] ✅ Message sent successfully (ID: " . $res['data']['message_id'] . ")");
            return [
                'status' => 'OK',
                'message_id' => $res['data']['message_id'],
                'response' => $res,
            ];
        } else {
            error_log("[$timestamp] ❌ Rubika API error. Response: " . $response);
            return [
                'status' => 'ERROR',
                'message' => 'Rubika API error',
                'response' => $res,
            ];
        }
    }
    
    function sendFileToRubika($fileUrl, $caption, $file_type, $rubikaToken, $rubika_channel, $reply_to_message_id = null) {
        
        $baseUrl = "https://botapi.rubika.ir/v3/$rubikaToken/";
        $tempFile = sys_get_temp_dir() . '/' . uniqid('rubika_') . '.' . pathinfo($fileUrl, PATHINFO_EXTENSION);
    
        try {
            // --- دانلود فایل ---
            $fileData = @file_get_contents($fileUrl);
            if ($fileData === false) {
                throw new Exception("❌ Failed to download file from: $fileUrl");
            }
            file_put_contents($tempFile, $fileData);
            // error_log("[Rubika] File downloaded: $tempFile");
    
            // --- نگاشت نوع فایل ---
            $map = [
                'photo' => 'Image',
                'image' => 'Image',
                'picture' => 'Image',
                'video' => 'Video',
                'voice' => 'Voice',
                'audio' => 'Voice',
                'file' => 'File',
                'document' => 'File',
                'gif' => 'Gif',
            ];
            $file_type = strtolower(trim($file_type));
            $file_type = $map[$file_type] ?? 'File';
    
            // --- درخواست upload_url ---
            $requestPayload = json_encode(['type' => $file_type]);
            $ch = curl_init($baseUrl . "requestSendFile");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                CURLOPT_POSTFIELDS => $requestPayload,
                CURLOPT_TIMEOUT => 15,
            ]);
            $uploadResponse = curl_exec($ch);
            if (curl_errno($ch)) throw new Exception("❌ CURL error on requestSendFile: " . curl_error($ch));
            curl_close($ch);
    
            $uploadData = json_decode($uploadResponse, true);
            if (empty($uploadData['data']['upload_url'])) {
                throw new Exception("❌ Invalid upload_url: " . $uploadResponse);
            }
            $uploadUrl = $uploadData['data']['upload_url'];
            // error_log("[Rubika] Upload URL obtained: $uploadUrl");
    
            // --- آپلود فایل ---
            $mime = mime_content_type($tempFile);
            $curlFile = new CURLFile($tempFile, $mime, basename($tempFile));
            $ch = curl_init($uploadUrl);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => ['file' => $curlFile],
                CURLOPT_CONNECTTIMEOUT => 15,
                CURLOPT_TIMEOUT => 120,
            ]);
            $uploadResult = curl_exec($ch);
            if (curl_errno($ch)) throw new Exception("❌ CURL error on file upload: " . curl_error($ch));
            curl_close($ch);
    
            $uploadResultData = json_decode($uploadResult, true);
            if (empty($uploadResultData['data']['file_id'])) {
                throw new Exception("❌ Upload failed: " . $uploadResult);
            }
            $fileId = $uploadResultData['data']['file_id'];
            // error_log("[Rubika] File uploaded successfully: $fileId");
    
            // --- ارسال فایل به روبیکا ---
            $payload = [
                'chat_id' => $rubika_channel,
                'file_id' => $fileId,
                'text' => $caption,
            ];
            if (!empty($reply_to_message_id)) $payload['reply_to_message_id'] = $reply_to_message_id;
    
            $ch = curl_init($baseUrl . "sendFile");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_TIMEOUT => 60,
            ]);
            $sendResponse = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (curl_errno($ch)) throw new Exception("❌ CURL error on sendFile: " . curl_error($ch));
            curl_close($ch);
    
            if ($httpCode !== 200) {
                throw new Exception("❌ Send failed with HTTP $httpCode: " . $sendResponse);
            }
    
            // error_log("[Rubika] File sent successfully to chat: $rubika_channel");
    
            return [
                'status' => 'OK',
                'response' => json_decode($sendResponse, true),
                'file_id' => $fileId,
            ];
    
        } catch (Exception $e) {
            error_log("[Rubika sendFile Error] " . $e->getMessage());
            return [
                'status' => 'ERROR',
                'message' => $e->getMessage(),
            ];
        } finally {
            if (file_exists($tempFile)) unlink($tempFile);
        }
    }

    
    // function sendFileToRubika($fileUrl, $caption_to_send_Rubika, $file_type, $rubikaToken, $rubika_channel, $reply_to_rubika = null) {
    //     sleep(0.2);
    //     $baseUrl = "https://botapi.rubika.ir/v3/$rubikaToken/";
    //     $tempFile = sys_get_temp_dir() . '/' . uniqid('rubika_') . '.' . pathinfo($fileUrl, PATHINFO_EXTENSION);
    
    //     try {
    //         // --- 1️⃣ دانلود فایل ---
    //         $fileData = @file_get_contents($fileUrl);
    //         if ($fileData === false) {
    //             throw new Exception("❌ Failed to download file from: $fileUrl");
    //         }
    //         file_put_contents($tempFile, $fileData);
    //         error_log("[Rubika] File downloaded: $tempFile");
    
    //         // --- تعیین نوع فایل ---
    //         $map = [
    //             'photo' => 'Image',
    //             'image' => 'Image',
    //             'picture' => 'Image',
    //             'video' => 'Video',
    //             'voice' => 'Voice',
    //             'audio' => 'Voice',
    //             'file' => 'File',
    //             'document' => 'File',
    //             'gif' => 'Gif',
    //         ];
    //         $file_type = strtolower(trim($file_type));
    //         $file_type = $map[$file_type] ?? 'File';
    
    //         // --- 2️⃣ درخواست آپلود ---
    //         $requestPayload = json_encode(['type' => $file_type]);
    //         $ch = curl_init($baseUrl . "requestSendFile");
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    //             CURLOPT_POSTFIELDS => $requestPayload,
    //             CURLOPT_TIMEOUT => 15,
    //         ]);
    //         $uploadResponse = curl_exec($ch);
    //         if (curl_errno($ch)) {
    //             throw new Exception("❌ CURL error on requestSendFile: " . curl_error($ch));
    //         }
    //         curl_close($ch);
    
    //         $uploadData = json_decode($uploadResponse, true);
    //         if (empty($uploadData['data']['upload_url'])) {
    //             throw new Exception("❌ Invalid upload_url: " . $uploadResponse);
    //         }
    //         $uploadUrl = $uploadData['data']['upload_url'];
    //         error_log("[Rubika] Upload URL obtained: $uploadUrl");
    
    //         // --- بررسی دسترسی به upload_url ---
    //         $ch = curl_init($uploadUrl);
    //         curl_setopt($ch, CURLOPT_NOBODY, true);
    //         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    //         curl_exec($ch);
    //         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    //         $err = curl_errno($ch) ? curl_error($ch) : null;
    //         curl_close($ch);
    
    //         if ($err || $httpCode >= 400) {
    //             throw new Exception("🚫 Upload server unreachable (probably blocked outside Iran). HTTP: $httpCode CURL: $err");
    //         }
    
    //         // --- 3️⃣ آپلود فایل ---
    //         $mime = mime_content_type($tempFile);
    //         $curlFile = new CURLFile($tempFile, $mime, basename($tempFile));
    //         $ch = curl_init($uploadUrl);
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_POSTFIELDS => ['file' => $curlFile],
    //             CURLOPT_CONNECTTIMEOUT => 15,
    //             CURLOPT_TIMEOUT => 120,
    //         ]);
    //         $uploadResult = curl_exec($ch);
    //         if (curl_errno($ch)) {
    //             throw new Exception("❌ CURL error on file upload: " . curl_error($ch));
    //         }
    //         curl_close($ch);
    
    //         $uploadResultData = json_decode($uploadResult, true);
    //         if (empty($uploadResultData['data']['file_id'])) {
    //             throw new Exception("❌ Upload failed: " . $uploadResult);
    //         }
    //         $fileId = $uploadResultData['data']['file_id'];
    //         error_log("[Rubika] File uploaded successfully: $fileId");
    
    //         // --- 4️⃣ ارسال فایل به روبیکا ---
    //         $payload = [
    //             'chat_id' => $rubika_channel,
    //             'file_id' => $fileId,
    //             'type' => $file_type,
    //             'text' => $caption_to_send_Rubika,
    //         ];
    //         if (!empty($reply_to_rubika)) {
    //             $payload['reply_to_message_id'] = $reply_to_rubika;
    //         }
    
    //         $ch = curl_init($baseUrl . "sendFile");
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    //             CURLOPT_POSTFIELDS => json_encode($payload),
    //             CURLOPT_TIMEOUT => 60,
    //         ]);
    //         $sendResponse = curl_exec($ch);
    //         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    //         if (curl_errno($ch)) {
    //             throw new Exception("❌ CURL error on sendFile: " . curl_error($ch));
    //         }
    //         curl_close($ch);
    
    //         if ($httpCode !== 200) {
    //             throw new Exception("❌ Send failed with HTTP $httpCode: " . $sendResponse);
    //         }
    
    //         error_log("[Rubika] File sent successfully to chat: $rubika_channel");
    
    //         return [
    //             'status' => 'OK',
    //             'response' => json_decode($sendResponse, true),
    //             'file_id' => $fileId,
    //         ];
    
    //     } catch (Exception $e) {
    //         error_log("[Rubika sendFile Error] " . $e->getMessage());
    //         return [
    //             'status' => 'ERROR',
    //             'message' => $e->getMessage(),
    //         ];
    //     } finally {
    //         // حذف فایل موقت
    //         if (file_exists($tempFile)) {
    //             unlink($tempFile);
    //         }
    //     }
    // }
    
    // function sendFileToRubika($fileUrl, $caption_to_send_Rubika, $file_type, $rubikaToken, $rubika_channel, $reply_to_rubika = null) {
        
    //     sleep(0.2);
        
    //     $baseUrl = "https://botapi.rubika.ir/v3/$rubikaToken/";
    //     $tempFile = sys_get_temp_dir() . '/' . uniqid('rubika_') . '.' . pathinfo($fileUrl, PATHINFO_EXTENSION);
    
    //     try {
    //         // --- 1️⃣ دانلود فایل ---
    //         $fileData = @file_get_contents($fileUrl);
    //         if ($fileData === false) {
    //             throw new Exception("❌ Failed to download file from: $fileUrl");
    //         }
    //         file_put_contents($tempFile, $fileData);
            
    //         $map = [
    //             'photo' => 'Image',
    //             'image' => 'Image',
    //             'picture' => 'Image',
    //             'video' => 'Video',
    //             'voice' => 'Voice',
    //             'audio' => 'Voice',
    //             'file' => 'File',
    //             'document' => 'File',
    //             'gif' => 'Gif',
    //         ];
    //         $file_type = strtolower(trim($file_type));
    //         $file_type = $map[$file_type] ?? 'File';

            
    //         // --- 2️⃣ درخواست آپلود ---
    //         $requestPayload = json_encode(['type' => $file_type]);
    //         $ch = curl_init($baseUrl . "requestSendFile");
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    //             CURLOPT_POSTFIELDS => $requestPayload,
    //         ]);
    //         $uploadResponse = curl_exec($ch);
    //         curl_close($ch);
    
    //         $uploadData = json_decode($uploadResponse, true);
    //         if (empty($uploadData['data']['upload_url'])) {
    //             throw new Exception("❌ Invalid upload_url: " . $uploadResponse);
    //         }
    
    //         $uploadUrl = $uploadData['data']['upload_url'];
    
    //         // --- 3️⃣ آپلود فایل ---
    //         $mime = mime_content_type($tempFile);
    //         $curlFile = new CURLFile($tempFile, $mime, basename($tempFile));
    
    //         $ch = curl_init($uploadUrl);
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_POSTFIELDS => ['file' => $curlFile],
    //             CURLOPT_TIMEOUT => 60,
    //         ]);
    //         $uploadResult = curl_exec($ch);
    //         curl_close($ch);
    
    //         $uploadResultData = json_decode($uploadResult, true);
    //         if (empty($uploadResultData['data']['file_id'])) {
    //             throw new Exception("❌ Upload failed: " . $uploadResult);
    //         }
    
    //         $fileId = $uploadResultData['data']['file_id'];
    
    //         // --- 4️⃣ ارسال فایل به روبیکا ---
    //         $payload = [
    //             'chat_id' => $rubika_channel,
    //             'file_id' => $fileId,
    //             'type' => $file_type,
    //             'text' => $caption_to_send_Rubika,
    //         ];
    //         if (!empty($reply_to_rubika)) {
    //             $payload['reply_to_message_id'] = $reply_to_rubika;
    //         }
    
    //         $ch = curl_init($baseUrl . "sendFile");
    //         curl_setopt_array($ch, [
    //             CURLOPT_RETURNTRANSFER => true,
    //             CURLOPT_POST => true,
    //             CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    //             CURLOPT_POSTFIELDS => json_encode($payload),
    //             CURLOPT_TIMEOUT => 60,
    //         ]);
    //         $sendResponse = curl_exec($ch);
    //         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    //         curl_close($ch);
    
    //         if ($httpCode !== 200) {
    //             throw new Exception("❌ Send failed with HTTP $httpCode: " . $sendResponse);
    //         }
    
    //         return [
    //             'status' => 'OK',
    //             'response' => json_decode($sendResponse, true),
    //             'file_id' => $fileId,
    //         ];
    
    //     } catch (Exception $e) {
    //         error_log("[Rubika sendFile Error] " . $e->getMessage());
    //         return [
    //             'status' => 'ERROR',
    //             'message' => $e->getMessage(),
    //         ];
    //     } finally {
    //         // --- 5️⃣ حذف فایل موقت ---
    //         if (file_exists($tempFile)) {
    //             unlink($tempFile);
    //         }
    //     }
    // }
    
    function editRubikaMessage($rubika_token, $rubika_chat_id, $rubika_msg_id, $new_text = null, $new_caption = null) {
        
        if (!empty($new_text) or !empty($new_caption)) {
            
            $url = "https://botapi.rubika.ir/v3/{$rubika_token}/editMessageText";
            $postFields = [
                'chat_id'    => $rubika_chat_id,
                'message_id' => $rubika_msg_id,
                'text'       => $new_text.$new_caption,
            ];
        } else {
            return [
                'status'  => 'ERROR',
                'message' => '❌ No text or caption provided for editing.'
            ];
        }
    
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_POSTFIELDS => json_encode($postFields),
        ]);
    
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
    
        // مدیریت خطاها
        if ($curl_error) {
            error_log("[Rubika Edit Error] CURL: $curl_error");
            return ['status' => 'ERROR', 'message' => $curl_error];
        }
    
        if ($http_code !== 200) {
            error_log("[Rubika Edit Error] HTTP $http_code Response: $response");
            return ['status' => 'ERROR', 'message' => "HTTP $http_code", 'response' => $response];
        }
    
        $decoded = json_decode($response, true);
        if (!$decoded) {
            return ['status' => 'ERROR', 'message' => '❌ Invalid JSON response', 'response' => $response];
        }
    
        return ['status' => 'OK', 'response' => $decoded];
    }
    
    //-------------------------------------
    
    function callScriptNonBlocking($url) {
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100); // فوراً برگشت
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 100);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: close']);
        
        curl_exec($ch);
        
        curl_close($ch);
    }
    
    function handleTelegramAlbum($media_group_id, $file_type, $file_id, $caption, $bale_chat_id, $channel_id = 0, $telegram_msg_id = null, $caption_to_send_rubika = null, $rubika_channel = null) {
    if (!$media_group_id || !$file_id) return;    // || !$bale_chat_id

    $connection = connect_to_db();

    // بررسی وجود رکورد آلبوم
    $res = $connection->query("SELECT * FROM eitaayarbot_album_messages 
                               WHERE media_group_id='$media_group_id' 
                                 AND bale_chat_id='$bale_chat_id' 
                               LIMIT 1");

    if ($row = $res->fetch_assoc()) {
        // 🔄 بروزرسانی رکورد موجود (افزودن file_id جدید)
        $new_files   = trim($row['files'] . ',' . $file_id, ',');
        $new_types   = trim($row['types'] . ',' . $file_type, ',');
        $new_caption = $row['caption'] ?: $caption;

        $connection->query("UPDATE eitaayarbot_album_messages 
                            SET files='$new_files',
                                types='$new_types',
                                caption='$new_caption',
                                updated_at=NOW(),
                                status='half'
                            WHERE id={$row['id']}");
        error_log("🟢 Updated album #{$row['id']} with new file_id: $file_id");
    } else {
        // 🆕 ساخت رکورد جدید (اولین فایل از آلبوم)
        $connection->query("INSERT INTO eitaayarbot_album_messages 
            (channel_id, telegram_msg_id, media_group_id, bale_chat_id, files, types, caption, rubika_caption, rubika_channel, status, created_at, updated_at)
            VALUES (
                '$channel_id',
                '$telegram_msg_id',
                '$media_group_id',
                '$bale_chat_id',
                '$file_id',
                '$file_type',
                '$caption',
                '$caption_to_send_rubika',
                '$rubika_channel',
                'half',
                NOW(),
                NOW()
            )");
        error_log("✅ Created new album record for group $media_group_id with file_id: $file_id");
    }

    // ⏱ ذخیره تایمر
    $albumDir = __DIR__ . "/albums";
    if (!is_dir($albumDir)) mkdir($albumDir, 0777, true);

    $timerFile = "{$albumDir}/album_timer_{$media_group_id}_{$bale_chat_id}.json";
    file_put_contents($timerFile, json_encode(['last_update' => time()]));

    // 🚀 اجرای async اسکریپت وضعیت آلبوم
    callScriptNonBlocking("https://bot.kanap.ir/baleapp_eitaayarbot/Album_status.php?media_group_id={$media_group_id}&bale_chat_id={$bale_chat_id}");
}

    
    // function handleTelegramAlbum($media_group_id, $file_type, $file_id, $caption, $bale_chat_id, $channel_id = 0, $telegram_msg_id = null) {
        
    //     if (!$media_group_id || !$file_id || !$bale_chat_id) return;
    
    //     $telegramToken = "33636894:nSY5zfmwCzwokO6WzDevMEu1hK5r4Gp9cnM";
    //     $connection = connect_to_db();
    
    //     // دریافت فایل از تلگرام
    //     $info = json_decode(file_get_contents("https://tapi.bale.ai/bot{$telegramToken}/getFile?file_id=$file_id"), true);
    //     if (!$info['ok']) return;
    
    //     $filePath = $info['result']['file_path'];
    //     $downloadUrl = "https://tapi.bale.ai/file/bot{$telegramToken}/$filePath";
    
    //     // مسیر ذخیره‌سازی فایل
    //     $albumDir = __DIR__ . "/albums/{$media_group_id}";
    //     if (!is_dir($albumDir)) mkdir($albumDir, 0777, true);
    
    //     $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        
    //     $uniqueId = bin2hex(random_bytes(8)); // 16 کاراکتر hex
        
    //     // $localPath = $albumDir . "/" . $uniqueId . "_{$file_type}." . $ext;
    //     $localPath = $albumDir . "/" . $uniqueId . "." . $ext;
    
    //     file_put_contents($localPath, file_get_contents($downloadUrl));
    
    //     // بررسی وجود رکورد آلبوم
    //     $res = $connection->query("SELECT * FROM eitaayarbot_album_messages 
    //                               WHERE media_group_id='$media_group_id' 
    //                                  AND bale_chat_id='$bale_chat_id' 
    //                               LIMIT 1");
    
    //     if ($row = $res->fetch_assoc()) {
    //         // بروزرسانی رکورد موجود
    //         $new_files = trim($row['files'] . ',' . $localPath, ',');
    //         $new_types = trim($row['types'] . ',' . $file_type, ',');
    //         $new_caption = $row['caption'] ?: $caption;
    
    //         $connection->query("UPDATE eitaayarbot_album_messages 
    //                             SET files='$new_files',
    //                                 types='$new_types',
    //                                 caption='$new_caption',
    //                                 updated_at=NOW(),
    //                                 status='half'
    //                             WHERE id={$row['id']}");
    //     } else {
    //         // ساخت رکورد جدید
    //         $connection->query("INSERT INTO eitaayarbot_album_messages 
    //             (channel_id, telegram_msg_id, media_group_id, bale_chat_id, files, types, caption, status, created_at, updated_at)
    //             VALUES (
    //                 '$channel_id',
    //                 '$telegram_msg_id',
    //                 '$media_group_id',
    //                 '$bale_chat_id',
    //                 '$localPath',
    //                 '$file_type',
    //                 '$caption',
    //                 'half',
    //                 NOW(),
    //                 NOW()
    //             )");
    //     }
    
    //     // ذخیره تایمر
    //     $timerFile = __DIR__ . "/albums/album_timer_{$media_group_id}_{$bale_chat_id}.json";
    //     file_put_contents($timerFile, json_encode(['last_update' => time()]));
    
    //     // صدا زدن فایل وضعیت
    //     callScriptNonBlocking("https://bot.kanap.ir/baleapp_eitaayarbot/Album_status.php?media_group_id={$media_group_id}&bale_chat_id={$bale_chat_id}");
    
    //     // $connection->close();
    // }
    
    //-------------------------------------
    
    function saveMessageMap($telegram_msg_id, $platform_msg_id, $platform, $channel_chat_id) {
        
        // mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        
        $connection = connect_to_db();
        if (!$connection) {
            throw new Exception("Failed to connect to DB");
        }
    
        $map = [
            'bale'   => 'bale_msg_id',
            'eitaa'  => 'eitaa_msg_id',
            'rubika' => 'rubika_msg_id',
        ];
    
        if (!isset($map[$platform])) {
            // $connection->close();
            throw new Exception("پلتفرم نامعتبر: $platform");
        }
        $column = $map[$platform]; // امن چون از لیست مجاز گرفته شده
    
        try {
            
            $selectSql = "SELECT id FROM eitaayarbot_message_map WHERE telegram_id = ? AND telegram_msg_id = ? LIMIT 1";
            $stmt = $connection->prepare($selectSql);
            if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
            $stmt->bind_param('ss', $channel_chat_id, $telegram_msg_id);
            $stmt->execute();
            $stmt->store_result();
    
            if ($stmt->num_rows > 0) {
                
                $stmt->bind_result($existingId);
                $stmt->fetch();
                $stmt->close();
    
                $updateSql = "UPDATE eitaayarbot_message_map SET {$column} = ? WHERE telegram_id = ? AND telegram_msg_id = ?";
                $ustmt = $connection->prepare($updateSql);
                if (!$ustmt) throw new Exception("Prepare failed: " . $connection->error);
                $ustmt->bind_param('sss', $platform_msg_id, $channel_chat_id, $telegram_msg_id);
                $ustmt->execute();
                $ustmt->close();
            } else {
                
                $stmt->close();
    
                $insertSql = "
                    INSERT INTO eitaayarbot_message_map
                        (telegram_id, telegram_msg_id, bale_msg_id, eitaa_msg_id, rubika_msg_id)
                    VALUES (?, ?, ?, ?, ?)
                ";
                $istmt = $connection->prepare($insertSql);
                if (!$istmt) throw new Exception("Prepare failed: " . $connection->error);
    
                $baleVal = ($platform === 'bale') ? $platform_msg_id : null;
                $eitaaVal = ($platform === 'eitaa') ? $platform_msg_id : null;
                $rubikaVal = ($platform === 'rubika') ? $platform_msg_id : null;
    
                $istmt->bind_param(
                    'sssss',
                    $channel_chat_id,
                    $telegram_msg_id,
                    $baleVal,
                    $eitaaVal,
                    $rubikaVal
                );
                $istmt->execute();
                $istmt->close();
            }
    
            $cleanupSql = "
                DELETE FROM eitaayarbot_message_map
                WHERE telegram_id = ?
                AND id NOT IN (
                    SELECT id FROM (
                        SELECT id FROM eitaayarbot_message_map
                        WHERE telegram_id = ?
                        ORDER BY id DESC
                        LIMIT 200
                    ) AS t
                )
            ";
            $cstmt = $connection->prepare($cleanupSql);
            if (!$cstmt) throw new Exception("Prepare failed: " . $connection->error);
            $cstmt->bind_param('ss', $channel_chat_id, $channel_chat_id);
            $cstmt->execute();
            $cstmt->close();
    
        }
        catch (Exception $e) {
            error_log("❌ DB Error in saveMessageMap(): " . $e->getMessage());
            throw $e;
        }
    
        return true;
    }
    
    //-------------------------------------
    
    function detect_text_received_and_reply() {
        
        $text           = $GLOBALS['text'];
        $chat_id        = $GLOBALS['chat_id'];
        $message_id     = $GLOBALS['message_id'];
        $thread_id      = $GLOBALS['thread_id'];
        $username       = $GLOBALS['username'];
        $first_name     = $GLOBALS['first_name'];
        $last_name      = $GLOBALS['last_name'];
        $from_id        = $GLOBALS['from_id'];
        $text_replied   = $GLOBALS['text_replied'];
        $update_array   = $GLOBALS['update_array'];
        
        // $caption    = $update_array["message"]["caption"];
        // $file_id    = $update_array["message"]["photo"]["2"]["file_id"];
        // $file_id1   = $update_array["message"]["video"]["file_id"];
        // $file_id2   = $update_array["message"]["document"]["file_id"];
        
        
        //------------------------ Keys
        
        $keyt   = '🟦 وضعیت کانال تلگرام 🟦';
        $keye   = '🟧 وضعیت کانال ایتا 🟧';
        $keyb   = '🟩 وضعیت کانال بله 🟩';
        $keyr   = '⬜ وضعیت کانال روبیکا ⬜';
        $abzar_key = "🛠 ابزارها";
        $re_key  = "🔂 جایگزینی لینک/کلمه";
        $adkey  = "➕ افزودن جایگزینی لینک/کلمه";
        $urlkey = "🔗 نمایش لینک‌ها در ایتا";
        $offkey = "🚫 خاموش";
        $onkey  = "✅ روشن";
        $rekey_e = "ایتا";
        $rekey_b = "بله";
        $rekey_r = "روبیکا";
        $key3   = 'وضعیت توکن ایتایار';
        $skey   = "وضعیت اشتراک";
        $key4   = "1️⃣ اشتراک یک ماهه – ۹۹,۰۰۰ تومان";
        $key5   = "3️⃣ اشتراک سه ماهه – ۲۷۰,۰۰۰ تومان";
        $key6   = "6️⃣ اشتراک شش ماهه – ۵۰۰,۰۰۰ تومان";
        $key7   = "✅ اشتراک یک ساله – ۹۹۰,۰۰۰ تومان";
        $bkey   = '🔙 بازگشت';
        
        
        $startkeys = [
                        'keyboard'          => [
                                                    [$keyt , $keye] ,
                                                    [$keyb , $keyr] ,
                                                    [$skey , $key3] ,
                                                    [$abzar_key],
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $startMarkup = json_encode($startkeys);
        
        
        $abzarkeys = [
                        'keyboard'          => [
                                                    [$re_key] ,
                                                    [$urlkey] ,
                                                    [$bkey] ,
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $abzarMarkup = json_encode($abzarkeys);
        
        
        $replacekeys = [
                        'keyboard'          => [
                                                    [$adkey] ,
                                                    [$bkey] ,
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $replaceMarkup = json_encode($replacekeys);
        
        
        $offonurlkeys = [
                        'keyboard'          => [
                                                    [$offkey] ,
                                                    [$onkey] ,
                                                    [$bkey] ,
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $offonurlMarkup = json_encode($offonurlkeys);
        
        
        $adreplacekeys = [
                        'keyboard'          => [
                                                    [$rekey_r , $rekey_b , $rekey_e] ,
                                                    [$bkey] ,
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $adreplaceMarkup = json_encode($adreplacekeys);
        
        
        $subskeys = [
                        'keyboard'          => [
                                                    [$key4] ,
                                                    [$key5] ,
                                                    [$key6] ,
                                                    [$key7] ,
                                                    [$bkey],
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $subsMarkup = json_encode($subskeys);
        
        
        $backkey = [
                        'keyboard'          => [
                                                    [$bkey] ,
                                                ] ,
                        'resize_keyboard'   => true ,
                        'one_time_keyboard' => false ,
                    ];
        $backMarkup = json_encode($backkey);
        
        //------------------------
        
        $merchant_id = "b2eea57e-5a57-435b-b72c-331164f250a8";   //"b2eea57e-5a57-435b-b72c-331164f250a8";
        $callback_url = "https://senderbot.ir/payments/payment_result.php";
        $currency = "IRT";
        
        $amount_1month = 990000;
        $amount_3month = 2700000;
        $amount_6month = 5000000;
        $amount_12month = 9900000;
        
        //------------------------

        $connection = connect_to_db();
            
            $res = $connection->query("SELECT * FROM baleapp_eitaayarbot WHERE telegram_id = $chat_id");
            
            if ($res && $res->num_rows > 0) {
                
                $row = $res->fetch_assoc();
                
                $eitatoken          = $row['eitatoken'];
                $eita_channel       = $row['eita_channel'];
                $rubika_channel     = $row['rubika_channel'];
                $bale_channel       = $row['bale_channel'];
                $channel_id         = $row['channel_id'];
                $tg_channel_title   = $row['tg_channel_title'];
                $end_subscription   = $row['end_subscription'];
                $waiting_db         = $row['waiting'];
                
                $rules = json_decode($row['replace_rules'], true);
                
            }
            
            switch ($text) {
                
                case "/start":
                    
                    
                    // $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot");
                    
                    // $connection -> query("UPDATE baleapp_eitaayarbot SET first_name = '$first_name', username = '$username' WHERE telegram_id = $chat_id");
                    // $connection -> query("INSERT INTO baleapp_eitaayarbot (telegram_id,first_name,username) VALUES ('$chat_id','$first_name','$username')");
                    
                    
                    //------------------------- add to group inline keyboard
                    
                    // $inline_keyboard_add = [
                        
                    //                         [
                    //                             [ 'text' => "Connect to channel" , 'url' => "http://t.me/baleapp_eitaayarbot?startchannel=addtochannel" ],
                    //                         ],
                    //                         [
                    //                             [ 'text' => "Send to friend" , 'switch_inline_query' => "\n\n👆 This is a bot with which you can have the price of any cryptocurrency, NFT price, USDT price, fear and greed index and many other features at the same time.😎\n\n\n t.me/AiPricesBot" ],
                    //                         ],
                    // ];
                    
                    // $inline_kb_options_add = [
                    //                             'inline_keyboard' => $inline_keyboard_add
                    // ];
                    
                    // //-------------------------
                    
                    // $json_kb_add = json_encode($inline_kb_options_add);
                    
                    $reply  = "<b>سلام $first_name عزیز 🫂</b>";
                    $reply .= "\n\nاین ربات مطالب کانال تلگرامتون رو به طور خودکار می‌فرسته به کانال ایتا و بله و روبیکا";
                    $reply .= "\n\n\nبرای اتصال کانال تلگرام به پیام‌رسان‌های داخلی ابتدا ربات را با دکمه زیر در کانال مورد نظر مدیر کنید"; 
                    $reply .= "\n\n\nبه شما هدیه استفاده رایگان یک هفته‌ای ربات تعلق گرفته که از حالا شروع شده. در این مدت میتوانید ربات را به خوبی تست کنید";
                    $reply .= "\n\n\n<a href='http://t.me/baleapp_eitaayarbot?startchannel=addtochannel'>افزودن ربات به ادمین‌های کانال</a>";
                    $reply .= "\n\n\nدر صورت نیاز به راهنمایی، می‌توانید به <a href='http://t.me/Yar36'>پشتیبانی</a> پیام دهید تا شما را راهنمایی کنیم.";
                    $reply .= "\n\n‌";
                    
                    $Markup = "$startMarkup";
                    
                break;
                
                case "$keyt":
                    
                    $reply  = "👋 جناب <b>$first_name</b> عزیز\n\n";
                    $reply .= "🔗 برای اتصال <b>کانال تلگرام</b> به <b>کانال ایتا</b>:\n\n";
                    $reply .= "✅ ربات را با لینک زیر یا به صورت دستی به‌عنوان <b>ادمین</b> اضافه کنید.\n\n";
                    $reply .= "🔄 یا برای تغییر کانال تلگرام، ابتدا ربات را از کانال کنونی حذف و سپس در کانال جدید ادمین کنید.\n";
                    $reply .= "\n👉 <a href='http://t.me/baleapp_eitaayarbot?startchannel=addtochannel'>افزودن ربات به ادمین‌های کانال</a>\n";
                    
                    if(isset($channel_id)) {
                        
                        $reply .= "\n🌱 کانال تلگرام متصل شده : <code>$tg_channel_title</code>";
                        
                    } else {
                        
                        $reply .= "\n\nشما هنوز کانال تلگرام خود را متصل نکرده اید";
                        
                    }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$keye":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 2 WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌸 جناب <b>$first_name</b> عزیز\n\n";
                    $reply .= "🌿 برای <b>تغییر دادن کانال ایتا</b> یا <b>اتصال مجدد</b>، لطفاً به راهنمای زیر توجه کنید:\n\n";
                    $reply .= "🍃 اگر کانال شما <b>عمومی</b> است، آیدی آن را با علامت @ ارسال کنید.\n\n";
                    $reply .= "🌼 نمونه: \n<code>@MyEitaaChannel</code>\n\n\n";
                    $reply .= "🍀 اگر کانال شما <b>خصوصی</b> است، باید <b>آیدی عددی</b> آن را از سایت <b>ایتایار</b>، قسمت <b>کانال‌ها</b> دریافت کرده و ارسال نمایید.\n";
                    
                    if(!empty($eita_channel)) {
                        
                        $reply .= "\n\n🌱 کانال ایتای کنونی شما: \n<code>$eita_channel</code>";
                        
                    } else {
                        
                        $reply .= "\n\n🚫 <i>هنوز هیچ کانال ایتا به حساب شما متصل نشده است.</i>\n";
                        $reply .= "\n\nدر صورت نیاز به راهنمایی، می‌توانید به <a href='http://t.me/Yar36'>پشتیبانی</a> پیام دهید تا شما را راهنمایی کنیم.";
                        $reply .= "\n\n‌";
                        
                    }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$keyb":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 3 WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌸 جناب <b>$first_name</b> عزیز\n\n";
                    $reply .= "🌿 برای <b>تغییر کانال بله</b> یا <b>اتصال مجدد</b>، کافیست مراحل زیر را انجام دهید:\n\n";
                    $reply .= "👉 <a href='https://ble.ir/senderobot?start=$chat_id'><b>روی این لینک بزنید و ربات @senderobot را استارت کنید</b></a> ✅\n\n";
                    $reply .= "🚀 سپس ربات را به کانال خود اضافه نمایید.\n\n";
                    $reply .= "🌱 بعد از افزودن، اتصال به صورت خودکار انجام می‌شود. 🌸\n";
                    
                    if(!empty($bale_channel)) {
                        
                        $reply .= "\n\n🌱 کانال بله‌ی کنونی شما: \n<code>$bale_channel</code>";
                        
                    } else {
                        
                        $reply .= "\n\n🚫 <i>هنوز هیچ کانال بله‌ای به حساب شما متصل نشده است.</i>\n";
                        $reply .= "\n\nدر صورت نیاز به راهنمایی، می‌توانید به <a href='http://t.me/Yar36'>پشتیبانی</a> پیام دهید تا شما را راهنمایی کنیم.";
                        $reply .= "\n\n‌";
                        
                    }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$keyr":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 4 WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌸 جناب <b>$first_name</b> عزیز\n\n";
                    
                    $reply .= "🌿 برای <b>تغییر دادن کانال روبیکا</b> یا <b>اتصال مجدد</b>، لطفاً مراحل زیر را با دقت انجام دهید:\n\n";
                    
                    $reply .= "📌 ابتدا ربات <code>senderobot</code> را در کانال روبیکای خود به عنوان ادمین اضافه نمایید.\n\n";
                    
                    $reply .= "🔹 سپس آیدی عمومی کانال را با علامت <b>@</b> در همینجا ارسال کنید.\n\n";
                    $reply .= "مثال:\n<code>@MyRubikaChannel</code>\n\n";
                    
                    $reply .= "⚠️ توجه داشته باشید:\n";
                    $reply .= "✅ اتصال تنها برای <b>کانال‌های عمومی</b> روبیکا فعال است.\n";
                    
                    if(!empty($rubika_channel)) {
                        
                        $reply .= "\n\n🌱 کانال روبیکای کنونی شما: \n<code>$rubika_channel</code>";
                        
                    } else {
                        
                        $reply .= "\n\n🚫 <i>هنوز هیچ کانال روبیکایی به حساب شما متصل نشده است.</i>\n";
                        $reply .= "\n\nدر صورت نیاز به راهنمایی، می‌توانید به <a href='http://t.me/Yar36'>پشتیبانی</a> پیام دهید تا شما را راهنمایی کنیم.";
                        $reply .= "\n\n‌";
                        
                    }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$abzar_key":
                    
                    $reply  = "🌱 <b>به بخش «ابزارها» خوش آمدی! 🌸</b>";
                    $reply .= "\n\nاینجا می‌تونی 🌿 ویژگی‌ها و تنظیمات اضافی ربات رو مدیریت کنی:";
                    $reply .= "\n\n🔗 <b>حالت نمایش لینک‌ها</b>";
                    $reply .= "\n• نمایش لینک بعد از پاراگراف";
                    $reply .= "\n• مخفی کردن کامل لینک‌ها";
                    $reply .= "\n\n✍️ <b>جایگزینی متن</b>";
                    $reply .= "\n• تغییر یا حذف واژه‌های مشخص در پیام‌ها";
                    $reply .= "\n\n🌺 امکانات جدید هم به زودی اضافه می‌شن!";
                    $reply .= "\n\nبا خیال راحت تنظیمات دلخواهت رو انتخاب کن و از تجربه بهتر با ربات لذت ببر 🌼";
                    
                    $Markup = "$abzarMarkup";
                    
                break;
                
                case "$re_key":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'remove_replace' WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌸 <b>مدیریت جایگزینی کلمه/لینک</b> 🌸\n\n";
                    $reply .= "با این قابلیت می‌تونی مشخص کنی که بعضی متن‌ها یا لینک‌ها، وقتی از تلگرام ارسال میشن، در پلتفرم‌های دیگه (ایتا / بله / روبیکا) به شکل دلخواهت جایگزین بشن. ✨\n\n";
                    $reply .= "📌 <b>راهنما:</b>\n";
                    $reply .= "1️⃣ پلتفرم موردنظر رو انتخاب کن.\n";
                    $reply .= "2️⃣ متن یا لینک داخل تلگرام رو بفرست.\n";
                    $reply .= "3️⃣ متن یا لینک جایگزین برای پلتفرم رو وارد کن.\n\n";
                    $reply .= "✅ بعد از این مراحل، قانون جایگزینی ذخیره میشه.\n\n\n";
                    
                    $reply .= "📋 <b>موارد جایگزینی ثبت‌شده:</b>\n";
                    $reply .= "--------------------------------\n";
                    
                    foreach (['eitaa','bale','rubika'] as $platform) {
                        
                        if (!empty($rules[$platform])) {
                            
                            foreach ($rules[$platform] as $rule) {
                                
                                if (($rule['status'] ?? '') !== 'active') continue;
                                
                                $source  = htmlspecialchars($rule['source']);
                                $target  = htmlspecialchars($rule['target']);
                                $rule_id = $rule['id'];
                                
                                $remove_url = "https://t.me/baleapp_eitaayarbot?start=rem_$rule_id&id=$chat_id";
                                
                                $reply .= "🔹 <b>$platform</b>\n";
                                $reply .= "<blockquote>ـ   <code>$source</code> : <code>$target</code></blockquote>\n";
                                $reply .= "<a href='$remove_url'>❌ حذف</a>\n";
                                $reply .= "----------------------------------\n";
                            }
                        }
                    }
                    
                    $Markup = "$replaceMarkup";
                    
                break;
                
                case "$adkey":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'waiting_platform' WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌿 <b>مرحله ۱: انتخاب پلتفرم</b>\n\n";
                    $reply .= "لطفاً مشخص کن این قانون جایگزینی برای کدوم پلتفرم باشه:\n\n";
                    $reply .= "➖ ایتــا\n";
                    $reply .= "➖ بــله\n";
                    $reply .= "➖ روبیکــا\n\n";
                    $reply .= "بعد از انتخاب، برو مرحله بعدی 🌸";
                    
                    $Markup = "$adreplaceMarkup";
                    
                break;
                
                case "$urlkey":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'url_on_eitaa' WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌿 <b>نحوه نمایش لینک‌ها در ایتا</b> 🌿";
                    $reply .= "\n\nاز آنجایی که ایتا از فرمت‌های متنی (مثل بولد، لینک‌دار کردن کلمات و...) پشتیبانی نمی‌کند، این بخش در ربات <b>ایتایار بات</b> در نظر گرفته شده تا انتخاب با شما باشد:";
                    $reply .= "\n\n🚫 <b>حالت خاموش</b>";
                    $reply .= "\nکلماتی که لینک دارند، بدون لینک ارسال می‌شوند.";
                    $reply .= "\n\n✅ <b>حالت روشن</b>";
                    $reply .= "\nاگر کلمه‌ای در یک پاراگراف لینک‌دار باشد، لینک آن بلافاصله بعد از همان پاراگراف نمایش داده می‌شود.";
                    $reply .= "\n\n🌸 با این امکان می‌توانید تجربه بهتری از انتقال مطالب به ایتا داشته باشید.";
                    
                    $Markup = "$offonurlMarkup";
                    
                break;
                
                case "$offkey":
                    
                    if($waiting_db === 'url_on_eitaa') {
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 , url_mode_in_eitaa = 0 WHERE telegram_id = $chat_id");
                        
                        $reply  = "🚫 <b>حالت خاموش فعال شد</b>";
                        $reply .= "\n\nاز این پس کلماتی که لینک‌دار هستند، <b>بدون لینک</b> به ایتا ارسال می‌شوند.";
                        $reply .= "\n\nاین حالت برای زمانی مناسب است که نمی‌خواهید لینک‌ها در متن پیام‌هایتان نمایش داده شوند.";
                        $reply .= "\n\n🌸 هر زمان که بخواهید می‌توانید حالت روشن را فعال کنید.";
                        
                        $Markup = "$startMarkup";
                    }
                    
                break;
                
                case "$onkey":
                    
                    if($waiting_db === 'url_on_eitaa') {
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 , url_mode_in_eitaa = 1 WHERE telegram_id = $chat_id");
                        
                        $reply  = "✅ <b>حالت روشن فعال شد</b>";
                        $reply .= "\n\nاز این پس اگر کلمه‌ای در یک پاراگراف لینک داشته باشد، <b>لینک آن بلافاصله بعد از همان پاراگراف</b> نمایش داده خواهد شد.";
                        $reply .= "\n\nاین ویژگی به خاطر ضعف ایتا در پشتیبانی از متن‌های لینک‌دار طراحی شده است تا همچنان بتوانید لینک‌ها را به مخاطبان خود منتقل کنید.";
                        $reply .= "\n\n🌿 هر زمان که بخواهید می‌توانید حالت خاموش را فعال کنید.";
                        
                        $Markup = "$startMarkup";
                    }
                    
                break;
                
                case "$rekey_e":
                    
                    if($waiting_db === 'waiting_platform') {
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_eitaa_org' WHERE telegram_id = $chat_id");
                        
                        startDraft($chat_id, "eitaa");
                        
                        $reply  = "🌸 <b>مرحله ۲: متن یا لینک در تلگرام</b>\n\n";
                        $reply .= "متن یا لینکی رو بفرست که داخل کانال تلگرام وجود داره و می‌خوای در مقصد تغییر کنه.\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>@TELEGRAM</code>\n\n";
                        $reply .= "⬅️ بعد از ارسال، برو مرحله بعدی 🌿";
                        
                        $Markup = "$backMarkup";
                    }
                    
                break;
                
                case "$rekey_b":
                    
                    if($waiting_db === 'waiting_platform') {
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_bale_org' WHERE telegram_id = $chat_id");
                        
                        startDraft($chat_id, "bale");
                        
                        $reply  = "🌸 <b>مرحله ۲: متن یا لینک در تلگرام</b>\n\n";
                        $reply .= "متن یا لینکی رو بفرست که داخل کانال تلگرام وجود داره و می‌خوای در مقصد تغییر کنه.\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>@TELEGRAM</code>\n\n";
                        $reply .= "⬅️ بعد از ارسال، برو مرحله بعدی 🌿";
                        
                        $Markup = "$backMarkup";
                    }
                    
                break;
                
                case "$rekey_r":
                    
                    if($waiting_db === 'waiting_platform') {
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_rubika_org' WHERE telegram_id = $chat_id");
                        
                        startDraft($chat_id, "rubika");
                        
                        $reply  = "🌸 <b>مرحله ۲: متن یا لینک در تلگرام</b>\n\n";
                        $reply .= "متن یا لینکی رو بفرست که داخل کانال تلگرام وجود داره و می‌خوای در مقصد تغییر کنه.\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>@TELEGRAM</code>\n\n";
                        $reply .= "⬅️ بعد از ارسال، برو مرحله بعدی 🌿";
                        
                        $Markup = "$backMarkup";
                    }
                    
                break;
                
                case "$key3":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 1 WHERE telegram_id = $chat_id");
                    
                    $reply  = "🔑 اگر قصد <b>تغییر توکن ایتایار</b> را دارید، لطفاً <b>توکن جدید</b> را ارسال کنید.\n\n";
                    $reply .= "⬅️ در غیر اینصورت با دکمه <b>بازگشت</b> به منوی اصلی برگردید تا از انجام اشتباه جلوگیری شود.\n";
                    
                    if(isset($eitatoken)) {
                        
                        $reply .= "\n\n🌿 <b>توکن کنونی شما:</b>\n<code>$eitatoken</code>";
                        
                    } else {
                        
                        $reply .= "\n\n🚫 <i>هنوز هیچ توکن ایتایار به حساب شما متصل نشده است.</i>\n";
                        $reply .= "\n🌸 برای اتصال، ابتدا وارد سایت <b>ایتایار</b> شوید و از بخش <b>API</b>، <b>توکن API</b> را کپی و در اینجا ارسال کنید.";
                        $reply .= "\n\n\nاگر سوال یا نیاز به راهنمایی داشتید، لطفاً به <a href='http://t.me/Yar36'>پشتیبانی پرداخت</a> پیام دهید تا با کمال میل شما را راهنمایی کنیم.";
                        $reply .= "\n\n‌";
                        
                    }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$skey":
                    
                    $daysLeft = max(0, ceil((strtotime($end_subscription) - time()) / 86400));
                    
                    $reply  = "‌\n⏳ <b>مدت باقی‌مانده اشتراک شما:</b> <b>$daysLeft</b> روز\n\n";
                    $reply .= "ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ\n";
                    
                    $reply .= "🌟 <b>بسته‌های اشتراک ربات ایتایار</b>\n\n\n";
                    // $reply .= "ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ\n\n";
                    
                    $reply .= "🟢 <b>پلن ماهانه:</b> ۹۹ هزار تومان\n\n";
                    $reply .= "🔵 <b>پلن سه‌ماهه:</b> ۲۷۰ هزار تومان\n(💰 صرفه‌جویی ۲۷ هزار تومان)\n\n";
                    $reply .= "🟡 <b>پلن شش‌ماهه:</b> ۵۰۰ هزار تومان\n(💰 صرفه‌جویی ۹۴ هزار تومان)\n\n";
                    $reply .= "🟣 <b>پلن یک‌ساله:</b> ۹۰۰ هزار تومان\n(💰 صرفه‌جویی ۲۸۸ هزار تومان)\n";
                    
                    $reply .= "ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ\n\n";
                    $reply .= "📩 برای خرید و فعال‌سازی اشتراک، لطفاً به <a href=\"https://t.me/YAR36\"><b>پشتیبانی پرداخت</b></a> پیام دهید.\n‌";
                    
                    
                    // $subsinlinekey = [
                    //     'inline_keyboard' => [
                    //         [
                    //             ['text' => '🟢 اشتراک ماهانه - ۹۹ هزار', 'url' => "$zarinpal_monthly"],
                    //             ['text' => '🔵 اشتراک سه ماهه - ۲۷۰ هزار', 'url' => "$zarinpal_three_month"],
                    //             ['text' => '🟣 اشتراک یک ساله - ۹۰۰ هزار', 'url' => "$zarinpal_yearly"]
                    //         ]
                    //     ]
                    // ];
                    // $subskey_inline = json_encode($subsinlinekey);
                    
                    $Markup = "$subsMarkup";
                    
                break;
                
                case "$key4":
                    
                    $amount = "$amount_1month";
                    $desc = "1";
                    
                    $paymentLink = createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chat_id, $desc);
                    
                    $reply  = "🌟 شما اشتراک <b>یک ماهه</b> را انتخاب کرده‌اید.\n\n";
                    
                    $reply .= "💳 پرداخت آنلاین از طریق زرین‌پال: <a href='" . $paymentLink . "'>لینک پرداخت</a>\n\n";
                    $reply .= "🏦 برای پرداخت کارت‌به‌کارت، به <a href='https://t.me/Yar36'><b>پشتیبانی پرداخت</b></a> پیام دهید.";
                    
                    // if ($paymentLink) {
                    //     $reply .= "\n\n💳 <b>لینک پرداخت اشتراک:</b> ";
                    //     $reply .= "<a href='" . $paymentLink . "'>🔗 پرداخت آنلاین</a>";
                    //     $reply .= "\n\n⚠️ در صورتی که صفحه پرداخت باز نشد، لطفاً VPN یا فیلترشکن خود را خاموش کنید و دوباره تلاش کنید.";
                    // } else {
                    //     $reply .= "\n\nدریافت لینک پرداخت ناموفق بود. لطفا به پشتیبانی پرداخت پیام دهید.";
                    // }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$key5":
                    
                    $amount = "$amount_3month";
                    $desc = "3";
                    
                    $paymentLink = createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chat_id, $desc);
                    
                    $reply  = "🌟 شما اشتراک <b>سه ماهه</b> را انتخاب کرده‌اید.\n\n";
                    
                    $reply .= "💳 پرداخت آنلاین از طریق زرین‌پال: <a href='" . $paymentLink . "'>لینک پرداخت</a>\n\n";
                    $reply .= "🏦 برای پرداخت کارت‌به‌کارت، به <a href='https://t.me/Yar36'><b>پشتیبانی پرداخت</b></a> پیام دهید.";
                    
                    // if ($paymentLink) {
                    //     $reply .= "\n\n💳 <b>لینک پرداخت اشتراک:</b> ";
                    //     $reply .= "<a href='" . $paymentLink . "'>🔗 پرداخت آنلاین</a>";
                    //     $reply .= "\n\n⚠️ در صورتی که صفحه پرداخت باز نشد، لطفاً VPN یا فیلترشکن خود را خاموش کنید و دوباره تلاش کنید.";
                    // } else {
                    //     $reply .= "\n\nدریافت لینک پرداخت ناموفق بود. لطفا به پشتیبانی پرداخت پیام دهید.";
                    // }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$key6":
                    
                    $amount = "$amount_6month";
                    $desc = "6";
                    
                    $paymentLink = createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chat_id, $desc);
                    
                    $reply  = "🌟 شما اشتراک <b>شش ماهه</b> را انتخاب کرده‌اید.\n\n";
                    
                    $reply .= "💳 پرداخت آنلاین از طریق زرین‌پال: <a href='" . $paymentLink . "'>لینک پرداخت</a>\n\n";
                    $reply .= "🏦 برای پرداخت کارت‌به‌کارت، به <a href='https://t.me/Yar36'><b>پشتیبانی پرداخت</b></a> پیام دهید.";
                    
                    // if ($paymentLink) {
                    //     $reply .= "\n\n💳 <b>لینک پرداخت اشتراک:</b> ";
                    //     $reply .= "<a href='" . $paymentLink . "'>🔗 پرداخت آنلاین</a>";
                    //     $reply .= "\n\n⚠️ در صورتی که صفحه پرداخت باز نشد، لطفاً VPN یا فیلترشکن خود را خاموش کنید و دوباره تلاش کنید.";
                    // } else {
                    //     $reply .= "\n\nدریافت لینک پرداخت ناموفق بود. لطفا به پشتیبانی پرداخت پیام دهید.";
                    // }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$key7":
                    
                    $amount = "$amount_12month";
                    $desc = "12";
                    
                    $paymentLink = createZarinpalPaymentLink($merchant_id, $callback_url, $amount, $chat_id, $desc);
                    
                    $reply  = "🌟 شما اشتراک <b>یک ساله</b> را انتخاب کرده‌اید.\n\n";
                    
                    $reply .= "💳 پرداخت آنلاین از طریق زرین‌پال: <a href='" . $paymentLink . "'>لینک پرداخت</a>\n\n";
                    $reply .= "🏦 برای پرداخت کارت‌به‌کارت، به <a href='https://t.me/Yar36'><b>پشتیبانی پرداخت</b></a> پیام دهید.";
                    
                    // if ($paymentLink) {
                    //     $reply .= "\n\n💳 <b>لینک پرداخت اشتراک:</b> ";
                    //     $reply .= "<a href='" . $paymentLink . "'>🔗 پرداخت آنلاین</a>";
                    //     $reply .= "\n\n⚠️ در صورتی که صفحه پرداخت باز نشد، لطفاً VPN یا فیلترشکن خود را خاموش کنید و دوباره تلاش کنید.";
                    // } else {
                    //     $reply .= "\n\nدریافت لینک پرداخت ناموفق بود. لطفا به پشتیبانی پرداخت پیام دهید.";
                    // }
                    
                    $Markup = "$backMarkup";
                    
                break;
                
                case "$bkey":
                    
                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 WHERE telegram_id = $chat_id");
                    
                    $reply  = "🌸 شما به <b>منوی اصلی</b> برگشتید.\n\n";
                    $reply .= "🌿 برای تغییر هر مورد، لطفاً آن را از منوی زیر انتخاب کنید.";
                    
                    $Markup = "$startMarkup";
                    
                break;
                
                
                default:
                    
                    if ($waiting_db == 1) {
                        
                        $token = $text;
                        
                        $tokenresult = testEitaToken($token);
                        if ($tokenresult['ok']) {
                            
                            $eitaayarusername = $tokenresult['username'];
                            
                            
                            if (!empty($eita_channel)) {
                                
                                $connection->query("UPDATE baleapp_eitaayarbot SET eitatoken = '$token', eitaayarusername = '$eitaayarusername', waiting = 0 WHERE telegram_id = $from_id");
                                
                                $reply = "✅ توکن ایتایار شما با موفقیت ثبت شد.";
                                $reply.= "\n\nToken:\n\n$token";
                                
                            } else {
                                
                                $connection->query("UPDATE baleapp_eitaayarbot SET eitatoken = '$token', eitaayarusername = '$eitaayarusername', waiting = 2 WHERE telegram_id = $from_id");
                                
                                $reply  = "✅ توکن ایتایار با موفقیت ثبت شد.\n\n";
                                $reply .= "📌 حالا لطفاً آیدی کانال ایتا را ارسال نمایید:\n\n";
                                $reply .= "📝 ابتدا کانال مورد نظرتان را در بخش <b>کانال‌ها</b> در سامانه <a href='https://eitaayar.ir'>ایتایار</a> ثبت کنید.\n\n";
                                $reply .= "🔹سپس اگر کانال شما عمومی است، آیدی آن را ارسال نمایید.\n\n";
                                $reply .= "مثال:\n<code>@MyEitaaChannel</code>\n\n";
                                $reply .= "🔹 اگر کانال <b>خصوصی</b> است، آیدی عددی آن را از لیست کانال‌ها در سایت ایتایار کپی کرده و اینجا ارسال نمایید.\n";
                                // $reply .= "🪪 <b>توکن ثبت‌شده شما:</b>\n\n<code>$token</code>";
                                $reply .= "\n\n‌";
                            }
                            
                            $Markup = "$startMarkup";
                            
                        } else {
                            $reply = "❌ توکن نامعتبر است.\n\nلطفاً توکن را بررسی و مجدداً ارسال کنید.\n\nتوکن‌های ایتایار معمولاً با bot... آغاز می‌شوند.";
                            
                            $Markup = "$backMarkup";
                            
                        }
                        
                    } elseif ($waiting_db == 2) {
                        // دریافت آیدی عددی کانال ایتا
                        $eita_channel = $text;
                        
                        if(isset($channel_id)) {
                            
                            if (testEitaChannel($eitatoken, $eita_channel)) {
                                
                                $connection->query("UPDATE baleapp_eitaayarbot SET eita_channel = '$eita_channel', waiting = 0 WHERE telegram_id = $from_id");
                                
                                $reply = "کانال با موفقیت ثبت شد. از حالا به بعد هر پیامی به کانال تلگرام ارسال کنید همانند ان در ایتا ارسال میشود";
                                
                                $Markup = "$startMarkup";
                                
                            } else {
                                
                                if(isset($eitatoken)) {
                                    
                                    $reply = "خطایی در ثبت کانال وجود دارد\n\nموارد زیر را بررسی کنید:\n\n1. ربات @sender در کانال ایتا ادمین باشد\n2.کانال را در ایتایار در بخش کانال ها اضافه کرده باشید\n3.آیدی عددی را درست ارسال کرده باشید";
                                    
                                    $Markup = "$backMarkup";
                                    
                                } else {
                                    
                                    $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 1 WHERE telegram_id = $from_id");
                                    
                                    $reply  = "⚠️ شما هنوز توکن ایتایار را از سایت <a href='https://eitaayar.ir'>ایتایار</a> دریافت نکرده و ارسال نکرده‌اید.\n\n";
                                    $reply .= "📌 لطفاً قبل از ثبت کانال، ابتدا توکن ایتایار را از سایت دریافت کرده و برای ما ارسال نمایید.\n";
                                    $reply .= "📝 سپس آیدی کانال ایتا را بفرستید.\n\n";
                                    $reply .= "⏳ منتظر ارسال توکن ایتایار شما هستیم.";
                                    
                                    $Markup = "$backMarkup";
                                }
                                
                            }
                        } else {
                            
                            $reply  = "⚠️ لطفاً قبل از هر اقدامی، ابتدا کانال تلگرام خود را به سامانه اضافه نمایید.\n\n";
                            $reply .= "🔗 برای اتصال <b>کانال تلگرام</b> به <b>کانال ایتا</b>:\n\n";
                            $reply .= "✅ ربات را با لینک زیر یا به صورت دستی به‌عنوان <b>ادمین</b> اضافه کنید.\n\n";
                            $reply .= "🔄 یا برای تغییر کانال تلگرام، ابتدا ربات را از کانال کنونی حذف و سپس در کانال جدید ادمین کنید.\n";
                            $reply .= "\n👉 <a href='http://t.me/baleapp_eitaayarbot?startchannel=addtochannel'>افزودن ربات به ادمین‌های کانال</a>\n";
                            
                            $Markup = "$backMarkup";
                        }
                        
                    } elseif ($waiting_db == 3) {
                        
                        $bale_channel = $text;
                        
                        $token = "2074728618:VW9YMtgNXO3TqrvpeJRl8HNXY197s3awLDG4435r";
                        
                        
                        if (testBaleChannel($token, $bale_channel)) {
                            
                            $connection->query("UPDATE baleapp_eitaayarbot SET bale_channel = '$bale_channel', waiting = 0 WHERE telegram_id = $from_id");
                            
                            $reply = "کانال با موفقیت ثبت شد. از حالا به بعد هر پیامی به کانال تلگرام ارسال کنید همانند ان در بله ارسال میشود";
                            
                            $Markup = "$startMarkup";
                            
                        } else {
                            
                            $reply = "خطایی در ثبت کانال وجود دارد\n\nموارد زیر را بررسی کنید:\n\n1. ربات @sender در کانال ایتا ادمین باشد\n2.کانال را در ایتایار در بخش کانال ها اضافه کرده باشید\n3.آیدی عددی را درست ارسال کرده باشید";
                            
                            $Markup = "$backMarkup";
                            
                        }
                        
                    } elseif ($waiting_db == 4) {
                        
                        $rubika_channel = $text;
                        $token = "BGFDI0JRZGFVFKSLENWJRFOXZGTXNSECSFANJELXKSSUSCDDUSMZGZTNYRJIXNOS";
                        
                        
                        // $token = "BGFDI0JRZGFVFKSLENWJRFOXZGTXNSECSFANJELXKSSUSCDDUSMZGZTNYRJIXNOS";
                        // $rubika_channel = "b0GESug0E2F0e083dde123adff832817";

                        if (testRubikaChannel($token, $rubika_channel)) {
                            
                            $connection->query("UPDATE baleapp_eitaayarbot SET rubika_channel = '$rubika_channel', waiting = 0 WHERE telegram_id = $from_id");
                            
                            $reply = "کانال با موفقیت ثبت شد. از حالا به بعد هر پیامی به کانال تلگرام ارسال کنید همانند ان در روبیکا ارسال میشود";
                            
                            $Markup = "$startMarkup";
                            
                        } else {
                            
                            $reply  = "⚠️ خطا در ثبت کانال روبیکا!\n\n\n";
                            $reply .= "برای رفع مشکل، مراحل زیر را انجام دهید:\n\n\n";
                            $reply .= "1️⃣ ابتدا ربات <a href='https://rubika.ir/senderobot'>senderobot</a> را به مشترکین کانال اضافه کنید.\n\n";
                            $reply .= "2️⃣ سپس آن را به‌عنوان ادمین کانال روبیکا تعیین نمایید.\n\n";
                            $reply .= "3️⃣ در پایان، آیدی کانال را (برای کانال عمومی با @) همین‌جا ارسال کنید.";
                            
                            $Markup = "$backMarkup";
                            
                        }
                    } 
                    
                    elseif ($waiting_db == "replace_eitaa_org") {
                        
                        setDraftSource($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_eitaa_new' WHERE telegram_id = $from_id");
                        
                        $reply  = "🌼 <b>مرحله ۳: متن یا لینک جایگزین</b>\n\n";
                        $reply .= "حالا متنی که باید در پلتفرم انتخابی جایگزین بشه رو بفرست 🌷\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>eitaa_channel</code>\n\n";
                        $reply .= "بعد از این مرحله، قانون جایگزینی ذخیره میشه ✅";
                        
                        $Markup = "$backMarkup";
                        
                        
                    } elseif ($waiting_db == "replace_bale_org") {
                        
                        setDraftSource($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_bale_new' WHERE telegram_id = $from_id");
                        
                        $reply  = "🌼 <b>مرحله ۳: متن یا لینک جایگزین</b>\n\n";
                        $reply .= "حالا متنی که باید در پلتفرم انتخابی جایگزین بشه رو بفرست 🌷\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>bale_channel</code>\n\n";
                        $reply .= "بعد از این مرحله، قانون جایگزینی ذخیره میشه ✅";
                        
                        $Markup = "$backMarkup";
                        
                        
                    } elseif ($waiting_db == "replace_rubika_org") {
                        
                        setDraftSource($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 'replace_rubika_new' WHERE telegram_id = $from_id");
                        
                        $reply  = "🌼 <b>مرحله ۳: متن یا لینک جایگزین</b>\n\n";
                        $reply .= "حالا متنی که باید در پلتفرم انتخابی جایگزین بشه رو بفرست 🌷\n\n";
                        $reply .= "🔹 مثال:\n";
                        $reply .= "<code>rubika_channel</code>\n\n";
                        $reply .= "بعد از این مرحله، قانون جایگزینی ذخیره میشه ✅";
                        
                        $Markup = "$backMarkup";
                        
                        
                    } elseif ($waiting_db == "replace_eitaa_new") {
                        
                        finalizeDraft($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 WHERE telegram_id = $from_id");
                        
                        $reply  = "✅ <b>تغییرات با موفقیت ثبت شد!</b>\n\n\n";
                        $reply .= "از حالا به بعد، هنگام ارسال پیام، تغییرات جایگزینی که تعریف کرده‌اید به صورت خودکار اعمال می‌شود 🌿✨\n\n";
                        $reply .= "📋 برای مشاهده لیست کلمات یا لینک‌های جایگزینی به بخش <b>وضعیت جایگزینی</b> مراجعه کنید و مدیریت آن‌ها را انجام دهید 🌸🌱\n\n";
                        
                        $Markup = "$startMarkup";
                        
                        
                    } elseif ($waiting_db == "replace_bale_new") {
                        
                        finalizeDraft($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 WHERE telegram_id = $from_id");
                        
                        $reply  = "✅ <b>تغییرات با موفقیت ثبت شد!</b>\n\n\n";
                        $reply .= "از حالا به بعد، هنگام ارسال پیام، تغییرات جایگزینی که تعریف کرده‌اید به صورت خودکار اعمال می‌شود 🌿✨\n\n";
                        $reply .= "📋 برای مشاهده لیست کلمات یا لینک‌های جایگزینی به بخش <b>وضعیت جایگزینی</b> مراجعه کنید و مدیریت آن‌ها را انجام دهید 🌸🌱\n\n";
                        
                        $Markup = "$startMarkup";
                        
                        
                    } elseif ($waiting_db == "replace_rubika_new") {
                        
                        finalizeDraft($chat_id, $text);
                        
                        $connection->query("UPDATE baleapp_eitaayarbot SET waiting = 0 WHERE telegram_id = $from_id");
                        
                        $reply  = "✅ <b>تغییرات با موفقیت ثبت شد!</b>\n\n\n";
                        $reply .= "از حالا به بعد، هنگام ارسال پیام، تغییرات جایگزینی که تعریف کرده‌اید به صورت خودکار اعمال می‌شود 🌿✨\n\n";
                        $reply .= "📋 برای مشاهده لیست کلمات یا لینک‌های جایگزینی به بخش <b>وضعیت جایگزینی</b> مراجعه کنید و مدیریت آن‌ها را انجام دهید 🌸🌱\n\n";
                        
                        $Markup = "$startMarkup";
                        
                        
                    }
                    
                    else if (strpos($text, '/start') === 0) {
                        
                        if($waiting_db === 'remove_replace') {
                            
                            // جدا کردن پارامتر بعد از /start
                            $parts = explode(' ', $text, 2);
                            $start_param = $parts[1] ?? null;
                            
                            if ($start_param) {
                                
                                // حالت حذف قانون
                                if (strpos($start_param, 'rem_') === 0) {
                                    
                                    $rule_id = substr($start_param, 4); // استخراج rule_id
                                    
                                    // --- حذف قانون از JSON ---
                                    $res = $connection->query("SELECT replace_rules FROM baleapp_eitaayarbot WHERE telegram_id='$chat_id'");
                                    $row = $res->fetch_assoc();
                                    $rules = json_decode($row['replace_rules'], true);
                                    
                                    foreach (['eitaa','bale','rubika'] as $platform) {
                                        
                                        if (!empty($rules[$platform])) {
                                            
                                            $rules[$platform] = array_values(array_filter($rules[$platform], function($r) use ($rule_id) {
                                                return ($r['id'] ?? '') !== $rule_id;
                                            }));
                                        }
                                    }
                                    
                                    $json = $connection->real_escape_string(json_encode($rules, JSON_UNESCAPED_UNICODE));
                                    $connection->query("UPDATE baleapp_eitaayarbot SET replace_rules='$json', waiting = 0 WHERE telegram_id='$chat_id'");
                                    
                                    
                                    $reply  = "🌸🌿 <b>✅ کلمه/لینک جایگزینی مورد نظر با موفقیت حذف شد!</b> 🌿🌸\n\n\n";
                                    $reply .= "تمام تغییرات با موفقیت اعمال شدند و قانون موردنظر از لیست حذف شد. 🌱🌷\n\n\n";
                                    $reply .= "✨ سپاس از اینکه از ایتایاربات استفاده می‌کنید! ✨\n\n";
                                    
                                    $Markup = "$startMarkup";
                                }
                            }
                            
                        } else {
                            
                            $reply  = "🌸🌿 <b>⚠️ این لینک حذف منقضی شده است!</b> 🌿🌸\n\n\n"; 
                            $reply .= "💡 توجه داشته باشید که هر بار ورود به بخش <b>وضعیت جایگزینی</b>، فقط امکان حذف یک مورد فراهم است 🌱🌷\n\n\n";
                            $reply .= "اگر قصد حذف مورد دیگری از لیست را دارید، لطفاً مجدد از منوی اصلی وارد بخش <b>جایگزینی لینک/متن</b> شوید 🌼✨\n\n\n";
                            
                            $Markup = "$startMarkup";
                            
                        }
                    }
                    
                break;
            }
            
        // $connection -> close();
        
        
        $url = $GLOBALS['bot_url']."/sendMessage";
        $post_params = [ 
                            'chat_id' => $GLOBALS['chat_id'] ,
                            'message_thread_id' => $GLOBALS['thread_id'],
                            'text' => $reply ,
                            'reply_markup' => $Markup ,
                            'disable_web_page_preview' => true,
                            'parse_mode' => 'HTML'
                        ];
            
       send_reply($url, $post_params);
        
    }
    
    //-------------------------------------
    
    function detect_inline_query_received_and_reply_1() {
        
        $inline_query    = $GLOBALS["inline_query"];
        $inline_query_id = $GLOBALS["inline_query_id"];
        
        
        
    }
    
    //-------------------------------------
    function detect_callback_received_and_reply() {
        
        $first_name     = $GLOBALS['first_name'];
        $last_name      = $GLOBALS['last_name'];
        $chat_id        = $GLOBALS['chat_id'];
        $callback_data  = $GLOBALS['data'];
        $message_id     = $GLOBALS['message_id'];
        $bot_url        = $GLOBALS['bot_url'];
    
        switch ($callback_data) {
            case '1':
                $text = "شما دکمه 1 را انتخاب کردید ✅";
                break;
            case '2':
                $text = "شما دکمه 2 را انتخاب کردید ✅";
                break;
            case '3':
                $text = "شما دکمه 3 را انتخاب کردید ✅";
                break;
            case '4':
                $text = "شما دکمه 4 را انتخاب کردید ✅";
                break;
            case '5':
                $text = "شما دکمه 5 را انتخاب کردید ✅";
                break;
            default:
                $text = "دکمه نامعتبر!";
                break;
        }
    
        // ارسال پیام متنی به کاربر
        $url = $bot_url . "/sendMessage";
        $post_params = [
            'chat_id' => $chat_id,
            'text' => $text,
            'parse_mode' => 'HTML'
        ];
        send_reply($url, $post_params);
    
        // پاسخ به callback query
        // $url = $bot_url . "/answerCallbackQuery";
        // $post_params = [
        //     'callback_query_id' => $GLOBALS['callback_query_id'],
        //     'text' => $text,
        //     'show_alert' => false
        // ];
        // send_reply($url, $post_params);
    
        // همچنین می‌توان پیام اصلی را ویرایش کرد (اختیاری)
        // $url = $bot_url . "/editMessageText";
        // $post_params = [
        //     'chat_id' => $chat_id,
        //     'message_id' => $message_id,
        //     'text' => $text
        // ];
        // send_reply($url, $post_params);
    }


    //------------------------------------- send message to users
    
    function admin_settings() {
        
        $text = $GLOBALS['text'];
        $update_array = $GLOBALS['update_array'];
        $caption = $update_array["message"]["caption"];
        $ad_record = $GLOBALS['ad_record'];
        
        //--------------------------
        
        $connection = connect_to_db();
            
            if($text == "/ad") {
                
                $reply = $ad_record;
                
                $chat_id_admin = "698468282";
                $url = $GLOBALS['bot_url'] . "/sendMessage";
                $post_params = [ 'chat_id' =>  $chat_id_admin , 'text' => $reply ];
                send_reply($url, $post_params);
                
                $connection -> query("UPDATE baleapp_eitaayarbot SET waiting = '$reply' WHERE telegram_id = 698468282");
                
                return;
            }
            
            $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot WHERE telegram_id = 698468282");
            
            while($row = $result -> fetch_assoc()) {
             
                $old_messages_db         = $row['waiting'];
            }
            
            
            if($old_messages_db == $ad_record ) {
                
                
                file_put_contents(__DIR__ . "/../ad.txt", $text);
                
                $connection -> query("UPDATE baleapp_eitaayarbot SET waiting = '' WHERE telegram_id = 698468282");
                
                
                $reply = "👇 ✅ Ad. text is Updated:\n\n $text";
                
                $chat_id_admin = "698468282";
                $url = $GLOBALS['bot_url'] . "/sendMessage";
                $post_params = [ 'chat_id' =>  $chat_id_admin , 'text' => $reply ];
                send_reply($url, $post_params);
                
            }
            
        // $connection -> close();
        
        //--------------------------
        
        if($text == "/users") {
            
            // فراخوانی فانکشن برای اتصال به دیتابیس
            $connection = connect_to_db(); // فرض می‌کنیم که این فانکشن اتصال را انجام می‌دهد
            
            // کوئری برای شمارش کاربران و گروه‌ها
            $sql_users = "SELECT COUNT(*) AS total_users FROM baleapp_eitaayarbot WHERE telegram_id >= 0 AND status = 'member'";
            $sql_groups = "SELECT COUNT(*) AS total_groups FROM baleapp_eitaayarbot WHERE telegram_id < 0 AND status = 'member'";
            
            // اجرای کوئری‌ها
            $result_users = $connection->query($sql_users);
            $result_groups = $connection->query($sql_groups);
            
            // ذخیره تعداد در متغیرها
            $total_users = 0;
            $total_groups = 0;
            
            if ($result_users && $result_users->num_rows > 0) {
                $row = $result_users->fetch_assoc();
                $total_users = $row['total_users'];
            }
            
            if ($result_groups && $result_groups->num_rows > 0) {
                $row = $result_groups->fetch_assoc();
                $total_groups = $row['total_groups'];
            }
            
            // حالا می‌توانید از متغیرهای $total_users و $total_groups استفاده کنید
            
            $chat_id_admin = "698468282";
            $reply = "users : $total_users \n\n groups: $total_groups";
            $url = $GLOBALS['bot_url'] . "/sendMessage";
            $post_params = [ 'chat_id' =>  $chat_id_admin , 'text' => $reply ];
            send_reply($url, $post_params);
            
            // $connection -> close();
        }
        
        //--------------------------Send a message to all persons
        
        // $message   = substr($text,5);
        // $text_chek = substr($text,0,5);
        // if($text_chek == "toall") {
            
            
            
        //     $connection = connect_to_db();
            
        //     $sql_users = "SELECT telegram_id FROM AiPricesBot WHERE status = 'member'";
        //     $result_users = $connection->query($sql_users);
            
        //     // آرایه برای ذخیره آیدی‌های ارسال شده
        //     $sent_ids = [];
            
        //     // بررسی و ارسال پیام به هر کاربر
        //     if ($result_users && $result_users->num_rows > 0) {
        //         while ($row = $result_users->fetch_assoc()) {
        //             $telegram_id = $row['telegram_id'];
                    
        //             // چک کردن اینکه آیا پیام قبلاً ارسال شده است یا خیر
        //             if (!in_array($telegram_id, $sent_ids)) {
        //                 // فرمت URL برای ارسال پیام
        //                 $url = $GLOBALS['bot_url'] . "/sendMessage";
        //                 $post_params = ['chat_id' => 698468282, 'text' => $message]; // پیام اصلی به کاربر
                        
        //                 $response = send_reply($url, $post_params);
                        
        //                 // بررسی وضعیت پاسخ
        //                 $responseData = json_decode($response, true);
        //                 $status_message = $responseData['ok'] ? "done" : "false";
                        
        //                 // ارسال وضعیت به چت ثابت
        //                 $status_url = $GLOBALS['bot_url'] . "/sendMessage";
        //                 $status_post_params = ['chat_id' => "698468282", 'text' => $status_message];
        //                 send_reply($status_url, $status_post_params);
                        
        //                 // اضافه کردن آیدی به آرایه ارسال شده
        //                 $sent_ids[] = $telegram_id;
                        
        //                 sleep(3); // برای جلوگیری از ارسال بیش از حد سریع
        //             }
        //         }
        //     }
            
            // $connection->close();
            // exit;
            
            // $connection = connect_to_db();
            
            // $sql_users = "SELECT telegram_id FROM AiPricesBot WHERE status = 'member'";
            // $result_users = $connection->query($sql_users);
            
            // // بررسی و ارسال پیام به هر کاربر
            // if ($result_users && $result_users->num_rows > 0) {
            //     while ($row = $result_users->fetch_assoc()) {
            //         $telegram_id = $row['telegram_id'];
                    
            //         // فرمت URL برای ارسال پیام
            //         $url = $GLOBALS['bot_url'] . "/sendMessage";
            //         $reply = $message;
            //         $post_params = [ 'chat_id' =>  "698468282" , 'text' => $telegram_id ];
            //         $response = send_reply($url, $post_params);
                    
            //         // بررسی وضعیت پاسخ
            //         $responseData = json_decode($response, true);
            //         if (isset($responseData['ok']) && $responseData['ok'] === true) {
                        
            //             $url = $GLOBALS['bot_url'] . "/sendMessage";
            //             $reply = "done";
            //             $post_params = [ 'chat_id' =>  "698468282" , 'text' => $reply ];
            //             send_reply($url, $post_params);
                        
            //         } else {
                        
            //             $url = $GLOBALS['bot_url'] . "/sendMessage";
            //             $reply = "false";
            //             $post_params = [ 'chat_id' =>  "698468282" , 'text' => $reply ];
            //             send_reply($url, $post_params);
                        
            //         }
            //         sleep(1);
            //     }
            // }
            
            // $connection -> close();
            // exit;
            
        // }
        
        //--------------------------Send a message to only one person
        
        
        if(isset($update_array['message']['reply_to_message']['text']))    { $reply_to_message = $update_array['message']['reply_to_message']['text']; }
        if(isset($update_array['message']['reply_to_message']['caption'])) { $reply_to_message = $update_array['message']['reply_to_message']['caption']; }
        
        $str_reply_to_msg = substr($reply_to_message,0,8);
        if(isset($update_array['message']['reply_to_message']) and $str_reply_to_msg == "feedback") {
            
            
            $explode_text = explode( "T_ID: " , $reply_to_message);
            $chat_id = $explode_text[1];
            $reply = "$text";
            $url = $GLOBALS['bot_url'] . "/sendMessage";
            $post_params = [
                            'text' => $reply ,
                            'chat_id' =>  $chat_id ,
                            'parse_mode' => 'Markdown'
                            ];
            $result = send_reply($url, $post_params);
            $result_array = json_decode($result, true);
            $ok_send = $result_array["ok"];
            
            
            if($ok_send == true) {
                
                $chat_id = "698468282";
                $reply = "result send: true";
                $url = $GLOBALS['bot_url'] . "/sendMessage";
                $post_params = [ 'chat_id' =>  $chat_id , 'text' => $reply ];
                send_reply($url, $post_params);
            }
            else{
                
                $chat_id = "698468282";
                $reply = "result send: false";
                $url = $GLOBALS['bot_url'] . "/sendMessage";
                $post_params = [ 'chat_id' =>  $chat_id , 'text' => $reply ];
                send_reply($url, $post_params);
            }
            
            return;
        }
        
        if(isset($update_array["message"])) {
            
            detect_text_received_and_reply();
            
        }
    }
    
    //-------------------------------------
    
    function show_cronjob() {
        
        $time_array = getdate( time() );
        
        $Seconds    = $time_array['seconds'];
        
        $connection = connect_to_db();
            
            $connection -> query("UPDATE message_chek SET send_chek = 'Deactive' WHERE channel_id = 'cronjob AiPrice' ");
            
            
            $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot WHERE id");
            
            while($row = $result -> fetch_assoc()) {
             
                $id_db = $row['id'];
            }
            
            for($num=1;$num<=$id_db;$num++) {
                
                $result = $connection -> query("SELECT * FROM baleapp_eitaayarbot WHERE id = '$num'");
                
                while($row = $result -> fetch_assoc()) {
                 
                    $chat_id_db   = $row['telegram_id'];
                }
                
                if($cronjob == "on") {
                    
                }
            }
            
        // $connection -> close();
        
        return;
    }
    //-------------------------------------
    
    function connect_to_db() {
        
        static $connection = null;
    
        if ($connection === null || $connection->connect_errno) {
            $connection = new mysqli("localhost", "cp53656_rgtrack_user", "Jw_O%bW[KlEE", "cp53656_rgtrack");
    
            if ($connection->connect_error) {
                die("Failed to connect to DB: " . $connection->connect_error);
            }
    
            $connection->query("SET NAMES utf8mb4");
        }
    
        return $connection;
    }

    //-------------------------------------
    
    function send_reply($url, $post_params) {
        
        $cu = curl_init();
        curl_setopt($cu, CURLOPT_URL, $url);
        curl_setopt($cu, CURLOPT_POSTFIELDS, $post_params);
        curl_setopt($cu, CURLOPT_RETURNTRANSFER, true);  // get result
        $result = curl_exec($cu);
        curl_close($cu);
        return $result;
    }
    //-------------------------------------
?>