<?php
class telegram extends CI_Controller {

	public function index(){
		$iskey_board = true;
		$array1 = array();
		$array2 = array();
		$array3 = array();
		$array4 = array();
		$array5 = array();
		$array6 = array();
		$array7 = array();
		$array8 = array();
		$array9 = array();
		$array10 = array();
		$arrayg1 = array();
		$arrayg2 = array();
		$arrayg3 = array();
		$arrayg4 = array();
		$this->load->model("telegram_model");
		$params   = $this->uri->segment(2);
		$update = json_decode(file_get_contents('php://input'));

require_once('simple_html_dom.php');
if(isset($update->message->chat->username)){
$username = $update->message->chat->username;
}else{
$username = "مشخص نیست";
}
$token = $this->telegram_model->get_token($params);
//$token = "445932654:AAEfc_C-PTWQP2tYXlPWQ_Sc9sf0ta1rdSQ";
$group = $this->telegram_model->get_group($params);
$tablename = "telebot_".$group;
//$responseJSON = file_get_contents("./assets/jbot/".$group.".json");
$callback = $update->callback_query->from->id;

if($callback){
    $id = $callback;
    $message = $update->callback_query->data;
}else{
    $id = $update->message->chat->id;
    $message = $update->message->text;
}

$chatid1 = $update->message->chat->id;

//$message = $update->message->text;
$user_id = $update->message->from->id;
$userid == $update->channel_post->from->id;


//$last_channel_post_id = $update->channel_post->message_id;

$username = $update->message->from->username;
$firstname = $update->message->from->first_name;
$lastname = $update->message->from->last_name;
$lastpost = $update->message->message_id;
$newmember = $update->message->new_chat_members;
$left_message = $update->message->left_chat_member;
$left_uid = $update->message->left_chat_member->id;
$newChannell = $update->message->chat->id;
$new_update = $update->update_id;
$isbot = $update->message->from->is_bot;
$chatType = $update->message->chat->type;

$chatid1 = $update->message->chat->id;

$chatname1 = $update->message->chat->title;
//***************************************
$capt = $update->message->caption;
$capt_entities = $update->message->caption_entities;

$forward_from_chat_title = $update->message->forward_from_chat->title;
$forward_from_chat_id = $update->message->forward_from_chat->id;
$forward_from_username = $update->message->forward_from->username;
$forward_from_userId = $update->message->forward_from->id;

$file = $update->File->file_id;

//***************************************
//************************************** replay variable
$eimoji = $update->message->sticker->emoji;
$stikername = $update->message->sticker->set_name;
$repl_to = $update->message->reply_to_message->from->username;
$repl_to_fname = $update->message->reply_to_message->from->first_name;
$repl_to_uid = $update->message->reply_to_message->from->id;

$repl_text = $update->message->reply_to_message->text;
$repl_caption = $update->message->reply_to_message->caption;
$repl_id = $update->message->reply_to_message->message_id;
$repl_st = $update->message->reply_to_message->sticker->file_id;

$repl_audio_fid = $update->message->reply_to_message->audio->file_id;
$repl_audio_per = $update->message->reply_to_message->audio->performer;
$repl_audio_tit = $update->message->reply_to_message->audio->title;
$repl_audio_size = $update->message->reply_to_message->audio->file_size;
$repl_audio_mim = $update->message->reply_to_message->audio->mime_type;

$repl_photo_fid = $update->message->reply_to_message->photo;


/*$message_audio_performer = $update->message->audio->performer;
$message_audio_title = $update->message->audio->title;
$message_audio_file_size = $update->message->audio->file_size;
$message_audio_thumb = $update->message->audio->thumb;*/

//******************************************************************************
 
$repl_video_fid = $update->message->reply_to_message->video->file_id;

$repl_voice_fid = $update->message->reply_to_message->voice->file_id;

$repl_document_fid = $update->message->reply_to_message->document->file_id;
//******************************************************************************
$callback_id = $update->callback_query->id;
$callback_message = $update->callback_query->data;
$callback_message_id = $update->callback_query->message->message_id;
$callback_inline_message_id = $update->callback_query->inline_message_id;
$callback_chatid = $update->callback_query->message->chat->id;
$callback_chatid2 = $update->callback_query->chat_instance;
$callback_user = $update->callback_query->from->id;
$callback_chatType = $update->callback_query->message->chat->type;
//******************************************************************************
$inline_query = $update->inline_query->query;
$inline_query_id = $update->inline_query->id;
$inline_query_uid = $update->inline_query->from->id;
//******************************************************************************
$message_audio = $update->message->audio->file_id;
$message_audio_size = $update->message->audio->file_size;
$message_audio_per = $update->message->audio->performer;
$message_audio_tit = $update->message->audio->title;
$message_photo = $update->message->photo;

$message_gif = $update->message->document->file_id;
$message_video = $update->message->video->file_id;
$message_doc_type = $update->message->document->mime_type;

$contactGet = $update->message->contact->phone_number;

$message_voice = $update->message->voice->file_id;

//******************************************************************************

$channelpost = $update->channel_post->message_id;
$channelname = $update->channel_post->chat->username;
$channeltitle = $update->message->forward_origin->title;

$channelid = $update->channel_post->chat->id;
$channelpost_audio_fid = $update->channel_post->audio->file_id;
$channelpost_audio_fsize = $update->channel_post->audio->file_size;
$channel_message = $update->channel_post->text;     // for direct post to channel
$channel_capt = $update->channel_post->caption;     // for direct post to channel

//*********************************** request

$cahtReqChatId = $update->chat_join_request->chat->id;
$chatReqUserId = $update->chat_join_request->from->id;

//*********************************** actionemoji

$emojiAction = $update->MessageReactionUpdated->chat->id;

//*********************************** time

$date = date("Y/m/d_H:i");
$date_fall = date("d_H");
$day = date("d");
$time = date("H");
$Minutes = date("i");
$Seconds = date("s");

//****************************************************************************** end of Define Variables


$message11 = $update->message->caption;
$repl_text = $update->message->reply_to_message->text;
$repl_caption = $update->message->reply_to_message->caption;


if(strlen($message11)>1 ){
    $entities = $update->message->caption_entities;
}elseif(strlen($repl_text)>1){
    $entities = $update->message->reply_to_message->entities;
}elseif(strlen($repl_caption)>1){
    $entities = $update->message->reply_to_message->caption_entities;
}else{
    $entities = $update->message->entities;
    
}

///============================================================================= functions
function getURLs($message11, $entities) { 
    $URLs = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->url) {
            $URLs[] = $entitie->url;
        }
        if ($entitie->type =='url') {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return $URLs;
}

function getCod($message11, $entities) { 
    $URLs = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->code) {
            $URLs[] = $entitie->code;
        }
        if ($entitie->type =='code') {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return $URLs;
}

function getmention($message11, $entities) {
    $URLs = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->mention) {
            $URLs[] = $entitie->mention;
        }
        if ($entitie->type =='mention') {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return $URLs;
}

function gethashtag($message11, $entities) {
    $URLs = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->hashtag) {
            $URLs[] = $entitie->hashtag;
        }
        if ($entitie->type =='hashtag') {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return $URLs;
}

function getlink($message11, $entities) { 
     $link = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16le", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->text_link) {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $link[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16le");
        }
    }
    return $link;
}

function getlinkMention($message11, $entities) { 
     $link = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    $message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->text_mention) {
            $URL16 = substr($message_encode, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            $link[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return $link;
}

function getlength($message11, $entities) { 
     $mention = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    //$message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        if ($entitie->type =='text_link') {
            $URL16 = substr($message11, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            //$URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        }
    }
    return ($entitie->length);
}

function getoffset($message11, $entities) { 
     $mention = [];
    //$message_encode = iconv('utf-8', 'utf-16le', $message); //or utf-16
    //$message_encode = mb_convert_encoding($message11, "UTF-16", "UTF-8"); //or utf-16le
    foreach ($entities as $entitie) {
        //if ($entitie->type =='text_link') {
            $URL16 = substr($message11, ($entitie->offset)*2, ($entitie->length)*2);
            //$URLs[] = iconv('utf-16le', 'utf-8', $URL16);
            //$URLs[] = mb_convert_encoding($URL16, "UTF-8", "UTF-16");
        //}
    }
    return ($entitie->offset);
}


if($update && $cahtReqChatId == '-1001155301071'){
    $this->telegram_model->send_message_only($token,'-1001155301071',"reqchat: ".$cahtReqChatId);
    $this->telegram_model->send_message_only($token,'-1001155301071',"requser: ".$chatReqUserId);
    
    //$res = $this->telegram_model->aproveReq($token,$cahtReqChatId,$chatReqUserId);
    //$this->telegram_model->send_message_only($token,'-1001155301071',$res);

}
///======================================================================= end of functions

$uid = $this->telegram_model->get_groupuid_byurl($params);
if($message == "/start"){
	//for wellcome text
	//for cunting
	$mon = $this->persiandate->jdate("Ym","","",'Asia/Tehran',"en");
	if($this->telegram_model->is_visited_users_exist($uid,$mon)){
		$get_number = $this->telegram_model->get_visited_users($uid,$mon);
		$data = array("number"=>($get_number+1));
		 $this->telegram_model->update_visited_users($uid,$mon,$data);
	}else{
		$data = array("number"=>1,"uid"=>$uid,"mon"=>$mon);
		$this->telegram_model->set_visited_users($data);
	}
	$result = $this->telegram_model->get_telegram_post($uid,"wellcome");
		$text = $result[0]->title;
		$this->telegram_model->send_message_only($token,$id,$text);
		$text = $result[0]->text;	
		$this->telegram_model->send_message_only($token,$id,$text);
		$images = directory_map('./assets/telegrams/'.$uid."/"."wellcome");
		//$iskey_board = false;
		foreach($images as $value){
			$imagename = explode(".",$value);
			$imagename = $imagename[0];
			$caption = $this->telegram_model->get_caption_image($uid,"wellcome",$imagename);
			
			if($caption == ""){
				
		$this->telegram_model->send_photo($token,$id,'./assets/telegrams/'.$uid."/"."wellcome"."/".$value);
			}else{
		$this->telegram_model->send_photo($token,$id,'./assets/telegrams/'.$uid."/"."wellcome"."/".$value,$caption);		
			}
		}
	$result = $this->telegram_model->get_telegram_bd_locate($tablename,"main_menu");
	foreach($result as $value){
	switch($value->level){
			case 1:
				if($value->material == 1){
				array_push($array1,$value->name);
				}else{
				if($value->func == 5){
				array_push($arrayg1,array(text=>$value->name,url=>$value->command));		
					}else{
				array_push($arrayg1,array(text=>$value->name,callback_data=>$value->name));		
					}
				}
				break;
			case 2:
				if($value->material == 1){
				array_push($array2,$value->name);
				}else{
				if($value->func == 5){
				array_push($arrayg2,array(text=>$value->name,url=>$value->command));		
					}else{
				array_push($arrayg2,array(text=>$value->name,callback_data=>$value->name));		
					}
				}
				break;
			case 3:
				
				if($value->material == 1){
				array_push($array3,$value->name);
				}else{
				if($value->func == 5){
				array_push($arrayg3,array(text=>$value->name,url=>$value->command));		
					}else{
				array_push($arrayg3,array(text=>$value->name,callback_data=>$value->name));		
					}
				}
				break;
			case 4:
				if($value->material == 1){
				array_push($array4,$value->name);
				}else{
				if($value->func == 5){
				array_push($arrayg4,array(text=>$value->name,url=>$value->command));		
					}else{
				array_push($arrayg4,array(text=>$value->name,callback_data=>$value->name));		
					}
				}
				break;
			case 5:
				array_push($array5,$value->name);
				break;
			case 6:
				array_push($array6,$value->name);
				break;
			case 7:
				array_push($array7,$value->name);
				break;
			case 8:
				array_push($array8,$value->name);
				break;
			case 9:
				array_push($array9,$value->name);
				break;
			case 10:
				array_push($array10,$value->name);
				break;
			
		}	
	}
}

//****************************************************************************** start all commands

//****************************************************************************** set captions

if(/*$chatid1 == '-1001155301071'*/ $chatid1 == '-1001269870637' || $chatid1 == '-1001444903218' ){
    
    $URLs = getURLs($capt, $entities);
    //$URLs1 = getlength($capt, $entities);
    $URLs2 = getlink($capt, $entities);
    $mention = getmention($capt, $entities);
    if($mention[0] == "@shahryar_org"){
        $mention_shahriar = "shahriar";
    }
    
    $URLs_m = getURLs($message, $entities);
    //$URLs1_m = getlength($message, $entities);
    $URLs2_m = getlink($message, $entities);
    $mention_m = getmention($message, $entities);
    
    if(count($mention) == 1){
        $length = getlength($message, $entities);
        $offset = strpos($message,"@");
        $message = substr_replace($message,"",$offset+$length);
        
        $length = getlength($capt, $entities);
        $offset = strpos($capt,"@");
        $capt = substr_replace($capt,"",$offset+$length);
    }
    $capt = str_replace($mention[0],"",$capt);
    $capt = str_replace($mention[1],"",$capt);
    $capt = str_replace($URLs[0],"",$capt);
    $capt = str_replace($URLs[1],"",$capt);
    $capt = str_replace($URLs2[0],"",$capt);
    $capt = str_replace($URLs2[1],"",$capt);
    
    $message = str_replace($mention_m[0],null,$message);
    $message = str_replace($mention_m[1],null,$message);
    /*$message = str_replace($URLs_m[0],"",$message);
    $message = str_replace($URLs_m[1],"",$message);
    $message = str_replace($URLs2_m[0],"",$message);
    $message = str_replace($URLs2_m[1],"",$message);
    */
    $capt = html_entity_decode($capt);
    //$message = html_entity_decode($message);
    if(strpos($message,"☔️") > 0){
        $capt = str_ireplace('😋','',$capt);
        $capt = str_ireplace('☔','',$capt);
    }
    
    $kalamat = ["💦","◍⃟🌴","❤️💛💚💙💜","➣","🆔","🆑","🇯‌🇴‌🇮‌🇳 ↯
    📍","👁‍🗨👁‍🗨👁‍🗨","😈👉","◍⃟🌹","→","👉⛱","👅","◍⃟🍁","🔵","|™","🏪","°","➰",
    
    "...🗣","●❥","┏━━🍷 ━━┓","┗━━🍷 ━━┛","🌚👉🏿"
    
    ,"◍⃟🌝","👉","👉🏼","🕊","◍⃟❣️","🍁","◍⃟🧡","❖","❄️","🎴","📋📋","➡️","📚📚📚📚📚📚",
    
    "❣️","✨","💛 ","☔️","📚 ","👇🏻","*","💲 ","⚛️ ","🔰🔰","❕ ","◼️","50
Elva ","™ ","◍⃟❣️ ","🇨hannel  ➣ ","🍃🌸",'📚','☯️','➡️','《','》','🍃 🌸'
    ,'Join 🔜','|',"𝕁𝕆𝕀ℕ🔜💥",'☔️😋','👉💯 😂👻🦈','☔😋','😋☔','👈','☔️😋','『','👳🏻‍♂',"🏼"
    ];
    
    for($i = 0; $i<count($kalamat); $i++){
       $capt = str_ireplace($kalamat[$i],"",$capt);
    }
    
    for($k = 0; $k<count($kalamat)+1; $k++){
       $message = str_ireplace($kalamat[$k],"",$message);
    }
    
    $message = str_ireplace('us:','',$message);
    $capt = str_ireplace('us:','',$capt);
    $capt = str_ireplace("اینستا👇👇","",$capt);
    
    $capt = str_ireplace("✍🏻 اثر:","اثر:",$capt);
    $capt = str_ireplace("✍🏼#","#",$capt);
    $capt = str_ireplace("✍🏽 #","#",$capt);
    $capt = str_ireplace("✍#","#",$capt);
    $capt = str_ireplace("✍ #","#",$capt);
    $capt = str_replace("✍️","",$capt);
    $capt = str_ireplace("Join 🔜","Join",$capt);
    
    $hashtag1 = gethashtag($capt, $entities);
    
    
    // 1. مدیریت هشتگ پست آزاد
    if(isset($hashtag1[0]) && $hashtag1[0] == "#پست_آزاد"){
        $h_len = mb_strlen($hashtag1[0]);
        $pos = mb_strpos($capt, $hashtag1[0]);
        if ($pos !== false) {
            $capt = trim(mb_substr($capt, $pos + $h_len));
        }
    }
    
    // 2. مدیریت کانال شهریار
    if(mb_strpos($capt, "@shahryar_org") !== false || mb_strpos($capt, "شهریار") !== false){
        
        // حذف تبلیغاتی که بین دو ایموجی محصور شده‌اند (حتی با وجود اینتر و فاصله)
        $capt = preg_replace('/[^\s\w]\s*کانال.*?[^\s\w]/us', '', $capt);
    
        // لیست کلمات سمی: هر خطی که شامل این کلمات باشد باید پاک شود
        $bad_lines = [
            'کانال تخصصی',
            'کانال رسمی',
            'اشعار استاد',
            'آثار استاد',
            'اینستاگرام ما',
            'کافه دوبیتی',
            'shahryar_org',
            'دنبال کنید'
        ];
        
        foreach($bad_lines as $line){
            // پیدا کردن محل کلمه کلیدی
            $pos = mb_strpos($capt, $line);
            if($pos !== false){
                // برش کپشن: از این کلمه به بعد هر چه هست (تبلیغات و امضا) حذف شود
                $capt = mb_substr($capt, 0, $pos);
            }
        }
    
        // حذف ایموجی‌های تک افتاده در انتهای متن که بعد از برش باقی ماندن
        $capt = preg_replace('/[\x{1F300}-\x{1F9FF}]/u', '', $capt, -1); 
        // این کد بالا فقط ایموجی‌های ته متن رو اگر خیلی رو مخ بودن پاک میکنه، اگر نمیخوای کلا ایموجی‌ها پاک بشن این خط رو بردار
    }
    
    // 3. تمیزکاری نهایی
    $capt = preg_replace("/(\n\s*){2,}/", "\n\n", $capt); 
    $capt = trim($capt);
    
    

if($chatid1 == '-1001155301071'){
    $this->telegram_model->send_message_only($token,'-1001155301071',trim("salam1") );
    $this->telegram_model->send_message_only($token,'-1001155301071',$channeltitle );
    $this->telegram_model->send_message_only($token,'-1001155301071',trim($channelid) );
}
    
    
    $capt = str_ireplace('پیج رسمی کانال تاریخ سیاه و سفید در #اینستاگرام','',$capt);
    $capt = str_ireplace('#اینستاگرام ما','',$capt);
    $capt = str_ireplace('پیج رسمی #اینستاگرام ما','',$capt);
    $capt = str_ireplace('اینستاگرام','',$capt);
    
    $capt = str_ireplace('کسخل','اسکل',$capt);
    $capt = str_ireplace('کصخل','اسکل',$capt);
    
    $capt = str_ireplace('جوک جوک ۰۰۱','',$capt);
    $capt = str_ireplace('us:','',$capt);
    $capt = str_ireplace('👻🦈','',$capt);
    $capt = str_ireplace('👉💯 😂👻🦈','',$capt);
    
    $capt = str_ireplace('💯 😂','',$capt);
    
    $st1 = strpos($capt,"•");
    $st2 = strrpos($capt,"•");
    $m = substr($capt,$st1,$st2-$st1+3);
    
    if($st1 > 0 && $st2 > 0){
        $capt = str_ireplace($m,"",$capt);  
    }
    
    $st3 = strpos($capt,"🔸");
    $st4 = strrpos($capt,"🔸");
    $mm = substr($capt,$st3,$st4-$st3+4);
    
    if($st3 > 0 && $st4 > 0){
        $capt = str_ireplace($mm,"",$capt);  
    }
    
    $st5 = strpos($capt,"♥️");
    $st6 = strrpos($capt,"♥");
    $mmm = substr($capt,$st5,$st6-$st5+3);
    
    if($st5 > 0 && $st6 > 0){
        $capt = str_ireplace($mmm,"",$capt);  
    }
    $st7 = strpos($capt,"👄️");
    $st8 = strrpos($capt,"👄");
    $mmm = substr($capt,$st7,$st7-$st7+3);
    
    if($st7 > 0 && $st8 > 0){
        $capt = str_ireplace($mmm,"",$capt);  
    }
    
    $capt = str_ireplace("\n\n\n\n\n","\n\n",$capt);
    $capt = str_ireplace("\n\n\n\n","\n\n",$capt);
    $capt = str_ireplace("\n\n\n","\n\n",$capt);
    //$capt = str_ireplace("\n\n","\n",$capt);
    
    $capt = str_ireplace("🔜","",$capt);
    $capt = str_replace("🔜","",$capt);
    $capt = str_replace("◍⃟♥️","",$capt);
    
    $regex_emoticon = '/[\x{2300}-\x{26FF}]/u';
    //preg_match( $regex_emoticon, $message,$mach);
    $capt = preg_replace($regex_emoticon, '', $capt);
    
    if( $chatid1 == '-1001269870637' ){
        
        $ca = str_word_count($capt,1);
        $ca2 = str_word_count($message,1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($ca));
        for($i=0; $i<count($ca);$i++){
            if($ca[$i] == "VieraMagazine" or $ca[$i] == "vs" or strpos($capt,'🎥 ') > 0){
                unset($ca[$i]);
            }
            
        }
        
        for($i =0 ; $i<count($ca); $i++){
            if(mb_strpos($capt,"ترند") == 1 && strpos($capt,"VieraBot") > 0){
                break;
            }
            $capt = str_ireplace($ca[$i],"",$capt);
        }
        if( !(strpos($message,"t.me/proxy?") > 0) ){
            //$this->telegram_model->send_message_only($token,'-1001155301071',"test proxy ");
            for($i=0; $i<count($ca2);$i++){
                if($ca2[$i] == "VieraMagazine" or $ca2[$i] == "vs" or strpos($message,'🎥 ') > 0){
                    unset($ca2[$i]);
                }
            }
            for($i =0 ; $i<count($ca2); $i++){
                $message = str_ireplace($ca2[$i],"",$message);
            }
        }
        
    }
    
    $capt = str_ireplace(':     

 ==>','',$capt);
    
    $message = trim($message);
    $capt = trim($capt);
    
    
    $capt = str_ireplace("@","",$capt);
    if( $chatid1 == '-1001444903218' ){
        //$message = $message."\n\n@CinemaCenterNews";
        $capt = $capt."\n\n@CinemaCenterNews";
    }else{
        if(strlen($message) > 15){
            //$message = $message."\n\n@VieraMagazine";
        }
        if(strlen($capt) > 15){
            $capt = $capt."\n\n@VieraMagazine";
        }
    }
    
    /*$this->telegram_model->send_message_only($token,'-1001155301071',$capt);
    $this->telegram_model->send_message_only($token,'-1001155301071',trim($message) );*/
}



//****************************************************************************** forward to vieramagazine

if($message && $chatid1 == '-1001269870637' ){
    //$this->telegram_model->send_message_only($token,'-1001155301071',strlen(stristr($URLs_m[0],"t.me/proxy?")) );
    //$this->telegram_model->send_message_only($token,'-1001155301071',strlen(stristr($URLs_m[1],"t.me/proxy?")) );
    if( count($URLs) == 0 || (strlen(stristr($URLs_m[0],"/proxy?")) == 0 && strlen(stristr($URLs_m[1],"/proxy?")) == 0)/*(strpos($URLs[0],"t.me/proxy?") == null && strpos($URLs[1],"t.me/proxy?") == null)*/ ){
        
        $message = str_ireplace($URLs[0],' ',$message);
        $message = str_ireplace("اینستا👇👇","",$message);
        $message = str_ireplace("📚اینستاگرام ما را دنبال کنید👇","",$message);
        if(count($mention) == 0){
            $ca = str_word_count($message,1);
            for($i =0 ; $i<count($ca); $i++){
                $message = str_ireplace($ca[$i],"",$message);
            }
            $message .= "\n\n@VieraMagazine";
            $zxx = $this->telegram_model->send_message_only($token,'@vieraMagazine',$message );
        }elseif(count($mention) == 1){
            $ca = str_word_count($message,1);
            for($i =0 ; $i<count($ca); $i++){
                $message = str_ireplace($ca[$i],"",$message);
            }
            //$start = strrpos($message,"@")-5;
            //$message = substr_replace($message,"",$start);
            $message = str_ireplace($mention[0],"",$message);
            $message .= "\n\n@VieraMagazine";
            //$this->telegram_model->send_message_only($token,'-1001155301071',"test1" );
            $zxx = $this->telegram_model->send_message_only($token,'@vieraMagazine',$message );
        }elseif(count($mention) == 2){
            
            //$this->telegram_model->send_message_only($token,'-1001155301071',$mention[0] );
            /*$start = strrpos($message,"@");
            $message = substr_replace($message,"",$start);
            $message = str_ireplace($mention[0],"",$message);*/
            $ca = str_word_count($message,1);
            for($i =0 ; $i<count($ca); $i++){
                $message = str_ireplace($ca[$i],"",$message);
            }
            $message = str_ireplace($mention[0],"",$message);
            $message = str_ireplace($mention[1],"",$message);
            $message .= "\n\n@VieraMagazine";
            //$this->telegram_model->send_message_only($token,'-1001155301071',"test2" );
            $zxx = $this->telegram_model->send_message_only($token,'@vieraMagazine',$message );
            
        }
    }else{
        $file_exict2 = glob("./application/images/*.jpg");
        $outFileName3 = "./application/image_new.jpg";
        $outFileName4 = "./application/image_new1111.jpg";
        $font2 = "./application/fonts/IRBADRBOLD.TTF";
            $name_en = $file_exict2[mt_rand(0,count($file_exict2)-1)];
            $outFileName = "$name_en";
            //$this->telegram_model->send_message_only($token,'-1001155301071',"else ->".$outFileName );
            //$new_html = file_get_html($pic_s_link[$num+1]->href);
            //$pic_b_link = $new_html->find('.hub-photomodal  img'); 
            //$size = $this->telegram_model->download_file2($pic_b_link[0]->src,$outFileName);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"else ->".$size );
            $image_resolotion2 = $this->telegram_model->imagesize($outFileName);
            $xx = $this->telegram_model->image_text($outFileName,$outFileName3,50,$image_resolotion2[1]-($image_resolotion2[1]/4),0,"@VieraMagazine");
            if($image_resolotion2[0] > 4500){
                //$font_size = 200;
                $font_size = $image_resolotion2[0]/25;
                $border = $font_size/26;
                //$border = 30;
            }elseif($image_resolotion2[0] > 3000){
                //$font_size = 130;
                $font_size = $image_resolotion2[0]/25;
                $border = $font_size/26;
                //$border = 30;
            }elseif($image_resolotion2[0] > 2000){
                //$font_size = 100;
                $font_size = $image_resolotion2[0]/24;
                $border = $font_size/26;
                //$border = 4;
            }elseif($image_resolotion2[0] > 1500){
                //$font_size = 75;
                $font_size = $image_resolotion2[0]/22;
                $border = $font_size/23;
                //$border = 3;
            }elseif($image_resolotion2[0] > 1000){
                //$font_size = 50;
                $font_size = $image_resolotion2[0]/21;
                $border = $font_size/22;
                //$border = 3;
            }elseif($image_resolotion2[0] >= 400){
                //$font_size = 30;
                $font_size = $image_resolotion2[0]/20;
                $border = $font_size/20;
                //$border = 2;
            }else{
                $font_size = null;
            }
            //$this->telegram_model->send_message_only($token,'-1001155301071', "resolotion: ".$image_resolotion2[0] );
            $result3 = exec("ffmpeg -y -i $outFileName  -filter_complex \"drawtext=text='@VieraMagazine':fontfile=$font2:fontsize=$font_size:fontcolor=#04fa38:borderw=$border:box=0:boxcolor=black@0.5:bordercolor=black@1.0:x=w/30:y=(h-text_h)/2+h/2*3/5\" $outFileName4 2>&1");
            $zxx = $this->telegram_model->send_photo_online($token,'-1001155301071',$outFileName4,"test new1");
            //$this->telegram_model->send_message_only($token,'-1001155301071', $xx );
            //$this->telegram_model->send_photo_online($token,'-1001155301071',$outFileName3,"test");
    }
    die();
    /*if( strpos($URLs_m[0],"t.me/proxy?") > 0 ){
            $text1 = "✅ پروکسی پر سرعت";
            $text2 = $URLs_m[0];
            $text3 = "برای دوستان خود نیز فروارد کنید";
            $text4 = '@vieraMagazine';
            $text5 = substr_replace($text2,"https",0,strpos($text2,":"));
            //$zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName3,$text1."\n\n".$text2."\n\n".$text3."\n\n".$text4);
            
            $zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName4,$text1."\n\n".$text5."\n\n".$text3."\n\n".$text4);
                //$this->telegram_model->send_message_only($token,'-1001155301071', $text5 );
            $pr = $zxx;
        }elseif( strpos($URLs_m[1],"t.me/proxy?") > 0 ){
            $text1 = "✅ پروکسی پر سرعت";
            $text2 = $URLs_m[1];
            $text3 = "برای دوستان خود نیز فروارد کنید";
            $text4 = '@vieraMagazine';
            $text5 = substr_replace($text2,"https",0,strpos($text2,":"));
            //$zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName3,$text1."\n\n".$text2."\n\n".$text3."\n\n".$text4);
            
            $zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName4,$text1."\n\n".$text5."\n\n".$text3."\n\n".$text4);
            $pr = $zxx;
        }elseif( strpos($URLs_m[1],"//proxy?") > 0 ){
            $text1 = "✅ پروکسی پر سرعت";
            $text2 = $URLs_m[1];
            $text3 = "برای دوستان خود نیز فروارد کنید";
            $text4 = '@vieraMagazine';
            $text5 = substr_replace($text2,"https",0,strpos($text2,":"));
            //$zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName3,$text1."\n\n".$text2."\n\n".$text3."\n\n".$text4);
            
            $this->telegram_model->send_message_only($token,'-1001155301071',$text5);
            
            $zxx = $this->telegram_model->send_photo_online($token,'-1001155301071',$outFileName4,$text1."\n\n".$text5."\n\n".$text3."\n\n".$text4);
            $pr = $zxx;
        }*/
        if( strpos($URLs_m[0],"/proxy?") > 0 || strpos($URLs_m[1],"/proxy?") > 0){
            $text1 = "✅ پروکسی پر سرعت";
            $text2 = $URLs_m[0];
            $text3 = "برای دوستان خود نیز فروارد کنید";
            $text4 = '@vieraMagazine';
            $text5 = substr_replace($text2,"https://t.me/",0,strpos($text2,"proxy"));
            //$zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName3,$text1."\n\n".$text2."\n\n".$text3."\n\n".$text4);
            
            $zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName4,$text1."\n\n".$text5."\n\n".$text3."\n\n".$text4);
                //$this->telegram_model->send_message_only($token,'-1001155301071', $text5 );
            $pr = $zxx;
        }
        die();
        if(strlen($pr) > 0){
            $proxy_json = json_decode($pr, true);
            //$this->telegram_model->send_message_only($token,'-1001155301071',$proxy_json["result"]["message_id"] );
            $prox = $this->telegram_model->get_temp(10);
            $text = $prox[0]->content.",".$proxy_json["result"]["message_id"];
            $text = substr($text,strpos($text,",")+1);
            //$this->telegram_model->send_message_only($token,'-1001155301071',$text );
            /*$m = explode(',',$prox[0]->content);
            array_shift($m);
            array_push($m, $proxy_json["result"]["message_id"]);
            $proxys = implode(',',$m);*/
            $data = array( "content"=>$text );
            $this->telegram_model->update_temp(10,$data);
            unlink($outFileName3);
            unlink($outFileName4);
            die();
        }
}

if($message_photo ){
    //$this->telegram_model->send_message_only($token,'-1001155301071','send in Group: '.$chatid1."\ngroup name: ".$chatname1."\n"."usernaeme: ".$usermehrsa."\n"."firstname: ".$firstmehrsa);
    //$xx = $this->telegram_model->send_photo($token,'-1001155301071',$message_photo[0]->file_id,$capt);
    if($chatid1 == '-1001269870637'){
        /*if( strpos($URLs[0],"t.me/proxy?") > 0 ){
            $text1 = "✅ پروکسی پر سرعت";
        $text2 = $URLs[0];
        $text3 = "برای دوستان خود نیز فروارد کنید";
        $text4 = '@vieraMagazine';
        $this->telegram_model->send_message_only($token,'@vieraMagazine',$text1."\n\n".$text2."\n\n".$text3."\n\n".$text4);
        }*/
        
        $outFileName = "./application/pic1.jpg";
        //$this->telegram_model->send_message_only($token,'-1001155301071',"ph: ".$message_photo[2]->file_id);
        if(strlen($message_photo[3]->file_id) > 0){
            $pic = $this->telegram_model->get_file($token,$message_photo[3]->file_id);
        }elseif(strlen($message_photo[2]->file_id) > 0){
            $pic = $this->telegram_model->get_file($token,$message_photo[2]->file_id);
        }elseif(strlen($message_photo[1]->file_id) > 0){
            $pic = $this->telegram_model->get_file($token,$message_photo[1]->file_id);
        }elseif(strlen($message_photo[0]->file_id) > 0){
            $pic = $this->telegram_model->get_file($token,$message_photo[0]->file_id);
        }
        
        $pic_file = json_decode($pic, true);      
            //$this->telegram_model->send_message_only($token,'-1001155301071',$pic_file["result"]["file_path"]);
        $url1 = "https://api.telegram.org/file/bot".$token."/".$pic_file["result"]["file_path"];
        $size = $this->telegram_model->download_file($url1,$outFileName); 
        $outFileName_img2 = "./application/img/logowatermark2.png";
        $outFileName_img3 = "./application/pic2.jpg";
        $outFileName4 = "./application/image_new1111.jpg";
        $font2 = "./application/fonts/IRBADRBOLD.TTF";
        $image_resolotion = $this->telegram_model->imagesize($outFileName);
        if($image_resolotion[0] > 4500){
            //$font_size = 200;
            $font_size = $image_resolotion[0]/26;
            $border = $font_size/13;
            //$border = 30;
        }elseif($image_resolotion[0] > 3000){
            //$font_size = 130;
            $font_size = $image_resolotion[0]/26;
            $border = $font_size/13;
            //$border = 30;
        }elseif($image_resolotion[0] > 2000){
            //$font_size = 100;
            $font_size = $image_resolotion[0]/25;
            $border = $font_size/12;
            //$border = 4;
        }elseif($image_resolotion[0] > 1500){
            //$font_size = 75;
            $font_size = $image_resolotion[0]/23;
            $border = $font_size/11;
            //$border = 3;
        }elseif($image_resolotion[0] > 1000){
            //$font_size = 50;
            $font_size = $image_resolotion[0]/22;
            $border = $font_size/11;
            //$border = 3;
        }elseif($image_resolotion[0] >= 400){
            //$font_size = 30;
            $font_size = $image_resolotion[0]/22;
            $border = $font_size/10;
            //$border = 2;
        }else{
            $font_size = $image_resolotion[0]/21;
            $border = $font_size/9;
            //$font_size = null;
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071', "size:  $size" );
        //$this->telegram_model->send_message_only($token,'-1001155301071', "resou:  $image_resolotion[0]" );
        
        if($image_resolotion[0] > 290 && $image_resolotion[1] > 200){
            //$result3 = exec("ffmpeg -y -i $outFileName  -filter_complex \"drawtext=text='@VieraMagazine':fontfile=$font2:fontsize=$font_size:fontcolor=#04fa38:borderw=$border:box=0:boxcolor=black@0.5:bordercolor=black@1.0:x=w/30:y=(h-text_h)/2+h/2*3/5\" $outFileName4 2>&1");
            $result3 = exec("ffmpeg -y -i $outFileName  -filter_complex \"drawtext=text='':fontfile=$font2:fontsize=$font_size:fontcolor=#04fa38:borderw=$border:box=0:boxcolor=black@0.5:bordercolor=black@1.0:x=w/30:y=(h-text_h)/2+h/2*3/5\" $outFileName4 2>&1");
            //$zxx = $this->telegram_model->send_photo_online($token,'-1001155301071',$outFileName4,$capt);
            //$size2 = $this->telegram_model->watermark_image($outFileName,$outFileName_img2, $outFileName_img3);
            $zxx = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName4 /*$outFileName_img3*/,$capt);
        }else{
            $zxx = $this->telegram_model->send_photo($token,'@vieraMagazine',$message_photo[0]->file_id,$capt);
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',$zxx);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$image_resolotion[0]);
        //$phsend = $this->telegram_model->send_photo_online($token,'@vieraMagazine',$outFileName_img3,$capt);
        unlink($outFileName);
        unlink($outFileName_img3);
        unlink($outFileName4);
    }
    if( $chatid1 == '-1001444903218' ){
        $zxx = $this->telegram_model->send_photo($token,'@CinemaCenterNews',$message_photo[0]->file_id,$capt);
        $sent_photo = json_decode($zxx, true);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$zxx);
        $data = array("last_post_time"=>date("H"),"last_post_id"=>$sent_photo["result"]["message_id"]);
        $this->telegram_model->update_post_sent("CinemaCenterNews","cinema",$data);
    } 
}

elseif ($message_video ){
    //$this->telegram_model->send_message_only($token,'-1001155301071','this capt: '.$message_video);
    //$xx = $this->telegram_model->send_video_online($token,'-1001155301071',$message_video,$capt);
    if($chatid1 == '-1001269870637'){
        
        $zxx = $this->telegram_model->send_video_online($token,'@VieraMagazine',$message_video,$capt);
    }
    if( $chatid1 == '-1001444903218' ){
        usleep(1000);
        $zxx = $this->telegram_model->send_video_online($token,'@CinemaCenterNews',$message_video,$capt);
        $sent = json_decode($zxx, true);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$zxx);
        $data = array("last_post_time"=>date("H"),"last_post_id"=>$sent["result"]["message_id"],"last_post_title"=>$capt);
        $updateCinema = $this->telegram_model->update_post_sent("CinemaCenterNews","cinema",$data);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$updateCinema);
    }
}

elseif ($message_audio){
    //$this->telegram_model->send_message_only($token,'-1001155301071','send in Group: '.$chatid1."\ngroup name: ".$chatname1);
    //$xx = $this->telegram_model->send_audio($token,'-1001155301071',$capt,$message_audio);
    if($chatid1 == '-1001269870637'){
        $zxx = $this->telegram_model->send_audio($token,'@VieraMagazine',$capt,$message_audio);
    }
}

elseif ($message_voice){
    //$this->telegram_model->send_message_only($token,'-1001155301071','send in Group: '.$chatid1."\ngroup name: ".$chatname1);
    //$xx = $this->telegram_model->send_audio($token,'-1001155301071',$capt,$message_audio);
    if($chatid1 == '-1001269870637'){
        $zxx = $this->telegram_model->send_audio($token,'@VieraMagazine',$capt,$message_voice);
    }
}

elseif ($message_gif){
    
    //if( strlen($capt)>150 ){
        //$this->telegram_model->send_message_only($token,'-1001155301071','send in Group: '.$chatid1."\ngroup name: ".$chatname1."\n"."usernaeme: ".$usermehrsa."\n"."firstname: ".$firstmehrsa);
        //$xx = $this->telegram_model->send_document_online($token,'-1001155301071',$message_gif,$capt);
        if($chatid1 == '-1001269870637'){
            $zxx = $this->telegram_model->send_document_online($token,'@VieraMagazine',$message_gif,$capt);
        }
        if( $chatid1 == '-1001444903218' ){
            $zxx = $this->telegram_model->send_document_online($token,'@CinemaCenterNews',$message_gif,$capt);
            $sent_photo = json_decode($zxx, true);
            //$this->telegram_model->send_message_only($token,'-1001155301071',$zxx);
            $data = array("last_post_time"=>date("H"),"last_post_id"=>$sent_photo["result"]["message_id"]);
            $this->telegram_model->update_post_sent("CinemaCenterNews","cinema",$data);
    }
    //}

}

//******************************************************************************
// viera id 876426668  ایدی ویرا
similar_text($message,"ویرا",$percent_viera1);
similar_text($message,"ویرااا",$percent_viera2);
similar_text($message,"ویرا جانم",$percent_viera3);
similar_text($message,"ویرا جونم",$percent_viera4);
similar_text($message,"ویرااا جونم",$percent_viera5);
similar_text($message,"ویرا جووونم",$percent_viera6);

if($message == "Remkey" || $message == "remkey"){
    $keyboard = array("keyboard" => array(),"resize_keyboard"=>true,"remove_keyboard" => true);
	$this->telegram_model->send_message($token,$id,".",$keyboard);
}
    
if($message == "پسرم" && $user_id == "53853580"){
    $x3 = $this->telegram_model->send_Action($token,$chatid1,"typing");
    $nu = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"جانم بابایی");  
}

if($message == "تگ"){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $tt2 = time()-120;
        $user_call2 = $this->telegram_model->get_groups_users35($chatid1,$user_id,$tt2 );
        
        //$this->telegram_model->send_message_only($token,'-1001155301071',"random 0= ".count($user_call2) );
        
        $random_user = [];//array_rand($user_call,5  );//count($user_call)
        
        if(count($user_call2) > 30){
            $counter_user = 20;
        }elseif(count($user_call2) > 15){
            $counter_user = 10;
        }elseif(count($user_call2) > 5){
            $counter_user = 5;
        }else{
            $counter_user = count($user_call2);
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',"random 1= ".$counter_user );
        for($g = 0; $g < $counter_user; $g++){
            /*if($user_id != "53853580"){
                $thisUser = $user_call2[$g]->user_id;
                $thisFj = json_decode($user_call2[$g]->Json_first);
                $this->telegram_model->send_message_only($token,'-1001155301071',"random 2= ".$thisFj );
            }*/
            if($counter_user > 10){
                //$user .= "<a href=\"tg://user?id=".$thisUser."\" >".$thisUser."</a>\n";
                $user .= "<a href=\"tg://user?id=".$user_call2[$g]->user_id."\" >".json_decode($user_call2[$g]->Json_first)."</a>\n"; 
            }else{
                $user .= "<a href=\"tg://user?id=".$user_call2[$g]->user_id."\" >".json_decode($user_call2[$g]->Json_first)."</a>\n\n"; 
                //$user .= "<a href=\"tg://user?id=".$thisUser."\" >".$thisUser."</a>\n\n"; 
            }
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',"random 0= ".$user );
        //$this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"الان صداشون میکنم برات");
        $resSend = $this->telegram_model->send_message_only($token,$chatid1,$user."\n\nبیاید بالا " );
        //$this->telegram_model->send_message_only($token,'-1001155301071',"random 2= ".$resSend );
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
    }
}

if($percent_viera1 > 97 || $percent_viera2 > 90 || $percent_viera3 > 89 || $percent_viera4 > 89 || $percent_viera5 > 89 || $percent_viera6 > 89){
    if($user_id == "53853580"){
        $num_message = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"جانم بابایی");  
    }elseif($user_id == "933548115" || $user_id == "2123939865"){
        $num_message = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"جانم مامانی");  
    }else{
        $num_message = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"جانم ".$firstname);  
    }
    //$this->telegram_model->send_message_only($token,'-1001155301071',$num_message);
    //$nm = json_decode($num_message,true);
    //$this->telegram_model->send_message_only($token,'-1001155301071',$nm["result"]["message_id"]);
    //$this->telegram_model->edit_message($token,$chatid1,$nm["result"]["message_id"],"test");
    
    /*}elseif( $get_user[0]->count_bad == 20 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"عزیزم داری دیگه زیادی بهم گیر میدی ها😉😉");
    }elseif( $get_user[0]->count_bad == 21 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"لطفا دیگه ریپلای نکن بزار یکم به کارای دیگه برسم بعد باهات صحبت کنم.🙏🌺🙏");
    }elseif( $get_user[0]->count_bad == 22 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"یکی بیاد منو از دست این نجات بده🤦‍♂️🤦‍♂️");
    }elseif( $get_user[0]->count_bad == 23 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"خدایا اینو بزار تو اولویت😝🏃‍♂️");
    }elseif( $get_user[0]->count_bad == 24 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"زیاد ازیت کنی سکوتت میکنم ها😐😐");
    }elseif( $get_user[0]->count_bad == 25 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"ببین بهت گفتما بعد نگی نگفتم😝😐");
    }elseif( $get_user[0]->count_bad == 26 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"پووووف داری مجبورم میکنی ها😒😒");
    }elseif( $get_user[0]->count_bad == 27 ){
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"خدایا اینو نزار تو الویت خودم درستش میکنم بخندیم😜😂😁");
    }elseif( $get_user[0]->count_bad == 28 ){
        $join_info = $this->telegram_model->get_member($token,$get_user[0]->user_id,$chatid1);
        $j = json_decode($join_info, true);
        if($j[result][status] == "creator" || $j[result][status] =="administrator" || $user_id == "53853580"){
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"حیف که ادمین هستی.درست نیست سکوتت کنم. به‌جاش باهات تا یک ساعت حرف نمیزنم.😏😏");
        }else{
            $ban = $this->telegram_model->restrict_member($token,$chatid1,$get_user[0]->user_id,$until_date = 120,$can_send_messages = false);
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"مجبورم کردی دیگه. 2 دقیقه سکوتت میکنم تا دیگه منو ازیت نکنی😜😂😂");
            
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"تا نیم ساعت هم جوابت رو نمیدم 😐😐");
        }
    }*/
}

if($repl_to == 'Vierabot'){
    
    $this->telegram_model->send_message_only($token,'-1001155301071',$chatid1."\n".$chatname1);
    $this->telegram_model->send_message_only($token,'-1001155301071',$user_id."\n".$username."\n".$firstname."\n*&\n".$message);
    
    if(($chatid1 == '-1001155301071' || $chatid1 == '-1001426543615') && substr($message,0,4) == "1234" ){
        /*$text_save = substr($message,4);
        $text_separete = explode("-",$message);
        $regex_emoticon = '/[\x{2300}-\x{1F9FF}]/u';
        $question_user = trim(substr($repl_text,strpos($repl_text,"*&")+2));
        $question_user = preg_replace($regex_emoticon, '', $question_user);
        //$answer_get = $this->telegram_model->get_telegram_answer();
        $question_get = $this->telegram_model->get_telegram_answer_like($question_user);
        $this->telegram_model->send_message_only($token,'-1001155301071',count($question_get)."-"-$question_user);
        
        $answer = $text_separete[1];
        $answer = str_ireplace("..",",",$answer);
        $emojiset =  $text_separete[2];
        preg_match_all( $regex_emoticon, $emojiset,$mach);
        $emojiset = json_encode($mach[0][0],true).",".json_encode($mach[0][1],true).",".json_encode($mach[0][2],true).",".json_encode($mach[0][3],true);
        $emojiset = str_ireplace(",null","",$emojiset);
        $answer_fun = $text_separete[3];
        $answer_fun = str_ireplace("..",",",$answer_fun);
        $emoji_fun = $text_separete[4];
        preg_match_all( $regex_emoticon, $emoji_fun,$mach);
        $emoji_fun = json_encode($mach[0][0],true).",".json_encode($mach[0][1],true).",".json_encode($mach[0][2],true).",".json_encode($mach[0][3],true);
        $emoji_fun = str_ireplace(",null","",$emoji_fun);
        $group = $text_separete[5];
        $this->telegram_model->send_message_only($token,'-1001155301071',$answer."-".$emojiset."-".$answer_fun."-".$emoji_fun);
        if(count($question_get) == 0 && $chatid1 == '-1001155301071'){
            $data = array("group"=>$group,"question"=>$question_user,"answer"=>$answer,"emojiset"=>$emojiset,"answer_fun"=>$answer_fun,"emoji_fun"=>$emoji_fun);
            $this->telegram_model->set_telegram_answer($data);
            //'-1001155301071'
            $this->telegram_model->send_message_only($token,$chatid1,"text: ".$question_user);
        }*/
    }
    
    similar_text($message,"بچه ها رو صدا کن",$percent7);
    similar_text($message,"بچه هارو صدا کن ویرا",$percent6);
    similar_text($message,"بچه ها رو صدا بزن",$percent5);
    similar_text($message,"بچه ها کجان؟",$percent4);
    similar_text($message,"بچه ها کجا هستن؟",$percent3);
    if($percent3 > 90 || $percent4 > 90 || $percent5 > 90 || $percent6 > 90 || $percent7 > 90 || $percent8 == 100){
        //$this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"دارم سیستمم رو بروزرسانی میکنم نمیتونم صداشون کنم ببخش");
        //$user_call = $this->telegram_model->get_groups_users3($chatid1);
        $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
        //if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
            $tt2 = time()-50;
            $user_call2 = $this->telegram_model->get_groups_users35($chatid1,$user_id,$tt2 );
            $random_user = [];
            
            if(count($user_call2) > 5){
                $counter_user = 5;
            }else{
                $counter_user = count($user_call2);
            }
            for($g = 0; $g < $counter_user; $g++){
                $user .= "<a href=\"tg://user?id=".$user_call2[$g]->user_id."\" >".json_decode($user_call2[$g]->Json_first)."</a>\n\n"; 
            }
            //$this->telegram_model->send_message_only($token,'-1001155301071',"random 0= ".$user );
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"الان صداشون میکنم برات");
            $this->telegram_model->send_message_only($token,$chatid1,trim($user)."\n\nبیاید بالا ببینم " );
        //}else{
            //$this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
        //}
        die();
    }
    
    $regex_emoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clear_string = preg_replace($regex_emoticons, '', $message);
    $regex_symbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clear_string = preg_replace($regex_symbols, '', $clear_string);
    $regex_transport = '/[\x{1F680}-\x{1F6FF}]/u';
    $message1 = preg_replace($regex_transport, '', $clear_string);
    $regex_emoticon = '/[\x{2300}-\x{1F9FF}]/u';
    preg_match( $regex_emoticon, $message,$mach);
    
    $newPercent = null;
    $indexPercent = null;
    $nm1 = mt_rand(0,4);
    $nm2 = mt_rand(0,4);
    $nm3 = mt_rand(0,7);
    $nm4 = mt_rand(0,7);
    $nm5 = mt_rand(0,7);
    $nm6 = mt_rand(0,7);
            
    //$em1 = [😀,😃,😄,😆,😂,🤣,😁,😅,🙃];
        
    //$em2 = [😡,🤬 ];
        
    //$em3 = [😤,😠,🤯 ];
        
    //$em4 = [🙂,😊,☺,️🙃,🌺,🌸,🌹,💐];
        
    //$em5 = [😕,🙁,😐,😑,😶,🤨,🧐];
        
    //$em6 = [❤,😘,🥰,💋,❤️,👄,😽,😚,😙,😗,😍];
        
    //$em7 = [😋,😛,😜,🤪,😝,👅];
        
    //$em8 = [👌,👍,👏,✌️,🙏];
        
    //$em9 = [😔,😞,☹️];
            
    //$this->telegram_model->send_message_only($token,'-1001155301071',"repl: ".$repl_to);
    /*if(strlen($eimoji) > 0){
        //$this->telegram_model->send_message_only($token,'-1001155301071', $stikername );
        //"khande_farsgraphic",
        $st_ar = [];
        $stik_array = ["payize2","Spoiledrabbitpack","RaniRabbit","Schubbi","Marshmallow_Couple_by_cocopry","Spoiled_Rabbit_by_cocopry","SpongeBob_by_cocopry"
                        ,"Donald_Duck_by_cocopry","Patrick_by_cocopry","Bunny_Boo"];
        //Gogoli_pack_3
        for($i = 0; $i < count($stik_array); $i++){
                
            $stik2 = $this->telegram_model->get_stickers($token,$stik_array[$i]);
            $s2 = json_decode($stik2, true);
                
            for($k = 0; $k < count($s2[result][stickers]); $k++){
                if( $eimoji == $s2[result][stickers][$k][emoji] ){
                    array_push($st_ar,$s2[result][stickers][$k][file_id]);
                    //$this->telegram_model->send_message_only($token,'-1001155301071', count($st_ar) );
                }
            } 
        }
        $select1 = mt_rand(0,count($st_ar)-1);
        $send_st = $this->telegram_model->send_stickers($token,$chatid1,$st_ar[$select1],$lastpost);
        $send_st = json_decode($send_st, true);
        //$this->telegram_model->send_message_only($token,'-1001155301071', $send_st );
    }
    $arrayn = ["ناراحت نباش اینم میگذره","گر نکوبی شیشه غم را به سنگ هفت رنگش میشود هفتاد رنگ","بیخیال دنیا دو روزه غصه نخور","نبینم ناراحت باشی"];
    if($mach[0] ){
            
        if( in_array($mach[0], $em1) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em1[$nm1].$em1[$nm2]);
        elseif($mach[0] =="😳" || $mach[0] =="😱")
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"تعجب نکن عزیزم😄😉");
        elseif($mach[0] =="🙄" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"چی شده ؟ 😐");
        elseif($mach[0] =="😏" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"😏😏😝");
            
        elseif($mach[0] =="😐" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"🤨🧐");
        elseif($mach[0] =="😍" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"😊😊");
        elseif($mach[0] =="😻" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"😊😊");
        elseif($mach[0] =="😢" )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"✋ ببشید ☹️🌸");
            
        elseif( is_numeric(strpos($message,"☹️" ) )  || is_numeric(strpos($message,"😔" ) ) ) 
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em5[mt_rand(0,count($em5)-1)].$arrayn[mt_rand(0,count($arrayn)-1)]);
                
        elseif(in_array($mach[0], $em2) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"چرا گوجه شدی؟".$em1[$nm1].$em1[$nm2]);
        elseif(in_array($mach[0], $em3) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"به اعصاب خودت مسلسل باش".$em1[$nm1].$em1[$nm2]);
        elseif(in_array($mach[0], $em4) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em4[$nm3].$em4[$nm4].$em4[$nm3]);
        elseif(in_array($mach[0], $em5) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em5[$nm3].$em5[$nm4].$em5[$nm3]);
        elseif(in_array($mach[0], $em6) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em6[$nm5].$em6[$nm6]);
        elseif(in_array($mach[0], $em7) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em7[mt_rand(0,count($em7)-1)].$em7[mt_rand(0,count($em7)-1)]);
        elseif(in_array($mach[0], $em8) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em8[mt_rand(0,count($em8)-1)].$em4[mt_rand(0,count($em4)-1)]);
        elseif(in_array($mach[0], $em9) )
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$em9[mt_rand(0,count($em9)-1)]."ناراحت نباش درست میشه");
    }*/
    
    $answer1 = $this->telegram_model->get_telegram_answer();
    $this->telegram_model->send_message_only($token,'-1001155301071', count($answer1) );
    for($i=0;$i<count($answer1);$i++){
        similar_text($message1,$answer1[$i]->question,$percent);
        if($percent > 82 && $percent > $newPercent){
            $newPercent = $percent;
            $indexPercent = $i;
        }
        if($i == count($answer1)-1){
            rand:$num3 = mt_rand(0,2);
            
            $counterApi = $this->telegram_model->get_temp(21);
            /*$this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
            die();*/
            if($num3 == 0){
                $ar1 = explode(",",$answer1[$indexPercent]->answer_fun);
                $ar2 = explode(",",$answer1[$indexPercent]->emoji_fun);
                $num1 = mt_rand(0,count($ar1)-1);
                $num2 = mt_rand(0,count($ar2)-1);
                $string = $ar1[$num1].json_decode($ar2[$num2],true);
                /*if(strlen($string) == 0 ){
                    if($counterApi[0]->content < 500){
                        $this->telegram_model->send_message_only($token,'-1001155301071',"here api gemini1");
                        //$x3 = $this->telegram_model->send_Action($token,$chatid1,"typing");
                        //$data = array("content"=>($counterApi[0]->content)+1);
                        //$this->telegram_model->update_temp(21,$data);
                        $result = $this->telegram_model->chatgpt1($message."\nبصورت طنز جواب بده");
                        $this->telegram_model->send_message_only($token,'-1001155301071',"here api gemini1  ".$result);
                        $apiAnswer = json_decode($result,true);
                        $this->telegram_model->send_message_only($token,$chatid1,$apiAnswer['result']);
                        if($apiAnswer['status']){
                            die();
                        }
                    }
                }*/
                $this->telegram_model->send_message_only($token,'-1001155301071', $newPercent );
                $this->telegram_model->send_message_only($token,'-1001155301071', $indexPercent );
                /*$x3 = $this->telegram_model->send_Action($token,$chatid1,"typing");
                sleep(3);*/
                $send = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$string);
                            
            }elseif( $num3 == 1 ){
                $ar1 = explode(",",$answer1[$indexPercent]->answer);
                $ar2 = explode(",",$answer1[$indexPercent]->emojiset);
                $num1 = mt_rand(0,count($ar1)-1);
                $num2 = mt_rand(0,count($ar2)-1);
                $string = $ar1[$num1].json_decode($ar2[$num2],true);
                /*if(strlen($string) == 0 ){
                    if($counterApi[0]->content < 500){
                        $this->telegram_model->send_message_only($token,'-1001155301071',"here api gemini2");
                        //$x3 = $this->telegram_model->send_Action($token,$chatid1,"typing");
                        //$data = array("content"=>($counterApi[0]->content)+1);
                        //$this->telegram_model->update_temp(21,$data);
                        $result = $this->telegram_model->chatgpt1($message);
                        $this->telegram_model->send_message_only($token,'-1001155301071',"here api gemini2:  ".$result);
                        $apiAnswer = json_decode($result,true);
                        $this->telegram_model->send_message_only($token,$chatid1,$apiAnswer['result']);
                        if($apiAnswer['status']){
                            die();
                        }
                    }
                }*/
                //$this->telegram_model->send_message_only($token,'-1001155301071', $indexPercent );
                /*$x3 = $this->telegram_model->send_Action($token,$chatid1,"typing");
                sleep(3);*/
                $send = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$string);
                            
            }else{
                if(strlen($answer1[$indexPercent]->music) > 0){
                    $ar1 = explode(",",$answer1[$indexPercent]->music);
                    $num1 = mt_rand(0,count($ar1)-1);
                    //$this->telegram_model->send_message_only($token,'-1001155301071', "voice: ".$num1 );
                    
                    $source_ogg = "./application/music/".$ar1[$num1].".ogg";
                    //$this->telegram_model->send_message_only($token,'-1001155301071', $source_ogg );
                    
                    //$dest_ogg = "./application/music/salam.ogg";
                    //$res = exec("ffmpeg -y -i $source_mp3 -ss 33 -to 39.40 -q:a 4 $dest_ogg 2>&1");
                    //$file_exict = glob("./application/music/*.ogg");
                    if(file_exists( $source_ogg )){
                        //$send = $this->telegram_model->send_voice_online($token,$chatid1,$source_ogg,$lastpost,"@VieraMagazine");
                        //$text = "<pre><code class=\"language-$ar1[$num1]\">.</code></pre>";
                        $send = $this->telegram_model->send_audio_online($token,$chatid1,"@VieraBot\n@VieraMagazine$text",$source_ogg,"@VieraMagazine","@VieraBot",$lastpost);
                        //$send = $this->telegram_model->send_audio_online($token,'-1001155301071',"@VieraBot\n@VieraMagazine$text",$source_ogg,"@VieraMagazine","@VieraBot",$lastpost);
                        //$send = json_decode($send,true);
                        //$this->telegram_model->send_message_only($token,'-1001155301071', $send['result']['caption_entities'][0]['language'] );
                        //$send = $this->telegram_model->send_audio_online($token,$chatid1,"@VieraMagazine",$source_ogg,"@VieraMagazine","@VieraBot",$lastpost);
                    }else{
                        //$source_ogg = "./application/music/".$ar1[$num1]."2.mp3";
                        //$msend = $this->telegram_model->send_audio_online($token,$chatid1,"@VieraMagazine",$source_ogg,"@VieraMagazine","@VieraBot",$lastpost);
                        //$send = $this->telegram_model->send_voice_online($token,$chatid1,$source_ogg,$lastpost,"@VieraMagazine");
                    }
                    
                }else{
                    goto rand;
                }
                /*$ar1 = explode(",",$answer1[$indexPercent]->answer);
                $ar2 = explode(",",$answer1[$indexPercent]->emojiset);
                $num1 = mt_rand(0,count($ar1)-1);
                $num2 = mt_rand(0,count($ar2)-1);
                $string = $ar1[$num1].json_decode($ar2[$num2],true);
                //$this->telegram_model->send_message_only($token,'-1001155301071', $newPercent );
                //$this->telegram_model->send_message_only($token,'-1001155301071', $indexPercent );
                $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$string);
                exit;*/
                /*if( $send_st[ok] != 1 ){
                    $this->telegram_model->send_message_only($token,'-1001155301071', $chatname1."\n".$chatid1."---\n".$message."---\n" );
                }*/
            }
        }
    }
    //$this->telegram_model->send_message_only($token,'-1001155301071', $send );
    if(strpos($send,"false") > 0 && strpos($send,"Bad Request") > 0 && strpos($send,"message text is empty") > 0){
        if($chatid1 != '-1001155301071' /*$user_id != '53853580'*/){
            //$this->telegram_model->send_message_only($token,'-1001155301071',$chatid1."\n".$chatname1);
            $this->telegram_model->send_message_only($token,'-1001426543615',"جواب اینو نداشتم: \n*&\n".$message);
        } 
    }
}

similar_text($message,"خداحافظ",$percent6);
similar_text($message,"بای",$percent7);
similar_text($message,"خدافز",$percent8);
similar_text($message,"باعی",$percent9);
similar_text($message,"بای بای",$percent10);

if( ($percent6 > 91 || $percent7 > 91 || $percent8 > 91 || $percent9 > 91 || $percent10 > 91) && strlen($repl_to_uid) === 0 ){
     
    $ans = ['برو به سلامت🌺✋','دیر نکنی😉','موازبت خودت باش🌺🌺','از کنار برو، دست مامان رو هم ول نکن😉😐','نه که خیلی چت کردی زودم برو😐😏😒',
'بای هانی😘✋','بالاخره هر اومدنی یه رفتنی داره🙁🙁','خدافزی✋','بودی حالا'];

    $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$ans[mt_rand(0,8)] );
   
}

//****************************************************************************** آب و هوا

if($percent_viera1 == 100 && strpos($message,"ویرا") == 0 &&( strpos($message,"آب") > 0 || strpos($message,"اب") > 0 )&& strpos($message,"هوا") > 0){
    //$this->telegram_model->send_message_only($token,'-1001155301071',$percent_viera2 );
    if(strpos($message,"هوا") - strpos($message,"آب") < 10 || strpos($message,"هوا") - strpos($message,"اب") < 10){
        $message = str_ireplace("ویرا","",$message);
        $message = str_ireplace("آب و هوای","",$message);
        $message = str_ireplace("آب وهوای","",$message);
        $message = str_ireplace("اب و هوای","",$message);
        $message = str_ireplace("اب وهوای","",$message);
        $message = str_ireplace("آب و هوا","",$message);
        $message = str_ireplace("آب وهوا","",$message);
        $message = str_ireplace("اب و هوا","",$message);
        $message = str_ireplace("اب وهوا","",$message);
        $city = trim($message);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$city );
        $url = "https://api.openweathermap.org/data/2.5/weather?q=$city&units=metric&appid=020cb54a184e7d6012e09e8607b54a99";
        //$url2 = "https://api.openweathermap.org/data/2.5/onecall?lat=35.6944&lon=51.4215&units=metric&exclude=daily&appid=020cb54a184e7d6012e09e8607b54a99";
        //$this->telegram_model->send_message_only($token,'-1001155301071',$url );
        $info_weather = file_get_html($url);
        $test = file_get_html($url)->plaintext;
        $weather = json_decode($info_weather, true);
        //$res = $this->telegram_model->send_message_only($token,$chatid1,$test );
        //$this->telegram_model->send_message_only($token,$chatid1,$res );
        $name = trim($weather['name']);
        if(strlen($name) == 0){
            $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه این شهر در اطلاعات من موجود نیست" );
        }else{
            $name1 = "<b>$name</b>";
            //$this->telegram_model->send_message_only($token,$chatid1,$name );
            $text = "<a href=\"tg://user?id=".$newmember[0]->id."\" >".$newmember[0]->first_name."</a>";
            $lat = $weather['coord']['lat'];
            $lon = $weather['coord']['lon'];
            //$this->telegram_model->send_message_only($token,$chatid1,$lat );
            $name_link = "<a href= 'https://www.google.com/maps/@36.307500909659346, 59.595239271947456' > ".$name1.'</a>';
            $name_link = "<a href= '#' > ".$name1.'</a>';
            $sky = trim($weather['weather'][0]['description']);
            if($sky == "Clouds"){
                $sky = "ابری ☁️";
            }elseif($sky == "few clouds"){
                $sky = "کمی ابری ☁️";
            }elseif($sky == "overcast clouds"){
                $sky = "ابری ☁️";
            }elseif($sky == "scattered clouds"){
                $sky = "ابر پراکنده ☁️";
            }elseif($sky == "broken clouds"){
                $sky = "ابر پراکنده ☁️";
            }elseif($sky == "clear sky"){
                $sky = "صاف ☀️";
            }elseif($sky == "Rain"){
                $sky = "بارانی 🌧";
            }elseif($sky == "light rain"){
                $sky = "باران کم 🌧";
            }elseif($sky == "Snow"){
                $sky = "برفی 🌨";
            }elseif($sky == "Mist"){
                $sky = "غبارآلود 🌫";
            }elseif($sky == "dust"){
                $sky = "گرد و خاک 🌫";
            }elseif($sky == "sand"){
                $sky = "گرد و خاک 🌫";
            }elseif($sky == "haze"){
                $sky = "مه آلود 🌫";
            }
            $sky = trim($sky);
            $temp = trim($weather['main']['temp']);
            $min_temp = trim($weather['main']['temp_min']." 🔻");
            $max_temp = trim($weather['main']['temp_max']." 🔺");
            $pressure = trim($weather['main']['pressure']." اتمسفر 🧭");
            $humidity = trim($weather['main']['humidity']." % 💦");
            $visibility = $weather['visibility'];
            $visibility = trim(round($visibility/1000)." کیلومتر");
            $windSpeed = trim($weather['wind']['speed']." 💨");
            
            $windDeg = trim($weather['wind']['deg']);
            if($windDeg == 0){
                $wdir = "شمال";
            }elseif($windDeg == 90){
                $wdir = "شرق";
            }elseif($windDeg == 180){
                $wdir = "جنوب";
            }elseif($windDeg == 270){
                $wdir = "غرب";
            }elseif($windDeg > 0 && $windDeg < 90){
                $wdir = "شمال شرق";
            }elseif($windDeg > 90 && $windDeg < 180){
                $wdir = "جنوب شرق";
            }elseif($windDeg > 180 && $windDeg < 270){
                $wdir = "جنوب غرب";
            }elseif($windDeg > 270 && $windDeg < 360){
                $wdir = "شمال غرب";
            }
            //$dt = $dt['wind']['deg'];
            $offset = trim($weather['timezone']);
            $lat = trim($weather['coord']['lat']);
            $lon = trim($weather['coord']['lon']);
            if(trim($weather['sys']['country']) == "IR"){
                $minus = 3600;
            }else{
                $minus = 0;
            }
            $timeInfo = file_get_contents("https://api.timezonedb.com/v2.1/get-time-zone?key=FZYE7ZNIF4P8&format=json&by=position&lat=$lat&lng=$lon");
            $json_content = json_decode($timeInfo, true);
            $country = $json_content['countryName'];
            $region = $json_content['regionName'];
            $city = $json_content['cityName'];
            $zone = $json_content['zoneName'];
            $zone = str_ireplace("\/","/",$zone);
            $offset = $json_content['gmtOffset'];
            $sunRise = $this->persiandate->jdate("H:i:s",$weather['sys']['sunrise'],"",$zone,"fa");
            $sunSet = $this->persiandate->jdate("H:i:s",$weather['sys']['sunset'],"",$zone,"fa");
            $time_now = $this->persiandate->jdate("H:i:s",$weather['sys']['sunrise']-$offset,"",$zone,"fa");
            $sunrise = trim($sunRise)." 🌞";
            $sunset = trim($sunSet)." 🌚";
            
            //$text = "نام شهر: $name_link - $city \n\n آسمان: $sky \n دمای فعلی: $temp \n حداکثر دما: $max_temp \n حداقل دما: $min_temp \n فشار هوا: $pressure \n رطوبت هوا: $humidity \n دید افقی: $visibility \n سرعت باد: $windSpeed \n جهت باد: $windDeg  $wdir \n طلوع خورشید: $sunrise \n غروب خورشید: $sunset \n\n @VieraBot\n@VieraMagazine";
            $text = "کشور: $country\nنام شهر: $name_link - $city \n\n آسمان: $sky \n دمای فعلی: $temp درجه \n فشار هوا: $pressure \n رطوبت هوا: $humidity \n دید افقی: $visibility \n سرعت باد: $windSpeed \n جهت باد: $wdir \n طلوع خورشید: $sunrise \n غروب خورشید: $sunset \n\n @VieraBot\n@VieraMagazine";
            //$text = "نام شهر: $name_link - $city \n\n آسمان: $sky \n دمای فعلی: $temp درجه \n فشار هوا: $pressure \n رطوبت هوا: $humidity \n دید افقی: $visibility \n سرعت باد: $windSpeed \n جهت باد: $wdir  \n\n @VieraBot\n@VieraMagazine";
            $text = $this->telegram_model->toPersianNum($text);
            $this->telegram_model->send_location($token,$chatid1,$lat,$lon,"$city - $name","نقشه");
            $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$text);
            //$this->telegram_model->send_message_only($token,$chatid1,$text );
            $html->clear();
            unset($html);
        }
    }
    $this->telegram_model->send_message_only($token,'-1001155301071',"آب و هوا ارسال شد" );
}

//******************************************************************************  اخبار

if($message === "اخبار سینما"){
    /*$this->telegram_model->send_message_only($token,$chatid1,"این سرویس در حال بروز رسانی است. متاسفانه در حال حاضر امکان استفاده از این سرویس نیست");
    die();*/
    $member = $this->telegram_model->get_member2($token,$user_id,"@VieraMagazine");
    if($member== "creator" || $member== "administrator" || $member== "member"){
        $last_news = $this->telegram_model->get_post_sent(1);
        //$this->telegram_model->send_message_only($token,$chatid1,$last_news[0]->last_post_id );
        $this->telegram_model->send_message_only($token,'-1001155301071',"اخبار سینما ارسال شد");
    
        $rexult = $this->telegram_model->forward($token,"@CinemaCenterNews",$last_news[0]->last_post_id,$chatid1);
        $rexult = $this->telegram_model->forward($token,"@CinemaCenterNews",($last_news[0]->last_post_id)-1,$chatid1);
        //$this->telegram_model->send_message($token,$id,$text,$keyboard);
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"برای استفاده از این سرویس باید در کانال مجله ویرا @VieraMagazine عضو باشید");
    }
}

// بررسی اینکه آیا پیام با "ویرا فیلم" شروع می‌شود یا خیر
if (mb_strpos($message, "ویرا فیلم") === 0) {
    $movieName = trim(mb_substr($message, 9)); 

    if (!empty($movieName)) {
        // فراخوانی متد TMDB
        $movie = $this->telegram_model->get_movie_info_tmdb($movieName);

        if ($movie) {
            $text = "🎬 *{$movie['title']}* ({$movie['year']})\n\n";
            $text .= "⭐️ امتیاز: " . $this->telegram_model->toPersianNum($movie['rating']) . " / 10\n\n";
            $text .= "📝 *خلاصه داستان:*\n" . $movie['plot'] . "\n\n";
            $text .= "🆔 @VieraBot";

            if (!empty($movie['poster'])) {
                $this->telegram_model->send_photo($token, $chatid1, $movie['poster'], $text);
            } else {
                $this->telegram_model->send_message_only($token, $chatid1, $text);
            }
        } else {
            $this->telegram_model->send_message_only($token, $chatid1, "❌ فیلمی با عنوان '$movieName' پیدا نشد.");
        }
    }
}

// تشخیص دستور ویرا دانلود فیلم
if (mb_strpos($message, "ویرا دانلود فیلم") === 0) {
    $movieName = trim(mb_substr($message, 16)); 

    if (!empty($movieName)) {
        $downloadLinks = $this->telegram_model->findDownloadLinks($movieName);

        if (!empty($downloadLinks)) {
            $text = "📂 *نتایج یافت شده برای:* \n🎬 `$movieName` \n";
            $text .= "────────────────\n\n";
            
            foreach ($downloadLinks as $index => $link) {
                $num = $this->telegram_model->toPersianNum($index + 1);
                
                // تمیز کردن عنوان برای نمایش
                $displayTitle = preg_replace('/\s+/', ' ', $link['title']);
                if(mb_strlen($displayTitle) > 55) $displayTitle = mb_substr($displayTitle, 0, 52) . "...";

                $text .= "$num - " . trim($displayTitle) . "\n";
                $text .= "🔗 لینک مشاهده: " . $link['url'] . "\n\n";
            }
            
            $text .= "────────────────\n";
            $text .= "🆔 @VieraBot";
            $this->telegram_model->send_message_only($token, $chatid1, $text);
        } else {
            $this->telegram_model->send_message_only($token, $chatid1, "❌ نتیجه دقیقی برای `$movieName` یافت نشد.");
        }
    }
}

//****************************************************************************** قیمت ارز
/*if($message == 'ویرا ارز آزاد'){
    $this->telegram_model->send_message_only($token,'-1001155301071', "here vaz");
    $this->telegram_model->send_message_only($token,'-1001155301071', $chatid1);
    //$fileMtime = jdate ("F d Y H:i:s.", filemtime("./application/NewArz.txt"));
    $fileMtimeDay = $this->persiandate->jdate("d",filemtime("./application/NewArz.txt"),"",'Asia/Tehran',"en");
    $today = $this->persiandate->jdate("d",time(),"",'Asia/Tehran',"en");
    $this->telegram_model->send_message_only($token,'-1001155301071', $fileMtimeDay);
    $this->telegram_model->send_message_only($token,'-1001155301071', $today);
    $text = file_get_contents("./application/NewArz.txt");
    $res = $this->telegram_model->send_message_only($token,$chatid1, $text."\n\n@VieraBot\n@VieraMagazine");
    $this->telegram_model->send_message_only($token,'-1001155301071', $res);
}*/
if($message == 'ویرا ارز12'){
    $this->telegram_model->send_message_only($token,'-1001155301071', "صبر کنید");
    //ini_set('max_execution_time', 10);
    $text = "بدلیل نوسانات زیاد بازار، قیمت‌ها مشخص نمی‌باشد. به زودی با اطلاعات دقیق در خدمت خواهم بود 🙏";
    //$arz = $this->telegram_model->send_message_only($token,$chatid1,$text );
        
    /*$html = file_get_html('https://www.iranjib.ir/showgroup/23/realtime_price/');
    $title = $html->find('.items_table');
    $row = $html->find('.items_table',2)->find('tr');
    $td = $html->find('.items_table tr td');
    //$tablo1_onc .= $row[5]->plaintext." ==> ".trim($row[22]->plaintext)."\n";
        
        $row = $html->find('.items_table',0)->find('tr');
        $this->telegram_model->send_message_only($token,'-1001155301071', "count: ".count($title));
        for($i=0; $i<count($row)-1; $i+=2){
            if($i==0){
                $arz_list .= $title[0]->children($i)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[0]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[0]->children($i)->children(1)->plaintext;
            }
            
            if(strlen($tablo1_1)>0)
            //$this->telegram_model->send_message_only($token,'-1001155301071',$tablo1_1."-".(trim($tablo1_2)) );
            $arz_list .= trim($tablo1_1)." ==> ".trim($tablo1_2)."\n";
        }
        $tablo1_1 ="";
        $row = $html->find('.items_table',1)->find('tr');
        for($i=0; $i<count($row); $i+=2){
            if($i==0){
                $arz_list .= "\n----------------------\n";
                $arz_list .= $title[1]->children($i)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[1]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[1]->children($i)->children(1)->plaintext;
            }
            if(strlen($tablo1_1)>0)
            $arz_list .= $tablo1_1." ==> ".$tablo1_2."\n";
        }
        $tablo1_1 ="";
        $row = $html->find('.items_table',2)->find('tr');
        for($i=0; $i<count($row); $i+=2){
            if($i==0){
                $arz_list .= "\n----------------------\n";
                $arz_list .= $title[2]->children(0)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[2]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[2]->children($i)->children(1)->plaintext;
            }
            if(strlen($tablo1_1)>0)
            $arz_list .= $tablo1_1." ==> ".$tablo1_2."\n";
        }
        $tablo1_1 ="";
        $row = $html->find('.items_table',4)->find('tr');
        
        for($i=0; $i<count($row); $i+=2){
            if($i==0){
                $arz_list .= "\n----------------------\n";
                $arz_list .= $title[4]->children(0)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[4]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[4]->children($i)->children(1)->plaintext;
            }
            if(strlen($tablo1_1)>0)
            $arz_list .= $tablo1_1." ==> ".$tablo1_2."\n";
        }
        $tablo1_1 ="";
        $row = $html->find('.items_table',5)->find('tr');
        for($i=0; $i<count($row); $i+=2){
            if($i==0){
                $arz_list .= "\n----------------------\n";
                $arz_list .= $title[5]->children(0)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[5]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[5]->children($i)->children(1)->plaintext;
            }
            if(strlen($tablo1_1)>0)
            $arz_list .= $tablo1_1." ==> ".$tablo1_2."\n";
        }
        $tablo1_1 ="";
        $row = $html->find('.items_table',7)->find('tr');
        //$this->telegram_model->send_message_only($token,'-1001155301071',"this this: ".count($row) );
        for($i=0; $i<count($row); $i+=2){
            if($i==0){
                $arz_list .= "\n----------------------\n";
                $arz_list .= $title[7]->children(0)->plaintext."\n\n";
            }else{
                $tablo1_1 = $title[7]->children($i)->children(0)->plaintext;
                $tablo1_2 = $title[7]->children($i)->children(1)->plaintext;
            }
            if(strlen($tablo1_1)>0)
            $arz_list .= $tablo1_1." ==> ".$tablo1_2."\n";
        }
    
    $arz_list = str_replace(" / ","",$arz_list);
    $arz_list = str_replace("    "," ",$arz_list);
    $arz_list = str_replace("  هر","هر",$arz_list);
    $arz_list = str_ireplace("Bitcoin","",$arz_list);
    $arz_list = str_ireplace("Ethereum","",$arz_list);
    $arz_list = str_ireplace("Litecoin","",$arz_list);
    $arz_list = str_ireplace("Ripple","",$arz_list);
    $arz_list = str_ireplace("عیار","",$arz_list);
    $arz_list = str_ireplace("در بازار تهران","",$arz_list);
    $arz_list = str_ireplace("شاخص کل بورس تهران","شاخص بورس ",$arz_list);    
    $arz_list = html_entity_decode($arz_list);
    //$arz = $this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر سیستم دریافت قیمت ارز اختلال دارد. لطفا بعدا امتحان کنید" );
    $arz = $this->telegram_model->send_message_only($token,$chatid1,$arz_list."\n@VieraMagazine" );
    $this->telegram_model->send_message_only($token,'-1001155301071',"قیمت ارز ارسال شد" );*/
    //$this->telegram_model->send_message_only($token,'-1001155301071',$arz );
    //$tablo1_onc = $title[0]->children(6)->children(2)->plaintext;
    //$arz = $this->telegram_model->send_message_only($token,'-1001155301071',$tablo1_onc );
    
        /*$arz = $this->telegram_model->send_message_only($token,'-1001155301071',count($row) );
        
        for($i=0; $i<count($td); $i++){
            if( strpos($td[$i]->plaintext,"%") ){
                $i += 4;
                continue;
                
            }else{
                $tablo1 .= $td[$i]->plaintext."\n";
                
            }
            
        }
    $tablo1 = str_ireplace("تهران","",$tablo1);
    $tablo1 = str_ireplace("
   ","==> ",$tablo1);
    $arz = $this->telegram_model->send_message_only($token,'-1001155301071',$tablo1 );*/
        
    //$fileMtime = date ("F d Y H:i:s.", filemtime("./application/NewArz.txt"));
    $fileMtimeDay = $this->persiandate->jdate("d",filemtime("./application/NewArz.txt"),"",'Asia/Tehran',"en");
    $today = $this->persiandate->jdate("d",time(),"",'Asia/Tehran',"en");
    if($fileMtimeDay == $today){
        $text = file_get_contents("./application/NewArz.txt");
        $text = $this->telegram_model->toPersianNum($text);
        $res = $this->telegram_model->send_message_only($token,$chatid1, "نرخ بازار آزاد\n\n".$text."\n\n@VieraBot\n@VieraMagazine");
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"قیمت‌های بازار آزاد بروزرسانی نشده. \nارسال نشد");
    }
    
}

if(mb_substr($message,0,14) == "ویراارزدیجیتال" || mb_substr($message,0,15) == "ویراارز دیجیتال" || mb_substr($message,0,16) == "ویرا ارز دیجیتال"/*$message == "ویرا ارز دیجیتال"*/){
    if(mb_strpos($message,"-") > 0){
        $input = trim(explode("-",$message)[1]);
        $currs = ["$input"];
    }else{
        $currs = ["btc","usdt","eth"];
    }
    for($i = 0; $i < count($currs); $i++){
        $res = $this->telegram_model->get_digcur($currs[$i]);
        $info = json_decode($res, true);
        $thisName = $currs[$i];
        $bestSell = $this->telegram_model->toPersianNum(number_format($info['stats']["$thisName-rls"]["bestSell"]));
        $bestBuy = $this->telegram_model->toPersianNum(number_format($info['stats']["$thisName-rls"]["bestBuy"]));
        $dayLow = $this->telegram_model->toPersianNum(number_format($info['stats']["$thisName-rls"]["dayLow"]));
        $dayHigh = $this->telegram_model->toPersianNum(number_format($info['stats']["$thisName-rls"]["dayHigh"]));
        $text = "اطلاعات #".$currs[$i]."\n\n";
        $text .= "بهترین فروش: ".$bestSell." ریال\n";
        $text .= "بهترین خرید: ".$bestBuy." ریال\n";
        $text .= "کمترین قیمت: ".$dayLow." ریال\n";
        $text .= "بیشترین قیمت: ".$dayHigh." ریال\n";
        $this->telegram_model->send_message_only($token,$chatid1,$text);
        //$this->telegram_model->send_message_only($token,$chatid1,"بهترین فروش: ".$bestSell." ریال");
        //$this->telegram_model->send_message_only($token,$chatid1,"بهترین خرید: ".$bestBuy." ریال");
        //$this->telegram_model->send_message_only($token,$chatid1,"کمترین قیمت: ".$dayLow." ریال");
        //$this->telegram_model->send_message_only($token,$chatid1,"بیشترین قیمت: ".$dayHigh." ریال");
    }
    
    //$res = $this->telegram_model->toPersianNum($res);
    
    
}

if($message == "ویرا ارز"){
    $all_prices = $this->telegram_model->get_tgju_all_data();
    
    if (is_array($all_prices)) {
        $text = "💰 *گزارش کامل بازار* 💰\n\n";

        // --- بخش طلا ---
        $text .= "🔸 *طلا*\n\n";
        $gold_ids = ['geram18', 'geram24', 'mesghal', 'gold_second_hand'];
        foreach($gold_ids as $id) {
            if(isset($all_prices[$id])) {
                $all_prices[$id]['name'] = str_ireplace(" عیار ","",$all_prices[$id]['name']);
                $all_prices[$id]['name'] = str_ireplace("عیار","",$all_prices[$id]['name']);
                $all_prices[$id]['name'] = $this->telegram_model->toPersianNum($all_prices[$id]['name']);
                $text .= "🔹 " . $all_prices[$id]['name'] . " : " . $this->telegram_model->toPersianNum($all_prices[$id]['price']) . "\n";
            }
        }

        // --- بخش سکه ---
        $text .= "\n🪙 *سکه*\n\n";
        $coin_ids = ['sekee', 'sekeb', 'nim', 'rob', 'gerami']; // شناسه‌های معروف سکه
        foreach($coin_ids as $id) {
            if(isset($all_prices[$id])) {
                $text .= "🔹 " . $all_prices[$id]['name'] . " : " . $this->telegram_model->toPersianNum($all_prices[$id]['price']) . "\n";
            }
        }

        // --- بخش ارز (۱۰ تای اول) ---
        $text .= "\n💵 *ارز*\n\n";
        $count = 0;
        foreach ($all_prices as $id => $data) {
            if ($data['type'] == 'currency' && $count < 30) {
                $text .= "🔹 " . $data['name'] . " : " . $this->telegram_model->toPersianNum($data['price']) . "\n";
                $count++;
            }
        }

        $text .= "\n⏰ " . date("H:i");
        $this->telegram_model->send_message_only($token, $chatid1, $text);
    }
}

//***************************************************************************************** حذف لینک
if($chatid1 == '-1002505974128'){
    $member = $this->telegram_model->get_member2($token,$user_id,'-1002505974128');
    //$this->telegram_model->send_message_only($token,$chatid1,$lastpost);
    if($member== "creator" || $member== "administrator"){
        $urlCap = getURLs($capt, $entities);
        $mentionCap = getmention($capt, $entities);
        $linkCap = getlink($capt, $entities);
        
        $capt = str_ireplace($mentionCap[0],"",$capt);
        $capt = str_ireplace($mentionCap[1],"",$capt);
        $capt = str_ireplace($urlCap[0],"",$capt);
        $capt = str_ireplace($urlCap[1],"",$capt);
        $capt = str_ireplace($linkCap[0],"",$capt);
        $capt = str_ireplace($linkCap[1],"",$capt);
            
        $capt = str_ireplace("پروکسی |","",$capt);
        $capt = str_ireplace("پروکسی","",$capt);
        $capt = str_ireplace("More Proxies :","",$capt);
        $capt = str_ireplace("  
   
   
   
   
","",$capt);

        $capt = str_ireplace("   
   
   
   ","",$capt);
        
        if($message_audio){
            $res = $this->telegram_model->send_audio($token,$chatid1,$capt,$message_audio);
        }elseif($message_photo){
            if(strlen($message_photo[2]->file_id) > 0){
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[2]->file_id,$capt);
            }elseif(strlen($message_photo[1]->file_id) > 0){
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[1]->file_id,$capt);
            }else{
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[0]->file_id,$capt);
            }
        }elseif($message_video){
            $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$message_video,$capt);
        }elseif($message_voice){
            $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$message_voice,$capt);
        }else{
            //$message_gif
            //$message_doc_type
            $res = $this->telegram_model->send_document_online($token,$chatid1,$message_gif,$capt);
        }
    }
    if($message_photo || $message_video || $message_audio || $message_gif || $message_voice)
    $p = $this->telegram_model->delete_message_one($token,$chatid1,$lastpost);
    //$this->telegram_model->send_message_only($token,$chatid1,$p);
}

if($chatid1 == '-1002744729720'){
    $member = $this->telegram_model->get_member2($token,$user_id,'-1002744729720');
    //$this->telegram_model->send_message_only($token,$chatid1,$lastpost);
    if($member== "creator" || $member== "administrator"){
        $urlCap = getURLs($capt, $entities);
        $mentionCap = getmention($capt, $entities);
        $linkCap = getlink($capt, $entities);
        
        $capt = str_ireplace($mentionCap[0],"",$capt);
        $capt = str_ireplace($mentionCap[1],"",$capt);
        $capt = str_ireplace($urlCap[0],"",$capt);
        $capt = str_ireplace($urlCap[1],"",$capt);
        $capt = str_ireplace($linkCap[0],"",$capt);
        $capt = str_ireplace($linkCap[1],"",$capt);
            
        $capt = str_ireplace("پروکسی |","",$capt);
        $capt = str_ireplace("پروکسی","",$capt);
        $capt = str_ireplace("More Proxies :","",$capt);
        $capt = str_ireplace("  
   
   
   
   
","",$capt);

        $capt = str_ireplace("   
   
   
   ","",$capt);
        
        if($message_audio){
            $res = $this->telegram_model->send_audio($token,$chatid1,$capt,$message_audio);
        }elseif($message_photo){
            if(strlen($message_photo[2]->file_id) > 0){
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[2]->file_id,$capt);
            }elseif(strlen($message_photo[1]->file_id) > 0){
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[1]->file_id,$capt);
            }else{
                $res = $this->telegram_model->send_photo($token,$chatid1,$message_photo[0]->file_id,$capt);
            }
        }elseif($message_video){
            $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$message_video,$capt);
        }elseif($message_voice){
            $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$message_voice,$capt);
        }else{
            //$message_gif
            //$message_doc_type
            $res = $this->telegram_model->send_document_online($token,$chatid1,$message_gif,$capt);
        }
    }
    if($message_photo || $message_video || $message_audio || $message_gif || $message_voice)
    $p = $this->telegram_model->delete_message_one($token,$chatid1,$lastpost);
    //$this->telegram_model->send_message_only($token,$chatid1,$p);
}
if($repl_to_uid && $message == "حذف لینک"){
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $member = $this->telegram_model->get_member2($token,$user_id,"@VieraMagazine");
    $type = json_decode($type, true);
    if($chatid1 == '-1001155301071' || $type['result']['type'] == "private"){
        if($member== "creator" || $member== "administrator" || $member== "member"){
            //$this->telegram_model->send_message_only($token,$chatid1,$member);
            if($repl_text){
                $url = getURLs($repl_text, $entities);
                $mention = getmention($repl_text, $entities);
                $link = getlink($repl_text, $entities);  
            }else{
                $url = getURLs($repl_caption, $entities);
                $mention = getmention($repl_caption, $entities);
                $link = getlink($repl_caption, $entities); 
            }
            if($repl_text){
                $repl_text = str_ireplace($mention[0],"",$repl_text);
                $repl_text = str_ireplace($mention[1],"",$repl_text);
                $repl_text = str_ireplace($url[0],"",$repl_text);
                $repl_text = str_ireplace($url[1],"",$repl_text);
                $repl_text = str_ireplace($link[0],"",$repl_text);
                $repl_text = str_ireplace($link[1],"",$repl_text);
                $this->telegram_model->send_message_only($token,$chatid1,$repl_text );
                $this->telegram_model->send_message_only($token,'-1001155301071',$repl_text );
            }else{
                $repl_caption = str_ireplace($mention[0],"",$repl_caption);
                $repl_caption = str_ireplace($mention[1],"",$repl_caption);
                $repl_caption = str_ireplace($url[0],"",$repl_caption);
                $repl_caption = str_ireplace($url[1],"",$repl_caption);
                $repl_caption = str_ireplace($link[0],"",$repl_caption);
                $repl_caption = str_ireplace($link[1],"",$repl_caption);
                if($repl_audio_fid){
                    $res = $this->telegram_model->send_audio($token,$chatid1,$repl_caption,$repl_audio_fid);
                    //$mid = json_decode($res, true)['result']['message_id'];
                    //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                    //$this->telegram_model->send_audio($token,'-1001155301071',$repl_caption,$repl_audio_fid);
                }elseif($repl_photo_fid){
                    if(strlen($repl_photo_fid[2]->file_id) > 0){
                        $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[2]->file_id,$repl_caption);
                        //$mid = json_decode($res, true)['result']['message_id'];
                        //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                        //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[2]->file_id,$repl_caption);
                    }elseif(strlen($repl_photo_fid[1]->file_id) > 0){
                        $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[1]->file_id,$repl_caption);
                        //$mid = json_decode($res, true)['result']['message_id'];
                        //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                        //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[1]->file_id,$repl_caption);
                    }else{
                        $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[0]->file_id,$repl_caption);
                        //$mid = json_decode($res, true)['result']['message_id'];
                        //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                        //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[0]->file_id,$repl_caption);
                    }
                }elseif($repl_video_fid){
                    $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$repl_video_fid,$repl_caption);
                    //$mid = json_decode($res, true)['result']['message_id'];
                    //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                    //$vidsend = $this->telegram_model->send_video_online($token,'-1001155301071',$repl_video_fid,$repl_caption);
                }elseif($repl_voice_fid){
                    $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$repl_voice_fid,$repl_caption);
                }else{
                    $res = $this->telegram_model->send_document_online($token,$chatid1,$repl_document_fid,$repl_caption);
                    //$mid = json_decode($res, true)['result']['message_id'];
                    //$this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
                    //$zxx = $this->telegram_model->send_document_online($token,'-1001155301071',$repl_document_fid,$repl_caption);
                }
            }
            if($chatid1 != '-1001155301071'){
                $mid = json_decode($res, true)['result']['message_id'];
                $this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
            }
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,"برای استفاده از این سرویس باید در کانال مجله ویر @VieraMagazine عضو باشید");
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"این سرویس فقط در پی وی من انجام میشود");
    }
    usleep(600);
}


//************************************************************************************************************ ویرایش پست

if($repl_to_uid && (substr($message,0,13) == "ویرایش:" || substr($message,0,14) == "ویرایش :" ) ){
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $member = $this->telegram_model->get_member2($token,$user_id,"@VieraMagazine");
    $type = json_decode($type, true);
    if($type['result']['type'] == "private" || $chatid1 == '-1001155301071'){
        if($member== "creator" || $member== "administrator" || $member== "member"){
            $edit_text = explode(":",$message);
            if(count($edit_text) > 2){
                $edit_text = trim($edit_text[1]).": ".$edit_text[2]." ".$edit_text[3]." ".trim($edit_text[4])." ".trim($edit_text[5]." ".trim($edit_text[6])." ".trim($edit_text[7])." ".trim($edit_text[8]));
            }else{
                $edit_text = trim($edit_text[1])." ".$edit_text[2];
            }
            
            if($repl_audio_fid){
                $res = $this->telegram_model->send_audio($token,$chatid1,$edit_text,$repl_audio_fid);
                //$this->telegram_model->send_audio($token,'-1001155301071',$edit_text,$repl_audio_fid);
            }elseif($repl_photo_fid){
                if(strlen($repl_photo_fid[2]->file_id) > 0){
                    $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[2]->file_id,$edit_text);
                    
                    //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[2]->file_id,$edit_text);
                }elseif(strlen($repl_photo_fid[1]->file_id) > 0){
                    $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[1]->file_id,$edit_text);
                    //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[1]->file_id,$edit_text);
                }else{
                    $res = $this->telegram_model->send_photo($token,$chatid1,$repl_photo_fid[0]->file_id,$edit_text);
                    //$this->telegram_model->send_photo($token,'-1001155301071',$repl_photo_fid[0]->file_id,$edit_text);
                }
            }elseif($repl_video_fid){
                $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$repl_video_fid,$edit_text);
                //$vidsend = $this->telegram_model->send_video_online($token,'-1001155301071',$repl_video_fid,$edit_text);
            }elseif($repl_voice_fid){
                $res = $vidsend = $this->telegram_model->send_video_online($token,$chatid1,$repl_voice_fid,$edit_text);
            }else{
                $res = $this->telegram_model->send_document_online($token,$chatid1,$repl_document_fid,$edit_text);
                //$this->telegram_model->send_document_online($token,'-1001155301071',$repl_document_fid,$edit_text);
            }
            if($chatid1 != '-1001155301071'){
                $mid = json_decode($res, true)['result']['message_id'];
                $this->telegram_model->forward($token,$chatid1,$mid,'-1001155301071');
            }
            
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,"برای استفاده از این سرویس باید در کانال مجله ویر @VieraMagazine عضو باشید");
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"این سرویس فقط در پی وی من انجام میشود");
    }
}

//****************************************************************************** downloader

/*if($message == 'zz'  && $chatid1 == '-1001155301071'){
    $groups_sent = $this->telegram_model->get_viera_group();
    $thisMessage = "متاسفانه برای برخی بروز رسانی‌ها از فردا بمدت 2 تا 3 روز فعالیت قطع میشود";
    //$this->telegram_model->send_message_only($token,'-1001155301071',count($groups_sent));
    for($i=0; $i < count($groups_sent); $i++){
        usleep(1000);
        $this->telegram_model->send_message_only($token,$groups_sent[$i]->group_id,$thisMessage);
        //$res = $this->telegram_model->edit_message_caption($token,'-1001155301071',139876,$thisMessage);
        //$p = $this->telegram_model->delete_message_one($token,$groups_sent[$i]->group_id,$thisMessage);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$p);
    }
    
}*/



if($repl_text){
    $message = $this->telegram_model->toEnglishNum($message);
    /*if($chatid1 != '-1001155301071' && $message == "دانلود"){
        $this->telegram_model->send_message_only($token,$chatid1,"درحال بروز رسانی هستیم. لطفا بعدا از این سیستم استفاده کنید" );
        die();
    }*/
    $join_info = $this->telegram_model->get_member2($token,$user_id,"@VieraMagazine");
    $url = getURLs($repl_text, $entities)[0];
    $mInfo = explode("-",$message);
     if($join_info != "member" && $join_info != "creator" && $join_info != "administrator" && $user_id != "53853580" && $user_id != "90575368" && $mInfo[0] == "دانلود" ){

        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"برای استفاده از این سرویس باید در کانال مجله ویرا @VieraMagazine عضو باشید");
        die();
    }
    if(strpos($url,"facebook.com") > 0){
        if(strlen($url) > 0 && $mInfo[0] == "دانلود"){
            $call_title = $mInfo[1];
            $call_capt = $mInfo[2];
            $cookies = "./application/facebook.txt";
            $source_del = "./application/$user_id";
            if(is_dir($source_del)){
                die();
            }else{
                $this->telegram_model->send_message_only($token,'-1001155301071',"لطفا کمی صبر کنید");
                exec("mkdir $source_del");
                $source = "./application/$user_id/source.mp4";
                $url = getURLs($repl_text, $entities)[0];
                //if(strpos($url,"watch?v=") > 0 || strpos($url,"hare/v/") > 0){
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"url: ".$url );
                        $down = exec("yt-dlp --write-info-json -f 'sd/hd' $url -o $source  2>&1");
                        //-f 'sd/b[height<=480]/hd' bv[vbr<700]+ba/bv[tbr<700]+ba/sd/hd 
                        //bv[vbr<300]+ba/bv[vbr<400]+ba/bv[vbr<500]+ba/bv[tbr<500]+ba
                        $this->telegram_model->send_message_only($token,'-1001155301071',"down: ".$down );
                //}
                //$down = exec("yt-dlp  -S '+res:480,ext:mp4,+size,+codec:avc:m4a' -o $source $url 2>&1");
                //$down = exec("yt-dlp --cookies $cookies -f '(bv[height<=360]+ba[asr<=44100])[vcodec!^=av01]' -S 'res:480,ext:mp4,+size,+codec:avc:m4a' $url 2>&1");
                $size = exec("du $source | cut -f1");
                $this->telegram_model->send_message_only($token,'-1001155301071',"size: ".$size );
                
                
                $info = file_get_contents("./application/$user_id/source.info.json");
                $info = json_decode($info, true);
                $duration_string = $info['duration_string'];
                $duration = $info['duration'];
                $artist = $info['artist'];
                $title = $info['title'];
                //$caption = $info['description'];
                //$result = exec("ffmpeg -i $sorc -vf 'scale=trunc(iw/3)*2:trunc(ih/3)*2' -crf 28 -preset veryfast $dest 2>&1");
                if($size < 50000){
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"here 1");
                    //$caption = "$caption\n\n@VieraBot";
                    //"-1001312951231"  videostack
                    $vidsend = $this->telegram_model->send_video($token,$chatid1,$source,"","",$caption);
                    //$vidsend = $this->telegram_model->send_video($token,"-1001312951231",$source,"","",$caption);
                    if($chatid1 != '-1001155301071'){
                        $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$source,"","",$caption);
                    }
                    //$this->telegram_model->send_message_only($token,'-1001155301071',$vidsend);
                }elseif($size < 200000){
                    $peace = $size / 45000;
                    $intsec = intval($peace);
                    $decimalsec = $peace- $intsec;
                    
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace - $intsec - $decimalsec");
                
                    $segTime = $duration / $peace;
                    
                    //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
                    
                    $change = exec("ffmpeg -i $source -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/facebt%03d.mp4 2>&1",$out);
                    
                    $list = glob("$source_del/facebt*.*");
                    for($i = 0; $i < count($list); $i++){
                        $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$caption);
                        //$vidsend2 = $this->telegram_model->send_video($token,"-1001312951231",$list[$i],"","",$caption);
                        if($chatid1 != '-1001155301071'){
                            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$caption);
                        }
                    }
                    //$this->telegram_model->send_message_only($token,'-1001155301071',$change);
                }else{
                    $this->telegram_model->send_message_only($token,'-1001155301071',"فایل شما بسیار حجیم تر از مقداری بود که ارسال شود");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"here 3");
                    /*unlink("../download/$user_id.mp4");
                    rename($source,"../download/$user_id.mp4");
                    $linkyou = "Https://tebresaneh.com/download/$user_id.mp4";
                    $linkbit = exec("curl -H 'Authorization: Bearer a3834ff6b93a19a419d6497f437a31a0062abed1' -H 'Content-Type: application/json' -X POST -d '{
                    \"long_url\": \"$linkyou\",
                    \"domain\": \"bit.ly\"
                    }' https://api-ssl.bitly.com/v4/shorten");
                    //$test = $this->telegram_model->get_short($url);
                    $linkJson = json_decode($linkbit, true);
                    $linkbit = $linkJson['link'];
                    $linkbit = $link = "<a href= '$linkbit'>"."لینک دانلود".'</a>';
                    $result_send = $this->telegram_model->send_message_only($token,$chatid1,$linkbit);*/
                }
                
                if(strpos($vidsend,"Too Large") > 0){
                    $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه فایل مورد نظر شما حجم بیشتر از حجم قابل ارسال توسط ربات‌های تلگرام دارد. لطفا از مدل زمانبندی با زمان مناسب استفاده کنید");
                }
            
                $result = exec("rm -rf $source_del");
                $text = "<a href='tg://user?id=".$user_id."'>User</a>";
                $this->telegram_model->send_message_only($token,'-1001155301071',"از فیسبوک دانلود شد\n$chatid1\n$firstname\n$user_id\n$text");

                //set_video_youtube($data);
                die();
                
            }
            
        }
    }
    elseif(strpos($url,"youtu") > 0){
        $ren = copy("./application/youtubecookies1.txt","./application/youtubecookies.txt");
        if(strlen($url) > 0 && $mInfo[0] == "دانلود صدا"){
            $source_del = "./application/$user_id";
            if(is_dir($source_del)){
                die();
            }else{
                $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
                exec("mkdir $source_del");
            }
            //$source = "./application/$user_id/source";
            $duration = exec("yt-dlp -w --write-info-json --print duration --skip-download --restrict-filenames --match-filters '!is_live' -f 'ba[filesize<50M]' -o '$source_del/%(title)s.%(ext)s' $url 2>&1");
            //--postprocessor-args 'ExtractAudio:-preset veryfast' -x --audio-format mp3
            if($duration < 1900){
                $down = exec("yt-dlp -w --write-info-json --embed-thumbnail -x --audio-format mp3 --match-filters '!is_live' -f 'ba[filesize<50M]' -o '$source_del/%(title)s.%(ext)s' $url 2>&1");
            }else{
                $down = exec("yt-dlp -w --write-info-json --embed-thumbnail --match-filters '!is_live' -f 'ba[filesize<50M][ext=m4a]/ba[filesize<50M][ext=webm]' -o '$source_del/%(title)s.%(ext)s' $url 2>&1");
            }
            //$this->telegram_model->send_message_only($token,'-1001155301071',"send aud res1: $down");
            //--restrict-filenames
            if(strpos($down,"format is not available") > 0){
                $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه فرمت این فایل با مشکل مواجه است و در حال حاضر امکان دریافت آن وجود ندارد");
            }
            
            $jsonFile = glob("$source_del/*.info.json")[0];
            
            //$ext = pathinfo($filename, PATHINFO_EXTENSION);
            
            $info = file_get_contents($jsonFile);
            $info = json_decode($info, true);
            $duration_string = $info['duration_string'];
            $duration = $info['duration'];
            $artist = $info['artist'];
            $title = $info['title'];
            //$caption = $info['description'];
            
            
            $source = glob("$source_del/*.{ogg,acc,m4a,oga,webm,mp3}",GLOB_BRACE)[0];
            $ren = copy($source,"$source_del/source.mp3");
            $source2 = "$source_del/source.mp3";
            $size = exec("du -h $source2 | cut -f1");
            $caption = "دانلود از یوتیوب توسط ربات ویرا\n\nحجم: $size\n\n@VieraBot";
            $sendAud = $this->telegram_model->send_audio_online($token,$chatid1,$caption,$source,"@VieraBot",$title);
            
            $result = exec("rm -rf $source_del");
            $text = "<a href='tg://user?id=".$user_id."'>User</a>";
            //$this->telegram_model->send_message_only($token,'-1001155301071',"از یوتیوب دانلود شد\n$chatid1\n$user_id\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"از یوتیوب دانلود شد\n$chatid1\n$user_id\n$username\n$firstname\n\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"$text");
            die();
        }
        elseif(strlen($url) > 0 && $mInfo[0] == "دانلود"){
            /*$cookies = "./application/youtubecookies.txt";
            $source_del = "./application/$user_id";
            //if($chatid1 != '-1001155301071'){
                //$this->telegram_model->send_message_only($token,$chatid1,"این سرویس در حال بروزرسانی است. لطفا بعدا از این سرویس استفاده کنید" );
                //die();
            //}
    
            if(is_dir($source_del)){
                //$exist = $this->telegram_model->get_youtube_timer2($url,$chatid1);
                //if($exist[0]->status == 0){
                    //$this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید. برای ارسال ویدئو با کیفیت مناسب کمی بیشتر زمان لازم است.");
                    //$data = array("status"=>1);
                    //$this->telegram_model->update_youtube_timer2($url,$chatid1,$data);
                //}
                die();
            }else{
                //$data = array("url"=>$url,"uid"=>$user_id,"time"=>time(),"chatid"=>$chatid1,"status"=>0);
                //$this->telegram_model->set_youtube_timer2($data);
                $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
                exec("mkdir $source_del");
            }
            $source = "./application/$user_id/source.mp4";
            $timeStart = $mInfo[1];
            $timeEnd = $mInfo[2];
            $time = "*$timeStart-$timeEnd";
            
            if(strlen($time) > 3){
                //$this->telegram_model->send_message_only($token,'-1001155301071',"time yut: $time");
                //$down = exec("yt-dlp --cookies $cookies --download-sections $time --throttled-rate 2000K -f 'b[filesize<45M]' -S '+res:720,ext:mp4,filesize:45M,+codec:avc:m4a' -o $source $url 2>&1");
                $down = exec("yt-dlp --cookies $cookies --write-info-json --download-sections $time -f 'b[ext=mp4][height<=480]/b[ext=mp4][height<=720]/bv[filesize<40M][ext=webm]+ba[filesize<5M][ext=m4a]/b[height<=480]' -o $source $url 2>&1");
            }else{
                //$this->telegram_model->send_message_only($token,'-1001155301071',"time yut: $time");
                //$down = exec("yt-dlp --cookies $cookies -w --throttled-rate 2000K -f 'b[filesize<45M]' -S '+res:720,ext:mp4,filesize:45M,+codec:avc:m4a'  -o $source $url 2>&1");
                if(strpos($url,"/shorts") > 0){
                    $down = exec("yt-dlp --cookies $cookies --write-info-json --match-filters '!is_live' -f 'b[height<=2160]/b[height<=1080]/bv[filesize<20M]+ba[filesize<5M]' --merge-output-format mp4  -o $source $url 2>&1");
                }else{
                    $down = exec("yt-dlp --cookies $cookies --write-info-json --match-filters '!is_live' -f 'b[ext=mp4][height<=480]/b[height<=480]/b[ext=mp4][height<=590]/bv[filesize<27M][ext=webm]+ba[filesize<3M][ext=m4a]/bv[filesize<37M][ext=webm]+ba[filesize<10M][ext=m4a]/b[ext=mp4][height<=720]/b[height<=720]/b[height<=1080]' --merge-output-format mp4 -o $source $url 2>&1");
                }
                
            }
            if(strpos($down,"format is not available") > 0){
                $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه فرمت این فایل با مشکل مواجه است و در حال حاضر امکان دریافت آن وجود ندارد");
            }
            //if(strpos($down,"format is not available") > 0){
                //$this->telegram_model->send_message_only($token,$chatid1,"متاسفانه خطایی در ارتباط با سرورهای یوتیوب پیش آمده. لطفا بعدا امتحان کنید");
            //}
            
            $size = exec("du $source | cut -f1");
            $this->telegram_model->send_message_only($token,'-1001155301071',"yout-down: $down");
            //$this->telegram_model->send_message_only($token,'-1001155301071',"yout-down: $size");
            $info = file_get_contents("./application/$user_id/source.info.json");
            $info = json_decode($info, true);
            $duration_string = $info['duration_string'];
            $duration = $info['duration'];
            $artist = $info['artist'];
            $title = $info['title'];
            //$caption = $info['description'];
        
            //$caption = $this->telegram_model->makeUrltoLink($caption);
            //if(mb_strlen($caption) > 1000){
                //$caption = mb_substr($caption,0,1000);
                //$caption = mb_substr($caption,0,mb_strrpos($caption,"\n"))."...";
            //}
            //preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $caption, $matches);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"email: count($matches[0])");
            //$this->telegram_model->send_message_only($token,'-1001155301071',"email: ".$matches[0][0]);
            //$caption = str_ireplace($matches[0][0],"",$caption);
            $up_date = $info['upload_date'];
            $tags = $info['tags'][0]."-".$info['tags'][1]."-".$info['tags'][2]."-".$info['tags'][3];
            $capt = "$url\n".$vsend['result']['video']['file_id']."\n$artist\n$title\n$duration\n$up_date\n$tags";
            $caption = "دانلود از یوتیوب توسط ربات ویرا\n\n@VieraBot";
            if($size < 50000){
                //$this->telegram_model->send_message_only($token,'-1001155301071',"here 1");
                //$caption = "$caption\n\n@VieraBot";
                //"-1001312951231"  videostack
                $vidsend = $this->telegram_model->send_video($token,$chatid1,$source,"","",$caption);
                //$vidsend = $this->telegram_model->send_video($token,"-1001312951231",$source,"","",$caption);
                if($chatid1 != '-1001155301071'){
                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$source,"","",$caption);
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',$vidsend);
            }elseif($size < 200000){
                if($duration > 5000){
                    $this->telegram_model->send_message_only($token,'-1001155301071',"this durat");
                    if($duration > 10000){
                        $peace = 13;
                    }elseif($duration > 8000){
                        $peace = 11;
                    }elseif($duration > 6000){
                        $peace = 9;
                    }elseif($duration > 4000){
                        $peace = 7;
                    }elseif($duration > 2000){
                        $peace = 5;
                    }else{
                        $peace = 3;
                    }
                }else{
                    if($size < 90000){
                        $peace = 2;
                    }elseif($size < 120000){
                        $peace = 3;
                    }elseif($size < 170000){
                        $peace = 4;
                    }else{
                        $peace = 5;
                    }
                }
                
                
                $segTime = $duration / $peace;
                $this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
                $this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
                $change = exec("ffmpeg -i $source -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/ytout%03d.mp4 2>&1",$out);
                $list = glob("$source_del/ytout*.*");
                for($i = 0; $i < count($list); $i++){
                    $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$caption);
                    //$vidsend2 = $this->telegram_model->send_video($token,"-1001312951231",$list[$i],"","",$caption);
                    if($chatid1 != '-1001155301071'){
                        $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$caption);
                    }
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',$change);
            }else{
                //$this->telegram_model->send_message_only($token,'-1001155301071',"here 3");
                unlink("../download/$user_id.mp4");
                rename($source,"../download/$user_id.mp4");
                $linkyou = "Https://tebresaneh.com/download/$user_id.mp4";
                $linkbit = exec("curl -H 'Authorization: Bearer a3834ff6b93a19a419d6497f437a31a0062abed1' -H 'Content-Type: application/json' -X POST -d '{
                \"long_url\": \"$linkyou\",
                \"domain\": \"bit.ly\"
                }' https://api-ssl.bitly.com/v4/shorten");
                //$test = $this->telegram_model->get_short($url);
                $linkJson = json_decode($linkbit, true);
                $linkbit = $linkJson['link'];
                $linkbit = $link = "<a href= '$linkbit'>"."لینک دانلود".'</a>';
                $result_send = $this->telegram_model->send_message_only($token,$chatid1,$linkbit);
            }
            
            //$dest = "./application/$user_id/dest-1234.mp4";
            //$result = exec("ffmpeg -i $source -vf 'scale=trunc(iw/3)*2:trunc(ih/3)*2' -crf 28 -preset veryfast $dest 2>&1");
            //$result_send = $this->telegram_model->send_message_only($token,'-1001155301071',$vidsend);
            
            $vsend = json_decode($vidsend, true);
            
            //$data = array("content"=>$vsend['result']['message_id']);
            //$this->telegram_model->update_temp(17,$data);
            
            
            //$ytv_temp = $this->telegram_model->get_temp(17);
            //$res = $this->telegram_model->edit_message_caption($token,'-1001155301071',$ytv_temp[0]->content,$capt);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"yout edit: $res");
            if(strpos($vidsend,"Too Large") > 0){
                $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه فایل مورد نظر شما حجم بیشتر از حجم قابل ارسال توسط ربات‌های تلگرام دارد. لطفا از مدل زمانبندی با زمان مناسب استفاده کنید");
            }
        
            $result = exec("rm -rf $source_del");
            $text = "<a href='tg://user?id=".$user_id."'>User</a>";
            //$this->telegram_model->send_message_only($token,'-1001155301071',"از یوتیوب دانلود شد\n$chatid1\n$user_id\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"از یوتیوب دانلود شد\n$chatid1\n$user_id\n$username\n$firstname\n\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"$text");
            //set_video_youtube($data);
            die();*/
            
            $cookies = "./application/youtubecookies.txt";
$source_del = "./application/$user_id";
$source = "$source_del/source.mp4";

if(is_dir($source_del)){
    // اگر پوشه وجود دارد ولی فایل نهایی نیست، یعنی فرآیند قبلی ناقص مانده؛ پاکسازی کن
    if(!file_exists($source)) exec("rm -rf $source_del");
    else die(); 
}

mkdir($source_del, 0777, true);
$this->telegram_model->send_message_only($token, $chatid1, "در حال دانلود ویدیو... لطفا منتظر بمانید.");

$timeStart = $mInfo[1];
$timeEnd = $mInfo[2];
$time = (strlen("*$timeStart-$timeEnd") > 3) ? "*$timeStart-$timeEnd" : "";

// دستور جدید: اولویت با فرمتی که خودش MP4 است و نیاز به ادغام ندارد (برای جلوگیری از ایجاد .part)
// اگر نبود، بهترین ویدیو و صدا را بگیر و با FFmpeg بچسبان
$format_string = "bestvideo[ext=mp4][height<=720][filesize<250M]+bestaudio[ext=m4a]/best[ext=mp4][height<=720]/best";

$dl_cmd = "yt-dlp --cookies $cookies --write-info-json --no-part --no-cache-dir ";
if ($time) $dl_cmd .= "--download-sections $time ";
$dl_cmd .= "-f \"$format_string\" --merge-output-format mp4 -o \"$source\" \"$url\" 2>&1";

$output = [];
exec($dl_cmd, $output);
$down_log = implode("\n", $output);

// بررسی وجود فایل نهایی
if(!file_exists($source)){
    // شانس آخر: دانلود با کمترین کیفیت ممکن بدون هیچ قید و شرطی
    exec("yt-dlp --cookies $cookies -f \"worst\" -o \"$source\" \"$url\"");
}

if(!file_exists($source)){
    $this->telegram_model->send_message_only($token, $chatid1, "خطا در دانلود. لطفا دوباره تلاش کنید.");
    $this->telegram_model->send_message_only($token, '-1001155301071', "Error Log ($user_id):\n" . substr($down_log, -500));
    exec("rm -rf $source_del");
    die();
}

// --- ادامه عملیات پارت‌بندی (همان کد قبلی با دقت بیشتر) ---

$sizeKB = exec("du -k \"$source\" | cut -f1");
$sizeMB = $sizeKB / 1024;

$infoFile = "$source_del/source.info.json";
$duration = 0;
if(file_exists($infoFile)){
    $infoData = json_decode(file_get_contents($infoFile), true);
    $duration = $infoData['duration'] ?? 0;
}

if ($sizeMB <= 48) {
    $this->telegram_model->send_video($token, $chatid1, $source, "", "", "دانلود مستقیم\n@VieraBot");
} else {
    $partsCount = ceil($sizeMB / 47);
    $segmentTime = ($duration > 0) ? floor($duration / $partsCount) : 60; // اگر دیتای تایم نبود، هر ۶۰ ثانیه ببر
    
    // استفاده از مسیر کامل FFmpeg برای اطمینان (معمولا در /usr/bin/ffmpeg)
    exec("ffmpeg -i \"$source\" -c copy -map 0 -segment_time $segmentTime -reset_timestamps 1 -f segment \"$source_del/part%03d.mp4\" 2>&1");
    
    $parts = glob("$source_del/part*.mp4");
    sort($parts);
    
    foreach($parts as $index => $partPath) {
        $pCaption = "بخش " . ($index + 1) . " از " . count($parts) . "\n@VieraBot";
        $this->telegram_model->send_video($token, $chatid1, $partPath, "", "", $pCaption);
    }
}

exec("rm -rf \"$source_del\"");
die();
            
        }
    }
    elseif(strpos($url,"instagram.com") > 0){//-------------------------- insta section
    
        if(strlen($url) > 0 && $mInfo[0] == "دانلود"){
            /*if($chatid1 != '-1001155301071'){
                $this->telegram_model->send_message_only($token,$chatid1,"درحال بروز رسانی هستیم. لطفا بعدا از این سیستم استفاده کنید" );
                die();
            }*/
            $sendCount = 0;
            if(mb_strpos($url,"ddinstagram") > 0 || gettype(mb_strpos($url,"ddinstagram")) == "integer"){
                $url = str_ireplace("ddinstagram","instagram",$url);
            }
            if(mb_strpos($url,"/?") > 0 || gettype(mb_strpos($url,"/?")) == "integer"){
                $url = substr($url,0,strpos($url,"/?"));
            }
            $dest_delet = "./application/$user_id";
            if(is_dir($dest_delet)){
                $diffTime = time()-filectime($dest_delet);
                if($diffTime > 70){
                    rmdir($dest_delet);
                    $result = exec("rm -rf $dest_delet");
                    exec("mkdir $dest_delet");
                }
                //die();
            }else{
                exec("mkdir $dest_delet");
            }
            $caption = "دانلود از اینستاگرام توسط ربات ویرا\n\n@VieraBot";
            $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
            $mediasend = "";
            $counterApi1 = $this->telegram_model->get_temp(18);
            $counterApi2 = $this->telegram_model->get_temp(19);
            $counterApi3 = $this->telegram_model->get_temp(22);
            $counterApi4 = $this->telegram_model->get_temp(23);
            if ($counterApi1[0]->content < 500) {
                $this->telegram_model->send_message_only($token, '-1001155301071', "insta = Api1");
            
                if ($counterApi1[0]->poet < time()) {
                    $poet = $counterApi1[0]->poet + 2592000;
                    $this->telegram_model->update_temp(18, array("content" => 0, "poet" => $poet));
                }
            
                $res = $this->telegram_model->get_insta($url);
                $res = json_decode($res, true);
            
                if (empty($res['messages']) && isset($res['data'])) {
                    $data = $res['data'];
                    $items = isset($data['carousel_media']) && !empty($data['carousel_media']) ? $data['carousel_media'] : [$data];
            
                    $max_items = 10;
                    $processed_count = 0;
            
                    foreach ($items as $index => $item) {
                        if ($processed_count >= $max_items) break;
            
                        $isVideo = ($item['is_video'] == "true" || $item['is_video'] === true || (isset($item['media_type']) && $item['media_type'] == 2));
                        $pk = $item['pk'] ?? ($index . time());
            
                        if ($isVideo) {
                            $video_url = "";
                            if (isset($item['video_versions']) && !empty($item['video_versions'])) {
                                $versions = $item['video_versions'];
                                $targetH = 480;
                                $closest = null;
                                $minDiff = null;
            
                                foreach ($versions as $v) {
                                    $h = (int)$v['height'];
                                    $diff = abs($h - $targetH);
                                    if ($minDiff === null || $diff < $minDiff) {
                                        $minDiff = $diff;
                                        $closest = $v;
                                    }
                                }
                                $video_url = $closest['url'];
                            } else {
                                $video_url = $item['video_url'] ?? "";
                            }
            
                            if ($video_url) {
                                $this->telegram_model->download_file($video_url, "$dest_delet/$pk.mp4");
                                $processed_count++; // افزایش شمارنده بعد از دانلود موفق
                            }
                        } else {
                            $img_url = $item['image_versions']['items'][0]['url'] ?? ($item['thumbnail_url'] ?? "");
                            if ($img_url) {
                                $this->telegram_model->download_file($img_url, "$dest_delet/$pk.jpg");
                                $processed_count++;
                            }
                        }
                    }
            
                    $vids = glob("$dest_delet/*.mp4");
                    $imgs = glob("$dest_delet/*.jpg");
                    $toSend = [];
            
                    if (count($vids) > 1) {
                        $inputFile = "$dest_delet/list.txt";
                        $totalSize = 0;
                        $listContent = "";
                        foreach ($vids as $v) {
                            $totalSize += filesize($v);
                            $listContent .= "file '" . basename($v) . "'\n";
                        }
            
                        if ($totalSize < 48 * 1024 * 1024) {
                            file_put_contents($inputFile, $listContent);
                            $out = "$dest_delet/final_combined.mp4";
                            exec("ffmpeg -f concat -safe 0 -i $inputFile -c copy $out 2>&1");
                            if (file_exists($out)) $toSend[] = $out;
                        } else {
                            $toSend = $vids;
                        }
                    } else {
                        $toSend = $vids;
                    }
            
                    foreach ($toSend as $file) {
                        if (!file_exists($file)) continue;
                        $currentSize = filesize($file);
            
                        if ($currentSize > 49 * 1024 * 1024) {
                            $peace = ceil($currentSize / (47 * 1024 * 1024));
                            $duration = (float)exec("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 " . escapeshellarg($file));
                            $segTime = $duration / $peace;
            
                            $pattern = $dest_delet . "/opt_part_%03d.mp4";
                            exec("ffmpeg -i " . escapeshellarg($file) . " -c copy -map 0 -f segment -segment_time $segTime -reset_timestamps 1 $pattern 2>&1");
            
                            $parts = glob($dest_delet . "/opt_part_*.mp4");
                            foreach ($parts as $p) {
                                $mediasend = $this->telegram_model->send_video($token, $chatid1, $p, "", "", $caption);
                                if ($chatid1 != '-1001155301071') $this->telegram_model->send_video($token, '-1001155301071', $p, "", "", $caption);
                                @unlink($p);
                            }
                        } else {
                            $mediasend = $this->telegram_model->send_video($token, $chatid1, $file, "", "", $caption);
                            if ($chatid1 != '-1001155301071') $this->telegram_model->send_video($token, '-1001155301071', $file, "", "", $caption);
                        }
                        @unlink($file);
                    }
            
                    foreach ($imgs as $img) {
                        $mediasend = $this->telegram_model->send_photo_online($token, $chatid1, $img, $caption);
                        @unlink($img);
                    }
            
                } else {
                    $this->telegram_model->send_message_only($token, '-1001155301071', "API 1 Error or Empty");
                }
            
                if (isset($mediasend)) {
                    $resObj = json_decode($mediasend, true);
                    if (isset($resObj['result']['message_id'])) {
                        $sendCount++;
                        $this->telegram_model->update_temp(18, array("content" => ($counterApi1[0]->content) + 1));
                        exec("rm -rf " . escapeshellarg($dest_delet));
                    }
                }
            }

            if($counterApi2[0]->content < 500 && $sendCount == 0){
                $this->telegram_model->send_message_only($token,'-1001155301071',"insta = Api2");
                
                if($counterApi1[0]->poet < time()){
                    $poet = $counterApi1[0]->poet + 2592000;
                    $data = array("content"=>0,"poet"=>$poet);
                    $this->telegram_model->update_temp(19,$data);
                }
            
                $res = $this->telegram_model->get_insta_2($url);
                $res = json_decode($res,true);
                
                if(isset($res['data']) && !empty($res['data'])){
                    $postData = $res['data'];
                    $mediaItems = isset($postData['carousel_media']) ? $postData['carousel_media'] : [$postData];
            
                    $maxItems = 10;
                    $processedCount = 0;
            
                    foreach($mediaItems as $mItem) {
                        if($processedCount >= $maxItems) break;
            
                        $pk = $mItem['pk'];
                        $isVideo = (isset($mItem['is_video']) && ($mItem['is_video'] == true || $mItem['is_video'] == "true"));
                        
                        if($isVideo){
                            $videoUrl = '';
                            if(!empty($mItem['video_versions'])){
                                $targetHeight = 480;
                                $closestVersion = null;
                                $minDiff = null;
            
                                foreach($mItem['video_versions'] as $version) {
                                    $currentHeight = (int)$version['height'];
                                    $diff = abs($currentHeight - $targetHeight);
            
                                    if ($minDiff === null || $diff < $minDiff) {
                                        $minDiff = $diff;
                                        $closestVersion = $version;
                                    }
                                }
                                $videoUrl = $closestVersion['url'];
                            } else {
                                $videoUrl = $mItem['video_url'] ?? '';
                            }
            
                            if($videoUrl){
                                $outFileName = "$dest_delet/$pk.mp4";
                                $this->telegram_model->download_file($videoUrl, $outFileName);
                                $processedCount++;
                            }
                        } else {
                            $imageUrl = !empty($mItem['image_versions']['items']) ? $mItem['image_versions']['items'][0]['url'] : ($mItem['thumbnail_url'] ?? '');
                            if($imageUrl){
                                $outFileName = "$dest_delet/$pk.jpg";
                                $this->telegram_model->download_file($imageUrl, $outFileName);
                                $processedCount++;
                            }
                        }
                    }
            
                    $downloaded_vids = glob("$dest_delet/*.mp4");
                    foreach($downloaded_vids as $vid_path) {
                        $size_kb = (int)exec("du -k $vid_path | cut -f1");
                        if($size_kb > 49152) { // آستانه 48 مگابایت
                            $p_name = pathinfo($vid_path, PATHINFO_FILENAME);
                            exec("ffmpeg -i $vid_path -c copy -map 0 -f segment -segment_size 47M -reset_timestamps 1 $dest_delet/{$p_name}_part%d.mp4");
                            unlink($vid_path); 
                        }
                    }
            
                    $insta_list_vid = glob("$dest_delet/*.mp4");
                    $insta_list_jpg = glob("$dest_delet/*.jpg");
            
                    if(count($insta_list_vid) > 0){
                        foreach($insta_list_vid as $vid){
                            $mediasend = $this->telegram_model->send_video($token, $chatid1, $vid, "", "", $caption);
                            if($chatid1 != '-1001155301071'){
                                $this->telegram_model->send_video($token, '-1001155301071', $vid, "", "", $caption);
                            }
                        }
                    } else {
                        foreach($insta_list_jpg as $img){
                            $mediasend = $this->telegram_model->send_photo_online($token, $chatid1, $img, $caption);
                        }
                    }
            
                    $resDecode = json_decode($mediasend, true);
                    $mid = $resDecode['result']['message_id'] ?? "";
                    
                    if(strlen($mid) > 0){
                        $sendCount++;
                        $updateData = array("content" => ($counterApi2[0]->content) + 1);
                        $this->telegram_model->update_temp(19, $updateData);
                        exec("rm -rf $dest_delet");
                    }
                } else {
                    $this->telegram_model->send_message_only($token,'-1001155301071',"API2 No Data");
                }
            }
            
            if($counterApi3[0]->content < 30 && $sendCount == 0){
                $this->telegram_model->send_message_only($token,'-1001155301071',"insta = Api3");
                if($counterApi1[0]->poet < time()){
                    $poet = $counterApi1[0]->poet + 86400;
                    $data = array("content"=>0,"poet"=>$poet);
                    $this->telegram_model->update_temp(22,$data);
                }
                $res = $this->telegram_model->get_insta_3($url);
                $res = json_decode($res,true);
                $message = $res['messages'];
                if(!isset($message) || strlen($message) == 0){
                    if(isset($res['Type']) && $res['Type'] == "Carousel"){
                        for($i = 0; $i < count($res['media']); $i++){
                            $ext = "";
                            if(strpos($res['media'][$i]['media'],"mp4") > 0){
                                $ext = "mp4";
                            }else{
                                $ext = "jpg";
                            }
                            $media = $res['media'][$i]['media'];
                            $outFileName = "$dest_delet/file$i.$ext";
                            $size = $this->telegram_model->download_file($media,$outFileName);
                            
                        }
                    }else{
                        $ext = "";
                        if(strpos($res['media'],"mp4") > 0){
                            $ext = "mp4";
                        }else{
                            $ext = "jpg";
                        }
                        
                        $media = $res['media'];
                        $outFileName = "$dest_delet/file.$ext";
                        $size = $this->telegram_model->download_file($media,$outFileName);
                    }
                    
                    $insta_list_vid = glob("$dest_delet/*.mp4");
                    $insta_list_jpg = glob("$dest_delet/*.jpg");
                    if(count($insta_list_vid) > 1){
                        $file_dest = $dest_delet."/file.mp4";
                        $file_org_size = 0;
                        $counter = 0;
                        for($z = 0; $z < count($insta_list_vid); $z++){
                            $srcFile = $insta_list_vid[$z];
                            $info_file1 = exec("du $srcFile | cut -f1");
                            $file_org_size += $info_file1;
                            if($file_org_size < 47000){
                                $file = "$dest_delet/input.txt";
                                $current = file_get_contents($file);
                                $fname = explode("/",$insta_list_vid[$z])[3];
                                $current .= "file '$fname'\n";
                                file_put_contents($file, $current);
                            }else{
                                $counter++;
                            }
                        }
                        
                        if($counter == 0){
                            $con = exec("ffmpeg -f concat -safe 0 -i $file -c copy $dest_delet/output.mp4 2>&1");
                            //$dec = exec("ffmpeg -i $dest_delet/output.mp4 -vcodec libx264 -crf 30 -preset veryfast $dest_delet/output1.mp4 2>&1");
                            //$this->telegram_model->send_message_only($token,'-1001155301071',$con);
                            $mediasend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output.mp4","","","$caption");
                            if($chatid1 != '-1001155301071'){
                                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',"$dest_delet/output.mp4","","",$caption);
                            }
                            //$vidsend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output1.mp4","","","test");
                        }else{
                            for($z = 0; $z < count($insta_list_vid); $z++){
                                $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[$z],"","","$caption");
                                if($chatid1 != '-1001155301071'){
                                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[$z],"","",$caption);
                                }
                            }
                        }
                    }elseif(count($insta_list_vid) > 0){
                        $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[0],"","","$caption");
                        if($chatid1 != '-1001155301071'){
                            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[0],"","",$caption);
                        }
                    }else{
                        for($i = 0; $i < count($insta_list_jpg); $i++){
                            $mediasend = $this->telegram_model->send_photo_online($token,$chatid1,$insta_list_jpg[$i],$caption);
                        }
                    }
                }else{
                    $this->telegram_model->send_message_only($token,'-1001155301071',"ظرفیت API3 تموم شده");
                }
                $mid = json_decode($mediasend, true)['result']['message_id'];
                if(strlen($mid) > 2){
                    $sendCount++;
                    $data = array("content"=>($counterApi1[0]->content)+1);
                    $this->telegram_model->update_temp(22,$data);
                    $result = exec("rm -rf $dest_delet");
                    if(is_dir($dest_delet)){
                        rmdir($dest_delet);
                    }
                    //die();
                }
            }
            if(/*$counterApi4[0]->content < 100*/0){
                
            }
            //////////////////////////////////////////////////////////////////////////////////yt
            if($sendCount == 0){
                $this->telegram_model->send_message_only($token,'-1001155301071',"yt-insta");
                $cookies = "./application/instacookies.txt";
                $ren = copy("./application/instacookies2.txt","./application/instacookies.txt");
                $down = exec("yt-dlp --cookies $cookies -w --write-info-json -f 'b[filesize<46M][ext=mp4]' -o '$dest_delet/%(title)s.%(ext)s' $url 2>&1");
                if(strpos($down,"Requested content is not available") > 0 || strpos($down,"Requested format is not available") > 0){
                    $down = exec("yt-dlp --cookies $cookies -w --write-info-json -f 'b[ext=mp4]'  -o '$dest_delet/%(title)s.%(ext)s'  $url 2>&1");
                }
                $this->telegram_model->send_message_only($token,'-1001155301071',$down);
                $insta_list_vid = glob("$dest_delet/*.mp4");
                //$file_surce_json = glob("$dest_delet/*.json");
                if(count($insta_list_vid) == 1){
                    $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[0],"","","$caption");
                    if($chatid1 != '-1001155301071'){
                        $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[0],"","",$caption);
                    }
                }elseif(count($insta_list_vid) > 1){
                    $file_dest = $dest_delet."/file.mp4";
                    $file_org_size = 0;
                    $counter = 0;
                    for($z = 0; $z < count($insta_list_vid); $z++){
                        $srcFile = $insta_list_vid[$z];
                        $info_file1 = exec("du $srcFile | cut -f1");
                        $file_org_size += $info_file1;
                        if($file_org_size < 47000){
                            $file = "$dest_delet/input.txt";
                            $current = file_get_contents($file);
                            $fname = explode("/",$insta_list_vid[$z])[3];
                            $current .= "file '$fname'\n";
                            file_put_contents($file, $current);
                        }else{
                            $counter++;
                        }
                    }
    
                    if($counter == 0){
                        $con = exec("ffmpeg -f concat -safe 0 -i $file -c copy $dest_delet/output.mp4 2>&1");
                        //$dec = exec("ffmpeg -i $dest_delet/output.mp4 -vcodec libx264 -crf 30 -preset veryfast $dest_delet/output1.mp4 2>&1");
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$con);
                        $mediasend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output.mp4","","","$caption");
                        if($chatid1 != '-1001155301071'){
                            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',"$dest_delet/output.mp4","","",$caption);
                        }
                        //$vidsend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output1.mp4","","","test");
                    }else{
                        for($z = 0; $z < count($insta_list_vid); $z++){
                            $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[$z],"","","$caption");
                            if($chatid1 != '-1001155301071'){
                                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[$z],"","",$caption);
                            }
                        }
                    } 
                }
                $resInfo = json_decode($mediasend, true);
                $mid = $resInfo['result']['message_id'];
                $okk = $resInfo['ok'];
                //$this->telegram_model->send_message_only($token,'-1001155301071',"here2");
                if(strlen($mediasend) == 0 && strlen($mid) == 0 && $okk != 1){
                    //////////////////////////////////////////////////////////////////////////////////gl
                    $this->telegram_model->send_message_only($token,'-1001155301071',"gal-insta");
                    $cookies = "./application/instacookies.txt";
                    $ren = copy("./application/instacookies2.txt","./application/instacookies.txt");
                    $down = exec("gallery-dl --cookies $cookies -D $dest_delet --write-metadata $url 2>&1",$out);
                    
                    if(strpos($down,"Requested content is not available") > 0 || strpos($down,"Requested format is not available") > 0){
                        
                    }
                    //$this->telegram_model->send_message_only($token,'-1001155301071',$down);
                    $insta_list_vid = glob("$dest_delet/*.mp4");
                    //$file_surce_json = glob("$dest_delet/*.json");
                    if(count($insta_list_vid) == 1){
                        $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[0],"","","$caption");
                        if($chatid1 != '-1001155301071'){
                            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[0],"","",$caption);
                        }
                    }else{
                        $file_dest = $dest_delet."/file.mp4";
                        $file_org_size = 0;
                        $counter = 0;
                        for($z = 0; $z < count($insta_list_vid); $z++){
                            $srcFile = $insta_list_vid[$z];
                            $info_file1 = exec("du $srcFile | cut -f1");
                            $file_org_size += $info_file1;
                            if($file_org_size < 47000){
                                $file = "$dest_delet/input.txt";
                                $current = file_get_contents($file);
                                $fname = explode("/",$insta_list_vid[$z])[3];
                                $current .= "file '$fname'\n";
                                file_put_contents($file, $current);
                            }else{
                                $counter++;
                            }
                        }
        
                        if($counter == 0){
                            $con = exec("ffmpeg -f concat -safe 0 -i $file -c copy $dest_delet/output.mp4 2>&1");
                            //$dec = exec("ffmpeg -i $dest_delet/output.mp4 -vcodec libx264 -crf 30 -preset veryfast $dest_delet/output1.mp4 2>&1");
                            //$this->telegram_model->send_message_only($token,'-1001155301071',$con);
                            $mediasend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output.mp4","","","$caption");
                            if($chatid1 != '-1001155301071'){
                                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',"$dest_delet/output.mp4","","",$caption);
                            }
                            //$vidsend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output1.mp4","","","test");
                        }else{
                            for($z = 0; $z < count($insta_list_vid); $z++){
                                $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[$z],"","","$caption");
                                if($chatid1 != '-1001155301071'){
                                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[$z],"","",$caption);
                                }
                            }
                        } 
                    }
                }
                
            }
            
            
            ////////////////////////////////////////////////////////////////////////////end
            /*$mid = json_decode($mediasend, true)['result']['message_id'];
            if(strlen($mid) > 2){
                $result = exec("rm -rf $dest_delet");
                die();
            }*/
            $text = "<a href='tg://user?id=".$user_id."'>User</a>";
            $this->telegram_model->send_message_only($token,'-1001155301071',"از اینستا دانلود شد\n$chatid1\n$username\n$firstname\n$user_id\n\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',$text);
            if(is_dir($dest_delet)){
                rmdir($dest_delet);
                $result = exec("rm -rf $dest_delet");
                die();
            }
        }
    }
    elseif(strpos($url,"tiktok.com") > 0){
        if(strlen($url) > 0 && $mInfo[0] == "دانلود"){
            $source_del = "./application/$user_id";
            if(is_dir($source_del)){
                die();
            }else{
                $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
                exec("mkdir $source_del");
            }
            $down = exec("yt-dlp -w --write-info-json 'b[filesize<46M][ext=mp4]' -o '$source_del/%(title)s.%(ext)s' $url 2>&1");
            
            $jsonFile = glob("$source_del/*.info.json")[0];
            
            //$ext = pathinfo($filename, PATHINFO_EXTENSION);
            
            $info = file_get_contents($jsonFile);
            $info = json_decode($info, true);
            $duration_string = $info['duration_string'];
            $duration = $info['duration'];
            $artist = $info['artist'];
            $title = $info['title'];
            
            $source = glob("$source_del/*.mp4")[0];
            $caption = "$title\n\nدانلود از تیک‌تاک توسط ربات ویرا\n\n@VieraBot";
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$source,"","",$caption);
            
            $result = exec("rm -rf $source_del");
            $text = "<a href='tg://user?id=".$user_id."'>User</a>";
            $this->telegram_model->send_message_only($token,'-1001155301071',"از تیک‌تاک دانلود شد\n$chatid1\n$user_id\n$username\n$firstname\n\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"$text");
        }
    }
    elseif(strpos($url,"linkedin.com") > 0){
        if(strlen($url) > 0 && $mInfo[0] == "دانلود"){
            $source_del = "./application/$user_id";
            if(is_dir($source_del)){
                die();
            }else{
                $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
                exec("mkdir $source_del");
            }
            $url = mb_substr($url,0,strpos($url,"?"));
            $this->telegram_model->send_message_only($token,'-1001155301071',$url);
            $down = exec("yt-dlp -w -o '$source_del/%(id)s.%(ext)s' $url 2>&1");
            
            //$this->telegram_model->send_message_only($token,'-1001155301071',"down: ".$down);
            $source = glob("$source_del/*.mp4")[0];
            $caption = "$title\n\nدانلود از لینکدین توسط ربات ویرا\n\n@VieraBot";
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$source,"","",$caption);
            if($chatid1 != '-1001155301071'){
                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$source,"","",$caption);
            }
            $result = exec("rm -rf $source_del");
            $text = "<a href='tg://user?id=".$user_id."'>User</a>";
            $this->telegram_model->send_message_only($token,'-1001155301071',"از لینکدین دانلود شد\n$chatid1\n$user_id\n$username\n$firstname\n\n$text");
            $this->telegram_model->send_message_only($token,'-1001155301071',"$text");
        }
    }
}


if($repl_text){
    if($chatid1 == '-1001155301071' && $message == "Sdd"){
        $dest_delet = "./application/$user_id";
        if(is_dir($dest_delet)){
            //$this->telegram_model->send_message_only($token,$chatid1,"سرورهای دانلود اینستاگرام کمی با کندی مواجه هستند. خیلی زود فایل مورد نظر رو براتون ارسال میکنم");
            //$this->telegram_model->send_message_only($token,$chatid1,"time: ");
            die();
        }else{
            exec("mkdir $dest_delet");
        }
        
        //$url = "https://www.instagram.com/p/DJJXpUxtFi8/";  //3 img
        $url = "https://www.instagram.com/p/DJXA1-hsLM4/?igsh=MTFoN3l5bXFmeXE3ZQ==";  //2 vid
        
        //$url = "https://www.instagram.com/p/DJzVBDLiPUA/";
        //$url = "https://www.instagram.com/p/DJhafHJPV2C/?utm_source=ig_web_copy_link";
        //$url = "https://www.instagram.com/reels/DJq0dVbInuq/";
        //$url = "https://www.instagram.com/reel/DJq0dV
                    
                    
        
        
        $counterApi1 = $this->telegram_model->get_temp(18);
        $counterApi2 = $this->telegram_model->get_temp(19);
        $counterApi3 = $this->telegram_model->get_temp(22);
        if($counterApi1[0]->poet < time()){
            $poet = $counterApi2[0]->poet + 2592000;
            $data = array("content"=>0,"poet"=>$poet);
            $this->telegram_model->update_temp(18,$data);
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',$counterApi2[0]->poet);
        //$this->telegram_model->send_message_only($token,'-1001155301071',time());
        if($counterApi2[0]->poet < time()){
            $poet = $counterApi2[0]->poet + 2592000;
            $data = array("content"=>0,"poet"=>$poet);
            $this->telegram_model->update_temp(19,$data);
        }
            
        if($counterApi3[0]->poet < time()){
            $poet = $counterApi3[0]->poet + 86400;
            $data = array("content"=>0,"poet"=>$poet);
            $this->telegram_model->update_temp(22,$data);
        }
        
        if($parts[3] == "p"){
            $mode = "feeds";
        }elseif($parts[3] == "reels" || $parts[3] == "reel"){
            $mode = "reels";
        }elseif($parts[3] == "stories"){
            $mode = "story";
            $storyCode = $parts[5];
        }
        $this->telegram_model->send_message_only($token,'-1001155301071',"short: ".$shortCode);
        $this->telegram_model->send_message_only($token,'-1001155301071',"story: ".$storyCode);
        $this->telegram_model->send_message_only($token,'-1001155301071',$mode);
        
        
        $info = $this->telegram_model->get_insta_3($shortCode,$mode);
        //$res = $this->telegram_model->send_message_only($token,'-1001155301071',"info: ".$info);
        
        $info1 = json_decode($info,true);
            
        $video_duration = $info1[0]['items'][0]['video_duration'];
        $carousel = $info1[0]['items'][0]['carousel_media'];
        
            
        if(count($carousel) > 1){
            for($i = 0; $i < count($carousel); $i++){
                $carousel_vid_count = count($info1[0]['items'][0]['carousel_media'][$i]['video_versions']);
                $carousel_img_count = count($info1[0]['items'][0]['carousel_media'][$i]['image_versions2']);
                $pk = $info1[0]['items'][0]['carousel_media'][$i]['pk'];
                //$this->telegram_model->send_message_only($token,'-1001155301071',$carousel_vid_count);
                //$this->telegram_model->send_message_only($token,'-1001155301071',$carousel_img_count);
                if($carousel_vid_count > 0){
                    $vid = $info1[0]['items'][0]['carousel_media'][$i]['video_versions']['candidates'][0]['url'];
                    //$this->telegram_model->send_message_only($token,'-1001155301071',$vid);
                    $outFileName = "$dest_delet/$pk.mp4";
                    $size = $this->telegram_model->download_file($vid,$outFileName);
                    
                    $file = "$dest_delet/input.txt";
                    // Open the file to get existing content
                    $current = file_get_contents($file);
                    // Append a new person to the file
                    $current .= "file '$pk.mp4'\n";
                    // Write the contents back to the file
                    file_put_contents($file, $current);
                    
                    //$write = file_put_contents("$dest_delet/$input.txt","file '$outFileName' \n");
                }elseif($carousel_img_count > 0){
                    $count_candid = count($info1[0]['items'][0]['carousel_media'][$i]['image_versions2']['candidates']);
                    $img = $info1[0]['items'][0]['carousel_media'][$i]['image_versions2']['candidates'][$count_candid-1]['url'];
                    $res = $this->telegram_model->send_photo($token,$chatid1,$img,"test");
                }
            }
            $con = exec("ffmpeg -f concat -safe 0 -i $file  -c copy $dest_delet/output.mp4 2>&1");
            $this->telegram_model->send_message_only($token,'-1001155301071',$con);
            $vidsend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output.mp4","","","test");
        }
        
        
        
        $this->telegram_model->send_message_only($token,'-1001155301071',$res);
        
    }
    
    if($chatid1 == '-1001155301071' && $message == "asdd"){
        $dest_delet = "./application/$user_id";
        if(is_dir($dest_delet)){
            die();
        }else{
            exec("mkdir $dest_delet");
        }
        
        //$res = $this->telegram_model->send_message_only($token,'-1001155301071',"inja: ");
        //$url = "https://www.instagram.com/p/DJJXpUxtFi8/";  //3 img
        $url = "https://www.instagram.com/p/DJXA1-hsLM4/?igsh=MTFoN3l5bXFmeXE3ZQ==";  //2 vid
        $counterApi3 = $this->telegram_model->get_temp(23);
        if($counterApi1[0]->poet < time()){
            $poet = $counterApi2[0]->poet + 2592000;
            $data = array("content"=>0,"poet"=>$poet);
            $this->telegram_model->update_temp(23,$data);
        }
        
        $info = $this->telegram_model->get_insta_4($url);
        //$res = $this->telegram_model->send_message_only($token,'-1001155301071',"info: ".$info);
        
        $info1 = json_decode($info,true);
        $data_count = count($info1['data']);

        $res = $this->telegram_model->send_message_only($token,'-1001155301071',"info1: ".$data_count);
        for($i = 0; $i < $data_count; $i++){
            //$res = $this->telegram_model->send_message_only($token,'-1001155301071',"info2: ".$i);
            $isVideo = $info1['data'][$i]['isVideo'];
            
            if($isVideo == true){
                $outFileName = "$dest_delet/video$i.mp4";
            }else{
                $outFileName = "$dest_delet/image$i.jpg";
            }
            $down_url = $info1['data'][$i]['media'];
            //$this->telegram_model->send_message_only($token,'-1001155301071',$down_url);
            
            $size = $this->telegram_model->download_file($down_url,$outFileName);
            
        }
        $caption = "دانلود از اینستاگرام توسط ربات ویرا\n\n@VieraBot";
        $insta_list_vid = glob("$dest_delet/*.mp4");
        $insta_list_jpg = glob("$dest_delet/*.{jpg,webp,bmp,jpeg}",GLOB_BRACE);
        
        if(count($insta_list_vid) > 1){
            $this->telegram_model->send_message_only($token,'-1001155301071',"some video");
            $file_dest = $dest_delet."/file.mp4";
            $file_org_size = 0;
            $counter = 0;
            for($z = 0; $z < count($insta_list_vid); $z++){
                $srcFile = $insta_list_vid[$z];
                $info_file1 = exec("du $srcFile | cut -f1");
                $file_org_size += $info_file1;
                if($file_org_size < 47000){
                    $file = "$dest_delet/input.txt";
                    $current = file_get_contents($file);
                    $fname = explode("/",$insta_list_vid[$z])[3];
                    $current .= "file '$fname'\n";
                    file_put_contents($file, $current);
                }else{
                    $counter++;
                }
            }
            if($counter == 0){
                $con = exec("ffmpeg -f concat -safe 0 -i $file -c copy $dest_delet/output.mp4 2>&1");
                $mediasend = $this->telegram_model->send_video($token,$chatid1,"$dest_delet/output.mp4","","","$caption");
                if($chatid1 != '-1001155301071'){
                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',"$dest_delet/output.mp4","","",$caption);
                }
            }else{
                for($z = 0; $z < count($insta_list_vid); $z++){
                    $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[$z],"","","$caption");
                    if($chatid1 != '-1001155301071'){
                        $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[$z],"","",$caption);
                    }
                }
            }
        }elseif(count($insta_list_vid) > 0){
            $this->telegram_model->send_message_only($token,'-1001155301071',"one video");
            $mediasend = $this->telegram_model->send_video($token,$chatid1,$insta_list_vid[0],"","","$caption");
            if($chatid1 != '-1001155301071'){
                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$insta_list_vid[0],"","",$caption);
            }
        }
        if(count($insta_list_jpg) > 0){
            $this->telegram_model->send_message_only($token,'-1001155301071',"some image");
            for($i = 0; $i < count($insta_list_jpg); $i++){
                $mediasend = $this->telegram_model->send_photo_online($token,$chatid1,$insta_list_jpg[$i],$caption);
                //$this->telegram_model->send_message_only($token,$chatid1,$mediasend);
            }
        }
        
        $mid = json_decode($mediasend, true)['result']['message_id'];
        if(strlen($mid) > 2){
            $result = exec("rm -rf $dest_delet");
            die();
        }
        
        
    }
}

if(/*$chatid1 == '-1001155301071' &&*/ mb_substr($message,0,5) == "ویرا:"){
    $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صیر کن");
    $text1 = trim(mb_substr($message,5));
    //$this->telegram_model->send_message_only($token,$chatid1,$text1);
    //$text = "انگشت دستم کبود شده. دلیلش چیه؟";
    $models = ['openai/gpt-oss-20b:free','tngtech/deepseek-r1t2-chimera:free','mistralai/mistral-small-3.2-24b-instruct:free',
    'moonshotai/kimi-k2:free','z-ai/glm-4.5-air:free'];
    $result = $this->telegram_model->chatAi($models[0],$text1);
    if (stripos($result, 'error') !== false) {
        $res = "اوووه 😅 خطا پیدا شد!";
        $this->telegram_model->send_message_only($token,"-1001155301071",substr($result,0,1000));
    } else {
        $res = json_decode($result, true)['choices'][0]['message']['content'];
    }
    $this->telegram_model->send_message_only($token,"-1001155301071",$res);
    $this->telegram_model->send_message_only($token,$chatid1,$res);
    
}

/*if($message == "sksk"){
    $this->telegram_model->send_message_only($token,"-1001155301071","salam");
    $url = "./application/badbadak.mp4";
    $mediasend = $this->telegram_model->send_video($token,"-1001155301071",$url,"","","بادبادک باز");
}*/



    //$this->telegram_model->send_message_only($token,'-1001155301071',"here Gm1 : ");
    //15
if($repl_video_fid || $repl_audio_fid || $repl_voice_fid){
    if($repl_audio_fid){
        $thisFid = $repl_audio_fid;
    }elseif($repl_voice_fid){
        $thisFid = $repl_voice_fid;
    }else{
        $thisFid = $repl_video_fid;
    }
    //$this->telegram_model->send_message_only($token,'-1001155301071',$thisFid);
    if(mb_strpos($message,"ویرا") == 0 && gettype(mb_strpos($message,"ویرا")) =="integer" ){
        $infoMessage = explode(" ",$message);
        if($infoMessage[1] == "اسم" && $infoMessage[2] == "موزیک"){
            $counterApi = $this->telegram_model->get_temp(13);
            //$diffTime = time() - $counterApi[0]->poet;
            //$this->telegram_model->send_message_only($token,'-1001155301071',$diffTime);
            if($counterApi[0]->content > 2500 ){
                $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
                $this->telegram_model->send_message_only($token,'-1001155301071',"تعداد 2500 تا آهنگ پیدا کردن پر شده");
                die();
            }
            if($counterApi[0]->poet < time() ){
                $data = array("content"=>0,"poet"=>$counterApi[0]->poet + 2592000);
                $this->telegram_model->update_temp(13,$data);
            }
            
            $data = array("content"=>($counterApi[0]->content)+1);
            $this->telegram_model->update_temp(13,$data);
            $waitRes = $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"لطفا کمی صبر کنید");
            $waitMid = json_decode($waitRes, true)['result']['message_id'];
            
            $source = "../download/$user_id.mp3";
            //rename($source,"../download/$user_id.mp4");
            $video_file = $this->telegram_model->get_file($token,$thisFid);
            $video_file = json_decode($video_file, true);
            $url1 = "https://api.telegram.org/file/bot".$token."/".$video_file["result"]["file_path"];
            $result = exec("ffmpeg -y -i $url1 -ss 00:00:03 -t 00:00:33 -vn -ab 256 $source 2>&1");
            //$this->telegram_model->send_message_only($token,'-1001155301071',$result);
            $music = "https://tebresaneh.com/download/$user_id.mp3";
            
            $res = $this->telegram_model->song_detect2($music);
            //$this->telegram_model->send_message_only($token,'-1001155301071',substr($res,500,1000));
            $res = json_decode($res,true);
            $title = $res['track']['title'];
            $subtitle = $res['track']['subtitle'];
            $image = $res['track']['share']['image'];
            $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
            if(strlen($title) == 0 && strlen($subtitle) == 0){
                $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"متاسفانه نتونستم پیداش کنم");
                //$this->telegram_model->send_message_only($token,$chatid1,"$title - $subtitle \n $image");
            }else{
                $picsend = $this->telegram_model->send_photo_reply($token,$chatid1,$image,"$title - $subtitle",$lastpost);
                if($chatid1 != '-1001155301071'){
                    $picsend = $this->telegram_model->send_photo($token,'-1001155301071',$image,"gm\n\n$title - $subtitle");
                }
            }
            unlink($music);
        }
    }
}


$musicCommand1 = "ویراموزیک";
$musicCommand2 = "ویرا موزیک";

if (gettype(strpos($message, $musicCommand1)) == "integer" && strpos($message, $musicCommand1) < 1 ||
    gettype(strpos($message, $musicCommand2)) == "integer" && strpos($message, $musicCommand2) < 1) {
    
    // کپی کردن کوکی‌ها
    copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
    $cookies = "./application/youtubecookies.txt";

    // ۱. ارسال پیام انتظار
    $waitRes = $this->telegram_model->send_message_only($token, $chatid1, "🔎 در حال جستجو در اینترنت...");
    $waitMid = json_decode($waitRes, true)['result']['message_id'] ?? null;

    // ایجاد پوشه اختصاصی کاربر
    $user_folder = "application/$user_id";
    $abs_path = FCPATH . $user_folder;
    if (!is_dir($abs_path)) {
        mkdir($abs_path, 0777, true);
    }

    // پاکسازی جستجوهای قبلی
    array_map('unlink', glob("$abs_path/*.json"));
    
    $cleanQuery = trim(str_replace([$musicCommand1, $musicCommand2, "-"], " ", $message));

    // مرحله اول: جستجو در ساوندکلاود (۴ مورد)
    $scCommand = "yt-dlp --no-check-certificates --write-info-json --skip-download --no-playlist --max-downloads 4 -o \"$abs_path/sc_%(id)s.%(ext)s\" \"scsearch4:$cleanQuery\" 2>&1";
    exec($scCommand);
    //copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
    // مرحله دوم: جستجو در یوتیوب (۴ مورد) با کوکی
    //$ytCommand = "yt-dlp --no-check-certificates --cookies $cookies --write-info-json --skip-download --no-playlist --max-downloads 4 -o \"$abs_path/yt_%(id)s.%(ext)s\" \"ytsearch4:$cleanQuery\" 2>&1";
    //exec($ytCommand);

    //$scList = "☁️ **SoundCloud:**\n";
    //$ytList = "\n🔴 **YouTube:**\n";
    
    $scButtons = array();
    $ytButtons = array();
    
    $scCounter = 1;
    $ytCounter = 1;

    // پیدا کردن تمام فایل‌های JSON
    $jsonFiles = glob("$abs_path/*.json");
    
    foreach ($jsonFiles as $file) {
        $content = file_get_contents($file);
        $info = json_decode($content, true);

        if (isset($info['_type']) && $info['_type'] === 'playlist') {
            unlink($file); 
            continue;
        }

        $fileName = basename($file);
        $title = mb_substr($info['title'] ?? 'Music', 0, 35);
        $fileKey = basename($file, '.info.json');
        $rlm = "\xE2\x80\x8F";
        if (strpos($fileName, 'sc_') !== false) {
            // بخش ساوندکلاود
            $scList .= $this->telegram_model->toPersianNum("$rlm.$scCounter. $title\n\n");
            $scButtons[] = array("text" => (string)$scCounter, "callback_data" => "vmu*$fileKey");
            $scCounter++;
        } else {
            // بخش یوتیوب
            $ytList .= "$ytCounter. $title\n";
            $ytButtons[] = array("text" => (string)$ytCounter, "callback_data" => "vmu*$fileKey");
            $ytCounter++;
        }
    }   

    // ساخت بدنه نهایی کیبورد
    $keyboardButtons = array();
    if (!empty($scButtons)) $keyboardButtons[] = $scButtons; // ردیف اول: ساوندکلاود
    if (!empty($ytButtons)) $keyboardButtons[] = $ytButtons; // ردیف دوم: یوتیوب

    // ردیف آخر: دکمه‌های ثابت
    $googleUrl = "https://www.google.com/search?q=" . urlencode($cleanQuery . " music");
    $keyboardButtons[] = array(
        array("text" => "🔎 جستجو در گوگل", "url" => $googleUrl),
        array("text" => "❌ لغو", "callback_data" => "vmu*del")
    );

    // حذف پیام انتظار
    if ($waitMid) {
        $this->telegram_model->delete_message_one($token, $chatid1, $waitMid);
    }
    copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
    if ($scCounter == 1 && $ytCounter == 1) {
        $this->telegram_model->send_message_only($token, $chatid1, "❌ نتیجه‌ای یافت نشد.");
    } else {
        $finalText = "🎧 نتایج یافت شده 🌐:\n\n" . $scList . $ytList;
        $keyboard = array("inline_keyboard" => $keyboardButtons);
        $this->telegram_model->send_message($token, $chatid1, $finalText, $keyboard);
    }
}

if ($callback_message) {
    $content = explode("*", $callback_message);
    // کپی کردن کوکی برای اطمینان
    copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
    
    if ($content[0] == "vmu") {
        $fileKey = $content[1];
        $cookies = "./application/youtubecookies.txt";
        $user_dir = "./application/$callback_user";
        $jsonPath = "$user_dir/$fileKey.info.json";

        if ($fileKey == "del") {
            $this->telegram_model->delete_message_one($token, $callback_chatid, $callback_message_id);
            exec("rm -rf " . escapeshellarg($user_dir));
            die();
        }

        // ۱. ارسال پیام اولیه
        $waitRes = $this->telegram_model->send_message_only($token, $callback_chatid, "📥 شروع عملیات...\n[▒▒▒▒▒▒▒▒▒▒] 0%");
        $waitMid = json_decode($waitRes, true)['result']['message_id'] ?? null;

        if (!file_exists($jsonPath)) {
            if ($waitMid) $this->telegram_model->delete_message_one($token, $callback_chatid, $waitMid);
            die();
        }

        // تشخیص سریع از روی نام فایل (FileKey)
        $isYoutube = (strpos($fileKey, 'yt_') !== false);
        $sourceName = $isYoutube ? "YouTube" : "SoundCloud";

        $jsonData = json_decode(file_get_contents($jsonPath), true);
        $fullUrl = $jsonData['webpage_url'];
        $title = $jsonData['title'] ?? 'Music';

        // ۲. تنظیمات مسیر و آدرس تلگرام
        $finalName = "dl_" . time();
        $finalPath = $user_dir . "/" . $finalName . ".mp3";
        $editUrl = "https://api.telegram.org/bot$token/editMessageText";

        $text20 = urlencode("📥 در حال استخراج صوت از $sourceName...\n[██▒▒▒▒▒▒▒▒] 20%");
        $text50 = urlencode("⚙️ در حال تبدیل به فرمت MP3...\n[█████▒▒▒▒▒] 50%");
        $text80 = urlencode("🚀 در حال نهایی‌سازی فایل...\n[████████▒▒] 80%");

        $chainCmd = "curl -s -X POST $editUrl -d chat_id=$callback_chatid -d message_id=$waitMid -d text=$text20 && ";
        $chainCmd .= "sleep 1 && ";
        $chainCmd .= "curl -s -X POST $editUrl -d chat_id=$callback_chatid -d message_id=$waitMid -d text=$text50 && ";
        $chainCmd .= "sleep 1 && ";
        $chainCmd .= "curl -s -X POST $editUrl -d chat_id=$callback_chatid -d message_id=$waitMid -d text=$text80 && ";
        
        // تنظیم پارامترها بر اساس تشخیص از روی نام فایل
        if ($isYoutube) {
            $cookieParam = "--cookies " . $cookies;
            $audioParams = "-f \"bestaudio/best\" --audio-quality 0";
        } else {
            $cookieParam = "";
            $audioParams = "-f \"ba\"";
        }
        copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
        // ۳. دستور دانلود نهایی
        $dlCmd = "yt-dlp --no-check-certificates $cookieParam $audioParams -x --audio-format mp3 -o " . escapeshellarg($user_dir . "/" . $finalName . ".%(ext)s") . " " . escapeshellarg($fullUrl);
    
        exec($chainCmd . $dlCmd . " 2>&1");

        // ۴. بررسی نهایی و ارسال
        if (file_exists($finalPath) && filesize($finalPath) > 0) {
            $finishedText = urlencode("✅ آماده ارسال!\n[██████████] 100%");
            exec("curl -s -X POST $editUrl -d chat_id=$callback_chatid -d message_id=$waitMid -d text=$finishedText");

            $caption = "🎶 $title\n@VieraMusik";
            $this->telegram_model->send_audio_online($token, $callback_chatid, $caption, $finalPath, "@VieraBot", $title, '');

            if ($waitMid) $this->telegram_model->delete_message_one($token, $callback_chatid, $waitMid);
            $this->telegram_model->delete_message_one($token, $callback_chatid, $callback_message_id);
            
            copy("./application/youtubecookies1.txt", "./application/youtubecookies.txt");
            $files = glob("$user_dir/*");
            foreach ($files as $f) { if (is_file($f)) unlink($f); }
            @rmdir($user_dir);
        } else {
            if ($waitMid) $this->telegram_model->delete_message_one($token, $callback_chatid, $waitMid);
            $this->telegram_model->send_message_only($token, $callback_chatid, "❌ متاسفانه خطایی در دانلود از $sourceName رخ داد.");
        }
        die();
    }
}




if(($chatid1 == '-1001155301071' || $chatid1 == '53853580') && gettype(strpos($message,"Vmvm")) == "integer"){
    
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "member" || $join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $ren = copy("./application/youtubecookies1.txt","./application/youtubecookies.txt");
        $this->telegram_model->send_message_only($token,'-1001155301071',"start music download : \n\n$chatid1\n$user_id" );
        $thisMusicTimerUser = $this->telegram_model->get_music_timer_user($user_id);
        if(count($thisMusicTimerUser) == 0){
            $data = array("uid"=>$user_id,"cid"=>$chatid1,"user_pid"=>$lastpost);
        	$this->telegram_model->set_telegram_music_timer($data);
        }else{
            //$this->telegram_model->send_message_only($token,'-1001155301071',"شما یک پردازش دیگر در مرحله اجرا دارید. لطفا تا پایان آن صبر کنیدو سپس درخواست بعدی را بدهید" );
            die();
        }
        
        $waitRes = $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
        $waitMid = json_decode($waitRes, true)['result']['message_id'];
        $message = $this->telegram_model->toEnglishNum($message);
        $info = explode("-",$message);
        if(count($info) > 2){
            $name = trim($info[1]);
            $title = trim($info[2]);
            $nameAndtitle = "$name $title";
        }else{
            $nameAndtitle = trim($info[1]);
        }
        
        $this->telegram_model->send_message_only($token,'-1001155301071',"vmvm: $nameAndtitle" );
        
        if(gettype(strpos($nameAndtitle,"#")) == "integer"){
            //$this->telegram_model->send_message_only($token,'-1001155301071',"cilip: here #" );
            //$musics = $this->telegram_model->get_music_by_tag(substr($nameAndtitle,1));
        }else{
            $musics = $this->telegram_model->get_telegram_music_sent_concat($nameAndtitle);
        }
        
        if(count($musics) > 0){
            $this->telegram_model->send_message_only($token,'-1001155301071',"vmvm: here1" );
            $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
            $text = $this->telegram_model->toPersianNum($text);
            $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
        	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
            $arraynumber = 0;
        	$jw = 1;
        	$row = 1;
        	if(count($musics) > 5){
        	    $counter = 5;
        	}else{
        	    $counter = count($musics);
        	}
        	for($i = 0; $i < $counter+2; $i++){
        	    if($i == $counter+1){
        	        array_push($arraydata[$arraynumber],array(text=>"❌ حذف درخواست",callback_data=>"vmu2*-delReq*-$user_id"));
        	    }elseif($i == $counter){
        	        if(mb_strlen($nameAndtitle) > 40){
        	            $nameAndtitle = mb_substr($nameAndtitle,0,40);
        	        }
        	        array_push($arraydata[$arraynumber],array(text=>"🔍 جستجوی بیشتر",callback_data=>"vmu2*-$nameAndtitle*-$user_id"));
        	    }else{
                    $t_vid = $musics[$i]->file_id;
                    $performer = $musics[$i]->performer_fa;
                    $title = $musics[$i]->title_fa;
                    $thisId = $musics[$i]->id;
                    //$nameSend = "$performer - $title";
                    $data = "vmu2*-$thisId*-$user_id";
        	        array_push($arraydata[$arraynumber],array(text=>"$performer - $title",callback_data=>$data));
        	    }
        		if($jw % 1 == 0){
        	        $arraynumber++;
        	    }
                $jw++;
            }
            $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
        	$keyboard =  array("inline_keyboard" => $arraydata);
        	$resKey = $this->telegram_model->send_message($token,$chatid1,$text,$keyboard);
        	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$resKey );
        	//$resKey = json_decode($resKey, true)['result']['message_id'];
        	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$resKey );
        	
        }else{
            
            $cookies = "./application/youtubecookies.txt";
            $source_del = "./application/$user_id";
            if(is_dir($source_del)){
                die();
            }else{
                exec("mkdir $source_del");
            }

            $down = exec("yt-dlp --cookies $cookies -f 'ba' --write-info-json --skip-download --max-downloads 5 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch15:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
            // --compat-options --no-check-certificates --cookies $cookies
            //$this->telegram_model->send_message_only($token,$chatid1,"$down" );
            $jsonFile = glob("$source_del/*.info.json");
            if( file_exists("$source_del/_.info.json") ){
                $this->telegram_model->send_message_only($token,$chatid1,"vmvm rename1: $down" );
                rename("$source_del/_.info.json","$source_del/_.info1.json");
            }else{
                for($k = 0; $k < count($jsonFile); $k++){
                    $string = file_get_contents($jsonFile[$k]);
        	        $json_content = json_decode($string, true);
                    $type = $json_content['_type'];
                    if($type == "playlist"){
                        $this->telegram_model->send_message_only($token,$chatid1,"vmvm rename2: $down" );
                        rename($jsonFile[$k],"$source_del/_.info1.json");
                    }
                }
            }
            
            
            /*$jsonFile1 = glob("$source_del/[!_]*.info.json", GLOB_BRACE);
            $this->telegram_model->send_message_only($token,'-1001155301071',"music1: here2 ".count($jsonFile1) );
            
            $jsonFile = glob("$source_del/*.info.json");
            $this->telegram_model->send_message_only($token,'-1001155301071',"music1: here2 ".count($jsonFile) );*/
            

            $jsonFile = glob("$source_del/*.info.json");
            $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
            $text = $this->telegram_model->toPersianNum($text);
            $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
        	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
            $arraynumber = 0;
        	$jw = 1;
        	$row = 1;
        	for($i = 0; $i < count($jsonFile)+1; $i++){
        	    if($i == count($jsonFile)){
        	        array_push($arraydata[$arraynumber],array(text=>"حذف درخواست",callback_data=>"vmu2*-delReq*-$user_id"));
        	    }else{
        	        $string = file_get_contents($jsonFile[$i]);
        	        $json_content = json_decode($string, true);
                    $vid = $json_content['id'];
                    $title = $json_content['title'];
                    $artist = $json_content['artist'];
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".$title );
                    //if(strlen($title) > 100){
                            
                    //}
        	        array_push($arraydata[$arraynumber],array(text=>$title,callback_data=>"vmu2*-$vid*-$user_id"));
        	    }
        		if($jw % 1 == 0){
        	        $arraynumber++;
        	    }
                $jw++;
            }
            $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
        	$keyboard =  array("inline_keyboard" => $arraydata);
        	$resKey = $this->telegram_model->send_message($token,$chatid1,$text,$keyboard);
        	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$resKey );
        	
        }
        $resKey = json_decode($resKey, true)['result']['message_id'];
    	if($resKey){
    	    $newTime = time()+120;
    	    $data = array("pid"=>$resKey,"time"=>$newTime);
    	    $updateRes = $this->telegram_model->update_music_timer($data,$user_id);
    	    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$updateRes );
    	}
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"برای استفاده از این سرویس باید در کانال مجله ویرا @VieraMagazine عضو باشید");
    }
}

$vidCommand1 = "ویراکیلیپ";
$vidCommand2 = "ویرا کیلیپ";
if(gettype(strpos($message,$vidCommand1)) == "integer" && strpos($message,$vidCommand1) < 1 ||
    gettype(strpos($message,$vidCommand2)) == "integer" && strpos($message,$vidCommand2) < 1){
        $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
        if($join_info == "member" || $join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
            $this->telegram_model->send_message_only($token,'-1001155301071',"start clip download : \n\n$chatid1\n$user_id" );
            $ren = copy("./application/youtubecookies1.txt","./application/youtubecookies.txt");
            $thisMusicTimerUser = $this->telegram_model->get_music_timer_user($user_id);
            if(count($thisMusicTimerUser) == 0){
                $data = array("uid"=>$user_id,"cid"=>$chatid1,"user_pid"=>$lastpost);
            	$this->telegram_model->set_telegram_music_timer($data);
            }else{
                //$this->telegram_model->send_message_only($token,'-1001155301071',"شما یک پردازش دیگر در مرحله اجرا دارید. لطفا تا پایان آن صبر کنیدو سپس درخواست بعدی را بدهید" );
                die();
            }
            $waitRes = $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
            $waitMid = json_decode($waitRes, true)['result']['message_id'];
            $message = $this->telegram_model->toEnglishNum($message);
            $info = explode("-",$message);
            if(count($info) > 2){
                $name = trim($info[1]);
                $title = trim($info[2]);
                $nameAndtitle = "$name $title";
            }else{
                $nameAndtitle = trim($info[1]);
            }
            
            //$this->telegram_model->send_message_only($token,'-1001155301071',"cilip: $nameAndtitle" );
            
            if(gettype(strpos($nameAndtitle,"#")) == "integer"){
                //$this->telegram_model->send_message_only($token,'-1001155301071',"cilip: here #" );
                $videos = $this->telegram_model->get_vid_by_tag(substr($nameAndtitle,1));
            }else{
                $videos = $this->telegram_model->get_vid_sent_concat($nameAndtitle);
            }
            
            //$this->telegram_model->send_message_only($token,'-1001155301071',"count cilip: ".count($videos) );
            
            if(count($videos) > 0){
                //$this->telegram_model->send_message_only($token,'-1001155301071',"clip: here1" );
                $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
                $text = $this->telegram_model->toPersianNum($text);
                $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
            	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
                $arraynumber = 0;
            	$jw = 1;
            	$row = 1;
            	if(count($videos) > 5){
            	    $counter = 5;
            	}else{
            	    $counter = count($videos);
            	}
            	for($i = 0; $i < $counter+2; $i++){
            	    if($i == $counter+1){
            	        array_push($arraydata[$arraynumber],array(text=>"❌ حذف درخواست",callback_data=>"vc*-delReq*-$user_id"));
            	    }elseif($i == $counter){
            	        if(mb_strlen($nameAndtitle) > 40){
            	            $nameAndtitle = mb_substr($nameAndtitle,0,40);
            	        }
            	        array_push($arraydata[$arraynumber],array(text=>"🔍 جستجوی بیشتر",callback_data=>"vc*-$nameAndtitle*-$user_id"));
            	    }else{
                        $t_vid = $videos[$i]->file_id;
                        $performer = $videos[$i]->performer;
                        $title = $videos[$i]->title;
                        $thisId = $videos[$i]->id;
                        //$nameSend = "$performer - $title";
                        $data = "vc*-$thisId*-$user_id";
            	        array_push($arraydata[$arraynumber],array(text=>"$performer - $title",callback_data=>$data));
            	    }
            		if($jw % 1 == 0){
            	        $arraynumber++;
            	    }
                    $jw++;
                }
                $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
            	$keyboard =  array("inline_keyboard" => $arraydata);
            	$resKey = $this->telegram_model->send_message($token,$chatid1,$text,$keyboard);
            	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$resKey );
            	$resKey = json_decode($resKey, true)['result']['message_id'];
            	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$resKey );
            	if($resKey){
            	    $newTime = time()+120;
            	    $data = array("pid"=>$resKey,"time"=>$newTime);
            	    $updateRes = $this->telegram_model->update_music_timer($data,$user_id);
            	    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here31 ".$updateRes );
            	}
            }else{
                $cookies = "./application/youtubecookies.txt";
                $source_del = "./application/$user_id";
                if(is_dir($source_del)){
                    die();
                }else{
                    exec("mkdir $source_del");
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',"clip: here2" );
                //$down = exec("yt-dlp -f 'ba' --write-info-json --max-downloads 3 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                /*$text = "";
                if(gettype(strpos($nameAndtitle,"#")) == "integer"){
                    $text = "--playlist-random";
                }*/
                $down = exec("yt-dlp --cookies $cookies -f 'b' --write-info-json --skip-download --max-downloads 5 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                // --compat-options --no-check-certificates --cookies $cookies
                //$this->telegram_model->send_message_only($token,$chatid1,"$down" );
                
                //rename("$source_del/_.info.json","$source_del/_.info1.json");
                //$jsonFile = glob("$source_del/[!_]*.info.json", GLOB_BRACE);
                
                $jsonFile = glob("$source_del/*.info.json");
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".count($jsonFile) );
                for($k = 0; $k < count($jsonFile); $k++){
                    $string = file_get_contents($jsonFile[$k]);
        	        $json_content = json_decode($string, true);
                    $type = $json_content['_type'];
                    if($type == "playlist"){
                        rename($jsonFile[$k],"$source_del/_.info1.json");
                    }
                }   
                $jsonFile = glob("$source_del/*.info.json");
                $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
                $text = $this->telegram_model->toPersianNum($text);
                $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
            	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
                $arraynumber = 0;
            	$jw = 1;
            	$row = 1;
            	for($i = 0; $i < count($jsonFile)+1; $i++){
            	    if($i == count($jsonFile)){
            	        array_push($arraydata[$arraynumber],array(text=>"حذف درخواست",callback_data=>"vc*-delReq*-$user_id"));
            	    }else{
            	        $string = file_get_contents($jsonFile[$i]);
            	        $json_content = json_decode($string, true);
                        $vid = $json_content['id'];
                        $title = $json_content['title'];
                        $artist = $json_content['artist'];
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".$title );
                        //if(strlen($title) > 100){
                                
                        //}
            	        array_push($arraydata[$arraynumber],array(text=>$title,callback_data=>"vc*-$vid*-$user_id"));
            	    }
            		if($jw % 1 == 0){
            	        $arraynumber++;
            	    }
                    $jw++;
                }
                $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
            	$keyboard =  array("inline_keyboard" => $arraydata);
            	$resKey = $this->telegram_model->send_message($token,$chatid1,$text,$keyboard);
            	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$resKey );
            	$resKey = json_decode($resKey, true)['result']['message_id'];
            	if($resKey){
            	    $newTime = time()+120;
            	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$resKey,"time"=>$newTime);
            	    $data = array("pid"=>$resKey,"time"=>$newTime);
            	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$lastpost,"time"=>$newTime);
            	    $updateRes = $this->telegram_model->update_music_timer($data,$user_id);
            	    //$this->telegram_model->set_telegram_music_timer($data);
            	}
            }
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,"برای استفاده از این سرویس باید در کانال مجله ویرا @VieraMagazine عضو باشید");
        }
    }

if($callback_message){
    $content = explode("*-",$callback_message);
    if($content[0] == "vmu"){
        $ren = copy("./application/youtubecookies1.txt","./application/youtubecookies.txt");
        //$this->telegram_model->send_message_only($token,'-1001155301071',$callback_message);
        if($content[2] != $callback_user){
            $this->telegram_model->send_message_only($token,$callback_chatid,"این درخواست از طرف کاربر دیگری بوده. شما مجاز به استفاده از آن نیستید.");
        }else{
            $source_del = "./application/$callback_user";
            if($content[1] == "delReq"){
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $this->telegram_model->clear_telegram_music_timer($callback_user);
                $result = exec("rm -rf $source_del");
            }else{
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $waitRes = $this->telegram_model->send_message_only($token,$callback_chatid,"لطفا کمی صبر کنید");
                $waitMid = json_decode($waitRes, true)['result']['message_id'];
                $cookies = "./application/youtubecookies.txt";
                $thisId = $content[1];
                $url = "https://www.youtube.com/watch?v=$thisId";
                //$this->telegram_model->send_message_only($token,'-1001155301071',"this url y: ".$url);
                //--no-check-certificates
                $down = exec("yt-dlp --cookies $cookies -f 'ba[ext=m4a]' --restrict-filenames -x --audio-format mp3 --audio-quality 5 --encoding UTF8 -o '$source_del/%(title)s.%(ext)s' $url 2>&1",$out);
                
                //$this->telegram_model->send_message_only($token,'-1001155301071',"download from y1: ".$down);
                
                $jsonFile = "$source_del/$thisId.info.json";
                $string = file_get_contents($jsonFile);
    	        $json_content = json_decode($string, true);
                $id = $json_content['id'];
                $title = $json_content['title'];
                $title = $json_content['title'];
                $title = str_ireplace("video","",$title);
                $title = str_ireplace("Video","",$title);
                $title = str_ireplace("VIDEO","",$title);
                $artist = $json_content['artist'];
                $desc = $json_content['description'];
                $duration = $json_content['duration'];
                $view = $json_content['view_count'];
                $imageId = $json_content['thumbnails'];
                $imageurl = $json_content['thumbnail'];
                /*$imageurl = [];
                for($z = 0; $z < count($imageId); $z++){
                    if(strpos($imageId[$z]['resolution'],"720") > 0 || $imageId[$z]['id'] == "34" || $imageId[$z]['id'] == "38" || $imageId[$z]['id'] == "40"){
                        //$imageurl[$z] = $imageId[$z]['url'];
                        array_push($imageurl, $imageId[$z]['url']);
                    }
                    
                }*/
                
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music image thumb: $imageurl");
                //$tags = json_encode($json_content['tags']);
                $tags = $json_content['tags'];
                for($x = 0; $x < count($tags); $x++){
                    $ca = str_word_count($tags[$x],1);
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"is inglish?: ".$ca[0]);
                    if($ca[0]){
                        continue;
                    }
                    if($x < count($tags)-1){
                        $allTags .= $tags[$x].",-,";
                    }else{
                        $allTags .= $tags[$x];
                    }
                }  
                $duration_string = $json_content['duration_string'];
                $track = glob("$source_del/*.mp3")[0];
                $size = exec("du -sh $track | cut -f1")."B";
                $caption = "$title\n\nحجم: $size\n\n@VieraBot\n@VieraMagazine";
                $logo = "./application/img/logowhite_full.png";
                $dest1 = "./application/$callback_user/musicSave-$chatid1.mp3";
                $result1 = exec("ffmpeg -y -f mp3 -i $track -i $logo -map 0:0 -map 1:0  -c copy -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' -map_metadata -1 $dest1 2>&1",$out);
                
                rename($dest1,$track);
                
                $sendAud = $this->telegram_model->send_audio_online($token,$callback_chatid,$caption,$track,"@VieraBot",$title);
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music send res: ".$sendAud);
                
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                $result = exec("rm -rf $source_del");
                if($callback_chatid != '-1001155301071'){
                    $caption2 = "$title\n$size\n$url\n$allTags\n\n@VieraBot\n@VieraMagazine";
                    $imageSend = $this->telegram_model->send_photo($token,'-1001155301071',$imageurl ,$caption2);
                    $this->telegram_model->send_message_only($token,'-1001155301071',"photo send res: ".$imageSend);
                    
                    /*$this->telegram_model->send_message_only($token,'-1001155301071',"count photos: ".count($imageurl));
                    for($k = 0; $k < count($imageurl); $k++){
                        
                        $this->telegram_model->send_message_only($token,'-1001155301071',"photo send res: ".$imageurl[$k]);
                        $imageSend = $this->telegram_model->send_photo($token,'-1001155301071',$imageurl[$k] ,$caption2);
                        
                        
                        if(json_decode($imageSend, true)['result']['message_id']){
                            break;
                        }
                    }*/
                    
                    $mid = json_decode($sendAud, true)['result']['message_id'];
                    $forwardRes = $this->telegram_model->forward($token,$callback_chatid,$mid,'-1001155301071');
                    $forwardMid = json_decode($forwardRes, true)['result']['message_id'];
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"forward mid: $forwardMid");
                    $this->telegram_model->edit_message_caption($token,'-1001155301071',$forwardMid,$caption2);
                }
            }
        }
    }
    elseif($content[0] == "vmu1"){
        if($content[3] != $callback_user){
            $this->telegram_model->send_message_only($token,$callback_chatid,"این درخواست از طرف کاربر دیگری بوده. شما مجاز به استفاده از آن نیستید.");
        }else{
            if($content[1] == "delReq"){
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                
            }elseif($content[1] == "nR"){
                $waitRes = $this->telegram_model->send_message_only($token,$callback_chatid,"لطفا کمی صبر کنید");
                $waitMid = json_decode($waitRes, true)['result']['message_id'];
                $cookies = "./application/youtubecookies.txt";
                $source_del = "./application/$callback_user";
                if(is_dir($source_del)){
                    die();
                }else{
                    exec("mkdir $source_del");
                }
                $nameAndtitle = $content[2];
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2" );
                //$down = exec("yt-dlp -f 'ba' --write-info-json --max-downloads 3 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                $down = exec("yt-dlp --cookies $cookies -f 'ba' --write-info-json --skip-download --max-downloads 4 --restrict-filenames -x --audio-format mp3 --audio-quality 5 --encoding UTF8 'ytsearch5:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                // --compat-options --no-check-certificates --cookies $cookies
                //$this->telegram_model->send_message_only($token,$chatid1,"$down" );
                
                //[vcodec=none]
                rename("$source_del/_.info.json","$source_del/_.info1.json");
                //$jsonFile = glob("$source_del/[!_]*.info.json", GLOB_BRACE);
                $jsonFile = glob("$source_del/*.info.json");
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".count($jsonFile) );
                
                $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
                $text = $this->telegram_model->toPersianNum($text);
                $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
            	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
                $arraynumber = 0;
            	$jw = 1;
            	$row = 1;
            	for($i = 0; $i < 5; $i++){
            	    if($i == 4){
            	        array_push($arraydata[$arraynumber],array(text=>"حذف درخواست",callback_data=>"vmu*-delReq*-$callback_user"));
            	    }else{
            	        $string = file_get_contents($jsonFile[$i]);
            	        $json_content = json_decode($string, true);
                        $id = $json_content['id'];
                        $title = $json_content['title'];
                        $artist = $json_content['artist'];
            	        array_push($arraydata[$arraynumber],array(text=>$title,callback_data=>"vmu*-$id*-$callback_user"));
            	    }
            		if($jw % 1 == 0){
            	        $arraynumber++;
            	    }
                    $jw++;
                }
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
            	$keyboard =  array("inline_keyboard" => $arraydata);
            	$resKey = $this->telegram_model->send_message($token,$callback_chatid,$text,$keyboard);
            	$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$resKey );
            	
            	/*$resKey = json_decode($resKey, true)['result']['message_id'];
            	if($resKey){
            	    $newTime = time()+120;
            	    $data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$resKey,"time"=>$newTime);
            	    $this->telegram_model->set_telegram_music_timer($data);
            	}*/
                
                
            }else{
                $thisIdSaved = $content[1];
                $track = $this->telegram_model->get_telegram_music_id($thisIdSaved);
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $perfa = $track[0]->performer_fa;
                $titfa = $track[0]->title_fa;
                $perfen = $track[0]->performer_en;
                $titlen = $track[0]->title_en;
                $hajm = $track[0]->hajm;
                
                $sub_title1 = "🔰| موزیک ".$mix."  ".$mood."  ".$pod."  ".$light;
            
                $sub_title2 = "👤| #".str_ireplace(" ","_",$perfa);
                
                $sub_title3 = "🎵| ".$titfa;
                
                $sub_title4 = "🔴| حجم ".trim($hajm).'MB';
                $capt_aud = $sub_title1."\n\n".$sub_title2."\n\n".$sub_title3."\n\n".$sub_title4."\n\n@VieraMagazine\n@VieraMusik";
                $sendAud = $this->telegram_model->send_audio($token,$callback_chatid,$capt_aud,$track[0]->file_id);
                //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$track[0]->title_en );
            }
        }
    }
    elseif($content[0] == "vmu2"){
        //$this->telegram_model->send_message_only($token,'-1001155301071',$callback_message);
        //$p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
        if($content[2] != $callback_user){
            $this->telegram_model->send_message_only($token,$callback_chatid,"این درخواست از طرف کاربر دیگری بوده. شما مجاز به استفاده از آن نیستید.");
            die();
        }else{
            $source_del = "./application/$callback_user";
            $req = $this->telegram_model->get_music_timer_user($callback_user);
            $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
            if($content[1] == "delReq"){
                //$p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $this->telegram_model->clear_telegram_music_timer($callback_user);
                $result = exec("rm -rf $source_del");
                die();
            }elseif(is_numeric($content[1])){
                // from memory
                $track = $this->telegram_model->get_telegram_music_id($content[1]);
                $this->telegram_model->send_message_only($token,'-1001155301071',$track[0]->file_id);
                $waitRes = $this->telegram_model->send_message_only($token,$callback_chatid,"لطفا کمی صبر کنید");
                $waitMid = json_decode($waitRes, true)['result']['message_id'];
                
                $perfa = $track[0]->performer_fa;
                $titfa = $track[0]->title_fa;
                $perfen = $track[0]->performer_en;
                $titlen = $track[0]->title_en;
                $titleSend = $titlen." - ".$perfen;
                $hajm = $track[0]->hajm;
                
                $sub_title1 = "🔰| موزیک ".$mix."  ".$mood."  ".$pod."  ".$light;
            
                $sub_title2 = "👤| #".str_ireplace(" ","_",$perfa);
                
                $sub_title3 = "🎵| ".$titfa;
                
                $sub_title4 = "🔴| حجم ".trim($hajm).'MB';
                $capt_aud = $sub_title1."\n\n".$sub_title2."\n\n".$sub_title3."\n\n".$sub_title4."\n\n@VieraMagazine\n@VieraMusik";
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                $sendAud = $this->telegram_model->send_audio($token,$callback_chatid,$capt_aud,$track[0]->file_id,"@VieraBot",$titleSend,$req[0]->user_pid);
                $this->telegram_model->clear_telegram_music_timer($callback_user);
                $result = exec("rm -rf $source_del");
            }else{
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $cookies = "./application/youtubecookies.txt";
                if(is_dir($source_del)){
                    // download from net
                    $allJsons = glob("$source_del/*.json");
                    if(count($allJsons) < 2){
                        die();
                    }
                    $this->telegram_model->send_message_only($token,'-1001155301071',"more112");
                    //$p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                    $thisId = $content[1];
                    $url = "https://www.youtube.com/watch?v=$thisId";
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"this url y: ".$url);
                    //--audio-quality 8
                    $down = exec("yt-dlp --cookies $cookies -f 'ba[filesize<200M]' -w --no-check-certificates --restrict-filenames -x --audio-format mp3 --encoding UTF8 -o '$source_del/%(title)s.%(ext)s' $url 2>&1",$out);
                    $this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$down);
                    
                    if(strpos($down, "format is not available") > 0){
                        $this->telegram_model->send_message_only($token,'-1001155301071',"متاسفانه این فایل قابل دریافت نبود");
                    }
                    
                    
                    //$result1 = exec("ffmpeg -y -f mp3 -i $source -i $cover -map 0:0 -map 1:0  -c copy -metadata Title='$title' -metadata artist='@VieraBot' -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' -map_metadata -1 $dest 2>&1",$out);
                    
                    /*preg_match_all('/\d+\.\d+/', $down, $matches, PREG_OFFSET_CAPTURE);
                    $size = $matches[0][1][0];
                    
                    $this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$size);
                    $unit = substr($down,strpos($down,$size),strlen($size)+3);
                    $this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$unit);
                    if(strpos($unit,"K") > 0 || strpos($unit,"k") > 0){
                        $size = number_format($size / 1000, 2, '.', '');
                    }elseif(strpos($unit,"G") > 0 || strpos($unit,"g") > 0){
                        $size = number_format($size * 1000, 2, '.', '');
                    }*/
                    
                    $jsonFile = "$source_del/$thisId.info.json";
                    $string = file_get_contents($jsonFile);
        	        $json_content = json_decode($string, true);
                    $id = $json_content['id'];
                    $title = $json_content['title'];
                    $title = str_ireplace("video","",$title);
                    $title = str_ireplace("Video","",$title);
                    $title = str_ireplace("VIDEO","",$title);
                    
                    $artist = $json_content['artist'];
                    $desc = $json_content['description'];
                    $duration = $json_content['duration'];
                    $durHuman = $json_content['duration_string'];
                    $view = $json_content['view_count'];
                    $fileSize = $json_content['filesize_approx'];
                    $imageId = $json_content['thumbnails'];
                    $imageurl = $json_content['thumbnail'];
                    $source = glob("$source_del/*.mp3")[0];
                    $sizeUnit = exec("du -sh $source | cut -f1")."B";
                    $size = substr($sizeUnit, 0, -2);
                    $caption = "$title\n\n$size MB\n\ntime: $durHuman\n\n@VieraBot";
                    /*if(strlen($artist) > 0){
                        $titleSend = "$title - $artist";
                    }else{
                        $titleSend = "$title";
                    }*/
                    
                    
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"more112 size: ".$size);
                    for($k = 0; $k < count($allJsons); $k++){
                        unlink($allJsons[$k]);
                    }
                    
                    $logo = "./application/img/logowhite_full.png";
                    $dest1 = "./application/$callback_user/musicSave.mp3";
                    //-map_metadata -1
                    //$result = exec("ffmpeg -y -i $url1  -vn -ab 256 -metadata artist='@vieraBot' $source 2>&1");
                    //-id3v2_version 3 -metadata:s:v title='$title' -metadata:s:v artist='t.me/VieraBot' -metadata:s:v comment='t.me/VieraMagazine'
                    $result1 = exec("ffmpeg -y -i $source -i $logo -map 0:0 -map 1:0 -c copy -id3v2_version 2 -metadata artist='t.me/vieraBot' -metadata copyright='Copyright 2009 Me' -metadata Comment='t.me/vieraBot' -metadata title='$title' $dest1 2>&1",$out);
                    rename($dest1,$source);
                    
                    if($size < 50){
                        $audsend = $this->telegram_model->send_audio_online($token,$callback_chatid,$caption,$source,"@VieraBot",$title,$req[0]->user_pid);
                        //$vidsend = $this->telegram_model->send_video_repl($token,$callback_chatid,$source,"","",$caption,$req[0]->user_pid);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"send from y: ".$vidsend);
                    }elseif($size < 200){
                        if($size < 90){
                            $peace = 2;
                        }elseif($size < 120){
                            $peace = 3;
                        }else{
                            $peace = 4;
                        }
                        
                        $segTime = ceil($duration / $peace);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
                        $change = exec("ffmpeg -i $source -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp3 2>&1",$out);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$change);
                        
                        $list = glob("$source_del/file*.*");
                        for($i = 0; $i < count($list); $i++){
                            $counter = $i+1;
                            $audsend = $this->telegram_model->send_audio_online($token,$callback_chatid,$caption,$list[$i],"@VieraBot",$title,$req[0]->user_pid);
                            if($chatid1 != '-1001155301071'){
                                $audsend = $this->telegram_model->send_audio_online($token,'-1001155301071',$caption,$list[$i],"@VieraBot",$title,$req[0]->user_pid);
                            }
                        }
                    }elseif($size > 150){
                        $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا بود نشد بفرستم");
                    }
                    
                    $this->telegram_model->clear_telegram_music_timer($callback_user);
                    $result = exec("rm -rf $source_del");
                    
                }else{
                    // search more 2
                    
                    exec("mkdir $source_del");
                    $nameAndtitle = $content[1];
                    $this->telegram_model->send_message_only($token,'-1001155301071',"more2");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2" );
                    //$down = exec("yt-dlp -f 'ba' --write-info-json --max-downloads 3 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                    /*$text = "";
                    if(gettype(strpos($nameAndtitle,"#")) == "integer"){
                        $text = "--playlist-random";
                    }*/ 
                    $down = exec("yt-dlp --cookies $cookies -f 'ba[filesize<300M]' --write-info-json --skip-download --max-downloads 5 --restrict-filenames --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                    // --compat-options --no-check-certificates --cookies $cookies
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"$down" );
                    //rename("$source_del/_.info.json","$source_del/_.info1.json");
                    //$jsonFile = glob("$source_del/[!_]*.info.json", GLOB_BRACE);
                    
                    $jsonFile = glob("$source_del/*.info.json");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".count($jsonFile) );
                    for($k = 0; $k < count($jsonFile); $k++){
                        $string = file_get_contents($jsonFile[$k]);
            	        $json_content = json_decode($string, true);
                        $type = $json_content['_type'];
                        if($type == "playlist"){
                            rename($jsonFile[$k],"$source_del/_.info1.json");
                        }
                    }
                    
                    $jsonFile = glob("$source_del/*.info.json");
                    $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
                    $text = $this->telegram_model->toPersianNum($text);
                    $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
                	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
                    $arraynumber = 0;
                	$jw = 1;
                	$row = 1;
                    for($i = 0; $i < count($jsonFile)+1; $i++){
                	    if($i == count($jsonFile)){
                	        array_push($arraydata[$arraynumber],array(text=>"حذف درخواست",callback_data=>"vmu2*-delReq*-$callback_user"));
                	    }else{
                	        $string = file_get_contents($jsonFile[$i]);
                	        $json_content = json_decode($string, true);
                            $vid = $json_content['id'];
                            $title = $json_content['title'];
                            $artist = $json_content['artist'];
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".$title );
                            //if(strlen($title) > 100){
                                    
                            //}
                	        array_push($arraydata[$arraynumber],array(text=>$title,callback_data=>"vmu2*-$vid*-$callback_user"));
                	    }
                		if($jw % 1 == 0){
                	        $arraynumber++;
                	    }
                        $jw++;
                    }
                    
                    $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                	$keyboard =  array("inline_keyboard" => $arraydata);
                	$resKey = $this->telegram_model->send_message($token,$callback_chatid,$text,$keyboard);
                	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$resKey );
                	$resKey = json_decode($resKey, true)['result']['message_id'];
                	if($resKey){
                	    $newTime = time()+120;
                	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$resKey,"time"=>$newTime);
                	    $data = array("pid"=>$resKey,"time"=>$newTime);
                	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$lastpost,"time"=>$newTime);
                	    $updateRes = $this->telegram_model->update_music_timer($data,$user_id);
                	    //$this->telegram_model->set_telegram_music_timer($data);
                	}
                    
                    
                }
            }
        }
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    elseif($content[0] == "vc"){
        if($content[2] != $callback_user){
            $this->telegram_model->send_message_only($token,$callback_chatid,"این درخواست از طرف کاربر دیگری بوده. شما مجاز به استفاده از آن نیستید.");
            die();
        }else{
            $source_del = "./application/$callback_user";
            $req = $this->telegram_model->get_music_timer_user($callback_user);
            if($content[1] == "delReq"){
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $this->telegram_model->clear_telegram_music_timer($callback_user);
                $result = exec("rm -rf $source_del");
                die();
            }elseif(is_numeric($content[1])){
                
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                
                $waitRes = $this->telegram_model->send_message_only($token,$callback_chatid,"لطفا کمی صبر کنید");
                $waitMid = json_decode($waitRes, true)['result']['message_id'];
                $cookies = "./application/youtubecookies.txt";
                $thisId = $content[1];
                $content = $this->telegram_model->get_telegram_video_byId($thisId);
                
                //$this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".count($content));
                
                if(isset($content)){
                    if(strlen($content[0]->t_vid) > 0){
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".count($content));
                        $vidsend1 = $this->telegram_model->send_video_repl_online($token,$callback_chatid,$content[0]->t_vid,"","",$caption,$req[0]->user_pid);
                        $this->telegram_model->clear_telegram_music_timer($callback_user);
                        $result = exec("rm -rf $source_del");
                    }else{
                        if(is_dir($source_del)){
                            die();
                        }else{
                            exec("mkdir $source_del");
                        }
                        $ytId = $content[0]->video_id;
                        $url = "https://www.youtube.com/watch?v=$ytId";
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"this url y: ".$url);
                        
                        //--playlist-random
                        $down = exec("yt-dlp --cookies $cookies -f 'b[height<=480][ext=mp4]/b[height<=720][ext=mp4]' --no-check-certificates --restrict-filenames --encoding UTF8 -o '$source_del/%(title)s.%(ext)s' $url 2>&1",$out);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$down);
                        
                        $jsonFile = "$source_del/$thisId.info.json";
                        $string = file_get_contents($jsonFile);
            	        $json_content = json_decode($string, true);
                        $id = $json_content['id'];
                        $title = $json_content['title'];
                        $artist = $json_content['artist'];
                        $desc = $json_content['description'];
                        $duration = $json_content['duration'];
                        $durHuman = $json_content['duration_string'];
                        $view = $json_content['view_count'];
                        $imageId = $json_content['thumbnails'];
                        $imageurl = $json_content['thumbnail'];
                        /*$imageurl = [];
                        for($z = 0; $z < count($imageId); $z++){
                            if(strpos($imageId[$z]['resolution'],"720") > 0 || $imageId[$z]['id'] == "34" || $imageId[$z]['id'] == "38" || $imageId[$z]['id'] == "40"){
                                //$imageurl[$z] = $imageId[$z]['url'];
                                array_push($imageurl, $imageId[$z]['url']);
                            }
                            
                        }*/
                        
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"music image thumb: $imageurl");
                        //$tags = json_encode($json_content['tags']);
                        $tags = $json_content['tags'];
                        for($x = 0; $x < count($tags); $x++){
                            $ca = str_word_count($tags[$x],1);
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"is inglish?: ".$ca[0]);
                            if($ca[0]){
                                continue;
                            }
                            if($x < count($tags)-1){
                                $allTags .= $tags[$x].",-,";
                            }else{
                                $allTags .= $tags[$x];
                            }
                        }  
                        $duration_string = $json_content['duration_string'];
                        $track = glob("$source_del/*.mp4")[0];
                        $size = exec("du -sh $track | cut -f1")."B";
                        $caption = "$title\n\nحجم: $size\n\nزمان: $durHuman\n\n@VieraBot\n@VieraMagazine";
                        
                        
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"music send res: ".count($req));
                        
                        //$vidsend1 = $this->telegram_model->send_video($token,$callback_chatid,$track,"","",$caption);
                        $vidsend1 = $this->telegram_model->send_video_repl($token,$callback_chatid,$track,"","",$caption,$req[0]->user_pid);
                        //$sendAud = $this->telegram_model->send_audio_online($token,$callback_chatid,$caption,$track,"@VieraBot",$title);
                        
                        
                        //$p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                        
                        if($callback_chatid != '-1001155301071'){
                            $caption2 = "$title\n$size\n$url\n$allTags\n\n@VieraBot\n@VieraMagazine";
                            $imageSend = $this->telegram_model->send_photo($token,'-1001155301071',$imageurl ,$caption2);
                            $this->telegram_model->send_message_only($token,'-1001155301071',"photo send res: ".$imageSend);
                            $mid = json_decode($vidsend1, true)['result']['message_id'];
                            $forwardRes = $this->telegram_model->forward($token,$callback_chatid,$mid,'-1001155301071');
                            $forwardMid = json_decode($forwardRes, true)['result']['message_id'];
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"forward mid: $forwardMid");
                            $this->telegram_model->edit_message_caption($token,'-1001155301071',$forwardMid,$caption2);
                        }
                        $this->telegram_model->clear_telegram_music_timer($callback_user);
                        $result = exec("rm -rf $source_del");
                    }
                }
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                $this->telegram_model->clear_telegram_music_timer($callback_user);
                $result = exec("rm -rf $source_del");
            }else{
                $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                $cookies = "./application/youtubecookies.txt";
                
                if(is_dir($source_del)){
                    $allJsons = glob("$source_del/*.json");
                    if(count($allJsons) < 1){
                        die();
                    }
                    $this->telegram_model->send_message_only($token,'-1001155301071',"more111");
                    //$thisMusicTimerUser = $this->telegram_model->get_music_timer_user($callback_user);
                    //$p = $this->telegram_model->delete_message_one($token,$callback_chatid,$thisMusicTimerUser[0]->pid);
                    $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$callback_message_id);
                    
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"more1");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"$source_del");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"$nameAndtitle");
                    $thisId = $content[1];
                    $url = "https://www.youtube.com/watch?v=$thisId";
                    $this->telegram_model->send_message_only($token,'-1001155301071',"this url y: ".$url);
                    /*$text = "";
                    if(gettype(strpos($nameAndtitle,"#")) == "integer"){
                        $text = "--playlist-random";
                    }*/
                    $down = exec("yt-dlp --cookies $cookies -f 'b[height<=360]/b[height<=480]/b[height<=720]' --no-check-certificates --restrict-filenames --encoding UTF8 -o '$source_del/%(title)s.%(ext)s' $url 2>&1",$out);
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$down);
                    preg_match_all('/\d+\.\d+/', $down, $matches, PREG_OFFSET_CAPTURE);
                    $size = $matches[0][1][0];
                    $this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$size);
                    $unit = substr($down,strpos($down,$size),strlen($size)+3);
                    $this->telegram_model->send_message_only($token,'-1001155301071',"download from y: ".$unit);
                    if(strpos($unit,"K") > 0 || strpos($unit,"k") > 0){
                        $size = number_format($size / 1000, 2, '.', '');
                    }elseif(strpos($unit,"G") > 0 || strpos($unit,"g") > 0){
                        $size = number_format($size * 1000, 2, '.', '');
                    }
                    
                    $jsonFile = "$source_del/$thisId.info.json";
                    $string = file_get_contents($jsonFile);
        	        $json_content = json_decode($string, true);
                    $id = $json_content['id'];
                    $title = $json_content['title'];
                    $artist = $json_content['artist'];
                    $desc = $json_content['description'];
                    $duration = $json_content['duration'];
                    $durHuman = $json_content['duration_string'];
                    $view = $json_content['view_count'];
                    $fileSize = $json_content['filesize_approx'];
                    $imageId = $json_content['thumbnails'];
                    $imageurl = $json_content['thumbnail'];
                    $caption = "$title\n\n$size MB\n\ntime: $durHuman\n\n@VieraBot";
                    $source = glob("$source_del/*.mp4")[0];
                    $this->telegram_model->send_message_only($token,'-1001155301071',"more112 size: ".$size);
                    if($size < 50){
                    
                        //$vidsend = $this->telegram_model->send_video($token,$callback_chatid,$source,"","",$caption);
                        $vidsend = $this->telegram_model->send_video_repl($token,$callback_chatid,$source,"","",$caption,$req[0]->user_pid);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"send from y: ".$vidsend);
                        
                    }elseif($size < 349){
                        if($size < 90){
                            $peace = 2;
                        }elseif($size < 120){
                            $peace = 3;
                        }elseif($size < 170){
                            $peace = 4;
                        }elseif($size < 210){
                            $peace = 5;
                        }elseif($size < 270){
                            $peace = 6;
                        }else{
                            $peace = 7;
                        }
                        
                        $segTime = ceil($duration / $peace);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
                        $change = exec("ffmpeg -i $source -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp4 2>&1",$out);
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$change);
                        
                        $list = glob("$source_del/file*.*");
                        for($i = 0; $i < count($list); $i++){
                            $counter = $i+1;
                            $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$title."\npart-$counter");
                            if($chatid1 != '-1001155301071'){
                                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$title."\npart-$counter");
                            }
                        }
                    }elseif($size > 250){
                        $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا بود شرمنده نشد بفرستم");
                    }
                    
                    $this->telegram_model->clear_telegram_music_timer($callback_user);
                    $result = exec("rm -rf $source_del");
                    
                }else{
                    exec("mkdir $source_del");
                    $nameAndtitle = $content[1];
                    $this->telegram_model->send_message_only($token,'-1001155301071',"more2");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2" );
                    //$down = exec("yt-dlp -f 'ba' --write-info-json --max-downloads 3 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                    /*$text = "";
                    if(gettype(strpos($nameAndtitle,"#")) == "integer"){
                        $text = "--playlist-random";
                    }*/
                    $down = exec("yt-dlp --cookies $cookies -f 'b' --write-info-json --skip-download --max-downloads 5 --restrict-filenames --playlist-random --encoding UTF8 'ytsearch20:$nameAndtitle' -o '$source_del/%(id)s.%(ext)s' 2>&1",$out);
                    // --compat-options --no-check-certificates --cookies $cookies
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"$down" );
                    //rename("$source_del/_.info.json","$source_del/_.info1.json");
                    //$jsonFile = glob("$source_del/[!_]*.info.json", GLOB_BRACE);
                    
                    $jsonFile = glob("$source_del/*.info.json");
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".count($jsonFile) );
                    for($k = 0; $k < count($jsonFile); $k++){
                        $string = file_get_contents($jsonFile[$k]);
            	        $json_content = json_decode($string, true);
                        $type = $json_content['_type'];
                        if($type == "playlist"){
                            rename($jsonFile[$k],"$source_del/_.info1.json");
                        }
                    }
                    
                    $jsonFile = glob("$source_del/*.info.json");
                    $text ="گزینه مورد نظر خود را انتخاب کنید\n\nبرای جلوگیری از اختلال این درخواست بعد از 2 دقیقه حذف میگردد";
                    $text = $this->telegram_model->toPersianNum($text);
                    $array_mon = array("1","2","3","4","5","6","7","8","9","10","11");
                	$arraydata = array(array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array(),array());
                    $arraynumber = 0;
                	$jw = 1;
                	$row = 1;
                    for($i = 0; $i < count($jsonFile)+1; $i++){
                	    if($i == count($jsonFile)){
                	        array_push($arraydata[$arraynumber],array(text=>"حذف درخواست",callback_data=>"vc*-delReq*-$callback_user"));
                	    }else{
                	        $string = file_get_contents($jsonFile[$i]);
                	        $json_content = json_decode($string, true);
                            $vid = $json_content['id'];
                            $title = $json_content['title'];
                            $artist = $json_content['artist'];
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"music: here2 ".$title );
                            //if(strlen($title) > 100){
                                    
                            //}
                	        array_push($arraydata[$arraynumber],array(text=>$title,callback_data=>"vc*-$vid*-$callback_user"));
                	    }
                		if($jw % 1 == 0){
                	        $arraynumber++;
                	    }
                        $jw++;
                    }
                    
                    $p = $this->telegram_model->delete_message_one($token,$callback_chatid,$waitMid);
                	$keyboard =  array("inline_keyboard" => $arraydata);
                	$resKey = $this->telegram_model->send_message($token,$callback_chatid,$text,$keyboard);
                	//$this->telegram_model->send_message_only($token,'-1001155301071',"music: here11 ".$resKey );
                	$resKey = json_decode($resKey, true)['result']['message_id'];
                	if($resKey){
                	    $newTime = time()+120;
                	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$resKey,"time"=>$newTime);
                	    $data = array("pid"=>$resKey,"time"=>$newTime);
                	    //$data = array("uid"=>$user_id,"cid"=>$chatid1,"pid"=>$lastpost,"time"=>$newTime);
                	    $updateRes = $this->telegram_model->update_music_timer($data,$user_id);
                	    //$this->telegram_model->set_telegram_music_timer($data);
                	}
                }
            }
            
        }
    }
}
    
if($chatid1 == '-1001155301071'){
    $saveMusicCommand = "ذخیره موزیک";
    //$this->telegram_model->send_message_only($token,'-1001155301071',"save music1: \n$message");
    if(gettype(strpos($message,$saveMusicCommand)) == "integer" && strpos($message,$saveMusicCommand) < 1){
        $content1 = explode("-",$message);
        $artistfa = trim($content1[1]);
        $titlefa = trim($content1[2]);
        $artisten = trim($content1[3]);
        $titleen = trim($content1[4]);
        $tags = trim($content1[5]);
        
        $content2 = explode("\n",$repl_caption);
        $namesrc = trim($content2[0]);
        $size = trim(substr($content2[1],0,-1));
        $src = trim($content2[2]);
        if(strlen($tags) == 0){
            $tags = str_ireplace("-,","",trim($content2[3]));
        }
        
        $this->telegram_model->send_message_only($token,'-1001155301071',"save music2:\n $artistfa\n$titlefa\n$artisten\n$titleen\n$tags\n$size\n$src");
        $data = array("title_en"=>$titleen,"title_fa"=>$titlefa,"performer_en"=>$artisten,"performer_fa"=>$artistfa,"hajm"=>$size,"mime"=>"mp3","src"=>$src,"tags"=>$tags);
        $this->telegram_model->set_telegram_music_sent($data);
    }
}

//befor music save
if($chatid1 == '-1001155301071' && $message_photo){ 
    if(gettype(strpos($capt,"pmc")) == "integer" || gettype(strpos($capt,"PMC")) == "integer"){
        if(strlen($message_photo[2]->file_id) > 0){
        
            $thisPhoto = $message_photo[2]->file_id;
        }elseif(strlen($message_photo[1]->file_id) > 0){
            
            $thisPhoto = $message_photo[1]->file_id;
        }else{
            $thisPhoto = $message_photo[0]->file_id;
        }
        $file = $this->telegram_model->get_file($token,$thisPhoto);
        $file = json_decode($file, true);
        $url1 = "https://api.telegram.org/file/bot".$token."/".$file["result"]["file_path"];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$url1);
        $mime = substr($url1,-3);
        
        $captNew = $this->telegram_model->remove_emoji($capt);
        $imgInfo = explode("\n",$captNew);
        
        $perf = trim($imgInfo[0]);
        $titl = trim($imgInfo[1]);
        $musicName = $perf."-".$titl;
        $source = "./application/$musicName.$mime";
        $hajm = $this->telegram_model->download_file2($url1,$source);
        
        $outFileName2 = "./application/pic2.jpg";
        $newSource = "./application/pic3.jpg";
        $outFileName_img2 = "./application/img/cadr-1.png";
        $outFileName_img3 = "./application/newsize_cadr.png";
        $outFileName_img4 = "./application/newsize_logowatermark.jpg";
        $outFileName_img5 = "./application/img/logo-watermark.png";
        
        $image_resolotion = $this->telegram_model->imagesize($source);
        $width = $image_resolotion[0];
        $height = $image_resolotion[1];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$width."-1-".$height );
        
        $this->telegram_model->cropimage($source,$outFileName2,0,0,-30,0,$width,$height,$width+60,$height-20);
        
        $image_resolotion1 = $this->telegram_model->imagesize($outFileName2);
        $width1 = $image_resolotion1[0];
        $height1 = $image_resolotion1[1];
        
        $this->telegram_model->resize_image2($outFileName_img2,$outFileName_img3,$width+130,$height);
        $this->telegram_model->resize_image2($outFileName_img5,$outFileName_img4,120,135);
        
        $this->telegram_model->watermark_image2($outFileName2,$outFileName_img3, $outFileName_img3,-65,0);
        $this->telegram_model->watermark_image2($outFileName_img3,$outFileName_img4, $source,10,$height1/2-20);
        
        $zxx = $this->telegram_model->send_photo_online($token,'-1001155301071',$source,$capt);
        
        unlink($outFileName_img3);
        unlink($outFileName_img4);
        unlink($outFileName2);
        $infoArray = ["ایرانی","خارجی","جدید","قدیمی","ریمیکس","شاد","غمگین","لایت","پادکست","عاشقانه"];
        for($i = 0; $i < count($infoArray); $i++){
            $infoText .= $i." - ".$infoArray[$i]."\n";
        }
        $this->telegram_model->send_message_only($token,'-1001155301071',$infoText );
    }
    
}

if($chatid1 == '-1001155301071' && $repl_audio_fid){
    $info = explode("-",$message);
    if($info[0] == "ذخیره"){
        if(gettype(strpos($repl_caption,"pmc")) == "integer" || gettype(strpos($repl_caption,"PMC")) == "integer"){
            $perfa = trim($info[1]);
            $titfa = trim($info[2]);
            $info = trim($info[3]);
            
            $infoArray = ["ایرانی","خارجی","جدید","قدیمی","ریمیکس","شاد","غمگین","لایت","پادکست","عاشقانه"];
            
            $picName = "./application/$repl_audio_per-$repl_audio_tit.jpg";
            $picNameFF = "./application/sourcePMC.jpg";
            rename($picName,$picNameFF);
            
            $dest1 = "./application/musicSave-$chatid1.mp3";
            
            //$source = "./application/";
            $file = $this->telegram_model->get_file($token,$repl_audio_fid);
            $file = json_decode($file, true);
            $url1 = "https://api.telegram.org/file/bot".$token."/".$file["result"]["file_path"];
            //$this->telegram_model->send_message_only($token,'-1001155301071',$url1);
            $mime = substr($url1,-3);
            $repl_audio_per = trim($repl_audio_per);
            $repl_audio_tit = trim($repl_audio_tit);
            $sendTitle = $repl_audio_per."-".$repl_audio_tit;
            $source = "./application/$repl_audio_per-$repl_audio_tit.$mime";
            $sourceFFau = "./application/sourcePMC.$mime";
            
            //$this->telegram_model->send_message_only($token,'-1001155301071',"hajm1: $sourceFF");
            $hajm = $this->telegram_model->download_file2($url1,$sourceFFau);
            
            
            $dest = "./application/VieraBot.mp3";
            $cover = "./application/img/logowhite_full.png";
            $result1 = exec("ffmpeg -y -f mp3 -i $sourceFFau -i $picNameFF -map 0:0 -map 1:0  -c copy -metadata Title='$sendTitle' -metadata artist='@VieraBot' -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' -map_metadata -1 $dest 2>&1",$out);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"hajm1: $result1");
            
            rename($dest,$source);
            rename($picNameFF,$picName);
            
            $tag_d1 = "✅ موزیک";

            if( strlen($mix) > 0 ){
                $tag_d6= "\n اجرا: ";       
            }else{
                $tag_d6= "\n خواننده: ";     
            }
            
            $tag_d7 = "\n موزیک: ";
            $tag_d8 = "\n\n@VieraMagazine\n@VieraMusik";
            /*$title = $info_music[0];
            $performer = $info_music[1];*/
            $cap_img = $tag_d1."\n".$tag_d3.$tag_d4.$tag_d5.$tag_d6.$perfa.$tag_d7.$titfa.$tag_d8;
            
            $sub_title1 = "🔰| موزیک ".$mix."  ".$mood."  ".$pod."  ".$light;
            
            $sub_title2 = "👤| #".str_ireplace(" ","_",$perfa);
            
            $sub_title3 = "🎵| ".$titfa;
            
            $sub_title4 = "🔴| حجم ".trim( round((intval($hajm)/1000000),1) ).'MB';
            $capt_aud = $sub_title1."\n\n".$sub_title2."\n\n".$sub_title3."\n\n".$sub_title4."\n\n@VieraMagazine\n@VieraMusik";
            
            $zxx = $this->telegram_model->send_photo_online($token,'@VieraMusik',$picName,$cap_img);
            $sendAud = $this->telegram_model->send_audio_online($token,'@VieraMusik',$capt_aud,$source,"@VieraBot",$sendTitle);
        }
        
        $vm1 = json_decode($sendAud, true);
        $data = array( 
                    "performer_fa"=>$perfa,
                    "title_fa"=>$titfa,
                    "title_en"=>$repl_audio_tit,
                    "performer_en"=>$repl_audio_per,
                    "file_id"=>$vm1["result"]["audio"]["file_id"],
                    "hajm"=>trim(round((intval($repl_audio_size)/1000000),1) ),
                    "time_set"=>time(),
                    "last_sent"=>1,
                    "info"=>$info,
                    "ch_pid"=>$vm1["result"]["message_id"]
                    
                    /*"mood"=>$mood,
                    "jadid"=>$jadid,
                    "light"=>$light,
                    "mix"=>$mix,
                    "pod"=>$pod,
                    "mime"=> $mime,
                    */
                    );
        $music_karbar = $this->telegram_model->set_telegram_music_sent($data);
        
        //$this->telegram_model->send_message_only($token,'-1001155301071',$music_karbar);
        
        /*$music_lastSent = $this->telegram_model->get_telegram_music_lastSent(1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($music_lastSent));
        $music_id = $music_lastSent[5]->id;
        $data = array("last_sent"=>0);
        $this->telegram_model->update_telegram_music_sent_lastSent($data,$music_id-5);*/
        $music_Sent1 = $this->telegram_model->get_telegram_music_sent($repl_audio_per,$repl_audio_tit);    
        $this->telegram_model->send_message_only($token,'-1001155301071',$music_Sent1[0]->title_en." -->"."در حافظه است");
        unlink($source);
        unlink($sourceFF);
        unlink($sourceFFau);
        unlink($picName);
        
        //جدید-حجم-میکس-مایم-لایت-مود-پاد-کانت-لایریک-تایم ست-چنل پی آی دی-لست سند-سورس-تگ
        /*$this->telegram_model->send_message_only($token,'-1001155301071',"1 ".$repl_audio_fid."\n".$repl_audio_per."\n".$repl_audio_tit."\n".$repl_audio_size);
        $this->telegram_model->send_message_only($token,'-1001155301071',"2 ".$hajm);
        $this->telegram_model->send_message_only($token,'-1001155301071',"3 ".$mime);*/
        /*$mention = getURLs($repl_caption, $entities);
        $this->telegram_model->send_message_only($token,'-1001155301071',"4 ".$mention[0]);*/
        
    }
}

if($chatid1 == '-1001155301071' && $message == " 123"){
    $thisMusic = $this->telegram_model->get_telegram_music_sent_info();
    //$this->telegram_model->send_message_only($token,'-1001155301071',$thisMusic[0]->file_id);
    $fid = $thisMusic[0]->file_id;
    $mix = $thisMusic[0]->mix;
    $light = $thisMusic[0]->light;
    $mood = $thisMusic[0]->mood;
    $pod = $thisMusic[0]->pod;
    
    $perfo = $thisMusic[0]->performer_en;
    $titel = $thisMusic[0]->title_en;
    $sendTitle = $titel."-".$perfo;
    $sendAud = $this->telegram_model->send_audio($token,'-1001155301071',"for info updateSKH-$fid",$thisMusic[0]->file_id,"@VieraBot",$sendTitle);
    $infoArray = ["ایرانی","خارجی","جدید","قدیمی","ریمیکس","شاد","غمگین","لایت","پادکست","عاشقانه"];
    for($i = 0; $i < count($infoArray); $i++){
        $infoText .= $i." - ".$infoArray[$i]."\n";
    }
    $this->telegram_model->send_message_only($token,'-1001155301071',$infoText );
}

if($chatid1 == '-1001155301071' && $repl_audio_fid){
    //$this->telegram_model->send_message_only($token,'-1001155301071',"this is \n".$repl_caption);
    if(strpos($repl_caption,"info updateSKH") > 0){
        $info = explode("updateSKH-",$repl_caption);
        $fid = $info[1];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$fid);
        $data = array("info"=>$message);
        $this->telegram_model->update_telegram_music_sent_info($data,$fid);
    }
}

if($chatid1 == '-1001155301071' && $repl_audio_fid){
    $info = explode("-",$message);
    if($info[0] == "آپدیت تگ"){
        $folder = "./application/$chatid1";
        if(is_dir($folder)){
            //$this->telegram_model->send_message_only($token,$chatid1,"سرورهای دانلود اینستاگرام کمی با کندی مواجه هستند. خیلی زود فایل مورد نظر رو براتون ارسال میکنم");
            //$this->telegram_model->send_message_only($token,$chatid1,"time: ");
            die();
        }else{
            exec("mkdir $folder");
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',$repl_audio_fid);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$repl_audio_per);
        $newPerf = $info[1];
        $newTitl = $info[2];
        
        $logo = "./application/img/logowhite_full.png";
        if(strlen($newTitl) > 0){
            $sendTitle = $newPerf."-".$newTitl;
        }else{
            $sendTitle = $newPerf;
        }
        
        $url = getURLs($repl_caption, $entities);
        $mention = getmention($repl_caption, $entities);
        $link = getlink($repl_caption, $entities);
        
        $repl_caption = str_ireplace($mention[0],"",$repl_caption);
        $repl_caption = str_ireplace($mention[1],"",$repl_caption);
        $repl_caption = str_ireplace($url[0],"",$repl_caption);
        $repl_caption = str_ireplace($url[1],"",$repl_caption);
        $repl_caption = str_ireplace($link[0],"",$repl_caption);
        $repl_caption = str_ireplace($link[1],"",$repl_caption);
        
        $file = $this->telegram_model->get_file($token,$repl_audio_fid);
        if(strpos($file,"file is too big") > 0){
            $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه ربات‌های تلگرام نمیتوانند فایل های بزرگ تر 20 مگابایت را دریافت کنند" );
            $result = exec("rm -rf $folder");
            die();
        }
        $file = json_decode($file, true);
        $url1 = "https://api.telegram.org/file/bot".$token."/".$file["result"]["file_path"];
        $mime = substr($url1,-3);
        //$source = "./application/$repl_audio_per-$repl_audio_tit.$mime";
        $source = "$folder/$newPerf-$newTitl.$mime";
        $sourceFFau = "$folder/source.$mime";
        $dest1 = "$folder/music.$mime";
        //$this->telegram_model->send_message_only($token,'-1001155301071',"hajm1: $sourceFF");
        $hajm = $this->telegram_model->download_file2($url1,$sourceFFau);
        //-af 'afade=type=out:start_time=55:duration=5'
        $result1 = exec("ffmpeg -y -f mp3 -i $sourceFFau -i $logo -map 0:0 -map 1:0  -c copy -metadata Title='$sendTitle' -metadata artist='@VieraBot' -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' -map_metadata -1 $dest1 2>&1",$out);
        
        rename($dest1,$source);
        $sendAud = $this->telegram_model->send_audio_online($token,$chatid1,$repl_caption,$source,"@VieraBot",$sendTitle);
        //$this->telegram_model->send_message_only($token,'-1001155301071',"ffmpg: $sendAud");
        unlink($source);
        unlink($sourceFFau);
        $result = exec("rm -rf $folder");
    }
}



if( /*$chatid1 == '-1001155301071'&&*/ $repl_to_uid && (strpos($repl_text,"pornhub.com") > 0) ){
   
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $type = json_decode($type, true);
    $this->telegram_model->send_message_only($token,'-1001155301071',$type['result']['type']);
    if($type['result']['type'] == "private" && $chatid1 == "53853580"){
        $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
        $source_del = "./application/$user_id";
        if(is_dir($source_del)){
            //$this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر شما یک ویدئو در جال پردازش دارید. لطفا درخواست خود را بعد از پایان ویدئوی قبلی ارسال کنید");
            die();
        }else{
            exec("mkdir $source_del");
        }
        $down = exec("yt-dlp --cookies $cookies --write-info-json -f 'b[height<=360]/b[height<=480]/b[height<=720]/b[height<=240]' --merge-output-format mp4 --encoding UTF8 $repl_text  -o '$source_del/%(id)s.%(ext)s' 2>&1",$out_title);
        //if(!(strpos($down,"Finished") > 0)){
            $this->telegram_model->send_message_only($token,'-1001155301071',$down);
        //}
        
        
        
        $vid = glob("$source_del/*.mp4",GLOB_BRACE)[0];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$vid);
        $size = exec("du $vid | cut -f1");
        $this->telegram_model->send_message_only($token,'-1001155301071',"size: ".$size);
        $id = substr($vid,strrpos($vid,"/")+1,-4);
        
        $info = file_get_contents("$source_del/$id.info.json");
        $info = json_decode($info, true);
        $duration_string = $info['duration_string'];
        $duration = $info['duration'];
        $artist = $info['artist'];
        $title = $info['title'];
        $caption = $info['description'];
        
        if(strlen(trim($duration)) == 0){
            $info_file = exec("mediainfo --Inform='Video;%Duration%:%BitRate%:%Height%' $vid");
            $info = explode(":",$info_file);
            //$Bitrate = $info[1];
            $duration = trim(round($info[0]/1000));
        }
        
        $this->telegram_model->send_message_only($token,'-1001155301071',"dur: ".$duration);
        if($size < 50000){
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$title);
        }elseif($size < 300000){
            if($size < 90000){
                $peace = 2;
            }elseif($size < 120000){
                $peace = 3;
            }elseif($size < 170000){
                $peace = 4;
            }elseif($size < 220000){
                $peace = 5;
            }elseif($size < 260000){
                $peace = 6;
            }else{
                $peace = 7;
            }
            
            $segTime = ceil($duration / $peace);
            $this->telegram_model->send_message_only($token,'-1001155301071',"peace: ".$peace);
            $this->telegram_model->send_message_only($token,'-1001155301071',"seg: ".$segTime);
            //die();
            $change = exec("ffmpeg -i $vid -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp4 2>&1",$out);
            $list = glob("$source_del/file*.*");
            for($i = 0; $i < count($list); $i++){
                $counter = $i+1;
                $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$title."\npart-$counter");
                if($chatid1 != '-1001155301071'){
                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$title."\npart-$counter");
                }
            }
        }elseif($size > 200000){
            $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا");
        }
        $text = "<a href='tg://user?id=".$user_id."'>User</a>";
        $this->telegram_model->send_message_only($token,'-1001155301071',"از هاب دانلود شد\n$chatid1\n$user_id\n$text");
        $result = exec("rm -rf $source_del");
        
        
    }
} 

if((mb_substr($message,0,9) == "ویراپورن1" || mb_substr($message,0,10) == "ویرا پورن1")){
    $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $type = json_decode($type, true);
    //$this->telegram_model->send_message_only($token,'-1001155301071',$type['result']['type']);
    if($type['result']['type'] == "private" && $chatid1 == "53853580"){
        
        $poCheck = $this->telegram_model->get_orderpo($user_id);
        //$this->telegram_model->send_message_only($token,'-1001155301071',"this 12");
        //$this->telegram_model->send_message_only($token,$chatid1,$poCheck[0]->cash);
        if($poCheck[0]->cash < 1000){
            $this->telegram_model->send_message_only($token,$chatid1,"موجودی شما کافی نمی‌باشد. لطفا اعتبار خود را افزایش دهید");
            die();
        }
        $source_del = "./application/$user_id";
        if(is_dir($source_del)){
            //$this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر شما یک ویدئو در جال پردازش دارید. لطفا درخواست خود را بعد از پایان ویدئوی قبلی ارسال کنید");
            die();
        }else{
            exec("mkdir $source_del");
        }
        if(mb_strpos($message,"-") > 0){
            $info = explode("-",$message);
            $item = str_ireplace(" ","+",trim($info[1]));
        }else{
            $item = "";
        }
        $cookies = "./application/pocookies.txt";
    
        $url_array = ["https://www.pornhub.com/playlist/75418201","https://www.pornhub.com/video?c=65","https://www.pornhub.com/video?c=8",
                    "https://www.pornhub.com/video?c=29","https://www.pornhub.com/categories/pornstar","https://www.pornhub.com/video/search?search=music+video&filter_category=121"];
        if(strlen($item) > 0){
            $url = "https://www.pornhub.com/video/search?search=$item";
        }else{
            $url = $url_array[mt_rand(0,5)];
        }
        //$this->telegram_model->send_message_only($token,'-1001155301071',$url);
        $vidNum = mt_rand(0,20);
        $down = exec("yt-dlp --cookies $cookies --write-info-json -f 'b[height<=360]/b[height<=480]/b[height<=720]' --merge-output-format mp4 -I $vidNum:$vidNum --encoding UTF8 $url  -o '$source_del/%(id)s.%(ext)s' 2>&1",$out_title);
        if(!(strpos($down,"Finished") > 0)){
            $this->telegram_model->send_message_only($token,'-1001155301071',$down);
        }
        //b[ext=mp4][height<=590]/bv[filesize<27M][ext=webm]+ba[filesize<3M][ext=m4a]
        
        $vid = glob("$source_del/*.mp4",GLOB_BRACE)[0];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$vid);
        $size = exec("du $vid | cut -f1");
        //$this->telegram_model->send_message_only($token,'-1001155301071',$sizeid);
        $id = substr($vid,strrpos($vid,"/")+1,-4);
        
        $info = file_get_contents("$source_del/$id.info.json");
        $info = json_decode($info, true);
        $duration_string = $info['duration_string'];
        $duration = $info['duration'];
        $artist = $info['artist'];
        $title = $info['title'];
        $caption = $info['description'];
        
        //$this->telegram_model->send_message_only($token,'-1001155301071',$title);
        if($size < 50000){
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$title);
        }elseif($size < 200000){
            if($size < 90000){
                $peace = 2;
            }elseif($size < 120000){
                $peace = 3;
            }elseif($size < 170000){
                $peace = 4;
            }else{
                $peace = 5;
            }
            
            $segTime = ceil($duration / $peace);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
            //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
            $change = exec("ffmpeg -i $vid -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp4 2>&1",$out);
            $list = glob("$source_del/file*.*");
            for($i = 0; $i < count($list); $i++){
                $counter = $i+1;
                $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$title."\npart-$counter");
                if($chatid1 != '-1001155301071'){
                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$title."\npart-$counter");
                }
            }
        }elseif($size > 200000){
            $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا");
        }
    }
    $this->telegram_model->send_message_only($token,'-1001155301071',"Po send result:\n $vidsend");
    $send_result = json_decode($vidsend, true);
    if($send_result['ok']){
        $this->telegram_model->send_message_only($token,'-1001155301071',"Po send result22: ok");
        //$data = array("uid"=>$user_id,"cash"=>0);
        $this->telegram_model->update_orderpo($user_id);
        $balance = $poCheck[0]->cash-10000;
        $this->telegram_model->send_message_only($token,$chatid1,"باقیمانده حساب شما: $balance تومان");
    }
    $text = "<a href='tg://user?id=".$user_id."'>User</a>";
    $this->telegram_model->send_message_only($token,'-1001155301071',"از هاب دانلود شد\n$chatid1\n$user_id\n$text");
    $result = exec("rm -rf $source_del");
}


if((mb_substr($message,0,9) == "ویراپورن2" || mb_substr($message,0,10) == "ویرا پورن2")){
    $this->telegram_model->send_message_only($token,'-1001155301071',"this po 2: ");
    
    $counterApi = $this->telegram_model->get_temp(2);
    //$diffTime = time() - $counterApi[0]->poet;
    if($counterApi[0]->content > 500){
        $this->telegram_model->send_message_only($token,'-1001155301071',"porn2 تعداد 500 درخواست خبر فیلم زده شده");
        $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
        die();
    }
    if($counterApi[0]->poet < time()){
        $data = array("content"=>0,"poet"=>$counterApi[0]->poet + 2592000);
        $this->telegram_model->update_temp(2,$data);
    }
    $data = array("content"=>($counterApi[0]->content)+1);
    $this->telegram_model->update_temp(2,$data);
    
    $source_del = "./application/$user_id";
    if(is_dir($source_del)){
        die();
    }else{
        exec("mkdir $source_del");
    }
    
    $url = "https://www.xvideos3.com/";
    $newList = $this->telegram_model->get_site_links($url);
    $newList = json_decode($newList,true);
    $this->telegram_model->send_message_only($token,'-1001155301071',count($newList['links']));
    $linksArray = array();
    for($i = 70; $i < 250; $i++){
        if(!in_array($newList['links'][$i], $linksArray) && strpos($newList['links'][$i],"/video.") > 0){
            array_push($linksArray,$newList['links'][$i]);;
        }
    }
    $this->telegram_model->send_message_only($token,'-1001155301071',count($linksArray));
    $index = mt_rand(0,count($linksArray)-1);
    $urlDown = $linksArray[$index];

    $urlDown = str_ireplace("https:/www.","https://",$urlDown);
    $down = exec("yt-dlp --write-info-json -f 'b[height<=360]/b[height<=480]/b[height<=720]/b' --merge-output-format mp4 --encoding UTF8 $urlDown  -o '$source_del/%(id)s.%(ext)s' 2>&1",$out_title);
    //$this->telegram_model->send_message_only($token,'-1001155301071',$down);
    //$title = substr($urlDown,strrpos($urlDown,"/"));
    
    $vid = glob("$source_del/*.mp4",GLOB_BRACE)[0];
    $vidJson = glob("$source_del/*.info.json",GLOB_BRACE)[0];
    //$this->telegram_model->send_message_only($token,'-1001155301071',$vid);
    $size = exec("du $vid | cut -f1");
    //$this->telegram_model->send_message_only($token,'-1001155301071',$size);
    $info = file_get_contents($vidJson);
    $info = json_decode($info, true);
    $duration_string = $info['duration_string'];
    $duration = $info['duration'];
    $artist = $info['artist'];
    $title = $info['title'];
    $desc = $info['description'];
    $caption = $title;
        
    $size = exec("du $vid | cut -f1");
    if($size < 50000){
        $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$title);
        if($chatid1 != '-1001155301071'){
            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$vid,"","",$title);
        }
    }elseif($size < 200000){
        if($size < 90000){
            $peace = 2;
        }elseif($size < 120000){
            $peace = 3;
        }elseif($size < 170000){
            $peace = 4;
        }else{
            $peace = 5;
        }
    
        $segTime = ceil($duration / $peace);
        //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
        //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
        $change = exec("ffmpeg -i $vid -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp4 2>&1",$out);
        $list = glob("$source_del/file*.*");
        for($i = 0; $i < count($list); $i++){
            $counter = $i+1;
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$title."\npart-$counter");
            if($chatid1 != '-1001155301071'){
                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$title."\npart-$counter");
            }
        }
    }elseif($size > 200000){
        $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا");
    }
    
    $result = exec("rm -rf $source_del");
}

if($message == "سفارش ویدئو" || $message == "سفارش ویدیو"){
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $type = json_decode($type, true);
    $this->telegram_model->send_message_only($token,'-1001155301071',"سفارش ویدیو داده شده\n".$type['result']['type']);
    if($type['result']['type'] == "private"){
        $data = array("uid"=>$user_id,"paytime"=>time(),"cash"=>0);
        $result = $this->telegram_model->set_orderpo($data);
        if($result){
            $this->telegram_model->send_message_only($token,$chatid1,"سفارش ثبت شد. پس از پرداخت مبلغ و ارسال فیش اکانت شما فعال می‌شود");
        }
    }
}

if($message == "ویرا متن"){
    //$res = $this->telegram_model->get_channel_posts();
    //$this->telegram_model->send_message_only($token,'-1001155301071',substr($res,0,200));
    $fromPo = mt_rand(1000, 5000);
    $toPo = $fromPo + 20;
    $file = "./application/input.json";
    $res = exec("curl 'https://api.apify.com/v2/acts/73JZk4CeKcDsWoJQu/runs?token=apify_api_tnKTFuJWe6g6ejDNKQf2hwCV9p2iLa3oirIu' -X POST -d '{\"channels\": [\"TeXt_NaZ_m\"],\"postsFrom\": $fromPo,\"postsTo\": $toPo,\"proxy\": {\"useApifyProxy\": true,\"apifyProxyGroups\": [\"RESIDENTIAL\"]}}' -H 'Content-Type: application/json'",$out_title);
    
    foreach($out_title as $line) {
        if(strpos($line,"DatasetId") > 0){
            $datasetId = trim(substr($line,strpos($line,":")+1,-2));
            $datasetId = trim(str_ireplace('"','',$datasetId));
            //$this->telegram_model->send_message_only($token,'-1001155301071',$datasetId );
            //$this->telegram_model->send_message_only($token,'-1001155301071',$line );
        }
        
    }
    
    $counterApi = $this->telegram_model->get_temp(19);
    $latDatasetId = $counterApi[0]->content;
    $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
    $data = array("content"=>$datasetId);
    $this->telegram_model->update_temp(19,$data);
    
    $outFileName = "./application/122222.txt";
    //$res = exec("curl 'https://api.apify.com/v2/datasets/$datasetId/items?token=apify_api_tnKTFuJWe6g6ejDNKQf2hwCV9p2iLa3oirIu' -X GET -H 'Content-Type: application/json'",$out_title1);
    file_put_contents($outFileName, fopen("https://api.apify.com/v2/datasets/$latDatasetId/items?clean=true&format=json&limit=1000", 'r'));
    $res = file_get_contents($outFileName);
    $res = json_decode($res, true);
    for($i = 0; $i < 5; $i++){
        $this->telegram_model->send_message_only($token,$chatid1,$res[$i]['text'] );
    }
    
    //$this->telegram_model->send_message_only($token,$chatid1,$res[1]['text'] );
}


if(strpos($repl_text,"xvideos") > 0 || strpos($repl_text,"xnxx") > 0 && $message == "دانلود"){
    $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
    $type = $this->telegram_model->get_chat($token,$chatid1);
    $type = json_decode($type, true);
    $this->telegram_model->send_message_only($token,'-1001155301071',"start Xv");
    if($type['result']['type'] == "private" && $chatid1 == "53853580"){
        $poCheck = $this->telegram_model->get_orderpo($user_id);
        if($poCheck[0]->cash < 1000){
            $this->telegram_model->send_message_only($token,$chatid1,"موجودی شما کافی نمی‌باشد. لطفا اعتبار خود را افزایش دهید");
            die();
        }
        $source_del = "./application/$user_id";
        if(is_dir($source_del)){
            //$this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر شما یک ویدئو در جال پردازش دارید. لطفا درخواست خود را بعد از پایان ویدئوی قبلی ارسال کنید");
            die();
        }else{
            exec("mkdir $source_del");
        }
        if(filter_var($repl_text, FILTER_VALIDATE_URL)){
            $url = filter_var($repl_text, FILTER_VALIDATE_URL);
        }else{
            $this->telegram_model->send_message_only($token,'-1001155301071',"لینک اشکال دارد");
            die();
        }
        
        //--cookies $cookies
        $down = exec("yt-dlp --write-info-json -f 'b[height<=360]/b[height<=480]/b[height<=720]' --embed-metadata --merge-output-format mp4 --encoding UTF8 $url  -o '$source_del/%(id)s.%(ext)s' 2>&1",$out_title);
        $this->telegram_model->send_message_only($token,'-1001155301071',$down);
        $vid = glob("$source_del/*.mp4",GLOB_BRACE)[0];
        $vidJson = glob("$source_del/*.info.json",GLOB_BRACE)[0];
        //$this->telegram_model->send_message_only($token,'-1001155301071',$vid);
        $size = exec("du $vid | cut -f1");
        //$this->telegram_model->send_message_only($token,'-1001155301071',$size);
        $info = file_get_contents($vidJson);
        $info = json_decode($info, true);
        $duration_string = $info['duration_string'];
        $duration = $info['duration'];
        $artist = $info['artist'];
        $title = $info['title'];
        $desc = $info['description'];
        $caption = $title;
        
        if($size < 50000){
            $this->telegram_model->send_message_only($token,'-1001155301071',"xv here 1");
            
            $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$caption);
            if($chatid1 != '-1001155301071'){
                $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$vid,"","",$caption);
            }
            
        }elseif($size < 200000){
            //$this->telegram_model->send_message_only($token,'-1001155301071',"xv here 2");
            if($size < 90000){
                $peace = 2;
            }elseif($size < 120000){
                $peace = 3;
            }elseif($size < 170000){
                $peace = 4;
            }else{
                $peace = 5;
            }
            
            $segTime = ceil($duration / $peace);
            //$this->telegram_model->send_message_only($token,'-1001155301071',"peace: $peace");
            //$this->telegram_model->send_message_only($token,'-1001155301071',$segTime);
            $change = exec("ffmpeg -i $vid -codec copy -map 0 -segment_time $segTime -reset_timestamps 1 -f segment $source_del/file%03d.mp4 2>&1",$out);
            $list = glob("$source_del/file*.*");
            for($i = 0; $i < count($list); $i++){
                $counter = $i+1;
                $vidsend = $this->telegram_model->send_video($token,$chatid1,$list[$i],"","",$title."\npart-$counter");
                if($chatid1 != '-1001155301071'){
                    $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$list[$i],"","",$title."\npart-$counter");
                }
            }
        }elseif($size > 200000){
            $this->telegram_model->send_message_only($token,'-1001155301071',"حجم بسیار بالا");
        }
        
        $result = exec("rm -rf $source_del");
        $send_result = json_decode($vidsend, true);
        if($send_result['ok']){
            //$this->telegram_model->send_message_only($token,'-1001155301071',"Xv send result22: ok");
            //$data = array("uid"=>$user_id,"cash"=>0);
            $this->telegram_model->update_orderpo($user_id);
            $balance = $poCheck[0]->cash-10000;
            $this->telegram_model->send_message_only($token,$chatid1,"باقیمانده حساب شما: $balance تومان");
        }
        $text = "<a href='tg://user?id=".$user_id."'>User</a>";
        $this->telegram_model->send_message_only($token,'-1001155301071',"از XV دانلود شد\n$chatid1\n$user_id\n$text");
        
    }
    
}
//****************************************************************************** inline command دستورات اینلاین در خط

if($inline_query == "ppp"){
    /*$counterApi = $this->telegram_model->get_temp(2);
    $diffTime = time() - $counterApi[0]->poet;
    if($counterApi[0]->content > 500 || $diffTime > 2592000 ){
        $this->telegram_model->send_message_only($token,'-1001155301071',"porn2 تعداد 500 درخواست خبر فیلم زده شده");
        $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
        die();
    }
    $data = array("content"=>($counterApi[0]->content)+1);
    $this->telegram_model->update_temp(2,$data);
    
    $url = "https://www.xvideos3.com/";
    $newList = $this->telegram_model->get_site_links($url);
    $newList = json_decode($newList,true);
    $linksArray = array();
    for($i = 70; $i < 250; $i++){
        if(!in_array($newList['links'][$i], $linksArray) && strpos($newList['links'][$i],"/video.") > 0){
            array_push($linksArray,$newList['links'][$i]);;
        }
    }
    $index = mt_rand(0,count($linksArray)-1);
    $urlDown = $linksArray[$index];
    
    $array_rand_test = array("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20");
    $array_rand_test = array_slice($array_rand_test,0,$end);
    $results = array();
	$counter = 1;
	for($i = 0; $i < $end; $i++){
	    $title_capt = "";
	    $title = "";
	    $vid = "";
	    $date = "";
	    $desc = "";
	    $thisId = $array_rand_test[$i];
	    //$thisId = $array_rand_test[$random_keys[$i]];
	    //$this->telegram_model->send_message_only($token,'-1001155301071',"inline: ".$videos[$thisId]->video_id);
        
        $title = "ویدئو ".($i+1);
        
        $vid = $videos[$thisId]->video_id;
        //$date = $this->persiandate->jdate("l Y/m/d",$videos[$thisId]->post_date,"",'Asia/Tehran',"fa");
        $caption = $videos[$thisId]->caption;
        $desc = $videos[$thisId]->descript;
        if(strlen($caption) > 2 && strlen($desc) > 2){
            $caption_all = "$title_capt\n\n$caption\n$desc\n\n@VieraBot\n@VieraMagazine";
        }elseif(strlen($caption) > 2){
            $caption_all = "$title_capt\n\n$caption\n\n@VieraBot\n@VieraMagazine";
        }else{
            $caption_all = "$title_capt\n\n@VieraBot\n@VieraMagazine";
        }
        
        $data = ["type" => "video","id" => "0$counter","title" => $title,"video_file_id" => $vid,"description"=>$caption,"caption"=>$caption_all];
        array_push($results,$data);
        $counter++;
    }
    $res = $this->telegram_model->inline_answer_video($token, $results, $inline_query_id);*/
	
}

if($inline_query == "اینستا"){
    $videos = $this->telegram_model->get_video_insta();
    if(count($videos) < 10){
	    $end = count($videos);
	}else{
	    $end = 10;
	}
    $array_rand_test = array("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20");
    //$array_rand_test = array("0","1","2","3","4","5","6","7","8","9","10","11","12","13");
    //$random_keys = array_rand($array_rand_test,10);
    $array_rand_test = array_slice($array_rand_test,0,$end);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"this count: ".count($array_rand_test));
    shuffle($array_rand_test);
    $results = array();
	$counter = 1;
	for($i = 0; $i < $end; $i++){
	    $title_capt = "";
	    $title = "";
	    $vid = "";
	    $date = "";
	    $desc = "";
	    $thisId = $array_rand_test[$i];
	    //$thisId = $array_rand_test[$random_keys[$i]];
	    //$this->telegram_model->send_message_only($token,'-1001155301071',"inline: ".$videos[$thisId]->video_id);
        if(strlen($videos[$thisId]->title) > 2){
            $title = $videos[$thisId]->title;
            $title_capt = "#".$videos[$thisId]->title;
        }else{
            $title = "ویدئو ".($i+1);
        }
        $vid = $videos[$thisId]->video_id;
        //$date = $this->persiandate->jdate("l Y/m/d",$videos[$thisId]->post_date,"",'Asia/Tehran',"fa");
        $caption = $videos[$thisId]->caption;
        $desc = $videos[$thisId]->descript;
        if(strlen($caption) > 2 && strlen($desc) > 2){
            $caption_all = "$title_capt\n\n$caption\n$desc\n\n@VieraBot\n@VieraMagazine";
        }elseif(strlen($caption) > 2){
            $caption_all = "$title_capt\n\n$caption\n\n@VieraBot\n@VieraMagazine";
        }else{
            $caption_all = "$title_capt\n\n@VieraBot\n@VieraMagazine";
        }
        
        $data = ["type" => "video","id" => "0$counter","title" => $title,"video_file_id" => $vid,"description"=>$caption,"caption"=>$caption_all];
        array_push($results,$data);
        $counter++;
    }
    $res = $this->telegram_model->inline_answer_video($token, $results, $inline_query_id);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"vid2:    ".$result[0]['video_file_id']);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"res:    ".$res);
}

//****************************************************************************** ویرایش تصویر

//******************************************************************************  حجم کم

/*if( ($chatid1 == '-1001155301071' || $chatid1 == '-1001700113991') && $repl_video_fid && $message == "حجم کم"){
    $message = $this->telegram_model->toEnglishNum($message);
    $thisSendWait = $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
    $waitMid = json_decode($thisSendWait, true)['result']['message_id'];
    $chat_send = $chatid1;
    $folder = "./application/$chatid1";
    if(is_dir($folder)){
        //$this->telegram_model->send_message_only($token,$chatid1,"سرورهای دانلود اینستاگرام کمی با کندی مواجه هستند. خیلی زود فایل مورد نظر رو براتون ارسال میکنم");
        //$this->telegram_model->send_message_only($token,$chatid1,"time: ");
        die();
    }else{
        exec("mkdir $folder");
    }
    $sorc = "$folder/sorc-123.mp4";
    $dest = "$folder/dest-1234.mp4";
    $mention = getmention($repl_caption, $entities);
    $urlcap = getURLs($repl_caption, $entities);
    $linkcap = getlink($repl_caption, $entities);
    $offset = getoffset($repl_caption, $entities);
    $repl_caption = mb_substr($repl_caption,0,$offset-1);
    
    $repl_caption = str_ireplace($mention[0],"",$repl_caption);
    $repl_caption = str_ireplace($mention[1],"",$repl_caption);
    $repl_caption = str_ireplace($mention[2],"",$repl_caption);
    $repl_caption = str_ireplace($urlcap[0],"",$repl_caption);
    $repl_caption = str_ireplace($urlcap[1],"",$repl_caption);
    $repl_caption = str_ireplace($linkcap[0],"",$repl_caption);
    $repl_caption = str_ireplace($linkcap[1],"",$repl_caption);
    $video_file = $this->telegram_model->get_file($token,$repl_video_fid);
    if(strpos($video_file,"file is too big") > 0){
        $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه ربات‌های تلگرام نمیتوانند فایل های بزرگ تر 20 مگابایت را دریافت کنند" );
        $result = exec("rm -rf $folder");
        die();
    }
    $video_file = json_decode($video_file, true);
    $url2 = "https://api.telegram.org/file/bot".$token."/".$video_file["result"]["file_path"];
    //$this->telegram_model->send_message_only($token,'-1001155301071',"url: ".$url2 );
    $size = $this->telegram_model->download_file2($url2,$sorc);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"url: ".$size );
    $old_crf = exec("ffmpeg -i $sorc -an -vframes 1 -f null - -v 48 2>&1 | grep -oE 'crf=[0-9\.]+'");
    $this->telegram_model->send_message_only($token,'-1001155301071',"حجم کم \n".$chat_send );
    //$this->telegram_model->send_message_only($token,'-1001155301071',"crf: ".$old_crf );
    if($crf < 25){
        $result = exec("ffmpeg -i $sorc -vf 'scale=trunc(iw/3)*2:trunc(ih/3)*2' -crf 28 -preset veryfast $dest 2>&1");
    }else{
        $result = exec("ffmpeg -i $sorc -vf 'scale=trunc(iw/3)*2:trunc(ih/3)*2' -preset veryfast $dest 2>&1");
    }
    //$this->telegram_model->//($token,'-1001155301071',"result: ".$result );
    if(strpos($result,"kb/s") > 0 || strpos($result,"Qavg:") > 0){
        $vidsend = $this->telegram_model->send_video($token,$chat_send,$dest,$w,$h,$repl_caption);
        $sendRes = json_decode($vidsend, true)['result']['message_id'];
        if($sendRes){
                    $p = $this->telegram_model->delete_message_one($token,$chatid1,$waitMid);
        }
    }
    $result = exec("rm -rf $folder");
}*/

if (($chatid1 == '-1001155301071' || $chatid1 == '-1001700113991') && $repl_video_fid && $message == "حجم کم") {
    
    // ۱. اطلاع‌رسانی شروع پردازش
    $thisSendWait = $this->telegram_model->send_message_only($token, $chatid1, "⏳ در حال بررسی و دریافت فایل از سرور تلگرام...");
    $waitMid = json_decode($thisSendWait, true)['result']['message_id'] ?? null;
    
    // ۲. ایجاد پوشه موقت اختصاصی برای این درخواست
    $tempId = time() . "_" . rand(100, 999);
    $folder = "./application/temp_low_$tempId";
    if (!is_dir($folder)) {
        mkdir($folder, 0777, true);
    }

    $sorc = "$folder/source.mp4";
    $dest = "$folder/compressed.mp4";

    // ۳. دریافت اطلاعات فایل از Bot API
    $video_file_raw = $this->telegram_model->get_file($token, $repl_video_fid);
    $video_file = json_decode($video_file_raw, true);

    if (isset($video_file["result"]["file_path"])) {
        $file_path = $video_file["result"]["file_path"];
        $file_url = "https://api.telegram.org/file/bot" . $token . "/" . $file_path;
        $file_size = $video_file["result"]["file_size"] ?? 0;

        // ۴. کنترل محدودیت ۲۰ مگابایت تلگرام
        if ($file_size > 20 * 1024 * 1024) {
             $this->telegram_model->edit_message($token, $chatid1, $waitMid, "❌ حجم این ویدیو حدود " . round($file_size / 1024 / 1024, 1) . " مگابایت است. ربات‌های معمولی اجازه دسترسی به فایل‌های بیش از ۲۰ مگابایت را ندارند.");
             exec("rm -rf " . escapeshellarg($folder));
             die();
        }

        // ۵. استفاده از متد بهینه smart_download برای دریافت فایل
        $download_res = $this->telegram_model->smart_download($file_url, $sorc);

        if (strpos($download_res, "SUCCESS") !== false && file_exists($sorc) && filesize($sorc) > 0) {
            
            $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚙️ فایل با موفقیت دریافت شد. در حال فشرده‌سازی و بهینه‌سازی حجم...");
            
            /**
             * ۶. اجرای FFMPEG با پارامترهای بهینه
             * - مقیاس ۶۰٪ (هوشمند و زوج)
             * - CRF 30 (تعادل عالی حجم و کیفیت)
             * - Preset Superfast (حداکثر سرعت پردازش)
             */
            $scale_filter = "scale='trunc(iw*0.6/2)*2:trunc(ih*0.6/2)*2'";
            $ffmpeg_cmd = "ffmpeg -y -i " . escapeshellarg($sorc) . " -vf $scale_filter -vcodec libx264 -crf 30 -preset superfast -pix_fmt yuv420p -acodec copy " . escapeshellarg($dest) . " 2>&1";
            
            exec($ffmpeg_cmd, $output);
            
            if (file_exists($dest) && filesize($dest) > 100) {
                
                // ۷. پاکسازی و آماده‌سازی کپشن
                $mention = (array)getmention($repl_caption, $entities);
                $urlcap  = (array)getURLs($repl_caption, $entities);
                $linkcap = (array)getlink($repl_caption, $entities);
                $offset  = getoffset($repl_caption, $entities);
                
                if ($offset > 0) {
                    $repl_caption = mb_substr($repl_caption, 0, $offset - 1);
                }
                
                $to_remove = array_filter(array_merge($mention, $urlcap, $linkcap));
                if (!empty($to_remove)) {
                    $repl_caption = str_ireplace($to_remove, "", $repl_caption);
                }
                $repl_caption = trim($repl_caption);

                // ۸. ارسال ویدیو نهایی و حذف پیام انتظار
                $vidsend = $this->telegram_model->send_video($token, $chatid1, $dest, "", "", $repl_caption);
                
                if (strpos($vidsend, '"ok":true') !== false) {
                    $this->telegram_model->delete_message_one($token, $chatid1, $waitMid);
                } else {
                    $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚠️ ویدیو فشرده شد اما در ارسال به تلگرام مشکلی پیش آمد.");
                }

            } else {
                $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚠️ متاسفانه عملیات فشرده‌سازی با خطا مواجه شد.");
            }
        } else {
            $this->telegram_model->edit_message($token, $chatid1, $waitMid, "❌ خطای دانلود: $download_res");
        }
    } else {
        $this->telegram_model->edit_message($token, $chatid1, $waitMid, "❌ سرور تلگرام اجازه دسترسی به مسیر این فایل را نداد.");
    }

    // ۹. پاکسازی دایرکتوری موقت (جلوگیری از پر شدن هارد سرور)
    if (is_dir($folder)) {
        exec("rm -rf " . escapeshellarg($folder));
    }
}

if($repl_video_fid && $message == "Grid"){
    $thisSendWait = $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
    $folder = "./application/$chatid1";
    if(is_dir($folder)){
        die();
    }else{
        exec("mkdir $folder");
    }
    $sorc = "$folder/sorc.mp4";
    $dest = "$folder/dest.jpg";
    $grid = "$folder/grid.jpg";
    $video_file = $this->telegram_model->get_file($token,$repl_video_fid);
    if(strpos($video_file,"file is too big") > 0){
        $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه ربات‌های تلگرام نمیتوانند فایل های بزرگ تر 20 مگابایت را دریافت کنند" );
        $result = exec("rm -rf $folder");
        die();
    }
    $video_file = json_decode($video_file, true);
    $url2 = "https://api.telegram.org/file/bot".$token."/".$video_file["result"]["file_path"];
    //$this->telegram_model->send_message_only($token,'-1001155301071',"url: ".$url2 );
    $size = $this->telegram_model->download_file2($url2,$sorc);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"url: ".$size );
    
    $info_file = exec("mediainfo --Inform='Video;%Duration%:%BitRate%:%Height%' $sorc");
    $info = explode(":",$info_file);
    //$Bitrate = $info[1];
    $duration = trim(round($info[0]/1000));
    //$this->telegram_model->send_message_only($token,'-1001155301071',"dur: ".$duration );
    if($duration < 8){
        $start = "00:00:03";
    }else{
        $start = "00:00:08";
    }
    $old_crf = exec("ffmpeg -ss $start -i $sorc -frames:v 1 -q:v 2 $dest");
    
    $size = $this->telegram_model->grid($dest,$grid);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"dimention: ".$size[0] );
    $sendphoto = $this->telegram_model->send_photo_online($token,'-1001155301071',$grid,"Orginal Size: ". $size[0]);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"sendphoto grid: ".$sendphoto );
    $result = exec("rm -rf $folder");
}

if($message == "مدل لوگو"){
    $this->telegram_model->send_message_only($token,$chatid1,"logo-height-width-border-textColor-Transparent");
}

if($chatid1 == '-1001155301071' && $repl_video_fid && mb_strpos($message,"ogo") > 0){
    $message = $this->telegram_model->toEnglishNum($message);
    $error_text = "ربات تلگرام فایل های تا حجم 20 مگابایت را میتواند از تلگرام دریافت کند. اگر فایل شما کوچکتر است در انتقال آن از تلگرام اشکالی پیش آمده، در این صورت دوباره امتحان کنید";
    similar_text(substr($message,0,4),"logo",$darsad);
    similar_text(substr($message,0,4),"Logo",$darsad2);
    
    if($darsad == 100 || $darsad2 == 100){
        $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
        $info = explode("-",$message);
        $color = array('#3e64ff' => 'آبی', '#ff0000' => 'قرمز', '#04fa38' => 'سبز', 'White' => 'سفید', 'black' => 'سیاه', 'HotPink' => 'صورتی', 'OrangeRed' => 'نارنجی', '#fff600' => 'زرد', 'Violet' => 'بنفش', 'Lime' => 'لیمویی', 'Chocolate' => 'قهوه ای');
        $logo = trim($info[1]);
        $height = trim($info[2]);
        $width = trim($info[3]);
        $border = trim($info[4]);
        $fontSize = trim($info[5]);
        $textColor = trim($info[6]);
        $Transparent = trim($info[7]);
        $boxOn = trim($info[8]);
        $boxTransparent = trim($info[9]);
        $boxSize = trim($info[10]);
        
        //$text_test = "logo: $logo\nheight: $height\nwidth: $width\nstart time: \nend time: \nborder: $border\nfontsize: $fontSize\ntextColor: $textColor\nTransparent: $Transparent";
        //$this->telegram_model->send_message_only($token,'-1001155301071',$text_test);
        
        $dest1 = "./application/dest_logo-$chatid1.mp4";
        $source = "./application/source_logo-$chatid1.mp4";
        $font = "./application/fonts/IRJADID.TTF";
        if(!file_exists($dest1)){
            
            //preg_match_all('!\d+!', $message, $matches);
            $video_file = $this->telegram_model->get_file($token,$repl_video_fid);
            
            $video_file = json_decode($video_file, true);
            $url1 = "https://api.telegram.org/file/bot".$token."/".$video_file["result"]["file_path"];
            //$this->telegram_model->send_message_only($token,'-1001155301071',"url".$url1);
            if(strpos($url1,".mp4") > 0 || strpos($url1,".MP4") || strpos($url1,".m4v") || strpos($url1,".M4V") > 0 || strpos($url1,".mov") || strpos($url1,".MOV") > 0 || strpos($url1,".mkv") || strpos($url1,".MKV") > 0){
                $size = $this->telegram_model->download_file2($url1,$source);
                $info_file = exec("mediainfo --Inform='Video;%Duration%:%BitRate%:%Height%' $source");
                $info = explode(":",$info_file);
                $Bitrate = $info[1];
                $duration = trim(round($info[0]/1000));
                if($duration > 60){
                    $s1 = 60;
                    $s2 = 50;
                }elseif($duration > 30){
                    $s1 = $duration*2/3;
                    $s2 = $duration*2/3-10;
                }else{
                    $s1 = 20;
                    $s2 = 10;
                }
                if($Bitrate > 1000000){
                    $Bitrate = round($Bitrate*4/10);
                }elseif($Bitrate > 600000){
                    $Bitrate = round($Bitrate*5/10);
                }elseif($Bitrate > 200000){
                    $Bitrate = round($Bitrate*6/10);
                }else{
                    $Bitrate = $Bitrate;
                }
                if($info[2] >720){
                    $fsize = 28;
                }elseif($info[2] >480){
                    $fsize = 26;
                }else{
                    $fsize = 20;
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',"durat".$duration);
                /*$fs = $duration*1/5;
                $fe = $duration*3/5;*/
                if($duration > 6){
                    $fs = 2;
                    $fe = $duration-3;
                }else{
                    $fs = 0;
                    $fe = $duration-3;
                }
                
                //$this->telegram_model->send_message_only($token,'-1001155301071',"fe".$fe);
                $Bitrate = exec("mediainfo --Inform='Video;%BitRate%' $url1 2>&1");
                if($Bitrate > 1000000){
                    $Bitrate = round($Bitrate*7/10);
                }elseif($Bitrate > 600000){
                    $Bitrate = round($Bitrate*9/10);
                }else{
                    $Bitrate = $Bitrate;
                }
                if(intval($height) == 0 || intval($height) < 0){
                    $height = "(h/6)";
                }
                if(intval($width) == 0 || intval($width) < 0){
                    $width = "(w-text_w)/2";
                }
                if(intval($fontSize) == 0 || intval($fontSize) < 0){
                    $fontSize = "h/18";
                }
                if(strlen($textColor) == 0){
                    $font_color = "white";
                }else{
                    $font_color = array_search($textColor, $color);
                }
                if(strpos($logo,"!@#") > 0){
                    $textLogo = explode("!@#",$logo);
                    $logo1 = $textLogo[0];
                    $logo2 = $textLogo[1];
                }else{
                    $logo1 = $logo;
                }
                if($border == ""){
                    $border = 2;
                }
                if($Transparent == ""){
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"trans 1");
                    $Transparent = 1;
                }
                if($boxOn != 1){
                    $boxOn = 0;
                }
                if($boxTransparent < 0 || $boxTransparent == NULL){
                    $boxTransparent = 0;
                }elseif($boxTransparent > 1){
                    $boxTransparent = 1;
                }
                if(($boxSize < 0 || $boxSize == NULL) && $boxOn == 0){
                    $boxSize = 0;
                }elseif($boxSize > 20 && $boxOn == 1){
                    $boxSize = 20;
                }elseif($boxSize == NULL && $boxOn == 1){
                    $boxSize = 5;
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',$font_color);
                /*if(intval($border) == 0 ){
                    $height = "(h/6)";
                }*/ 
                $text_test = "logo: $logo\nheight: $height\nwidth: $width\nstart time: \nend time: \nborder: $border\ntextColor: $font_color\nTransparent: $Transparent";
                //$this->telegram_model->send_message_only($token,'-1001155301071',$text_test);
                if(!file_exists($dest1)){
                    //$result = exec("ffmpeg -i $source -filter_complex \"[0]split[base][text];[text]drawtext=fontfile=$font:text=$logo1:borderw=$border:bordercolor=black@1: fontcolor=$font_color@$Transparent:fontsize=$fontSize: box=0: boxcolor=black@0.5:boxborderw=5:x=$width:y=h-line_h-$height,format=yuva444p,drawtext=fontfile=$font:text=$logo2:borderw=2:bordercolor=black@1: fontcolor=$font_color@1:fontsize=$fontSize: box=0: boxcolor=black@0.5:boxborderw=5:x=$width:y=h-$height+10,format=yuva444p,fade=t=in:st=$fs:d=3:alpha=1,fade=t=out:st=$fe:d=3:alpha=1[subtitles];[base][subtitles]overlay\" -b:v $Bitrate -preset veryfast $dest1 2>&1");  50% complet
                    $result = exec("ffmpeg -i $source -filter_complex \"[0]split[base][text];[text]drawtext=fontfile=$font:text=$logo1:borderw=$border:bordercolor=black@1: fontcolor=$font_color@$Transparent:fontsize=$fontSize: box=$boxOn: boxcolor=black@$boxTransparent:boxborderw=$boxSize:x=$width:y=h-line_h-$height,format=yuva444p[subtitles];[base][subtitles]overlay\" -b:v $Bitrate -preset superfast $dest1 2>&1");
                }
                
                //$result = exec("ffmpeg -i $source -filter_complex \"[0]split[base][text];[text]drawtext=fontfile=$font:text=$logo:borderw=2:bordercolor=black@1: fontcolor=white@1:fontsize=h/20: box=0: boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=h-line_h-$height,format=yuva444p,fade=t=in:st=$fs:d=3:alpha=1,fade=t=out:st=$fe:d=3:alpha=1[subtitles];[base][subtitles]overlay\" -b:v $Bitrate -preset veryfast $dest1 2>&1");
                
                $this->telegram_model->send_message_only($token,'-1001155301071',"logo res: ".$result);
                
                if(strpos($result,"kb/s") > 0 || strpos($result,"muxing") > 0 || strpos($result,"Qavg:") > 0){
                    $chat_send = substr($dest1,strpos($dest1,"-")+1,-4);
                    $vidsend = $this->telegram_model->send_video($token,$chat_send,$dest1,$w,$h,$repl_caption);
                    if($chat_send != '-1001155301071'){
                        $vidsend = $this->telegram_model->send_video($token,-1001155301071,$dest1,$w,$h,$repl_caption);
                    }
                }
                unlink($source);
                unlink($dest1);
            }else{
                $this->telegram_model->send_message_only($token,'-1001155301071',$error_text);
            }
        }else{
            die();
        }
    }else{
        $this->telegram_model->send_message_only($token,'-1001155301071',"دستور را اشتباه وارد کردید");
    }
}

if (strpos($message, "کراپ") === 0 && $repl_video_fid) {
    
    $userId = $chatid1;
    $folder = "./application/work_$userId";
    
    if (is_dir($folder)) {
        $this->telegram_model->send_message_only($token, $chatid1, "⚠️ شما یک پردازش فعال دارید. لطفاً صبور باشید.");
        die();
    }
    mkdir($folder, 0777, true);

    $thisSendWait = $this->telegram_model->send_message_only($token, $chatid1, "🔍 در حال آنالیز ویدئو...");
    $waitMid = json_decode($thisSendWait, true)['result']['message_id'] ?? null;

    $sorc = "$folder/source.mp4";
    $dest = "$folder/cropped.mp4";
    $logFile = "$folder/progress.txt";

    $message = $this->telegram_model->toEnglishNum($message);
    preg_match('!\d+!', $message, $matches);
    $val = isset($matches[0]) ? (int)$matches[0] : 0;

    $video_file_raw = $this->telegram_model->get_file($token, $repl_video_fid);
    $video_file = json_decode($video_file_raw, true);

    if (isset($video_file["result"]["file_path"])) {
        $file_url = "https://api.telegram.org/file/bot" . $token . "/" . $video_file["result"]["file_path"];
        $this->telegram_model->smart_download($file_url, $sorc);

        if (file_exists($sorc) && filesize($sorc) > 0) {
            
            $fileSizeMB = filesize($sorc) / 1024 / 1024;
            $duration = (float)shell_exec("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 " . escapeshellarg($sorc));
            $dimensions = shell_exec("ffprobe -v error -select_streams v:0 -show_entries stream=width,height,bit_rate -of csv=s=x:p=0 " . escapeshellarg($sorc));
            $dim_parts = explode('x', trim($dimensions));
            $width = (int)$dim_parts[0];
            $height = (int)$dim_parts[1];
            $bitrate = (isset($dim_parts[2]) && (int)$dim_parts[2] > 0) ? (int)$dim_parts[2] : 2000000;

            $crop_filter = "";
            if (strpos($message, "بالا") !== false && strpos($message, "پایین") !== false) $crop_filter = "crop=iw:ih-$val*2:0:$val";
            elseif (strpos($message, "چپ") !== false && strpos($message, "راست") !== false) $crop_filter = "crop=iw-$val*2:ih:$val:0";
            elseif (strpos($message, "بالا") !== false) $crop_filter = "crop=iw:ih-$val:0:$val";
            elseif (strpos($message, "پایین") !== false) $crop_filter = "crop=iw:ih-$val:0:0";
            elseif (strpos($message, "راست") !== false) $crop_filter = "crop=iw-$val:ih:0:0";
            elseif (strpos($message, "چپ") !== false) $crop_filter = "crop=iw-$val:ih:$val:0";

            if ($crop_filter != "") {
                $ffmpeg_cmd = "ffmpeg -y -i " . escapeshellarg($sorc) . " -vf " . escapeshellarg($crop_filter) . " -vcodec libx264 -b:v " . $bitrate . " -maxrate " . ($bitrate * 1.1) . " -bufsize " . ($bitrate * 2) . " -preset superfast -acodec copy -progress " . escapeshellarg($logFile) . " " . escapeshellarg($dest) . " > /dev/null 2>&1 &";
                exec($ffmpeg_cmd);
                
                $lastPercent = 0;
                $startTime = time();
                $sleepTime = ($fileSizeMB < 5) ? 600000 : 1000000; 

                while (true) {
                    $logContent = file_exists($logFile) ? @file_get_contents($logFile) : "";
                    $isFinished = !shell_exec("pgrep -f " . escapeshellarg($dest));
                    
                    $realPercent = 0;
                    if (preg_match('/out_time_us=(\d+)/', $logContent, $matches)) {
                        $currentSeconds = $matches[1] / 1000000;
                        $realPercent = ($duration > 0) ? round(($currentSeconds / $duration) * 100) : 0;
                    }

                    if ($isFinished) {
                        // اگر پردازش تمام شده، نوار را با سرعت به سمت ۱۰۰ می‌بریم
                        $lastPercent += 20; 
                    } else {
                        // نمایش بر اساس دیتای واقعی یا گام‌های زمانی
                        if ($realPercent > $lastPercent) {
                            $lastPercent = $realPercent;
                        } else {
                            $lastPercent += ($fileSizeMB < 5) ? 10 : 5;
                        }
                    }

                    if ($lastPercent >= 100) {
                        $lastPercent = 100;
                        $bar = str_repeat("■", 10);
                        $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚙️ در حال پردازش ویدئو...\n\n$bar 100%");
                        break; // خروج سریع از حلقه برای ارسال
                    }

                    $bar = str_repeat("■", floor($lastPercent / 10)) . str_repeat("□", 10 - floor($lastPercent / 10));
                    $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚙️ در حال پردازش ویدئو...\n\n$bar $lastPercent%");

                    // تنظیم وقفه: اگر تمام شده سریع‌تر بچرخ، اگر نه مطابق حجم فایل
                    usleep($isFinished ? 200000 : $sleepTime);
                    
                    if (time() - $startTime > 600) break;
                }

                clearstatcache(); 
                if (file_exists($dest) && filesize($dest) > 100) {
                    $finalSize = round(filesize($dest) / 1024 / 1024, 2);
                    $this->telegram_model->edit_message($token, $chatid1, $waitMid, "✅ تکمیل شد (حجم: $finalSize MB).\nدر حال ارسال...");
                    
                    $res = $this->telegram_model->send_video($token, $chatid1, $dest, "", "", $repl_caption);
                    if ($res) {
                        $this->telegram_model->delete_message_one($token, $chatid1, $waitMid);
                    }
                } else {
                    $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚠️ خطا در تولید فایل خروجی.");
                }
            }
        }
    }
    // پاکسازی نهایی
    if (is_dir($folder)) {
        exec("rm -rf " . escapeshellarg($folder));
    }
}

if(($chatid1 == '-1001155301071' || $chatid1 == '-1001700113991') && gettype(mb_strpos($message,"محو")) == "integer" ){
    $message = $this->telegram_model->toEnglishNum($message);
    $error_text = "ربات تلگرام فایل های تا حجم 20 مگابایت را میتواند از تلگرام دریافت کند. \nحجم فایل شما بیشتر است";
    similar_text(substr($message,0,6),"محو",$darsad);
    if($darsad == 100){
        if($repl_video_fid || $repl_audio_fid){
            
            $source_del = "./application/$chatid1";
            if(is_dir($source_del)){
                //$this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر شما یک ویدئو در جال پردازش دارید. لطفا درخواست خود را بعد از پایان ویدئوی قبلی ارسال کنید");
                die();
            }else{
                exec("mkdir $source_del");
            }
            $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
            
            /*if(!is_numeric($start) || !is_numeric($end)){
                $this->telegram_model->send_message_only($token,$chatid1,"زمان‌ها را بدرستی وارد نکرده‌اید. لطفا زمان‌ها را بر اساس ثانیه وارد کنید" );
                exec("rm -rf $source_del 2>&1");
                die();
            }*/
            $this->telegram_model->send_message_only($token,'-1001155301071',"محو $chatid1 \n$user_id" );
            if($repl_video_fid){
                $get_file = $this->telegram_model->get_file($token,$repl_video_fid);
            }else{
                $get_file = $this->telegram_model->get_file($token,$repl_audio_fid);
            }
            $get_file = json_decode($get_file, true);
            $url1 = "https://api.telegram.org/file/bot".$token."/".$get_file["result"]["file_path"];
            //$this->telegram_model->send_message_only($token,'-1001155301071',$url1 );
            $mime = substr($url1,-3);
            $dest1 = "$source_del/cuted.$mime";
            $source = "$source_del/source.$mime";
            //$this->telegram_model->send_message_only($token,'-1001155301071',$mime );
            $size = $this->telegram_model->download_file2($url1,$source);
            
            $info_audio = exec("mediainfo --Inform='Audio;%Duration%:%BitRate%:%Height%:%Width%' $source");
            
            $infoAud = explode(":",$info_audio);
            $audDur = $infoAud[0]/1000;
            
            if(is_numeric(trim(mb_substr($message,3)))){
                // har do samt fade
                $startIn = 0;
                $startOut = $audDur - trim(mb_substr($message,3));
                $fadeDur = trim(mb_substr($message,3));
                $command = "afade=t=in:st=$startIn:d=$fadeDur,afade=t=out:st=$startOut:d=$fadeDur";
            }else{
                $info = mb_substr($message,3);
                $times = explode("-",$info);
                if(trim($times[0]) == "اول"){
                    $startIn = 0;
                    $fadeDur = trim($times[1]);
                    $command = "afade=t=in:st=$startIn:d=$fadeDur";
                }elseif(trim($times[0]) == "آخر"){
                    $startOut = $audDur - trim($times[1]);
                    $fadeDur = trim($times[1]);
                    $command = "afade=t=out:st=$startOut:d=$fadeDur";
                }
                
            }
            
            if($mime == "mp3"){
                $result = exec("ffmpeg -n -f mp3 -i $source -af '$command' -preset veryfast $dest1 2>&1");
            }else{
                $result = exec("ffmpeg -n -i $source -ss $start -to $end -avoid_negative_ts make_zero -codec copy -preset veryfast $dest1 2>&1");
            }
            
            if(strpos($result,"kb/s") > 0 || strpos($result,"muxing") > 0 || strpos($result,"Qavg:") > 0){
                //$chat_send = substr($dest1,strpos($dest1,"-")+1,-4);
                if($mime == "mp3"){
                    $resSend = $this->telegram_model->send_audio_online($token,$chatid1,$repl_caption,$dest1,"@VieraBot","$repl_audio_tit-$repl_audio_per");
                }else{
                    $resSend = $this->telegram_model->send_video($token,$chatid1,$dest1,$w,$h,$repl_caption);
                }
                //$this->telegram_model->send_message_only($token,'-1001155301071',$resSend );
            }
            exec("rm -rf $source_del 2>&1");
            
        }
    }
}

if (($chatid1 == '-1001155301071' || $chatid1 == '-1001700113991') && strpos($message, "برش") === 0) {
    
    $message = $this->telegram_model->toEnglishNum($message);
    
    if ($repl_video_fid || $repl_audio_fid) {
        
        $userId = $chatid1;
        $folder = "./application/trim_$userId";
        
        if (is_dir($folder)) {
            $this->telegram_model->send_message_only($token, $chatid1, "⚠️ شما یک پردازش فعال دارید. لطفا صبور باشید.");
            die();
        }
        mkdir($folder, 0777, true);

        $waitMsg = $this->telegram_model->send_message_only($token, $chatid1, "🔍 در حال آنالیز و دریافت فایل...");
        $waitMid = json_decode($waitMsg, true)['result']['message_id'] ?? null;

        $info = mb_substr($message, 3);
        $times = explode("-", $info);
        $start = isset($times[0]) ? (float)trim($times[0]) : null;
        $end = isset($times[1]) ? (float)trim($times[1]) : null;

        if ($start === null || $end === null || $end <= $start) {
            $this->telegram_model->edit_message($token, $chatid1, $waitMid, "❌ زمان‌ها را به درستی وارد نکرده‌اید. مثال: برش 10-30");
            exec("rm -rf " . escapeshellarg($folder));
            die();
        }

        $duration_to_cut = $end - $start;

        $file_id = $repl_video_fid ? $repl_video_fid : $repl_audio_fid;
        $get_file = $this->telegram_model->get_file($token, $file_id);
        $get_file_json = json_decode($get_file, true);
        
        if (!isset($get_file_json["result"]["file_path"])) {
            $this->telegram_model->edit_message($token, $chatid1, $waitMid, "❌ خطا در دریافت فایل.");
            exec("rm -rf " . escapeshellarg($folder));
            die();
        }

        $file_path = $get_file_json["result"]["file_path"];
        $url = "https://api.telegram.org/file/bot" . $token . "/" . $file_path;
        $ext = pathinfo($file_path, PATHINFO_EXTENSION);
        
        $sorc = "$folder/source.$ext";
        $dest = "$folder/cut.$ext";
        $logFile = "$folder/progress.txt";

        $this->telegram_model->smart_download($url, $sorc);

        if (file_exists($sorc) && filesize($sorc) > 0) {
            
            $fileSizeMB = filesize($sorc) / 1024 / 1024;
            $fadeDuration = 5;
            $fadeStart = $duration_to_cut - $fadeDuration;
            if ($fadeStart < 0) { $fadeStart = 0; $fadeDuration = $duration_to_cut; }

            // حفظ پارامترهای FFMPEG برای دقت ثانیه‌ای و انکودینگ درست
            if ($repl_audio_fid || in_array($ext, ['mp3', 'ogg', 'wav'])) {
                $ffmpeg_cmd = "ffmpeg -y -ss $start -t $duration_to_cut -i " . escapeshellarg($sorc) . " -af 'afade=type=out:start_time=$fadeStart:duration=$fadeDuration' -acodec libmp3lame -ab 128k -preset veryfast -progress " . escapeshellarg($logFile) . " " . escapeshellarg($dest) . " > /dev/null 2>&1 &";
            } else {
                $v_info = shell_exec("ffprobe -v error -select_streams v:0 -show_entries stream=bit_rate -of csv=p=0 " . escapeshellarg($sorc));
                $bitrate = ((int)$v_info > 0) ? (int)$v_info : 2000000;
                $ffmpeg_cmd = "ffmpeg -y -ss $start -t $duration_to_cut -i " . escapeshellarg($sorc) . " -vcodec libx264 -b:v " . $bitrate . " -preset superfast -af 'afade=type=out:start_time=$fadeStart:duration=$fadeDuration' -acodec aac -shortest -avoid_negative_ts make_zero -progress " . escapeshellarg($logFile) . " " . escapeshellarg($dest) . " > /dev/null 2>&1 &";
            }

            exec($ffmpeg_cmd);
            
            $lastPercent = 0;
            $startTime = time();
            $sleepTime = ($fileSizeMB < 5) ? 600000 : 1000000;

            // دقیقاً همان منطق درصدگیر کد خودتان
            while (true) {
                $logContent = file_exists($logFile) ? @file_get_contents($logFile) : "";
                $isFinished = !shell_exec("pgrep -f " . escapeshellarg($dest));
                
                $realPercent = 0;
                if (preg_match('/out_time_us=(\d+)/', $logContent, $matches)) {
                    $currentPos = $matches[1] / 1000000;
                    $realPercent = ($duration_to_cut > 0) ? round(($currentPos / $duration_to_cut) * 100) : 0;
                }

                if ($isFinished) {
                    $lastPercent += ($lastPercent < 90) ? 20 : 5;
                } else {
                    if ($realPercent > $lastPercent) $lastPercent = $realPercent;
                    else $lastPercent += ($fileSizeMB < 5) ? 10 : 5;
                }

                if ($lastPercent >= 100) {
                    $lastPercent = 100;
                    $bar = str_repeat("■", 10);
                    $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚙️ در حال برش...\n\n$bar 100%");
                    break;
                }

                $bar = str_repeat("■", floor($lastPercent / 10)) . str_repeat("□", 10 - floor($lastPercent / 10));
                $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚙️ در حال برش فایل...\n\n$bar $lastPercent%");

                usleep($isFinished ? 200000 : $sleepTime);
                if (time() - $startTime > 600) break;
            }

            clearstatcache();
            if (file_exists($dest) && filesize($dest) > 1000) {
                $this->telegram_model->edit_message($token, $chatid1, $waitMid, "✅ در حال ارسال...");

                $isSentSuccess = false;
                $errorMsgId = null;

                // تلاش برای ارسال و دریافت رسید (Message ID)
                for ($attempt = 1; $attempt <= 2; $attempt++) {
                    if ($repl_audio_fid) {
                        $res = $this->telegram_model->send_audio_online($token, $chatid1, $repl_caption, $dest, "@VieraBot", "$repl_audio_tit");
                    } else {
                        $res = $this->telegram_model->send_video($token, $chatid1, $dest, "", "", $repl_caption);
                    }

                    $resData = json_decode($res, true);
                    if (isset($resData["result"]["message_id"])) {
                        $isSentSuccess = true;
                        break; 
                    } else {
                        if ($attempt == 1) {
                            $errRes = $this->telegram_model->send_message_only($token, $chatid1, "⚠️ اختلال در تلگرام. در حال تلاش مجدد...");
                            $errorMsgId = json_decode($errRes, true)['result']['message_id'] ?? null;
                            sleep(2);
                        }
                    }
                }

                if ($isSentSuccess) {
                    // حذف پیام‌های انتظار و خطا
                    $this->telegram_model->delete_message_one($token, $chatid1, $waitMid);
                    if ($errorMsgId) $this->telegram_model->delete_message_one($token, $chatid1, $errorMsgId);
                    
                    // ارسال گزارش به کانال
                    $report_text = "📥 گزارش برش موفق\n\n👤 Chat: $chatid1\n\n⏱ $start تا $end";
                    if ($repl_audio_fid) {
                        $this->telegram_model->send_audio_online($token, '-1001155301071', $report_text, $dest, "@VieraBot", "Log");
                    } else {
                        $this->telegram_model->send_video($token, '-1001155301071', $dest, "", "", $report_text);
                    }
                }
            } else {
                $this->telegram_model->edit_message($token, $chatid1, $waitMid, "⚠️ خطا در پردازش فایل.");
            }
        }
    }
    if (is_dir($folder)) exec("rm -rf " . escapeshellarg($folder));
}

if($repl_voice_fid && ($message == "تبدیل به mp3") ){
    $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
    $result = exec("mkdir ./application/$chatid1");
    $dest1 = "./application/$chatid1/Change-by-Viera-$lastpost.mp3";
    $cover = "./application/img/logowhite_full.png";
    $source = "./application/$chatid1/source-$lastpost.mp3";
    
    $voice_file = $this->telegram_model->get_file($token,$repl_voice_fid);
    $voice_file = json_decode($voice_file, true);
    $url1 = "https://api.telegram.org/file/bot".$token."/".$voice_file["result"]["file_path"];
    
    $result = exec("ffmpeg -y -i $url1  -vn -ab 256 -metadata artist='@vieraBot' $source 2>&1");
    $result1 = exec("ffmpeg -y -f mp3 -i $source -i $cover -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' $dest1 2>&1");
    $this->telegram_model->send_audio_online($token,$chatid1,"",$dest1,'@vieraBot',"Change-by-Viera",$lastpost);
    $result = exec("rm -rf ./application/$chatid1");
    
    //$this->telegram_model->send_message_only($token,'-1001155301071',"cap1: ".$repl_voice_fid );
}

if($repl_to_uid && ($message == "صداجدا" || $message == "صدا جدا") ){
    if($repl_video_fid){
        $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید");
        $result = exec("mkdir ./application/$chatid1");
        $dest1 = "./application/$chatid1/Extract-by-Viera-$lastpost.mp3";
        $cover = "./application/img/logowhite_full.png";
        $source = "./application/$chatid1/source-$lastpost.mp3";
        //preg_match_all('!\d+!', $message, $matches);
        //$this->telegram_model->send_message_only($token,'-1001155301071',"cap1: ".$repl_caption );
        $mention = getmention($repl_caption, $entities);
        $urlcap = getURLs($repl_caption, $entities);
        $linkcap = getlink($repl_caption, $entities);
        $repl_caption = str_ireplace($mention[0],"",$repl_caption);
        $repl_caption = str_ireplace($mention[1],"",$repl_caption);
        $repl_caption = str_ireplace($urlcap[0],"",$repl_caption);
        $repl_caption = str_ireplace($linkcap[0],"",$repl_caption);
        $video_file = $this->telegram_model->get_file($token,$repl_video_fid);
        $video_file = json_decode($video_file, true);
        $url1 = "https://api.telegram.org/file/bot".$token."/".$video_file["result"]["file_path"];
        //$this->telegram_model->send_message_only($token,'-1001155301071',"cap2: ".$repl_caption );
        if(strpos($url1,".mp4") > 0 || strpos($url1,".MP4") || strpos($url1,".m4v") || strpos($url1,".M4V") > 0 || strpos($url1,".mov") || strpos($url1,".MOV") > 0 || strpos($url1,".mkv") || strpos($url1,".MKV") > 0){
            $result = exec("ffmpeg -y -i $url1  -vn -ab 256 -metadata artist='@vieraBot' $source 2>&1");
            $result1 = exec("ffmpeg -y -f mp3 -i $source -i $cover -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' $dest1 2>&1");
            //$result3 = exec("ffmpeg -y -i $url1  -vn -ab 256 -metadata artist='@vieraBot' $dest1 | -i $dest1 -i $cover -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title='Album cover' -metadata:s:v comment='Cover (Front)' $dest1 2>&1");
            //$this->telegram_model->send_message_only($token,'-1001155301071',$result );
            //$this->telegram_model->send_message_only($token,'-1001155301071',$result3 );
            $this->telegram_model->send_audio_online($token,$chatid1,$repl_caption,$dest1,'@vieraBot',"Extract-by-Viera",$lastpost);
            $result = exec("rm -rf ./application/$chatid1");
            //unlink($dest1);
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,"ربات های API به فایل‌های با حجم بیشتر از 20 مگابایت دسترسی ندارند" );
        }
        $result = exec("rm -rf ./application/$chatid1");
    }
}



//******************************************************************** groups command

if($message == "خوش آمد گویی فعال"){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $group = $this->telegram_model->get_Controler($chatid1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($group) );
        if( count($group) > 0 ){
            if( $group[0]->wellcom == "yes" ){
                $this->telegram_model->send_message_only($token,$chatid1,'این گزینه قبلا برای شما فعال شده' );
            }else{
                $data = array("wellcom"=>"yes");
                $this->telegram_model->update_Controler($chatid1,$data);
                $this->telegram_model->send_message_only($token,$chatid1,"خوش آمد گویی فعال شد" );
            }
        }else{
            $data = array("groupid"=>$chatid1,"wellcom"=>"yes");
            $this->telegram_model->set_Controler($data);
            $this->telegram_model->send_message_only($token,$chatid1,"خوش آمد گویی فعال شد" );
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
    }
}
if($message == "قطع خوش آمد گویی"){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $group = $this->telegram_model->get_Controler($chatid1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($group) );
        if( count($group) > 0 ){
            if( $group[0]->wellcom == "yes" ){
                
                $data = array("wellcom"=>"no");
                $this->telegram_model->update_Controler($chatid1,$data);
                $this->telegram_model->send_message_only($token,$chatid1,"خوش آمد گویی حذف شد" );
            }else{
                $this->telegram_model->send_message_only($token,$chatid1,'این گزینه از قبل غیر فعال بود' );
            }
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,'این گزینه از قبل غیر فعال بود' );
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
    }
}

if($message == "حذف ربات روشن"){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $group = $this->telegram_model->get_Controler($chatid1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($group) );
        if( count($group) > 0 ){
            if( $group[0]->remove_bot == "yes" ){
                $this->telegram_model->send_message_only($token,$chatid1,'این گزینه قبلا برای شما فعال شده' );
            }else{
                $data = array("remove_bot"=>"yes");
                $this->telegram_model->update_Controler($chatid1,$data);
                $this->telegram_model->send_message_only($token,$chatid1,"حذف ربات فعال شد" );
            }
        }else{
            $data = array("groupid"=>$chatid1,"remove_bot"=>"yes");
            $this->telegram_model->set_Controler($data);
            $this->telegram_model->send_message_only($token,$chatid1,"حذف ربات فعال شد" );
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
    }
}
if($message == "حذف ربات خاموش"){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $group = $this->telegram_model->get_Controler($chatid1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',count($group) );
        if( count($group) > 0 ){
            if( $group[0]->remove_bot == "yes" ){
                $data = array("remove_bot"=>"no");
                $this->telegram_model->update_Controler($chatid1,$data);
                $this->telegram_model->send_message_only($token,$chatid1,"حذف ربات غیر فعال شد" );
            }else{
                $this->telegram_model->send_message_only($token,$chatid1,'این گزینه از قبل غیر فعال بود' );
            }
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,'این گزینه از قبل غیر فعال بود' );
        }
    }else{
        $this->telegram_model->send_message_only($token,$chatid1,"شما مجاز به استفاده از این فرمان نیستی 😉😉");
    }
}

if($repl_id && $message == 'پین' ){
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info == "creator" || $join_info =="administrator" || $user_id == "53853580"){
        $this->telegram_model->pin_ChatMessage($token,$chatid1,$repl_id);
    }
}

if($message == "لینک بسته"){
    $chek = $this->telegram_model->get_chek_link($chatid1);
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info== "creator" || $join_info== "administrator" || $user_id == "53853580" /*|| $join_info== "member"*/ ){
        if( in_array($chatid1, array_column($chek, 'group_id')) ){
            $this->telegram_model->send_message_only($token,$chatid1,"قفل لینک در حال حاضر فعال است");
        }else{
            $data = array("group_id"=>$chatid1);
            $this->telegram_model->set_chek_link($data);
            $this->telegram_model->send_message_only($token,$chatid1,"قفل لینک فعال شد");
        }
    }
}
if($message == "لینک باز"){
    $chek = $this->telegram_model->get_chek_link($chatid1);
    $join_info = $this->telegram_model->get_member2($token,$user_id,$chatid1);
    if($join_info== "creator" || $join_info== "administrator" || $user_id == "53853580" ){
        if( in_array($chatid1, array_column($chek, 'group_id')) ){
            $this->telegram_model->clear_chek_link($chatid1);
            $this->telegram_model->send_message_only($token,$chatid1,"قفل لینک غیر فعال شد");
        }else{
            $this->telegram_model->send_message_only($token,$chatid1,"قفل لینک در حال حاضر غیر فعال است");
        }
    }
    
}
    
if($message == "ویرا پست"){
    $last_post_mag = $this->telegram_model->get_post_sent(17);
    $array_rand = [];
    $last_pid = $last_post_mag[0]->last_post_id;
    for($i = $last_pid; $i> $last_pid-30; $i--){
        array_push($array_rand,$i);
    }
    $random_keys=array_rand($array_rand,2);
    for($i = 0; $i < 2; $i++){
        $this->telegram_model->forward($token,'@VieraMagazine',$array_rand[$random_keys[$i]],$chatid1);
    }
    $this->telegram_model->send_message_only($token,$chatid1,"برو حالشو ببر😂😉😉" );
    $this->telegram_model->send_message_only($token,'-1001155301071',"پست ارسال شد" );
}

if($message == "ویرا لینک بده"  ||  $message == "ویرا لینک" ){
    $admins = $this->telegram_model->get_admin($token,$chatid1);
    $admin = json_decode($admins, true);
    $vieraAdmin = 0;
    for($i = 0; $i < count($admin['result']); $i++){
        if($admin['result'][$i]['user']['username'] == "Vierabot"){
            $vieraAdmin = 1;
        }
    }
    if($vieraAdmin >0){
        $join_info = $this->telegram_model->get_member($token,$user_id,$chatid1);
        //$this->telegram_model->send_message_only($token,'-1001155301071',$join_info);
        $join_info = json_decode($join_info, true);
        if($join_info["result"]["status"] == "creator" || $join_info["result"]["status"] == "administrator" || $user_id == "53853580"){
            $new_ivite = $this->telegram_model->get_link($token,$chatid1);
            $invite_link = json_decode($new_ivite, true);
            $this->telegram_model->send_message_only($token,$chatid1,$invite_link["result"]);
            $this->telegram_model->revok_link($token,$chatid1,$invite_link["result"]);
        }
    }else{
        $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,"من ادمین نیستم که لینک بدم 😐");
    }
}

similar_text($message,"ویرا فال",$darsadFal1);
similar_text($message,"ویرا فال بگیر",$darsadFal2);
similar_text($message,"فال حافظ",$darsadFal3);
similar_text($message,"viera faal begir",$darsadFal4);
//$this->telegram_model->send_message_only($token,'-1001155301071',"darsad $darsadFal1");
if($darsadFal1 > 85 || $darsadFal2 > 85 || $darsadFal3 > 85 || $darsadFal4 > 85 /*$message == "ویرا فال" || $message == "ویرافال بگیر" || $message == "ویرا فال بگیر" || $message =="viera faal begir" || $callback_message=== "فال حافظ"*/){
    
    for($i =0; $i < 10; $i++){
        $rand1 = mt_rand(0,495);
        $fall = $this->telegram_model->get_telegram_faal2($rand1);
        if(count($fall) > 0){
            $content = $fall[0]->ghazal;
            $content1 = $fall[0]->tabir;
            break;
        }
    }
    
    //$text = '<a href="tg://user?id=123456789"> '.$Gold_ounce_now[0]->plaintext.'</a>';
    if(isset($username)){
        $user = "<a href=\"tg://user?id=".$user_id."\" >".$username."</a>";
    }else{
        $user = "<a href=\"tg://user?id=".$user_id."\" >".$firstname."</a>";
    }
    $content1 = "تعبیر فال شما:  ".$user."\n\n🕊🍀════🎀════🍀🕊"."\n".$content1."🕊🍀════🎀════🍀🕊";
    $content = "فال شما:  ".$user."\n\n🕊🌺════🎀════🌺🕊\n".$content."\n🕊🌺════🎀════🌺🕊";
    
    //$this->telegram_model->send_message_only($token,$chatid1,$username2);
    //$this->telegram_model->send_message_only($token,$chatid1,$content);
    
    $this->telegram_model->send_message_only_replay($token,$chatid1,$lastpost,$content);
    $this->telegram_model->send_message_only($token,$chatid1,$content1);
    
}

// الگوی منظم برای پذیرش هر دو حالت چسبیده و جدا + فیلتر دقیق روز و ماه
if (preg_match('/^(ویرا\s?تقویم|ویراتقویم)(?:\s+(\d{1,2})\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند))?$/ui', $message, $matches)) {
    
    $word_ignore = ["عاشورا", "مجتهد", "روحانی", "سپاه", "فلسطین", "خمینی", "خامنه‌ای", "خامنه ای", "قمری", "مرجع تقلید", "بسیج", "انقلاب اسلامی"];
    $ignore_pattern = '/' . implode('|', array_map('preg_quote', $word_ignore)) . '/ui';

    if (!empty($matches[2]) && !empty($matches[3])) {
        $day_v = $this->telegram_model->toPersianNum($matches[2]); 
        $month_v = $matches[3];
        $dandm = $day_v . "_" . $month_v;
        $display_date = $day_v . " " . $month_v;
    } else {
        $dandm = $this->persiandate->jdate("j_F", time(), "", 'Asia/Tehran', "fa");
        $display_date = $this->persiandate->jdate("l j F Y", time(), "", 'Asia/Tehran', "fa");
    }

    $bastan = $this->persiandate->jdate("سال چینی: q\nماه باستانی: p", time(), "", 'Asia/Tehran', "fa");
    $time_now = $this->persiandate->jdate("H:i:s", time(), "", 'Asia/Tehran', "fa");

    $url = "https://fa.wikipedia.org/wiki/" . urlencode($dandm);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) return;

    $html = str_get_html($response);
    
    // ۱. حذف فیزیکی تگ‌های رفرنس از کل صفحه قبل از هر کاری
    foreach($html->find('sup.reference') as $ref) {
        $ref->outertext = '';
    }

    $results = ['monasebat' => "", 'roydad' => "", 'zadrooz' => "", 'marg' => ""];
    
    foreach ($html->find('h2, .mw-heading2') as $header) {
        $h_text = mb_strtolower(trim($header->plaintext));
        $target = "";
        
        if (strpos($h_text, 'ناسبت') !== false) $target = 'monasebat';
        elseif (strpos($h_text, 'ویداد') !== false) $target = 'roydad';
        elseif (strpos($h_text, 'ادروز') !== false) $target = 'zadrooz';
        elseif (strpos($h_text, 'گذشت') !== false || strpos($h_text, 'مرگ') !== false) $target = 'marg';

        if ($target !== "") {
            $sibling = $header->next_sibling();
            while ($sibling && $sibling->tag !== 'ul' && !in_array($sibling->tag, ['h2', 'h3'])) {
                $sibling = $sibling->next_sibling();
            }

            if ($sibling && $sibling->tag === 'ul') {
                $items = $sibling->find('li');
                $count = 0;
                foreach ($items as $li) {
                    if ($count >= 6) break;
                    
                    // ۲. تبدیل تمام فضاهای خالی عجیب به فضای معمولی
                    $text = str_replace(["&nbsp;", "\xc2\xa0"], " ", $li->plaintext);
                    $text = trim($text);
                    
                    // ۳. حذف براکت‌هایی که فقط عدد دارند (با هر تعداد فاصله)
                    $text = preg_replace('/\[\s*[0-9۰-۹]+\s*\]/u', '', $text);
                    
                    // ۴. پاکسازی نهایی با str_replace برای اطمینان
                    $text = str_ireplace(['ویرایش', 'نیازمند منبع', '[نیازمند منبع]', '[]'], '', $text);
                    $text = preg_replace('/\s+/u', ' ', $text);
                    $text = trim($text);

                    if (!preg_match($ignore_pattern, $text) && mb_strlen($text) > 10) {
                        $results[$target] .= "✦ " . $text . "\n";
                        $count++;
                    }
                }
            }
        }
    }

    $final_msg = "📅 تقویم: $display_date\n⌚ ساعت: $time_now\n$bastan\n\n";
    $final_msg .= "📌 #مناسبت‌ها\n" . ($results['monasebat'] ?: "موردی ثبت نشده است\n") . "\n";
    $final_msg .= "🚩 #رویدادها\n" . ($results['roydad'] ?: "موردی ثبت نشده است\n") . "\n";
    $final_msg .= "🎂 #زادروزها\n" . ($results['zadrooz'] ?: "موردی ثبت نشده است\n") . "\n";
    $final_msg .= "🕯 #درگذشت‌ها\n" . ($results['marg'] ?: "موردی ثبت نشده است\n") . "\n";
    $final_msg .= "@VieraBot";

    $this->telegram_model->send_message_only($token, $chatid1, html_entity_decode($final_msg));
    
    $html->clear();
    unset($html);
}


if (mb_substr($message, 0, 9) == "ویرا ساعت" || mb_substr($message, 0, 8) == "ویراساعت") {
    
    $text = trim(str_ireplace(["ویراساعت", "ویرا ساعت"], "", $message));
    $time = time();
    $zone = "Asia/Tehran";
    $cityDisplay = "تهران";
    $custom_time_string = null;

    if (!empty($text)) {
        // ۱. یافتن مختصات شهر
        $locationData = $this->telegram_model->get_locat(urlencode($text));
        $location = json_decode($locationData, true);

        if (!empty($location) && isset($location[0])) {
            $lat = $location[0]['latitude'];
            $lng = $location[0]['longitude'];
            $cityDisplay = $location[0]['name'];

            // ۲. دریافت زمان دقیق از API با cURL
            $url = "https://api.timezonedb.com/v2.1/get-time-zone?key=FZYE7ZNIF4P8&format=json&by=position&lat=$lat&lng=$lng";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
            $timeInfo = curl_exec($ch);
            curl_close($ch);

            $json_content = json_decode($timeInfo, true);
            if ($json_content && $json_content['status'] == "OK") {
                $time = $json_content['timestamp']; 
                $zone = $json_content['zoneName'];
                $parts = explode(" ", $json_content['formatted']);
                $custom_time_string = $parts[1]; 
            } else {
                $this->telegram_model->send_message_only($token, $chatid1, "⚠️ خطا در دریافت زمان جهانی. ساعت تهران نمایش داده می‌شود.");
            }
        } else {
            $this->telegram_model->send_message_only($token, $chatid1, "❌ شهر « $text » پیدا نشد. نام را به انگلیسی وارد کنید.");
        }
    }

    // محاسبات تاریخ و ساعت نمایش
    $date1 = $this->persiandate->jdate("امروز l j F ( f ) Y", $time, "", $zone, "fa");
    $date1 = str_ireplace(["( بهار )", "( تابستان )", "( پاییز )", "( زمستان )"], ["🍀", "🌞", "🍁", "☃️"], $date1);
    $date3 = "برابر با: " . date('Y.m.d F', $time);
    
    $display_time = ($custom_time_string) ? $this->telegram_model->toPersianNum($custom_time_string) : $this->persiandate->jdate("H:i:s", $time, "", $zone, "fa");
    $time_now = "ساعت: " . $display_time . " به وقت $cityDisplay";
    
    $date2 = $this->persiandate->jdate("z", $time, "", $zone, "en");
    $day_toend = $this->telegram_model->toPersianNum("روزهای باقیمانده تا پایان سال: " . (365 - intval($date2)) . " روز");
    $bastan = $this->persiandate->jdate("سال چینی: q\nماه باستانی: p", $time, "", $zone, "fa");

    // --- استخراج از ویکی‌پدیا (دقیقاً متد ویرا تقویم) ---
    $day_wiki = $this->persiandate->jdate("j", $time, "", $zone, "en"); 
    $month_wiki = $this->persiandate->jdate("F", $time, "", $zone, "fa");
    $wiki_url = "https://fa.wikipedia.org/wiki/" . urlencode($day_wiki . "_" . $month_wiki);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $wiki_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    $response = curl_exec($ch);
    curl_close($ch);

    $monasebat = "";
    if ($response) {
        $html = str_get_html($response);
        if ($html) {
            // ۱. حذف فیزیکی رفرنس‌ها
            foreach($html->find('sup.reference') as $ref) {
                $ref->outertext = '';
            }

            foreach ($html->find('h2, .mw-heading2') as $header) {
                $h_text = mb_strtolower(trim($header->plaintext));
                
                // فقط بخش مناسبت‌ها را می‌خواهیم
                if (strpos($h_text, 'ناسبت') !== false) {
                    $sibling = $header->next_sibling();
                    while ($sibling && $sibling->tag !== 'ul' && !in_array($sibling->tag, ['h2', 'h3'])) {
                        $sibling = $sibling->next_sibling();
                    }

                    if ($sibling && $sibling->tag === 'ul') {
                        $items = $sibling->find('li');
                        $count = 0;
                        $ignore_pattern = '/عاشورا|مجتهد|روحانی|سپاه|فلسطین|خمینی|خامنه‌ای|قمری|بسیج/';
                        
                        foreach ($items as $li) {
                            if ($count >= 4) break;
                            
                            $t = str_replace(["&nbsp;", "\xc2\xa0"], " ", $li->plaintext);
                            $t = trim($t);
                            
                            // حذف براکت‌های عددی
                            $t = preg_replace('/\[\s*[0-9۰-۹]+\s*\]/u', '', $t);
                            $t = str_ireplace(['ویرایش', 'نیازمند منبع', '[نیازمند منبع]', '[]'], '', $t);
                            $t = preg_replace('/\s+/u', ' ', $t);
                            $t = trim($t);

                            if (!preg_match($ignore_pattern, $t) && mb_strlen($t) > 10) {
                                $monasebat .= "✦ " . $t . "\n";
                                $count++;
                            }
                        }
                    }
                    break; // پیدا شد، خارج شو
                }
            }
            $html->clear();
            unset($html);
        }
    }

    $final_msg = "$date1\n$date3\n\n$time_now\n\n$bastan\n$day_toend";
    if (!empty($monasebat)) $final_msg .= "\n\n#مناسبت‌ها\n" . $monasebat;
    $final_msg .= "\n@VieraBot";

    $this->telegram_model->send_message_only($token, $chatid1, html_entity_decode($final_msg));
}


if (mb_substr($message, 0, 3) == "فال") {
    $months_map = [
        "فروردین" => "aries",
        "اردیبهشت" => "taurus",
        "خرداد" => "gemini",
        "تیر" => "cancer",
        "مرداد" => "leo",
        "شهریور" => "virgo",
        "مهر" => "libra",
        "آبان" => "scorpio",
        "آذر" => "sagittarius",
        "دی" => "capricorn",
        "بهمن" => "aquarius",
        "اسفند" => "pisces"
    ];

    $user_month = trim(str_ireplace("فال", "", $message));
    
    if (isset($months_map[$user_month])) {
        $sign = $months_map[$user_month];
        
        // ۱. دریافت فال انگلیسی از یک منبع معتبر (Horoscope.com)
        $url = "https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign=" . (array_search($sign, array_values($months_map)) + 1);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);

        $en_text = "";
        if ($response) {
            $html = str_get_html($response);
            if ($html) {
                $p_tag = $html->find('.main-horoscope p', 0);
                if ($p_tag) {
                    $en_text = $p_tag->plaintext;
                    // حذف تاریخ ابتدای متن انگلیسی (معمولا با " - " جدا می‌شود)
                    if (strpos($en_text, " - ") !== false) {
                        $en_text = explode(" - ", $en_text, 2)[1];
                    }
                }
                $html->clear();
                unset($html);
            }
        }

        if (!empty($en_text)) {
            // ۲. ارسال متن به Gemini برای ترجمه هوشمند و روان به فارسی
            $apiKey = ""; // در محیط اجرای کد به صورت خودکار جایگذاری می‌شود
            $systemPrompt = "You are a professional astrologer and translator. Translate the following daily horoscope to Persian (Farsi) in a very friendly, poetic, and positive tone. Do not use literal translation; make it sound like a real Persian horoscope.";
            $userQuery = "Translate this horoscope for $user_month ($sign): " . $en_text;

            $payload = [
                'contents' => [
                    ['parts' => [['text' => $userQuery]]]
                ],
                'systemInstruction' => [
                    ['parts' => [['text' => $systemPrompt]]]
                ]
            ];

            $ch = curl_init("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=$apiKey");
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            // پیاده‌سازی Retry با Exponential Backoff برای API
            $retry = 0;
            $api_res = false;
            while ($retry < 3) {
                $api_res = curl_exec($ch);
                if ($api_res) break;
                $retry++;
                sleep(pow(2, $retry));
            }
            curl_close($ch);

            $translated_text = "";
            if ($api_res) {
                $result = json_decode($api_res, true);
                $translated_text = $result['candidates'][0]['content']['parts'][0]['text'] ?? "";
            }

            if (!empty($translated_text)) {
                $today = $this->persiandate->jdate("l j F Y", time(), "", "Asia/Tehran", "fa");
                $final_msg = "🔮 فال روزانه ویرا (منبع جهانی)\n📅 $today\n✨ متولدین #$user_month\n\n$translated_text\n\n@VieraBot";
                $this->telegram_model->send_message_only($token, $chatid1, $final_msg);
            } else {
                $this->telegram_model->send_message_only($token, $chatid1, "⚠️ خطایی در ترجمه فال رخ داد. لطفاً لحظاتی دیگر تلاش کنید.");
            }
        } else {
            $this->telegram_model->send_message_only($token, $chatid1, "⚠️ امکان دریافت فال از منبع جهانی فراهم نشد.");
        }
    } else {
        $this->telegram_model->send_message_only($token, $chatid1, "❌ لطفاً نام ماه را درست وارد کنید.\nمثال: فال فروردین");
    }
}


//******************************************************************** my command

if($chatid1 == '-1001155301071' ){
   
    if(mb_strpos($message,"ویرا") == 0 && gettype(mb_strpos($message,"ویرا")) =="integer" ){
        $infoMessage = explode(" ",$message);
        if($infoMessage[1] == "ترند"){
            //Possible values: \"Now\", \"Music\", \"Movies\", \"Gaming\"
            if($infoMessage[2] == "حالا"){
                $category = "Now";
            }elseif($infoMessage[2] == "فیلم"){
                $category = "Movies";
            }elseif($infoMessage[2] == "" || $infoMessage[2] == "موزیک"){
                $category = "Music";
            }else{
                die();
            }
            if(strlen($category) > 0){
                $source_del = "./application/$user_id";
                if(is_dir($source_del)){
                    die();
                }else{
                    $this->telegram_model->send_message_only($token,$chatid1,"لطفا کمی صبر کنید" );
                    exec("mkdir $source_del");
                }
                $res = $this->telegram_model->get_yout_trends($category);
                $res = json_decode($res,true);
                $video_list = $res['videos'];
                
                for($i = 0; $i < 6; $i++){
                    $thisId = $res['videos'][$i]['video_id'];
                    $thisLength = $res['videos'][$i]['video_length'];
                    $thisViews = $this->telegram_model->toPersianNum(number_format($res['videos'][$i]['number_of_views']));
                    $thisType = $res['videos'][$i]['type'];
                    $thistitile = $res['videos'][$i]['title'];
                    $thisPubTime = $res['videos'][$i]['published_time'];
                    $thisPubTime = str_ireplace("hours ago","ساعت قبل",$thisPubTime);
                    $thisPubTime = str_ireplace("days ago","روز قبل",$thisPubTime);
                    $thisPubTime = str_ireplace("weeks ago","هفته قبل",$thisPubTime);
                    $thisPubTime = $this->telegram_model->toPersianNum($thisPubTime);
                    
                    $url = "https://www.youtube.com/watch?v=$thisId";
                    
                    sscanf($thisLength, "%d:%d:%d", $hours, $minutes, $seconds);
                    $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
                    //$this->telegram_model->send_message_only($token,$chatid1,$time_seconds);
                    if($time_seconds < 800){
                        $cookies = "./application/youtubecookies.txt";
                        $source = "$source_del/source.mp4";
                        if($thisType == "shorts"){
                            $down = exec("yt-dlp --cookies $cookies --write-info-json -f 'b[ext=mp4][height<=2160]/bv[filesize<17M][ext=webm]+ba[filesize<3M][ext=m4a]' --merge-output-format mp4  -o $source $url 2>&1");
                        }else{
                            $down = exec("yt-dlp --cookies $cookies --write-info-json -f 'b[ext=mp4][height<=480]/b[ext=mp4][height<=590]/bv[filesize<27M][ext=webm]+ba[filesize<3M][ext=m4a]/b[ext=mp4][height<=720]' --merge-output-format mp4 -o $source $url 2>&1");
                        }
                    }
                    //$insta_list_vid = glob("$dest_delet/*.mp4");
                    if(strpos($down,"format is not available") > 0){
                        $this->telegram_model->send_message_only($token,$chatid1,"متاسفانه فرمت این فایل با مشکل مواجه است و در حال حاضر امکان دریافت آن وجود ندارد");
                    }
                        
                    $caption = "#ترند_امروز\n\n$thistitile \n\nمدت: $thisLength\nزمان انتشار: $thisPubTime\nتعداد بازدید: $thisViews\n\n@VieraBot";
                    
                    $vid = "$source_del/last.mp4";
                    $size = exec("du $source | cut -f1");
                    if($size < 47000){
                        $font = "./application/fonts/IRJADID.TTF";
                        if($resolotion > 1080){
                            $font_size = 40;
                            $border = 2;
                            $xx = 50;
                            $crf = 31;
                        }elseif($resolotion > 720){
                            $font_size = 30;
                            $border = 2;
                            $xx = 50;
                            $crf = 30;
                        }elseif($resolotion > 640){
                            $font_size = 22;
                            $border = 1;
                            $xx = 40;
                            $crf = 29;
                        }elseif($resolotion > 480){
                            $font_size = 18;
                            $border = 1;
                            $xx = 20;
                            $crf = 28;
                        }else{
                            $font_size = 15;
                            $border = 1;
                            $xx = 20;
                            $crf = 27;
                        }
                        //$this->telegram_model->send_message_only($token,'-1001155301071',$font_size);
                        $result = exec("ffmpeg -y -i $source -filter_complex \"[0]split[base][text];[text]drawtext=fontfile=$font:text=@VieraMagazine:borderw=1:bordercolor=black@1: fontcolor=white@1:fontsize=$font_size: box=0: boxcolor=black@1:boxborderw=0:x=$xx:y=(h-text_h)/2+h/2*3/4,drawtext=fontfile=$font:text=Today Trend:borderw=1:bordercolor=black@1: fontcolor=white@1:fontsize=$font_size: box=0: boxcolor=black@1:boxborderw=0:x=$xx:y=(h-text_h)/2+(h/2*3/4)+text_h+5,format=yuva444p[subtitles];[base][subtitles]overlay\" -crf 29 -preset superfast $vid 2>&1");
                        //$this->telegram_model->send_message_only($token,"-1001155301071",$result);
                        
                        $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$caption);
                        //$vidsend = $this->telegram_model->send_video($token,"-1001312951231",$source,"","",$caption);
                        if($chatid1 != '-1001155301071'){
                            $vidsend = $this->telegram_model->send_video($token,'-1001155301071',$vid,"","",$caption);
                        }
                    }
                    unlink($source);
                }
            }
            $result = exec("rm -rf $source_del");
        }
    }
}

if($message == "Sdsdsd"){
    
    $counterApi = $this->telegram_model->get_temp(3);
    $diffTime = time() - $counterApi[0]->poet;
    if($counterApi[0]->content > 500 || $diffTime > 2592000 ){
        $this->telegram_model->send_message_only($token,'-1001155301071',"تعداد 500 درخواست دیتای فیلم زده شده");
        $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
        die();
    }
    if($counterApi[0]->poet + 2592000 > time()){
        $data = array("content"=>0,"poet"=>$counterApi[0]->poet + 2592000);
        $this->telegram_model->update_temp(3,$data);
    }
    $data = array("content"=>($counterApi[0]->content)+1);
    $this->telegram_model->update_temp(3,$data);
    
    $name = urlencode("captain america: brave new world");
    $res = $this->telegram_model->get_tmdb($name);
    //$this->telegram_model->send_message_only($token,'-1001155301071',"t2: ".$res);
    
    $res = json_decode($res,true);
    $movieId = $res['results'][0]['id'];
    $title = $res['results'][0]['original_title'];
    $release_date = $res['results'][0]['release_date'];
    $popularity = $res['results'][0]['popularity'];
    $image = "https://image.tmdb.org/t/p/w600_and_h900_bestv2".$res['results'][0]['poster_path'];
    
    $this->telegram_model->send_message_only($token,'-1001155301071',"t2: ".$movieId);
    $this->telegram_model->send_message_only($token,'-1001155301071',"t2: ".$title);
    $this->telegram_model->send_message_only($token,'-1001155301071',"t3: ".$release_date);
    $this->telegram_model->send_message_only($token,'-1001155301071',"t4: ".$popularity);
        
    $this->telegram_model->send_message_only($token,'-1001155301071',$image);
    if(strlen($movieId) > 0){
        $res2 = $this->telegram_model->get_tmdb2($movieId);
        $res2 = json_decode($res2,true);
        $imdb_id = $res2['imdb_id'];
        $this->telegram_model->send_message_only($token,'-1001155301071',$imdb_id);
    }
    if(strlen($imdb_id) > 0){
        $res3 = $this->telegram_model->get_movienews2($imdb_id);
        $res3 = json_decode($res3,true);
        
        $stars = $res3['stars'][0];
        $this->telegram_model->send_message_only($token,'-1001155301071',$stars);
    }
    
    
}
    

if($chatid1 == '-1001155301071'){
    if(mb_strpos($message,"اینفو") == 0 && gettype(mb_strpos($message,"اینفو")) =="integer" ){
        $this->telegram_model->send_message_only($token,$chatid1,"start list info");
        $this->telegram_model->send_message_only($token,$chatid1,"list name: top film honarmand");
        $infoMessage = explode(" ",$message);
        if($infoMessage[1] == "تاپ"){
            $category = "TOP";
        }elseif($infoMessage[1] == "فیلم"){
            $category = "MOVIE";
        }elseif($infoMessage[1] == "هنرمند"){
            $category = "CELEBRITY";
        }
        
        $counterApi = $this->telegram_model->get_temp(1);
        $diffTime = time() - $counterApi[0]->poet;
        //$this->telegram_model->send_message_only($token,'-1001155301071',$diffTime);
        
        if($counterApi[0]->content > 500 || $diffTime > 0 ){
            $this->telegram_model->send_message_only($token,'-1001155301071',"تعداد 500 خبر درخواست خبر فیلم زده شده");
            $this->telegram_model->send_message_only($token,'-1001155301071',$counterApi[0]->content);
            die();
        }
        if($counterApi[0]->poet > time()){
            $data = array("content"=>0,"poet"=>$counterApi[0]->poet + 2592000);
            $this->telegram_model->update_temp(1,$data);
        }
        $data = array("content"=>($counterApi[0]->content)+1);
        $this->telegram_model->update_temp(1,$data);
        
        $res = $this->telegram_model->get_movienews($category);
        $res = json_decode($res,true);
        for($i = 0; $i < 10; $i++){
            $articleTitle =  $res['data']['news']['edges'][$i]['node']['articleTitle']['plainText'];
            $articleTitle = $this->telegram_model->translate($articleTitle);
            $counterApi = $this->telegram_model->get_temp(20);
            if($counterApi[0]->poet < time()){
                $data = array("content"=>0,"poet"=>$counterApi[0]->poet + 2592000);
                $this->telegram_model->update_temp(20,$data);
            }
            $articleTitle = json_decode($articleTitle,true);
            $articleTitle = $articleTitle['data']['translations'][0]['translatedText'];
            //$this->telegram_model->send_message_only($token,$chatid1,"here0: $articleTitle");
            $image = $res['data']['news']['edges'][$i]['node']['image']['url'];
            $image_height = $res['data']['news']['edges'][$i]['node']['image']['height'];
                
            $outFileName = "./application/pic1.jpg";
            $size = $this->telegram_model->download_file($image,$outFileName);
            //$this->telegram_model->send_message_only($token,$chatid1,"here1: $size");
            $outFileName_img2 = "./application/img/logowatermark2.png";

            $outFileName4 = "./application/image_new1111.jpg";
            $font2 = "./application/fonts/IRBADRBOLD.TTF";

            if($image_height > 4500){
                $font_size = $image_height/26;
                $border = $font_size/13;
            }elseif($image_height > 3000){
                $font_size = $image_height/26;
                $border = $font_size/13;
            }elseif($image_height > 2000){
                $font_size = $image_height/25;
                $border = $font_size/12;
            }elseif($image_height > 1500){
                $font_size = $image_height/23;
                $border = $font_size/11;
            }elseif($image_height > 1000){
                $font_size = $image_height/22;
                $border = $font_size/11;
            }elseif($image_height >= 400){
                $font_size = $image_height/22;
                $border = $font_size/10;;
            }else{
                $font_size = $image_height/21;
                $border = $font_size/9;
            }
                
            //$this->telegram_model->send_message_only($token,$chatid1,"here2: $font_size");
            if($image_height > 290){
                $result3 = exec("ffmpeg -y -i $outFileName  -filter_complex \"drawtext=text='@cinemaCenterNews':fontfile=$font2:fontsize=$font_size:fontcolor=#04fa38:borderw=$border:box=0:boxcolor=black@0.5:bordercolor=black@1.0:x=w/30:y=(h-text_h)/2+h/2*3/5\" $outFileName4 2>&1");
                $zxx = $this->telegram_model->send_photo_online($token,$chatid1,$outFileName4,$articleTitle);
                //$this->telegram_model->send_message_only($token,$chatid1,"here200");
            }else{
                $zxx = $this->telegram_model->send_photo_online($token,$chatid1,$outFileName,$articleTitle);
                //$this->telegram_model->send_message_only($token,$chatid1,"here300");
            }
            unlink($outFileName);
            unlink($outFileName4);
            sleep(1);
          //$this->telegram_model->send_photo($token,$chatid1,$image,$articleTitle);
          //$this->telegram_model->send_message_only($token,$chatid1,$articleTitle);
        }
        
        
        
    }
}

if($chatid1 == '-1001155301071' && $message == "تریلر"){
    $upcoming = $this->telegram_model->getOfficialTrailersForDownload();
    
    // تنظیم مسیرها بر اساس خواسته شما
    $user_folder = "application/$user_id";
    $source_del = "./" . $user_folder;
    $abs_path = FCPATH . $user_folder; // مسیر مطلق برای چک کردن فایل و ارسال

    // ایجاد پوشه اگر وجود نداشته باشد
    if (!is_dir($abs_path)) {
        mkdir($abs_path, 0777, true);
    }

    $cookies = "./application/youtubecookies.txt";
    $archive = "./application/archive1.txt";

    foreach ($upcoming as $video) {
        $urlDown = $video['url'];
        $movieTitle = $video['title'];
        $yt_id = $video['yt_id'];
        
        // نام فایل نهایی (id یوتیوب)
        $fileName = $yt_id . ".mp4";
        $vid = $abs_path . "/" . $fileName;

        // دستور yt-dlp با مسیر جدید شما
        $text = "yt-dlp -w --cookies " . escapeshellarg($cookies) . " -f 'b[filesize<18M][ext=mp4]/b[height<=480][filesize<18M][ext=mp4]/bv[height<=720][filesize<18M][ext=mp4]+ba[ext=m4a]/b' --merge-output-format mp4 --download-archive " . escapeshellarg($archive) . " --restrict-filenames " . escapeshellarg($urlDown) . " -o " . escapeshellarg($source_del . "/%(id)s.mp4");
        
        $out = [];
        $return_var = 0;
        exec($text, $out, $return_var);
        
        // بررسی آرشیو برای جلوگیری از ارسال تکراری
        $is_new = true;
        foreach ($out as $line) {
            if (strpos($line, 'has already been recorded in archive') !== false) {
                $is_new = false;
                break;
            }
        }

        // فقط در صورت دانلود جدید و موفقیت آمیز
        if ($return_var === 0 && $is_new) {
            // یک وقفه کوتاه برای اطمینان از بسته شدن فایل توسط سیستم
            clearstatcache();
            
            if (file_exists($vid)) {
                $caption = "🎬 <b>Trailer: " . $movieTitle . "</b>\n\n";
                $caption .= "📝 " . (mb_strlen($video['desc']) > 800 ? mb_substr($video['desc'], 0, 800) . "..." : $video['desc']);
                
                // ارسال ویدیو
                $vidsend = $this->telegram_model->send_video($token, $chatid1, $vid, "", "", $caption);
                
                // اطلاع رسانی موفقیت
                $this->telegram_model->send_message_only($token, $chatid1, "✅ تریلر ارسال شد: " . $movieTitle);
            } else {
                // اگر فایل باز هم پیدا نشد، خروجی yt-dlp را برای دیباگ می‌فرستیم
                $debug_info = end($out);
                $this->telegram_model->send_message_only($token, $chatid1, "❌ خطا: فایل در $vid یافت نشد. آخرین خروجی: " . $debug_info);
            }
        }
    }
}


if($chatid1 == '-1001155301071' || $chatid1 == '-4542272924' /*&& $message == "yyy1"*/){
    $message = $this->telegram_model->toEnglishNum($message);
    $infoMessage = explode(" ",$message);
    if(mb_strpos($message,"ساعت") != 6 && mb_strpos($message,"ساعت") != 5 && $infoMessage[1] != "ساعت" && $infoMessage[0] == "پسرم" && strlen($message) > 4){
        $this->telegram_model->send_message_only($token,$chatid1,"start list skh");
        $source_del = "./application/$user_id";
        
        $ren = copy("./application/youtubecookies1.txt","./application/youtubecookies.txt");
        $cookies = "./application/youtubecookies.txt";
        //$url1 = "https://www.youtube.com/c/ScreenCultureOfficial/videos"; //cinema 1
        $url1 = "https://www.youtube.com/@MovieTrailersSourceHD/videos"; //cinema 1
        $url2 = "https://www.youtube.com/c/afv/videos"; //khande 1
        $url3 = "https://www.youtube.com/@afv/shorts";  //khande2
        $url4 = "https://www.youtube.com/c/LOLComediHa/videos"; //khande3
        $url5 = "https://www.youtube.com/@LOLComediHa/shorts";  //khande4
        $url6 = "https://www.youtube.com/gags/videos";  //khande5
        $url7 = "https://www.youtube.com/@gags/shorts"; //khande6
        $url8 = "https://www.youtube.com/@JinJin1609/videos";  //khande7
        $url9 = "https://www.youtube.com/@PranksCity/videos";  //khande8
        $url10 = "https://www.youtube.com/@boxtoxtv/shorts";  //khande9
        $url11 = "https://www.youtube.com/@boxtoxtv/videos";  //khande10
        $url12 = "https://www.youtube.com/@semiraynosetoca05/videos"; //khande11
        
        $url13 = "https://www.youtube.com/@Whathowtry/videos";  //coktail 1
        $url14 = "https://www.youtube.com/@Whathowtry/shorts";  //coktail 2
        $url15 = "https://www.youtube.com/@TipsyBartender/videos"; //coktail 3
        $url16 = "https://www.youtube.com/@TipsyBartender/shorts"; //coktail 4
        $url17 = "https://www.youtube.com/@TopShelfCocktails/videos"; //coktail 5
        $url18 = "https://www.youtube.com/@TopShelfCocktails/shorts"; //coktail 6
        $url19 = "https://www.youtube.com/@QueenBeeMixology/videos"; //coktail 7
        $url20 = "https://www.youtube.com/@QueenBeeMixology/shorts"; //coktail 8
        
        $url21 = "https://www.youtube.com/c/VladSlickBartender/videos";  //barman
        $url22 = "https://www.youtube.com/@erekavetrini3398/shorts"; //recipe 1
        
        $url23 = "https://www.youtube.com/user/radiojavan/videos"; //radiojavan
        $url24 = "https://www.youtube.com/c/caltexrecordsmusic/videos"; //caltext  not good
        $url25 = "https://www.youtube.com/c/avangmusic/videos"; //avang music
        $url26 = "https://www.youtube.com/c/PeppaPigDE/videos";  //papa pigs
        
        $url27 = "https://www.youtube.com/channel/UCe_S9TuCnx_iY4m-mStne3Q/videos";

        $url28 = "https://www.youtube.com/user/dwlearngerman/videos"; //german learn
        $url29 = "https://www.youtube.com/c/TaranehEnterprise/videos";
        $url30 = "https://www.youtube.com/@KinoCheck.com/videos"; //cinema 2
        $url31 = "https://www.youtube.com/@trailerspot4k/videos"; //cinema 3
        $url32 = "https://www.youtube.com/@khstudio/videos"; //cinema 4
        $url33 = "https://www.youtube.com/@stryderhd/videos"; //cinema 5
        $url34 = "https://www.youtube.com/@RapidTrailer/videos";  //cinema 6
        
    
        $cheker = 0;
        if($infoMessage[1] == "سینما" && $infoMessage[2] == "1"){
            $urlDown = $url1;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }if($infoMessage[1] == "سینما" && $infoMessage[2] == "2"){
            $urlDown = $url30;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }if($infoMessage[1] == "سینما" && $infoMessage[2] == "3"){
            $urlDown = $url31;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }if($infoMessage[1] == "سینما" && $infoMessage[2] == "4"){
            $urlDown = $url32;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }if($infoMessage[1] == "سینما" && $infoMessage[2] == "5"){
            $urlDown = $url33;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }if($infoMessage[1] == "سینما" && $infoMessage[2] == "6"){
            $urlDown = $url34;
            $archive = "./application/archive1.txt";
            $caption1 = "#سینما  #تریلر\n\n";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "1"){
            $urlDown = $url2;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "2"){
            $urlDown = $url3;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "3"){
            $urlDown = $url4;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "4"){
            $urlDown = $url5;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "5"){
            $urlDown = $url6;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "6"){
            $urlDown = $url7;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "7"){
            $urlDown = $url8;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "8"){
            $urlDown = $url9;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "9"){
            $urlDown = $url10;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "10"){
            $urlDown = $url11;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "خنده" && $infoMessage[2] == "11"){
            $urlDown = $url12;
            $archive = "./application/archive2.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "1"){
            $urlDown = $url13;
            $archive = "./application/archive13.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "2"){
            $urlDown = $url14;
            $archive = "./application/archive14.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "3"){
            $urlDown = $url15;
            $archive = "./application/archive15.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "4"){
            $urlDown = $url16;
            $archive = "./application/archive3.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "5"){
            $urlDown = $url17;
            $archive = "./application/archive3.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "6"){
            $urlDown = $url18;
            $archive = "./application/archive3.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "7"){
            $urlDown = $url19;
            $archive = "./application/archive3.txt";
        }elseif($infoMessage[1] == "کوکتل" && $infoMessage[2] == "8"){
            $urlDown = $url20;
            $archive = "./application/archive3.txt";
        }
        //$this->telegram_model->send_message_only($token,$chatid1,"start $message");
        //$this->telegram_model->send_message_only($token,$chatid1,"start $urlDown");
        if(strlen($urlDown) > 0){
            if(is_dir($source_del)){
            //$this->telegram_model->send_message_only($token,$chatid1,"در حال حاضر شما یک ویدئو در جال پردازش دارید. لطفا درخواست خود را بعد از پایان ویدئوی قبلی ارسال کنید");
                die();
            }else{
                exec("mkdir $source_del");
            }
            //$source_del = "./application/$user_id";
        
            //$source = "./application/$user_id/source.mp4";
            //$archive = "./application/archive.txt";
            //--playlist-random   --dateafter $thisDate       
            //$thisDate = date("YMD");
            //-S '+res,ext:mp4,+size'
            
            //--download-archive $archive   bv[filesize<17M][ext=webm]+ba[filesize<3M][ext=m4a]/   --merge-output-format mkv --convert-subs srt  --sub-langs 'fa'
            // -f 'b[height<=720][height=>360][filesize<45M][ext=mp4]/bv[filesize<17M][ext=webm]+ba[filesize<3M][ext=m4a]'
            //-S '+res:480,ext:mp4,filesize:40M,+vcodec:avc'
    
            $down = "";
            
            if($infoMessage[1] == "سینما"){
                $text = "yt-dlp -w --cookies ./application/youtubecookies.txt -f 'b[filesize<18M][ext=mp4]/b[height<=480][filesize<18M][ext=mp4]/bv[height<=720][filesize<18M][ext=mp4]+ba[ext=m4a]/b[filesize<48M]/b' -I 1:5 --merge-output-format mp4 --write-info-json --download-archive $archive --restrict-filenames $urlDown -o '$source_del/%(id)s.mp4'";
                $this->telegram_model->send_message_only($token,'-1001155301071',"match2: ".$text);
                $down = exec($text,$out);
            }elseif(strpos($urlDown,"short") > 0){
                $text = "yt-dlp -w --cookies youtubecookies.txt -f 'b[height<=1500][ext=mp4]' -I 1:5 --write-info-json --download-archive $archive  --restrict-filenames $urlDown -o '$source_del/%(id)s.%(ext)s'";
                $this->telegram_model->send_message_only($token,'-1001155301071',"match3: ".$text);
                $down = exec($text,$out);
            }else{
                $text = "yt-dlp -w --cookies youtubecookies.txt -f 'b[filesize<47M][ext=mp4]' -I 1:5 --write-info-json --download-archive $archive  --restrict-filenames $urlDown -o '$source_del/%(id)s.%(ext)s'";
                $this->telegram_model->send_message_only($token,'-1001155301071',"match4: ".$text);
                $down = exec($text,$out);
            }
            /*for($k = 0; $k < 15; $k++){
                $this->telegram_model->send_message_only($token,'-1001155301071',"match1: ".$out[$k]);
            } */
            /*$all_vtt = glob("$source_del/*.srt");
            for($k = 0; $k < 5; $k++){
                //cleanVttFile($all_vtt[$k], "$source_del/$k.vtt");
                process_subtitle_file($all_vtt[$k], "$source_del/$k.srt");
            }   
            die();*/
            $this->telegram_model->send_message_only($token,'-1001155301071',"match1: ".$down);
            $result = exec("rm -rf $source_del/New_Music_Videos.info.json");
            
            /*$exict_vid = glob("$source_del/*.mp4");
            for($i = 0; $i < count($exict_vid); $i++){
                $thisId = substr($exict_vid[$i],strrpos($exict_vid[$i],"/")+1,strrpos($exict_vid[$i],".mp4")-strrpos($exict_vid[$i],"/")-1);
                $this->telegram_model->send_message_only($token,'-1001155301071',$thisId);
                $size = exec("du $exict_vid[$i] | cut -f1");
                if($size > 20000){
                    $change = exec("ffmpeg -i $track[$i] -codec copy -map 0 -segment_time 240 -reset_timestamps 1 -f segment $source_del/$thisId-ytoub%03d.mp4 2>&1",$out);
                }
            }*/
            
            
            $imagur_exict_jsn = glob("$source_del/*.json");
            for($i = 0; $i < count($imagur_exict_jsn); $i++){
                
                //$vid = $imagur_exict_vid[$i];
                $text = file_get_contents($imagur_exict_jsn[$i]);
                $text = json_decode($text, true);
                if($text['_type'] == "playlist"){
                    continue;
                }
                $title = $text['title'];
                if($infoMessage[2] == "1"){
                    
                    if(mb_strpos($title,"–") > 0){
                        $title1 = trim(mb_substr($title,0,mb_strrpos($title," –")));
                        //$title1 = trim(mb_substr($title1,0,mb_strrpos($title," -")));
                    }else{
                        $title1 = trim(mb_substr($title,0,mb_strrpos($title," |")));
                    }
                    $this->telegram_model->send_message_only($token,'-1001155301071',"112 \n".$title1);
                    //$title1 = substr($title,0,strpos($title,"- Trailer"));
                    //$title2 = substr($title,0,strpos($title,"- PROMO TRAILER"));
                    //$title3 = substr($title,0,strpos($title,"- First Trailer"));
                    //$title4 = substr($title,0,strpos($title,"| Trailer"));
                    //$title4 = substr($title,0,strpos($title,"| Trailer"));
                }
                
                $id = $text['id'];
                $resolotion = $text['height'];
                //$vid = "./application/$user_id/$id.*";
                $vid = glob("$source_del/$id.{mp4,webm,gif,mkv}",GLOB_BRACE)[0];
                
                //$this->telegram_model->send_message_only($token,'-1001155301071',"cinemahere1 $vid");
                    if($infoMessage[1] == "سینما"){
                        $dest = "./application/$user_id/source1.mp4";
                        if($infoMessage[2] == "1" || $infoMessage[2] == "5"){
                            $time = $text['duration']-12;
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"cinemahere1");
                            $result = exec("ffmpeg -y -i $vid -codec copy -t $time -avoid_negative_ts make_zero -preset superfast $dest 2>&1");
                        }elseif($infoMessage[2] == "2"){
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"cinemahere2");
                            $result = exec("ffmpeg -y -i $vid -codec copy -ss 00:00:03 -avoid_negative_ts make_zero -preset superfast $dest 2>&1");
                        }elseif($infoMessage[2] == "3"){
                            $time = $text['duration']-14;
                            //$this->telegram_model->send_message_only($token,'-1001155301071',"cinemahere3");
                            $result = exec("ffmpeg -y -i $vid -codec copy -t $time -avoid_negative_ts make_zero -preset superfast $dest 2>&1");
                        }else{
                            rename($vid,$dest);
                        }
                        //$this->telegram_model->send_message_only($token,'-1001155301071',"111 \n".$result);
                        $size = exec("du $dest | cut -f1");
                        if($size < 50000){
                            $font = "./application/fonts/IRJADID.TTF";
                            if($resolotion > 1080){
                                $font_size = 40;
                                $border = 2;
                            }elseif($resolotion > 720){
                                $font_size = 30;
                                $border = 2;
                            }elseif($resolotion > 640){
                                $font_size = 22;
                                $border = 1;
                            }else{
                                $font_size = 18;
                                $border = 1;
                            }
                            //$this->telegram_model->send_message_only($token,'-1001155301071',$font_size);
                            $result = exec("ffmpeg -y -i $dest -filter_complex \"[0]split[base][text];[text]drawtext=fontfile=$font:text=Telegram/CinemaCenterNews:borderw=1:bordercolor=black@1: fontcolor=white@1:fontsize=$font_size: box=0: boxcolor=black@1:boxborderw=0:x=50:y=h-line_h-70,format=yuva444p[subtitles];[base][subtitles]overlay\" -preset superfast $vid 2>&1");
                        }else{
                            $this->telegram_model->send_message_only($token,'-1001155301071',"حجمش زیاد بود");
                        }
                    }
                    //$this->telegram_model->send_message_only($token,'-1001155301071',"222 \n".$result);
                    $caption = $caption1.$title."\n\n@VieraBot\n@vieraMagazine";
                    $vidsend = $this->telegram_model->send_video($token,$chatid1,$vid,"","",$caption);
                    
            
                //$this->telegram_model->send_message_only($token,'-1001155301071',$vidsend);
            }
            $vsend = json_decode($vidsend, true);
            if(strlen($vsend['result']['message_id']) > 0){
                $data = array("content"=>$vsend['result']['message_id']);
                $this->telegram_model->update_temp(16,$data);
            }
            
            $result = exec("rm -rf $source_del");
        }
    }
}


//*******************************************************************  game

/*$score = $update->message->dice->value;
if($score){
    $this->telegram_model->send_message_only($token,'-1001155301071',$score);
}
if($chatid1 == '-1001155301071' && $message == "game"){
    
}*/

//******************************************************************* system command
if($message == "tmtmtm" || $message == "تخلیه تمپ"){
    $temp_dir = sys_get_temp_dir();
    $file_exict2 = glob("$temp_dir/*");
    $result = exec("rm -rf $temp_dir/*");
    $this->telegram_model->send_message_only($token,'-1001155301071',"count: ".count($file_exict2) );
}

if($message == "حذف پوشه من"){
    $result = exec("rm -rf ./application/$chatid1");
}

if($time%4 == 0 && $Minutes == 3 && $Seconds < 20 ){
    //$this->telegram_model->send_message_only($token,'-1001155301071',6%4 );
    /*$this->telegram_model->send_message_only($token,'-1001155301071',"del start " );
    $temp_dir = sys_get_temp_dir();
    $file_exict2 = glob("$temp_dir/*");
    $result = exec("rm -rf $temp_dir/*");
    $this->telegram_model->send_message_only($token,'-1001155301071',"count: ".count($file_exict2) );*/
    if($time == 0){
        //**************** temp translate counter
        $data = array("name"=>time(),"content"=>0);
        $this->telegram_model->update_temp(15,$data);
    }
    if($day == 1 && $time == 0){
        //**************** temp bing img counter
        $data = array("content"=>0);
        $this->telegram_model->update_temp(13,$data);
    }
}

if($message == "خالی کردن تمپ 1"){
    $this->telegram_model->send_message_only($token,'-1001155301071',"del start " );
    $temp_dir = sys_get_temp_dir();
    $file_exict2 = glob("$temp_dir/*");
    $result = exec("rm -rf $temp_dir/*");
    $this->telegram_model->send_message_only($token,'-1001155301071',"count: ".count($file_exict2) );
}

/*if(count($newmember) && $newmember[0]->username == "Vierabot"){
    $text = "خوشحالم که به گروهتون دعوتم کردید. \n\nبرای استفاده از راهنما، لطفا بدون ریپلای کردن کلمه « راهنمای ویرا » را ارسال کنید🙏🌺";
    $this->telegram_model->send_message_only($token,$chatid1,$text );
    $member = $this->telegram_model->get_member_count($token,$chatid1);
    $data = array("group_id"=>$chatid1,"group_name"=>$chatname1,"last_post_time"=>time(),'magazin'=>"yes",'vierabon'=>"",'member'=>$member);
    $this->telegram_model->set_viera_group($data);
    $this->telegram_model->send_message_only($token,'-1001155301071',"viera added to new group: \n".$chatid1."\n".$chatname1 );
    $this->telegram_model->send_message_only($token,'-1001155301071',$chatid1 );
}*/

if(count($left_message)){
    
    $this->telegram_model->clear_groups_users($chatid1,$left_uid);

}

if($chatid1 == '-1001155301071' && $message == "Rold"){
    $resultsAc = $this->telegram_model->get_groups_users_inactive();
    $this->telegram_model->send_message_only($token,'-1001155301071',count($resultsAc) );
    
    //$this->telegram_model->send_message_only($token,'-1001155301071',$resultsAc[0]->user_id."->".$resultsAc[0]->user_name );
    //$this->telegram_model->send_message_only($token,'-1001155301071',$resultsAc[0]->group_id );
    
    for($i = 0; $i < count($resultsAc); $i++){
        $results = $this->telegram_model->get_member($token,/*$user_id*/ $resultsAc[$i]->user_id,$resultsAc[$i]->group_id);
        $resJson = json_decode($results, true);
        
        if($resJson["error_code"] > 0){
            //$this->telegram_model->send_message_only($token,'-1001155301071',$resJson["error_code"] );
            $this->telegram_model->send_message_only($token,'-1001155301071',$resultsAc[$i]->user_id." -> ".$resultsAc[$i]->group_id );
            //$this->telegram_model->send_message_only($token,'-1001155301071',"delet gid" );
            $data = array("group_id"=>NULL);
            $this->telegram_model->update_groups_users($resultsAc[$i]->group_id,$resultsAc[$i]->user_id,$data);
            //$this->telegram_model->clear_groups_users($resultsAc[$i]->group_id,$resultsAc[$i]->user_id);
        }else{
            $this->telegram_model->send_message_only($token,'-1001155301071'," not not delet gid" );
        }
    }
}

/*if($chatid1 == '-1001155301071' &&  $message == "fff"){
    $this->telegram_model->send_message_only($token,'-1001155301071',"this find: " );
    $html = file_get_html('https://oib.postbank.ir/ib/ibangen.aspx');
    $title = $html->find('input');
    //$row = $html->find('.items_table',2)->find('tr');
    //$td = $html->find('.items_table tr td');
    //$tablo1_onc .= $row[5]->plaintext." ==> ".trim($row[22]->plaintext)."\n";
    $this->telegram_model->send_message_only($token,'-1001155301071',"this find: ".count($title) );
}*/

if($message == "lleftt"){
    $var = '-1001155301071';
    $del_act = $this->telegram_model->leave_chat($token,$var);
    $this->telegram_model->send_message_only($token,'-1001155301071',$del_act);
        
    /*$this->telegram_model->clear_post_sent_group( $var );
    $this->telegram_model->clear_viera_group( $var );
    $this->telegram_model->clear_Controler($var);
    $this->telegram_model->clear_groups_users_group($var);*/
}



if($message){
    
    $thisMusicTimer = $this->telegram_model->get_telegram_music_timer();
    if(count($thisMusicTimer) > 0){
        $this_uid = $thisMusicTimer[0]->uid;
        $this_cid = $thisMusicTimer[0]->cid;
        $this_pid = $thisMusicTimer[0]->pid;
        $p = $this->telegram_model->delete_message_one($token,$this_cid,$this_pid);
        $this->telegram_model->clear_telegram_music_timer($this_uid);
        $source_del = "./application/$this_uid";
        $result = exec("rm -rf $source_del");
    }
    
    //*********************************************************************  UPDATE GROUP Users
    
    
    
    //*********************************************************************  UPDATE GROUP Details
    
    $member = $this->telegram_model->get_member_count($token,$chatid1);
    $data = array('group_id'=>$chatid1,'group_name'=>$chatname1,'magazin'=>'yes','vierabon'=>'yes','last_post_time'=>time(),'last_post_id'=>$lastpost,'member'=>$member);
    $data1 = array('group_id'=>$chatid1,'group_name'=>$chatname1,'last_post_time'=>time(),'last_post_id'=>$lastpost,'member'=>$member);
    //$this->telegram_model->set_viera_group($data);
    $this->telegram_model->update_viera_group($chatid1,$data1);
    
    $exist_user = $this->telegram_model->get_groups_users($chatid1,$user_id);
    $jsonfirst = json_encode($firstname);
    if(count($exist_user) == 0){
        //$firstname = html_entity_decode($firstname);
        if(/*$user_id == '111677712'*/ $chatid1 == '-1001155301071'){
            $this->telegram_model->send_message_only($token,'-1001155301071',"first name: ".$firstname );
        }
        $data2 = array('group_id'=>$chatid1,'user_id'=>$user_id,'user_name'=>$username,'first_name'=>$firstname,'persian_name'=>'',
        'last_name'=>$lastname,'post_id'=>$lastpost,'online_time'=>time(),'Json_first'=>$jsonfirst);
        $added = $this->telegram_model->set_groups_users($data2);
        //$this->telegram_model->send_message_only($token,'-1001155301071',"add shod: ".$added );
    }else{
        //if($chatid1 == '-1001155301071'){
            $data = array("user_name"=>"$username","first_name"=>$firstname,"Json_first"=>$jsonfirst,"last_name"=>$lastname,"online_time"=>time());
            $update = $this->telegram_model->update_groups_users2($chatid1,$user_id,$data);
        //}
    }
    
    //********************************************************** automatic remove key from chats
    /*$type = $this->telegram_model->get_chat($token,$chatid1);
    $type = json_decode($type, true);
    
    
    if($type['result']['type'] != "private"){
        $this->telegram_model->send_message_only($token,'-1001155301071',"klid: ".$type['result']['type']);
        $this->telegram_model->send_message_only($token,'-1001155301071',"klid: ".$type['result']['id']."\n".$type['result']['first_name']);
        
        $keyboard = array("keyboard" => array(),"resize_keyboard"=>true,"remove_keyboard" => true);
    	$test = $this->telegram_model->send_message($token,$chatid1,".",$keyboard);
    	//$this->telegram_model->send_message_only($token,'-1001155301071',$test);
    	$del_act = $this->telegram_model->delete_message_one($token,$chatid1,$lastpost+1);
    }*/
}

if($chatid1 == '-1001155301071' && $message == "دانلودد"/*$update*/){
    $this->telegram_model->send_message_only($token,'-1001155301071',"please wait");
    $url = "https://www.instagram.com/reels/DBd-X6Gt4JN/";
    $res = $this->telegram_model->get_insta_2($url);
    $links = json_decode($res, true);
    $vid = $links['data'][0]['media'];
    $outFileName = "./application/new.mp4";
    $size = $this->telegram_model->download_file($vid,$outFileName); 
    //$res = $this->telegram_model->send_message_only($token,'-1001155301071',$emojiAction);
    $this->telegram_model->send_message_only($token,'-1001155301071',$size);
}


if($chatid1 == '-1001155301071' && $message == "Psps"){
    //kill process
    $res = exec('ps -eo pid,etime,cmd | grep ffmpeg |grep -v grep');
    $res = substr($res,0,strpos($res,"ffmpeg"));
    $detail = explode(" ",$res);
    $arrayNew = array();
    for($i = 0; $i < count($detail); $i++){
        if(strlen($detail[$i]) > 0){
            if(strpos($detail[$i],":") > 0){
                $arrayNew['time'] = $detail[$i];
            }else{
                $arrayNew['pid'] = $detail[$i];
            }
            
        }
        
    }
    $this->telegram_model->send_message_only($token,'-1001155301071',$arrayNew['pid']);
    $thisPid = $arrayNew['pid'];
    $ami = shell_exec('whoami');
    $this->telegram_model->send_message_only($token,'-1001155301071',substr($ami,0,500));
    //$ret = exec("kill  -9  $thisPid");
    //$ret = shell_exec("pkill ffmpeg 2>&1");
    //$ret = shell_exec("taskkill /im $thisPid /F /T /PID ");
    
    //$ret = shell_exec("echo 'Fkhlonhl961763!1' | sudo -u root -S | kill  -15  $thisPid 2>&1");
    $this->telegram_model->send_message_only($token,'-1001155301071',substr($ret,0,500));
    $this->telegram_model->send_message_only($token,'-1001155301071',substr($output,0,500));
}
    
if($iskey_board){
 

/*$keyboard = array("keyboard" => array($array1,$array2,$array3,$array4,$array5,$array6,$array7,$array8,$array9,$array10),"resize_keyboard"=>true);
$this->telegram_model->send_message($token,$id,$message,$keyboard);
$text = "لطفا یکی از موارد زیر را انتخاب کنید.";
//$this->telegram_model->send_message_inline($token,$id,$keyboard);
$keyboard =  array("inline_keyboard" => array($arrayg1,$arrayg2,$arrayg3,$arrayg4));
$this->telegram_model->send_message($token,$id,$text,$keyboard);*/

}



 //$this->load->helper('string');
 //echo random_string('alnum', 30);
	}
}
?>