<?php
class telegram_model extends CI_Model {
    public function send_message($tokenkey,$id,$text,$keyboard=null){
        
$params=[
    'chat_id'=>$id,
    'text'=>$text,
	'reply_markup'=>json_encode($keyboard),
	'parse_mode'=>'HTML',
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/SendMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function edit_message($tokenkey,$chatid,$m_id,$text){
$params=[
    
	'message_id'=>$m_id,
    'text'=>$text,
    'chat_id'=> $chatid,
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/editMessageText");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function edit_message_key($tokenkey,$chatid,$m_id,$text,$keyboard){
$params=[
    
	'message_id'=>$m_id,
    'text'=>$text,
    'chat_id'=> $chatid,
    'reply_markup'=>json_encode($keyboard),
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/editMessageText");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function edit_message_markup($tokenkey,$chatid,$m_id,$text,$keyboard){
$params=[
    
	'message_id'=>$m_id,
    'text'=>$text,
    'chat_id'=> $chatid,
    'reply_markup'=>json_encode($keyboard),
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/editMessageReplyMarkup");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function edit_message_caption($tokenkey,$chatid,$m_id,$text){
$params=[
    
	'message_id'=>$m_id,
    'caption'=>$text,
    'chat_id'=> $chatid,
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/editMessageCaption");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_admin($tokenkey,$chatid){
$params=[
    'chat_id'=>$chatid
];

$ch = curl_init("https://api.telegram.org/bot".$tokenkey."/getChatAdministrators");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_member($tokenkey,$user_id,$chatid='@VieraMagazine'){
$params=[
    'chat_id'=>$chatid,
    'user_id'=> $user_id,
];

$ch = curl_init("https://api.telegram.org/bot".$tokenkey."/getChatMember");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function get_member2($tokenkey,$user_id,$chatid){
    $params=[
        'chat_id'=>$chatid,
        'user_id'=> $user_id,
    ];
    
    $ch = curl_init("https://api.telegram.org/bot".$tokenkey."/getChatMember");
    
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($result, true);
    return $result["result"]["status"];
}

public function get_member_count($tokenkey,$chatid){
$params=[
    'chat_id'=>$chatid,
];

$ch = curl_init("https://api.telegram.org/bot".$tokenkey."/getChatMembersCount");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
return $result["result"];
//return $result;
}

public function kick_member($tokenkey,$chatid,$user_id,$until = 0){
$params=[
    'chat_id'=>$chatid,
    'user_id'=> $user_id,
    'until_date'=>$until,
];

$ch = curl_init("https://api.telegram.org/bot".$tokenkey."/kickChatMember");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function forward($tokenkey,$from,$postid,$chatid){


$params=[
    'chat_id'=>$chatid,
    'from_chat_id'=>$from,
    'message_id' =>$postid,
];

$ch = curl_init("https://api.telegram.org/bot".$tokenkey."/forwardMessage");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;

}

public function send_message_inline($tokenkey,$id,$keyboard){
$params=[
    'chat_id'=>$id,
	'reply_markup'=>json_encode($keyboard),
	'parse_mode'=>'HTML',
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/SendMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}

public function send_message_only($tokenkey,$cid,$text){
$params=[
    'chat_id'=>$cid,
    'text'=>$text,
    'parse_mode'=>'HTML',
    
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/SendMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}


public function send_message_only_replay($tokenkey,$id,$messageid,$text){
$params=[
    'chat_id'=>$id,
    'text'=>$text,
    'reply_to_message_id'=>$messageid,
    'parse_mode'=>'HTML',
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/SendMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_message_answer_callback($tokenkey,$id,$callback_id,$text){
$params=[
    'text'=>$text,
    'callback_query_id'=>$callback_id,
    'show_alert'=>true,
    'cache_time'=>10,
    'parse_mode'=>'HTML',
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/answerCallbackQuery");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function inline_answer($tokenkey,$inline_query_id, $results){
$params=[
    
    'inline_query_id'=>$inline_query_id,
    'results'=>json_encode($results),
    //'reply_markup'=>json_encode($keyboard),
    'cache_time'=>10,
    'next_offset'=> 'یوتوب'
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/answerInlineQuery");
//$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/InlineQueryResultVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}


public function inline_answer_video($tokenkey, $results, $inline_query_id){
$params=[
    'inline_query_id'=>$inline_query_id,
    'results'=>json_encode($results),
    'cache_time'=>5
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/answerInlineQuery");
//$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/InlineQueryResultVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function delete_message($tokenkey,$chat_id,$message_id){
    for($i=$message_id;$i>$message_id-1000;$i--){
$params=[
    'chat_id'=>$chat_id,
    'message_id'=>$i,
];

$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/deleteMessage");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
        
    }
return $result;
}
public function delete_message_one($tokenkey,$chat_id,$message_id){
   
$params=[
    'chat_id'=>$chat_id,
    'message_id'=>$message_id,
	
];

$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/deleteMessage");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_photo($tokenkey,$id,$url,$caption = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'photo'=> $url,
	"caption"=>$caption,
	'parse_mode'=>'HTML',
];
}else{
$params=[
    'chat_id'=>$id,
    'photo'=> $url,
    'parse_mode'=>'HTML',
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendPhoto");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_photo_reply($tokenkey,$id,$url,$caption = null,$replay_to = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'photo'=> $url,
	"caption"=>$caption,
	'parse_mode'=>'HTML',
	'reply_to_message_id'=>$replay_to
];
}else{
$params=[
    'chat_id'=>$id,
    'photo'=> $url,
    'parse_mode'=>'HTML',
    'reply_to_message_id'=>$replay_to
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendPhoto");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_photo_online($tokenkey,$id,$url,$caption = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    /*'photo'=> $url,*/
    'photo'=> new CURLFile($url),
	"caption"=>$caption,
	'parse_mode'=>'HTML',
];
}else{
$params=[
    'chat_id'=>$id,
    /*'photo'=> $url,*/
    'photo'=> new CURLFile($url),
    
    'parse_mode'=>'HTML',
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendPhoto");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_photo_online_group($tokenkey,$id,$url,$caption= null){

    $params=[
        'chat_id'=>$id,
        /*'photo'=> $url,*/
        'media'=> json_encode($url),
    ];

$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendMediaGroup");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function post($tokenkey, $postContent)
{
    $url = "https://api.telegram.org/bot" . $tokenkey . "/sendMediaGroup";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postContent);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}


public function send_video_repl($tokenkey,$id,$url,$width,$height,$caption,$replay_to=null){
    
$params=[
    'chat_id'=>$id,
    'video'=> new CURLFile($url),
	"caption"=>$caption,
	"supports_streaming"=>true,
	"width"=>$width,
	"height"=>$height,
	'reply_to_message_id'=>$replay_to
];

$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_video_repl_online($tokenkey,$id,$url,$width,$height,$caption,$replay_to=null){
    
$params=[
    'chat_id'=>$id,
    'video'=> $url,
	"caption"=>$caption,
	"supports_streaming"=>true,
	"width"=>$width,
	"height"=>$height,
	'reply_to_message_id'=>$replay_to
];

$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_video($tokenkey,$id,$url,$width,$height,$caption = null){
    
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'video'=> new CURLFile($url),
	"caption"=>$caption,
	"supports_streaming"=>true,
	"width"=>$width,
	"height"=>$height
];
}else{
$params=[
    'chat_id'=>$id,
    'video'=> new CURLFile($url),
    
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function send_video2($tokenkey,$id,$url,$caption = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'video'=> new CURLFile($url),
	"caption"=>$caption,
	"supports_streaming"=>true,
	//"width"=>1280,
	//"height"=>720
];
}else{
$params=[
    'chat_id'=>$id,
    'video'=> new CURLFile($url),
    "supports_streaming"=>true,
	//"width"=>1280,
	//"height"=>720
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_video_online($tokenkey,$id,$url,$caption = null,$width = null ,$height = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'video'=> $url,
	"caption"=>$caption,
	"width"=>$width,
	"height"=>$height
];
}else{
$params=[
    'chat_id'=>$id,
    'video'=> $url,
    "width"=>$width,
	"height"=>$height
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVideo");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function send_animation($tokenkey,$id,$url,$caption = null){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'animation'=> new CURLFile($url),
	"caption"=>$caption,
];
}else{
$params=[
    'chat_id'=>$id,
    'animation'=> new CURLFile($url),
    
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendAnimation");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function send_document($tokenkey,$id,$url,$caption = "null"){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'document'=> new CURLFile($url),
    /*'document'=> $url,*/
    'parse_mode'=>'HTML',
	"caption"=>$caption
];
}else{
$params=[
    'chat_id'=>$id,
    'parse_mode'=>'HTML',
    'document'=> new CURLFile($url),
    /*'document'=> $url,*/
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendDocument");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_document_online($tokenkey,$id,$url,$caption = "null"){
if($caption != "null"){
$params=[
    'chat_id'=>$id,
    'document'=> $url,
    'parse_mode'=>'HTML',
	"caption"=>$caption
];
}else{
$params=[
    'chat_id'=>$id,
    'parse_mode'=>'HTML',
    'document'=> $url,
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendDocument");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_audio($tokenkey,$chatid,$caption,$link,$performer,$title,$replay_to,$keyboard=null){
    
$params=[
    'chat_id'=>$chatid,
    'audio'=>$link,
    'performer'=>$performer /*"skh"*/,
    'title'=>$title/*"@VieraMagazine"*/,
    'caption'=>$caption,
    'thumb'=>$thumb,
    'reply_to_message_id'=>$replay_to
    //'reply_markup'=>json_encode($keyboard),
	
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendAudio");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function send_audio_online($tokenkey,$chatid,$caption,$link,$performer,$title,$replay_to){
if($caption != "null"){
$params=[
    'chat_id'=>$chatid,
    'audio'=> new CURLFile($link),
	"caption"=>$caption,
	'performer'=>$performer /*"skh"*/,
    'title'=>$title/*"@VieraMagazine"*/,
    'parse_mode'=>'HTML',
    'reply_to_message_id'=>$replay_to
];
}else{
$params=[
    'chat_id'=>$id,
    'audio'=> new CURLFile($link),
    'performer'=>$performer /*"skh"*/,
    'title'=>$title/*"@VieraMagazine"*/,
    'parse_mode'=>'HTML',
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendAudio");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_voice_online($tokenkey,$chatid,$caption,$link){
if($caption != "null"){
$params=[
    'chat_id'=>$chatid,
    'audio'=> new CURLFile($link),
	"caption"=>$caption,
    'duration'=>20
];
}else{
$params=[
    'chat_id'=>$chatid,
    'audio'=> new CURLFile($link),
    'duration'=>20
];	
}
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVoice");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_Action($tokenkey,$chatid,$action){
        
$params=[
    'chat_id'=>$chatid,
    'action'=> $action,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendChatAction");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function leave_chat($tokenkey,$chatid){
        
$params=[
    'chat_id'=>$chatid,
  
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/leaveChat");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_chat($tokenkey,$chatid){
        
$params=[
    'chat_id'=>$chatid,
  
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/getChat");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_userphoto($tokenkey,$user_id){
        
$params=[
    'user_id'=>$user_id,
  
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/getUserProfilePhotos");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function pin_ChatMessage($tokenkey,$chat_id,$message_id){
        
$params=[
    'chat_id'=>$chat_id,
    'message_id'=>$message_id,
  
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/pinChatMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function unpin_ChatMessage($tokenkey,$chat_id){
        
$params=[
    'chat_id'=>$chat_id,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/unpinChatMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_stickers($tokenkey,$sticker_name){
        
$params=[
    'name'=>$sticker_name,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/getStickerSet");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_stickers($tokenkey,$chat_id,$sticker_name,$reply_id){
        
$params=[
    'chat_id'=>$chat_id,
    'sticker'=>$sticker_name,
    'reply_to_message_id'=>$reply_id,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendSticker");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function restrict_member($tokenkey,$chat_id,$user_id,$until_date = null,$can_send_messages = false){
        
$params=[
    'chat_id'=>$chat_id,
    'user_id'=>$user_id,
    'until_date'=>$until_date,
    'can_send_messages'=>$can_send_messages
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/restrictChatMember");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function no_restrict_member($tokenkey,$chat_id,$user_id,$can_send_messages = true){
        
$params=[
    'chat_id'=>$chat_id,
    'user_id'=>$user_id,
    'can_send_messages'=>$can_send_messages,
    'can_send_media_messages'=>$can_send_messages,
    'can_send_polls'=>$can_send_messages,
    'can_send_other_messages'=>$can_send_messages,
    'can_add_web_page_previews'=>$can_send_messages,
    'can_change_info'=>$can_send_messages,
    'can_invite_users'=>$can_send_messages,
    'can_pin_messages'=>$can_send_messages,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/restrictChatMember");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function get_link($tokenkey,$chat_id){
        
$params=[
    'chat_id'=>$chat_id
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/exportChatInviteLink");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function revok_link($tokenkey,$chat_id,$link){
        
$params=[
    'chat_id'=>$chat_id,
    'invite_link'=>$link
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/revokeChatInviteLink");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function set_chat_permition($tokenkey,$chat_id,$permit,$sen_media){
        
$params=[
    'chat_id'=>$chat_id,
    'permissions'=>$permit,
    
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/setChatPermissions");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function aproveReq($tokenkey,$chat_id,$user_id){
        
$params=[
    'chat_id'=>$chat_id,
    'user_id'=>$user_id,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/approveChatJoinRequest");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function promot_member($tokenkey,$chat_id,$user_id,$can_message,$can_del){
        
$params=[
    'chat_id'=>$chat_id,
    'user_id'=>$user_id,
    'can_edit_messages'=>$can_message,
    'can_delete_messages'=>$can_del
    
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/promoteChatMember");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function send_location($tokenkey,$id,$latitude,$longitude,$title,$address){

$params=[
    'chat_id'=>$id,
    'latitude'=> $latitude,
	"longitude"=>$longitude,
	"title"=>$title,
	"address"=>$address
];
	
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendVenue");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_me1($tokenkey){
        
$params=[
    'chat_id'=>$chat_id,
    'permissions'=>$permit,
    
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/getMe");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function get_file($tokenkey,$file_id){
        
$params=[
    'file_id'=>$file_id,
    
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/getFile");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function translate($message){
    
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://google-translator9.p.rapidapi.com/v2",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => json_encode([
    		'q' => $message,
    		'source' => 'en',
    		'target' => 'fa-IR',
    		'format' => 'text'
    	]),
    	CURLOPT_HTTPHEADER => [
    		"Content-Type: application/json",
    		"x-rapidapi-host: google-translator9.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
        
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function translate2($message){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://kiara-translate.p.rapidapi.com/get_translated/",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => "{\r\"input\": \"$message\",\r\"lang\": \"fa\"\r}",
    	CURLOPT_HTTPHEADER => [
    		"content-type: application/json",
    		"x-rapidapi-host: kiara-translate.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
        $res = json_decode($response, true);
        return $res['translated'];
    }
}

public function translate3($message){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://just-translated.p.rapidapi.com/?lang=fa&text=$message",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: just-translated.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
        $res = json_decode($response, true);
        return $res['text'][0];
    }
}

public function translate4($message){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://deep-translate1.p.rapidapi.com/language/translate/v2",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => json_encode([
    		'q' => "$message",
    		'source' => 'auto',
    		'target' => 'fa'
    	]),
    	CURLOPT_HTTPHEADER => [
    		"Content-Type: application/json",
    		"x-rapidapi-host: deep-translate1.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function translate5($message){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://translateai.p.rapidapi.com/google/translate/text",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => json_encode([
    		'origin_language' => 'auto',
    		'target_language' => 'fa',
    		'words_not_to_translate' => ''/*'Para; Experimenta'*/,
    		'input_text' => "$message"
    	]),
    	CURLOPT_HTTPHEADER => [
    		"Content-Type: application/json",
    		"x-rapidapi-host: translateai.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	echo "cURL Error #:" . $err;
    } else {
    	echo $response;
    }
}
        
public function get_tgju_currency_prices() {
    $url = "https://www.tgju.org/currency";
    $logFile = FCPATH . 'application/scraper_errors.log';

    // چک کردن وجود کتابخانه‌های لازم
    if (!class_exists('DOMDocument')) {
        file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Error: DOMDocument is not installed on this server." . PHP_EOL, FILE_APPEND);
        return false;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');

    $html = curl_exec($ch);
    $error = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode != 200) {
        file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Error: HTTP Code $httpCode. Curl Error: $error" . PHP_EOL, FILE_APPEND);
        return false;
    }

    try {
        $doc = new DOMDocument();
        libxml_use_internal_errors(true);
        // لود کردن با اینکودینگ صحیح
        @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html);
        $xpath = new DOMXPath($doc);

        $rows = $xpath->query("//tr[@data-market-row]");
        
        $currencies = [];
        foreach ($rows as $row) {
            $id = $row->getAttribute('data-market-row');
            
            // استخراج نام از تگ th یا td اول
            $nameNode = $xpath->query(".//th", $row)->item(0);
            $priceNode = $xpath->query(".//td[1]", $row)->item(0);
            
            if ($nameNode && $priceNode) {
                $currencies[$id] = [
                    'name' => trim($nameNode->nodeValue),
                    'price' => trim($priceNode->nodeValue)
                ];
            }
        }

        if (empty($currencies)) {
            file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Error: No rows found in HTML." . PHP_EOL, FILE_APPEND);
            return false;
        }

        return $currencies;

    } catch (Exception $e) {
        file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Exception: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
        return false;
    }
}

public function get_tgju_all_data() {
    // لیست صفحاتی که باید اسکرپ شوند
    $urls = [
        'currency' => "https://www.tgju.org/currency",
        'gold'     => "https://www.tgju.org/gold-chart",
        'coin'     => "https://www.tgju.org/coin"
    ];
    
    $logFile = FCPATH . 'application/scraper_errors.log';
    $all_data = [];

    if (!class_exists('DOMDocument')) {
        file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Error: DOMDocument is not installed." . PHP_EOL, FILE_APPEND);
        return false;
    }

    foreach ($urls as $type => $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');

        $html = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode != 200 || empty($html)) {
            file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Error: Failed to load $url (Code: $httpCode)" . PHP_EOL, FILE_APPEND);
            continue; // رفتن به آدرس بعدی در صورت خطا
        }

        try {
            $doc = new DOMDocument();
            libxml_use_internal_errors(true);
            @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html);
            $xpath = new DOMXPath($doc);

            // جستجوی تمام ردیف‌هایی که دیتای بازار دارند
            $rows = $xpath->query("//tr[@data-market-row]");
            
            foreach ($rows as $row) {
                $id = $row->getAttribute('data-market-row');
                
                // فیلتر کردن موارد درخواستی شما برای طلا و سکه (در صورت نیاز به محدود کردن)
                // اگر می‌خواهید همه را بگیرید، این شرط‌ها را بردارید
                
                $nameNode = $xpath->query(".//th", $row)->item(0);
                // در برخی جداول نام در td اول است، اگر th نبود td اول را چک میکنیم
                if (!$nameNode) {
                    $nameNode = $xpath->query(".//td[1]", $row)->item(0);
                    $priceNode = $xpath->query(".//td[2]", $row)->item(0);
                } else {
                    $priceNode = $xpath->query(".//td[1]", $row)->item(0);
                }
                
                if ($nameNode && $priceNode) {
                    $all_data[$id] = [
                        'name' => trim($nameNode->nodeValue),
                        'price' => trim($priceNode->nodeValue),
                        'type' => $type // مشخص کردن اینکه طلا، سکه یا ارز است
                    ];
                }
            }
        } catch (Exception $e) {
            file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Exception on $url: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
        }
    }

    return (!empty($all_data)) ? $all_data : false;
}

public function get_text_img($url){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://ocrly-image-to-text.p.rapidapi.com/?imageurl=$url&filename=sample.jpg",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: ocrly-image-to-text.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
    	
    	return $response/*"language: ".$res['language']."\n\n".$res['text']*/;
    }
}

public function get_img($message){
    $curl = curl_init();
    $offset = mt_rand(0,500);
    curl_setopt_array($curl, [
        //CURLOPT_URL => "https://bing-image-search1.p.rapidapi.com/images/search?q=$message&safeSearch=off&offset=$offset",
    	CURLOPT_URL => "https://bing-image-search1.p.rapidapi.com/images/search?q=$message&offset=$offset",
    	//CURLOPT_URL => "https://bing-image-search1.p.rapidapi.com/images/trending",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: bing-image-search1.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
    	
    	return $response/*"language: ".$res['language']."\n\n".$res['text']*/;
    }
}

public function get_vid($message){
    $curl = curl_init();
    $offset = mt_rand(0,500);
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://bing-video-search1.p.rapidapi.com/videos/search?q=$message&offset=$offset&qft=+filterui:duration-short+filterui:site-youtube.com&FORM=VRFLTR",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: bing-video-search1.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
    	
    	return $response;
    }
}

public function get_text_img2($url){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://image-text-recognition.p.rapidapi.com/recognite_by_url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => "url=".$url,
    	CURLOPT_HTTPHEADER => [
    		"content-type: application/x-www-form-urlencoded",
    		"x-rapidapi-host: image-text-recognition.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    /*$res = json_decode($response, true);
    $array_text = array("language"=>$res['language'],"text"=>$res['text']);*/
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
    	
    	return $response/*"language: ".$res['language']."\n\n".$res['text']*/;
    }
}

public function chatAi($model,$text){
    //$apiKey = "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";
    $api_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZTVhZWZkYzQtYzMxMS00NzA3LTg2ODgtMzhkNzViZjc4MDgzIiwidHlwZSI6ImFwaV90b2tlbiJ9.T5OT8oYkqnlerSI-m4aSJ2IjHb18UIpU3qX2eqV0w9E"; // کلید API رو اینجا بذار
    $apiKey = "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";
    $models = ['tngtech/deepseek-r1t2-chimera:free','mistralai/mistral-small-3.2-24b-instruct:free','openai/gpt-oss-20b:free'];
    $ch = curl_init("https://openrouter.ai/api/v1/chat/completions");
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(
            [
                "model" => $model,
                "messages" => [
                    [
                        "role" => "system",
                        "content" => "همیشه پاسخ‌ها را به صورت دوستانه، همراه با ایموجی‌های مرتبط بگو و فقط وقتی سلام کردن بگو سلام 🔥✨."
                    ],
                    [
                        "role" => "user",
                        "content" => $text
                    ]
                ],
                "max_tokens" => 1000,
                "top_p" => 0.9,
                "temperature" => 0.2
            ],
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        )
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return $response;
}

    
public function askMistralWithImage($apiKey, $question, $imageUrl) {
    $payload = [
        "model" => "mistralai/mistral-small-3.2-24b-instruct:free",
        "temperature" => 0.7,
        "max_tokens" => 800,
        "messages" => [
            [
                "role" => "system",
                "content" => "پاسخ‌ها را دوستانه و همراه با ایموجی‌های مرتبط بده 😎📷"
            ],
            [
                "role" => "user",
                "content" => [
                    ["type" => "input_text",  "text" => $question],
                    ["type" => "input_image", "image_url" => $imageUrl],
                ]
            ]
        ]
    ];

    $ch = curl_init("https://openrouter.ai/api/v1/chat/completions");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $apiKey,
            "Content-Type: application/json",
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // اگر خطاست، پیام خوانا برگردان
    if ($httpCode >= 400) {
        return "API error ($httpCode): " . $response;
    }

    $data = json_decode($response, true);
    return $data['choices'][0]['message']['content'] ?? "No content in response.";

}


public function chatgpt1($text){
    //https://rapidapi.com/swift-api-swift-api-default/api/search-gpt/playground/apiendpoint_418ad589-1f9c-494e-9ce8-f2e0f2087eb6
    $curl = curl_init();
    
curl_setopt_array($curl, [
	CURLOPT_URL => "https://chatgpt-42.p.rapidapi.com/conversationllama3",
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_ENCODING => "",
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 30,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => "POST",
	CURLOPT_POSTFIELDS => json_encode([
		'messages' => [
				[
								'role' => 'user',
								'content' => $text
				]
		],
		'web_access' => null
	]),
	CURLOPT_HTTPHEADER => [
		"Content-Type: application/json",
		"x-rapidapi-host: chatgpt-42.p.rapidapi.com",
		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
	],
]);
        
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}
 
public function get_locat($city){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://api.api-ninjas.com/v1/geocoding?city=$city",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"content-type: application/json",
    		"X-Api-Key: Hw8tblyzBWjwC82WafvrcA==7srElYGbxDpu1LIe",
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    if ($err) {
        return "cURL Error #:" . $err;
    } else {
    	
    	return $response;
    }
}

public function get_app_playstore($name){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://api-playstore.p.rapidapi.com/apiv2/$name/search",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: api-playstore.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function song_detect($name){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://shazam.p.rapidapi.com/songs/detect",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => "$name",
    	CURLOPT_HTTPHEADER => [
    		"content-type: text/plain",
    		"x-rapidapi-host: shazam.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function song_detect2($music){
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://shazam-song-recognition-api.p.rapidapi.com/recognize/url?url=$music",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: shazam-song-recognition-api.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_whois($name){
    $curl = curl_init();
    $counter = str_word_count($name);
    if($counter == 0){
        $CURLOPT_URL = "https://zozor54-whois-lookup-v1.p.rapidapi.com/getDomainsFromIp?ip=$name";
    }else{
        $CURLOPT_URL = "https://zozor54-whois-lookup-v1.p.rapidapi.com/?domain=$name&format=json";
    }
    curl_setopt_array($curl, [
    	CURLOPT_URL => $CURLOPT_URL/*"https://zozor54-whois-lookup-v1.p.rapidapi.com/?domain=$name&format=json"*/,
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_FOLLOWLOCATION => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: zozor54-whois-lookup-v1.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_short($long){
        
/*$curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://api-ssl.bitly.com/v4/shorten",
    	//CURLOPT_RETURNTRANSFER => true,
    	//CURLOPT_FOLLOWLOCATION => true,
    	//CURLOPT_ENCODING => "",
    	//CURLOPT_MAXREDIRS => 10,
    	//CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	//CURLOPT_POSTFIELDS => "$name",
    	CURLOPT_HTTPHEADER => [
    	    "Authorization: Bearer a3834ff6b93a19a419d6497f437a31a0062abed1",
    	    "Content-Type: application/json",
    		"long_url: $long",
            "domain: bit.ly",
            //"group_guid: Ba1bc23dE4F"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }*/
    
}

public function makeUrltoLink($string) {
 // The Regular Expression filter
 $reg_pattern = "/(((http|https|ftp|ftps)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\:[0-9]+)?(\/\S*)?/";
 
 // make the urls to hyperlinks
 return preg_replace($reg_pattern, '@VieraMagazine', $string);
}

public function send_dice($tokenkey,$chatid,$emoji){
        
$params=[
    'chat_id'=>$chatid,
    'emoji'=>$emoji,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendDice");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function file_size($url){
     $ch = curl_init($url);

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_HEADER, TRUE);
     curl_setopt($ch, CURLOPT_NOBODY, TRUE);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     $data = curl_exec($ch);
     $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

     curl_close($ch);
     return $size;
}
public function convert_size_unit($bytes){
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
}
public function download_file($url,$outFileName){
   
   if(is_file($url)) {
        copy($url, $outFileName); 
    } else {
        $options = array(
          CURLOPT_FILE    => fopen($outFileName, 'w'),
          CURLOPT_HEADER => 0,
          CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
          CURLOPT_URL     => $url
        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        curl_exec($ch);
        $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        curl_close($ch);
        return $size;
    }
   
}
public function download_file2($url,$outFileName){
   
   $size = file_put_contents($outFileName, fopen($url, 'r'));
   return $size;
}

public function download_file4($url,$file_name){
    file_put_contents($file_name, file_get_contents($url));
}

public function cURLcheckBasicFunctions()
    {
      if( !function_exists("curl_init") &&
          !function_exists("curl_setopt") &&
          !function_exists("curl_exec") &&
          !function_exists("curl_close") ) return false;
      else return true;
    }
    
    /*
     * Returns string status information.
     * Can be changed to int or bool return types.
     */
public function download_file3($url, $file)
    {
      if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
      $ch = curl_init();
      if($ch)
      {
    
        $fp = fopen($file, "w");
        if($fp)
        {
          if( !curl_setopt($ch, CURLOPT_URL, $url) )
          {
            fclose($fp); // to match fopen()
            curl_close($ch); // to match curl_init()
            return "FAIL: curl_setopt(CURLOPT_URL)";
          }
          if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
            curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
            if( !curl_setopt($ch, CURLOPT_HEADER, $curlopt_header)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
            if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
            if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
            if( !curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects) ) return "FAIL: curl_setopt(CURLOPT_MAXREDIRS)";
    
            return curl_exec($ch);
        } else {
            curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
            if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
            if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
            if( !curl_setopt($ch, CURLOPT_HEADER, true)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
            if( !curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)) return "FAIL: curl_setopt(CURLOPT_RETURNTRANSFER)";
            if( !curl_setopt($ch, CURLOPT_FORBID_REUSE, false)) return "FAIL: curl_setopt(CURLOPT_FORBID_REUSE)";
            curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
        }
          // if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true) ) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
          // if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
          // if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
          if( !curl_exec($ch) ) return "FAIL: curl_exec()";
          curl_close($ch);
          fclose($fp);
          return "SUCCESS: $file [$url]";
        }
        else return "FAIL: fopen()";
      }
      else return "FAIL: curl_init()";
    }

/**
 * متد جامع دانلود فایل با پشتیبانی از cURL و استریمینگ
 * این متد برای دانلود فایل‌های سنگین از تلگرام و سایر سرورها بهینه شده است.
 */
public function smart_download($url, $destination) {
    // ۱. بررسی مقدماتی: آیا آدرس معتبر است؟
    if (filter_var($url, FILTER_VALIDATE_URL) === false) {
        return "FAIL: Invalid URL";
    }

    // ۲. تلاش برای دانلود با cURL (روش استاندارد و امن)
    if (function_exists('curl_init')) {
        $ch = curl_init();
        $fp = fopen($destination, 'wb');
        
        $options = [
            CURLOPT_URL            => $url,
            CURLOPT_FILE           => $fp,
            CURLOPT_HEADER         => 0,
            CURLOPT_FOLLOWLOCATION => true, // دنبال کردن ریدایرکت‌ها
            CURLOPT_MAXREDIRS      => 5,
            CURLOPT_TIMEOUT        => 300,  // ۵ دقیقه مهلت برای فایل‌های بزرگ
            CURLOPT_CONNECTTIMEOUT => 20,   // ۲۰ ثانیه مهلت اتصال
            CURLOPT_SSL_VERIFYPEER => false, // نادیده گرفتن خطای SSL در صورت نیاز
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) TelegramBot'
        ];

        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        fclose($fp);

        if ($result && $httpCode == 200) {
            return "SUCCESS: Downloaded to $destination";
        } else {
            // اگر cURL شکست خورد و فایل خالی ماند، آن را پاک کن
            if (file_exists($destination)) unlink($destination);
            
            // اگر مشکل از cURL بود، برو سراغ متد جایگزین (Fallback)
        }
    }

    // ۳. متد جایگزین (Fallback) اگر cURL جواب نداد یا نصب نبود
    if (ini_get('allow_url_fopen')) {
        try {
            // استفاده از استریم به جای file_get_contents برای جلوگیری از پر شدن RAM
            $source = fopen($url, 'r');
            $dest = fopen($destination, 'w');
            if ($source && $dest) {
                stream_copy_to_stream($source, $dest);
                fclose($source);
                fclose($dest);
                return "SUCCESS: Downloaded via Stream";
            }
        } catch (\Exception $e) {
            return "FAIL: " . $e->getMessage();
        }
    }

    return "FAIL: All download methods failed. (HTTP Code: $httpCode | Error: $error)";
}


public function send_poll($tokenkey,$chat_id,$quest,$answer,$anony,$multi,$type){
        
$params=[
    'chat_id'=>$chat_id,
    'question'=>$quest,
    'options'=>$answer,
    'is_anonymous'=>$anony,
    'allows_multiple_answers'=>$multi,
    'type'=>$type
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/sendPoll");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function stop_poll($tokenkey,$chat_id,$mid){
        
$params=[
    'chat_id'=>$chat_id,
    'message_id'=>$mid,
];
$ch =curl_init("https://api.telegram.org/bot".$tokenkey."/stopPoll");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function get_insta($url){
    //social-api1-instagram/api/instagram-scraper-api2/playground/apiendpoint_e26c53d4-3c75-4aec-a1e0-39d2904c7e72
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-scraper-api2.p.rapidapi.com/v1/post_info?code_or_id_or_url=$url&include_insights=true",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-scraper-api2.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_insta_2($url){
    //https://rapidapi.com/social-lens-social-lens-default/api/instagram-social-api/playground/apiendpoint_4e6fc2e0-bc53-4867-ae43-7438a0b3392e
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-social-api.p.rapidapi.com/v1/post_info?code_or_id_or_url=$url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-social-api.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_insta_21($url){
    //https://rapidapi.com/mohammadtahapourabbas/api/instagram-downloader-scraper-reels-igtv-posts-stories/playground/apiendpoint_9ef9fc17-b30c-476b-9205-7453b2054e24
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-downloader-scraper-reels-igtv-posts-stories.p.rapidapi.com/v1/instagram?url=$url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-downloader-scraper-reels-igtv-posts-stories.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_insta_3($url){
    //https://rapidapi.com/7scorp-7scorp-default/api/instagram-story-downloader-media-downloader/playground/apiendpoint_a04aaaec-99db-476b-9f1a-34ddc031950d
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-story-downloader-media-downloader.p.rapidapi.com/index?url=$url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-story-downloader-media-downloader.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_insta_31($url,$mode){
    $curl = curl_init();
    //feeds 
    if($mode == "story"){
        $text = "ig_profile?ig";
    }else{
        $text = "media_by_id?shortcode";
    }
    //$sendText = "https://instagram-bulk-profile-scrapper.p.rapidapi.com/clients/api/ig/$text=$url&response_type=$mode";
    //return $sendText;
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-bulk-profile-scrapper.p.rapidapi.com/clients/api/ig/$text=$url&response_type=$mode",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-bulk-profile-scrapper.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_insta_4($url){
    //https://rapidapi.com/mohammadtahapourabbas/api/instagram-downloader-scraper-reels-igtv-posts-stories/playground/apiendpoint_9ef9fc17-b30c-476b-9205-7453b2054e24

    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://instagram-downloader-scraper-reels-igtv-posts-stories.p.rapidapi.com/scraper?url=$url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: instagram-downloader-scraper-reels-igtv-posts-stories.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_yout_trends($type = "Music"){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://youtube-v2.p.rapidapi.com/trending/?lang=en&country=us&section=$type",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: youtube-v2.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_site_links($thisSite){
    //https://rapidapi.com/hkgarments001/api/scrape-all-websites/playground/apiendpoint_5f35810b-a8cd-4ec8-a3bc-0a5e22b54e13
    //https://rapidapi.com/zilinskivan/api/web-scrapper3/playground/apiendpoint_515a2a2a-c615-4058-aeb7-0e569d3461d9
    //https://rapidapi.com/zackproser/api/url-intelligence/playground/apiendpoint_2d879c54-cd93-438a-a230-917e417d297e
    //https://rapidapi.com/zilinskivan/api/web-scrapper3/playground/apiendpoint_515a2a2a-c615-4058-aeb7-0e569d3461d9
    $curl = curl_init();

    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://url-intelligence.p.rapidapi.com/rip?target=$thisSite",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: url-intelligence.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_movie_download_links($title) {
    // جستجوی مستقیم در یک موتور جستجوی سبک و بدون محدودیت
    // ما به دنبال صفحات دانلود فیلم می‌گردیم
    $query = urlencode($title . " download movie");
    $url = "https://www.ask.com/web?q=" . $query;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');

    $html = curl_exec($ch);
    curl_close($ch);

    if (empty($html)) return false;

    // استخراج لینک‌های نتایج جستجو با Regex بسیار ساده
    // این الگو لینک‌های خارجی را پیدا می‌کند
    preg_match_all('/class="PartialSearchResults-item-title-link" href="(.*?)" target="_blank">(.*?)<\/a>/i', $html, $matches);

    $links = [];
    $count = 0;

    if (!empty($matches[1])) {
        foreach ($matches[1] as $index => $url) {
            if ($count >= 5) break;

            $domain = parse_url($url, PHP_URL_HOST);
            $siteTitle = strip_tags($matches[2][$index]);

            // حذف نتایج تبلیغاتی خود سایت جستجوگر
            if (strpos($url, 'ask.com') === false && strpos($url, 'http') === 0) {
                $links[] = [
                    'url' => $url,
                    'title' => $siteTitle,
                    'domain' => $domain
                ];
                $count++;
            }
        }
    }

    return (!empty($links)) ? $links : false;
}


function findDownloadLinks($query) {
    $query = trim($query);
    if (empty($query)) return [];

    $allLinks = [];
    $used_urls = [];
    $queryLower = mb_strtolower($query);
    $queryWords = explode(' ', $queryLower);

    // لیست دو سایت اصلی که با سرور شما سازگار هستند
    $sites = [
        'Film2Media' => 'https://www.myf2m.info/?s=',
        'DigiMoviez' => 'https://digimoviez.com/?s='
    ];

    foreach ($sites as $siteName => $baseUrl) {
        $searchUrl = $baseUrl . urlencode($query);
        
        $ch = curl_init($searchUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0"
        ]);
        
        $html = curl_exec($ch);
        curl_close($ch);

        if (empty($html)) continue;

        // استخراج لینک‌ها با دقت روی تگ a
        preg_match_all('/<a\s+[^>]*href=["\'](https?:\/\/[^"\']+)["\'][^>]*>(.*?)<\/a>/isu', $html, $matches, PREG_SET_ORDER);
        
        $siteMatches = [];
        foreach ($matches as $match) {
            // محدودیت ۵ لینک برای هر سایت
            if (count($siteMatches) >= 5) break; 

            $url = $match[1];
            $title = trim(strip_tags($match[2]));
            $titleLower = mb_strtolower($title);

            // فیلتر لینک‌های تکراری و سیستمی
            if (in_array($url, $used_urls)) continue;
            if (strpos($url, 'imdb.com') !== false || strpos($url, '/category/') !== false || strlen($title) < 3) continue;

            // شرط ۱: تمام کلمات جستجو باید در عنوان یا لینک باشند
            $hasAllWords = true;
            foreach ($queryWords as $word) {
                if (mb_strpos($titleLower, $word) === false && mb_strpos($url, $word) === false) {
                    $hasAllWords = false;
                    break;
                }
            }

            if ($hasAllWords) {
                // شرط ۲: حل مشکل Salt/Saltburn با مرز کلمه (Word Boundary)
                // اگر جستجو کوتاه است، باید کلمه به صورت مستقل وجود داشته باشد
                if (count($queryWords) === 1 && mb_strlen($query) <= 5) {
                    $pattern = '/\b' . preg_quote($queryLower, '/') . '\b/iu';
                    if (!preg_match($pattern, $titleLower) && !preg_match($pattern, $url)) {
                        continue; 
                    }
                }

                $used_urls[] = $url;
                $siteMatches[] = [
                    'url' => $url,
                    'title' => $title
                ];
            }
        }
        
        if (!empty($siteMatches)) {
            $allLinks = array_merge($allLinks, $siteMatches);
        }
    }
    
    // اگر مجموع لینک‌ها از ۱۰ تا بیشتر شد، برای شلوغ نشدن تلگرام می‌توانید اینجا محدودش کنید
    return array_slice($allLinks, 0, 10); 
}


public function getOfficialTrailersForDownload() {
    $bearerToken = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyYWY1OWM1YjRmM2U5ZDg1MjNkNjU5ZTU4MzEyY2M5MyIsIm5iZiI6MTcxOTA2MTQwMi4wMTk5MjcsInN1YiI6IjY2NzZjOTk5NTVhOTgyM2Q3ZjIzMmJiMSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.gkrPijRLibcNnPXHjBnU_yx3p3UkLzee0VR_YvrBscc";
    
    // تغییر زبان به fa-IR برای دریافت عنوان و توضیحات فارسی
    $url = "https://api.themoviedb.org/3/movie/upcoming?include_adult=false&language=fa-IR&page=1";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $bearerToken,
        'accept: application/json',
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if (!isset($data['results'])) return [];

    $trailers = [];
    foreach (array_slice($data['results'], 0, 5) as $movie) {
        $movieId = $movie['id'];
        
        // دریافت ویدیوها (ویدیوها معمولاً تگ زبان ندارند، اما با fa-IR هم تست می‌کنیم)
        $vUrl = "https://api.themoviedb.org/3/movie/" . $movieId . "/videos?language=en-US";
        $vCh = curl_init();
        curl_setopt($vCh, CURLOPT_URL, $vUrl);
        curl_setopt($vCh, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($vCh, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($vCh, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $bearerToken,
            'accept: application/json',
        ]);
        
        $vRes = curl_exec($vCh);
        curl_close($vCh);
        
        $vData = json_decode($vRes, true);
        if (isset($vData['results'])) {
            foreach ($vData['results'] as $v) {
                if ($v['site'] == 'YouTube' && $v['type'] == 'Trailer' && $v['official'] == true) {
                    $trailers[] = [
                        'id'    => $movieId,
                        'title' => $movie['title'], // عنوان فارسی
                        'desc'  => $movie['overview'], // توضیحات فارسی
                        'url'   => "https://www.youtube.com/watch?v=" . $v['key'],
                        'yt_id' => $v['key']
                    ];
                    break;
                }
            }
        }
    }
    return $trailers;
}




public function get_movie_info_tmdb($title) {
    // توکن خود را اینجا قرار دهید
    $bearerToken = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyYWY1OWM1YjRmM2U5ZDg1MjNkNjU5ZTU4MzEyY2M5MyIsIm5iZiI6MTcxOTA2MTQwMi4wMTk5MjcsInN1YiI6IjY2NzZjOTk5NTVhOTgyM2Q3ZjIzMmJiMSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.gkrPijRLibcNnPXHjBnU_yx3p3UkLzee0VR_YvrBscc";

    // ۱. مرحله اول: جستجوی فیلم (بدون محدودیت زبان برای اطمینان از یافتن نتیجه)
    $searchUrl = "https://api.themoviedb.org/3/search/movie?query=" . urlencode($title) . "&include_adult=false";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $searchUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $bearerToken,
        'accept: application/json',
    ]);

    $searchResponse = curl_exec($ch);
    $searchData = json_decode($searchResponse, true);
    curl_close($ch);

    if (empty($searchData['results'])) {
        return false; // فیلم پیدا نشد
    }

    // انتخاب اولین نتیجه
    $firstResult = $searchData['results'][0];
    $movieId = $firstResult['id'];

    // ۲. مرحله دوم: دریافت جزئیات کامل به زبان فارسی
    // اگر دیتای فارسی نباشد، TMDB به طور خودکار فیلدهای خالی را با انگلیسی پر می‌کند
    $detailUrl = "https://api.themoviedb.org/3/movie/{$movieId}?language=fa-IR";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $detailUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $bearerToken,
        'accept: application/json',
    ]);

    $detailResponse = curl_exec($ch);
    $details = json_decode($detailResponse, true);
    curl_close($ch);

    // اگر ترجمه فارسی موجود نبود، یک بار دیگر برای دریافت عنوان اصلی و خلاصه انگلیسی تلاش می‌کنیم
    if (empty($details['overview'])) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.themoviedb.org/3/movie/{$movieId}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $bearerToken,
            'accept: application/json',
        ]);
        $details = json_decode(curl_exec($ch), true);
        curl_close($ch);
    }
    
    return [
        'title'   => $details['title'] ?? $details['original_title'],
        'rating'  => number_format($details['vote_average'], 1),
        'plot'    => $details['overview'] ?: 'توضیحاتی در دسترس نیست.',
        'poster'  => !empty($details['poster_path']) ? "https://image.tmdb.org/t/p/w500" . $details['poster_path'] : null,
        'year'    => !empty($details['release_date']) ? substr($details['release_date'], 0, 4) : 'نامشخص',
        'runtime' => $details['runtime'] ?? 0,
        'url'     => "https://www.themoviedb.org/movie/" . $movieId
    ];
}

public function get_tmdb($name){

    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://api.themoviedb.org/3/search/movie?query=$name&include_adult=true&language=en-US&page=1",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_POSTFIELDS => "",
    	CURLOPT_HTTPHEADER => [
    		'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyYWY1OWM1YjRmM2U5ZDg1MjNkNjU5ZTU4MzEyY2M5MyIsIm5iZiI6MTcxOTA2MTQwMi4wMTk5MjcsInN1YiI6IjY2NzZjOTk5NTVhOTgyM2Q3ZjIzMmJiMSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.gkrPijRLibcNnPXHjBnU_yx3p3UkLzee0VR_YvrBscc',
            'accept: application/json',
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_tmdb2($vidId){

    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://api.themoviedb.org/3/movie/$vidId?language=en-US",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_POSTFIELDS => "",
    	CURLOPT_HTTPHEADER => [
    		'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyYWY1OWM1YjRmM2U5ZDg1MjNkNjU5ZTU4MzEyY2M5MyIsIm5iZiI6MTcxOTA2MTQwMi4wMTk5MjcsInN1YiI6IjY2NzZjOTk5NTVhOTgyM2Q3ZjIzMmJiMSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.gkrPijRLibcNnPXHjBnU_yx3p3UkLzee0VR_YvrBscc',
            'accept: application/json',
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_site_links2(){
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://url-scraper1.p.rapidapi.com/url",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "POST",
    	CURLOPT_POSTFIELDS => json_encode([
    		'url' => 'https://www.xnxx.com/search/familial_relations'
    	]),
    	CURLOPT_HTTPHEADER => [
    		"Content-Type: application/json",
    		"x-rapidapi-host: url-scraper1.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_movienews($cat = 'TOP'){
    //https://rapidapi.com/davethebeast/api/imdb232/playground/apiendpoint_ff71ce02-7002-404b-9958-11ff650827b2
    //https://rapidapi.com/ntd119/api/imdb-com/playground/apiendpoint_779542d8-1823-45e5-bb53-3565f2759a0d
    //https://rapidapi.com/apidojo/api/imdb8/playground/apiendpoint_5ef5f28a-92b7-4ce8-8630-c750d2d1390a
    //https://rapidapi.com/apidojo/api/online-movie-database
    
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://online-movie-database.p.rapidapi.com/news/v2/get-by-category?category=$cat&first=10&country=US&language=en-US",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"x-rapidapi-host: online-movie-database.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_movienews2($moviId){
    //https://rapidapi.com/davethebeast/api/imdb232/playground/apiendpoint_fb307653-c7f2-4a16-8381-1849c96d613a
    //https://rapidapi.com/amrelrafie/api/movies-tv-shows-database/playground/apiendpoint_79b48db4-db41-4e46-9f80-51a75c0945e4
    //https://rapidapi.com/amrelrafie/api/movies-tv-shows-database/playground/apiendpoint_f68d1997-d6ec-4c5c-967b-e1789c5366e5
    $curl = curl_init();
    curl_setopt_array($curl, [
    	CURLOPT_URL => "https://movies-tv-shows-database.p.rapidapi.com/?movieid=$moviId",
    	CURLOPT_RETURNTRANSFER => true,
    	CURLOPT_ENCODING => "",
    	CURLOPT_MAXREDIRS => 10,
    	CURLOPT_TIMEOUT => 30,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    	CURLOPT_HTTPHEADER => [
    		"Type: get-movie-details",
    		"x-rapidapi-host: movies-tv-shows-database.p.rapidapi.com",
    		"x-rapidapi-key: 819a8e4776msh2194711d3a46669p16d3acjsnda4b00617e7f"
    	],
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	return "cURL Error #:" . $err;
    } else {
    	return $response;
    }
}

public function get_digcur($name){
        
    /*$params=[
        'chat_id'=>$chat_id,
        'message_id'=>$mid,
    ];*/
    $ch =curl_init("https://apiv2.nobitex.ir/market/stats?srcCurrency=$name&dstCurrency=rls");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_HTTPGET, 1);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function append_file($txt,$outFileName){
     
    $myfile = fopen($outFileName, "a") or die("Unable to open file!");
    //$txt = "Mickey Mouse\n";
    //fwrite($myfile, $txt);
    //$txt = "Minnie Mouse\n";
    fwrite($myfile, $txt);
    fclose($myfile);

}
public function watermark_image($target, $wtrmrk_file, $newcopy) {
    $watermark = imagecreatefrompng($wtrmrk_file);
    imagealphablending($watermark, false);
    imagesavealpha($watermark, true);
    $img = imagecreatefromjpeg($target);
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    $wtrmrk_w = imagesx($watermark);
    $wtrmrk_h = imagesy($watermark);
    $dst_x = 50/*($img_w / 2) - ($wtrmrk_w / 2)*/; // For centering the watermark on any image
    if($img_h > 200){
        $dst_y = $img_h-50; // For centering the watermark on any image
    }else{
        $dst_y = (($img_h / 2) + ($wtrmrk_h / 2)); // For centering the watermark on any image
    }
    
    imagecopy($img, $watermark, $dst_x, $dst_y, 0, 0, $wtrmrk_w, $wtrmrk_h);
    imagejpeg($img, $newcopy,100);
    imagedestroy($img);
    imagedestroy($watermark);
    return $img_w."-".$img_h;
}
public function imagesize($target) {
    
    $img = imagecreatefromjpeg($target);
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    $resolotion = [$img_w,$img_h];
    return $resolotion;
}

public function watermark_image2($target, $wtrmrk_file, $newcopy,$x,$y) {
    $watermark = imagecreatefrompng($wtrmrk_file);
    //$alpha_channel = imagecolorallocatealpha($watermark, 255, 14, 48, 127);
    //imagecolortransparent($watermark, $alpha_channel);
    imagealphablending($watermark, false);
    imagesavealpha($watermark, true);
    $img = imagecreatefromjpeg($target);
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    $wtrmrk_w = imagesx($watermark);
    $wtrmrk_h = imagesy($watermark);
    $dst_x = $x/*($img_w / 2) - ($wtrmrk_w / 2)*/; // For centering the watermark on any image
    $dst_y = $y/*(($img_h / 2) + ($wtrmrk_h / 2))+50*/; // For centering the watermark on any image
    
    imagecopy($img, $watermark, $dst_x, $dst_y, 0, 0, $wtrmrk_w, $wtrmrk_h);
    imagejpeg($img, $newcopy,200);
    imagedestroy($img);
    imagedestroy($watermark);
}
public function cropimage($source,$destination,$dst_x,$dst_y,$src_x,$src_y,$dst_w,$dst_h,$src_w,$src_h){
    /*$dst_x = 0;   // X-coordinate of destination point
    $dst_y = -5;   // Y-coordinate of destination point
    $src_x = 0; // Crop Start X position in original image
    $src_y = 0; // Crop Srart Y position in original image
    $dst_w = 360; // Thumb width
    $dst_h = 320; // Thumb height
    $src_w = 298; // Crop end X position in original image
    $src_h = 240; // Crop end Y position in original image
    */
    // Creating an image with true colors having thumb dimensions (to merge with the original image)
    $dst_image = imagecreatetruecolor($dst_w, $dst_h);
    // Get original image
    $src_image = imagecreatefromjpeg($source);
    // Cropping
    imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    // Saving
    imagejpeg($dst_image, $destination,100);
}
public function resize_image($img,$dest,$width,$height){
    $image = imagecreatefromjpeg ( $img );
    $new_image = imagecreatetruecolor ( $width, $height );
    imagealphablending($new_image , false);
    imagesavealpha($new_image , true);
    imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
    //$image = $new_image;
    
    imagealphablending($image , false);
    imagesavealpha($image , true);
    imagejpeg ( $new_image, $dest );
}

public function resize_image2($img,$dest,$width,$height){
    $image = imagecreatefrompng ( $img );
    $new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
    imagealphablending($new_image , false);
    imagesavealpha($new_image , true);
    imagecopyresampled ( $new_image, $image, /*dx*/0, /*y*/0, /*sx*/0, /*y*/0, /*new_width*/$width, /*new_height*/$height, imagesx ( $image ), imagesy ( $image ) );
    //$image = $new_image;
    
    imagealphablending($image , false);
    imagesavealpha($image , true);
    imagepng ( $new_image, $dest );
}

public function image_text($source,$destination,$cord_x,$cord_y,$rotate,$text){
    $image_resolotion2 = $this->telegram_model->imagesize($source);
    
    $image = imagecreatefromjpeg($source) ;
    $white = imagecolorallocate($image , 255 , 255 , 255);
    $black = imagecolorallocate($image , 0 , 0 , 0);
    $green = imagecolorallocate($image , 4 , 250 , 56);
    if($image_resolotion2[0] > 4500){
        $font_size = 200;
        $plus = 6;
        $cord_x += 50;
    }elseif($image_resolotion2[0] > 3000){
        $font_size = 130;
        $plus = 5;
        $cord_x += 50;
    }elseif($image_resolotion2[0] > 2000){
        $font_size = 95;
        $plus = 4;
    }elseif($image_resolotion2[0] > 1500){
        $font_size = 70;
        $plus = 4;
    }elseif($image_resolotion2[0] > 1000){
        $font_size = 40;
        $plus = 3;
    }elseif($image_resolotion2[0] >= 400){
        $font_size = 16;
        $plus = 1;
    }else{
        $font_size = null;
        $plus = 0;
    }
    $font = "./application/fonts/IRAMIR.TTF";
    $font1 = "./application/fonts/IRBADR.TTF";
    $font2 = "./application/fonts/IRBADRBOLD.TTF";
    $coordinates_x = $cord_x/*50*/;
    $coordinates_y = $cord_y/*100*/;
    $angle = $rotate/*0*/;
    //$text = "@VieraMagazine";
    
    imagettftext($image , $font_size , $angle , $coordinates_x+$plus , $coordinates_y , $black , $font2 , $text);
    imagettftext($image , $font_size , $angle , $coordinates_x , $coordinates_y+$plus , $black , $font2 , $text);
    imagettftext($image , $font_size , $angle , $coordinates_x-$plus , $coordinates_y , $black , $font2 , $text);
    imagettftext($image , $font_size , $angle , $coordinates_x , $coordinates_y-$plus , $black , $font2 , $text);
    imagettftext($image , $font_size , $angle , $coordinates_x , $coordinates_y , $green , $font2 , $text);
    imagejpeg($image, $destination,100);
    imagedestroy($image);
    return $image_resolotion2[0]."-".$image_resolotion2[1];
}

public function grid($imgpath,$dest){
    //$imgpath = "duck.jpg";
    $img = imagecreatefromjpeg($imgpath);
    $size = getimagesize($imgpath);
    $width = $size[0];
    $height = $size[1];
    $red   = imagecolorallocate($img, 255,   0,   0);
    
    $xgrid = 5;
    $ygrid = 5;
    
    $xgrid1 =round(($width/100));
    $ygrid1 = round(($height/100));
    
    // Calulate each cell width/height
    $xgridsize = $width / $xgrid;
    $hgridsize = $height / $ygrid;
    
    $xgridsize1 = $width / $xgrid1;
    $hgridsize1 = $height / $ygrid1;
    
    $dim1 = $width."-".$height;
    $dim2 = $xgridsize."-".$hgridsize;
    $dim3 = $xgridsize1."-".$hgridsize1;
    $gridSize = $xgrid1."-".$ygrid1;
    
    $c = 'A';
    
    for ($j=0; $j < $ygrid1; $j++) {
        for ($i=0; $i < $xgrid1; $i++) {
            
            $sy = $hgridsize1 * $j;
            $sx = $xgridsize1 * $i;
            imagerectangle($img, $sx, $sy, $sx + $xgridsize1, $sy + $hgridsize1, $red);
            if($j == 0 && $i == 0){
                //$this->addTextToCell($img, $sx, $xgridsize1, $sy + $hgridsize1, $hgridsize1, $c . ($i + 1));
                $this->addTextToCell($img, $sx, $xgridsize1, $sy - 10 + $hgridsize1, $hgridsize1, "100");
                $this->addTextToCell($img, $sx, $xgridsize1, $sy + 10 + $hgridsize1, $hgridsize1, "100"/*($i*100)."/".($j*100)*/);
            }
        }
        $c++;
    }
    imagejpeg($img, $dest);
    imagedestroy($img);
    return [$dim1,$dim2,$dim3,$gridSize];
    $dim1."\n".$dim2."\n".$dim3."\n".$gridSize;
}

public function addTextToCell($img, $cellX, $cellWidth, $cellY, $cellHeight, $text) {

    // Calculate text size
    $font = "./application/fonts/IRJADID.TTF";
    $text_box = imagettfbbox(15, 0, $font, $text);
    $text_width = $text_box[2]-$text_box[0];
    $text_height = $text_box[7]-$text_box[1];

    // Calculate x/y position
    $textx = $cellX + ($cellWidth / 2) - ($text_width/2);
    $texty = $cellY - ($cellHeight / 2) - ($text_height/2);
    
    //$textx = ($cellWidth - $cellX)/2 - $text_width/2;
    //$texty = ($cellHeight - $cellY)/2 - $text_height/2;
    // Set color and draw
    $color = imagecolorallocate($img, 0, 0, 255);
    $color = imagecolorallocate($img, 255, 255, 255);
    imagettftext($img, 15, 0, $textx, $texty, $color, $font, $text);
}

public function num_index($text){
    preg_match('/^\D*(?=\d)/', $text, $m);
    return isset($m[0]) ? strlen($m[0]) : false;
}
public function toPersianNum($number)
    {
        $number = str_replace("1","۱",$number);
        $number = str_replace("2","۲",$number);
        $number = str_replace("3","۳",$number);
        $number = str_replace("4","۴",$number);
        $number = str_replace("5","۵",$number);
        $number = str_replace("6","۶",$number);
        $number = str_replace("7","۷",$number);
        $number = str_replace("8","۸",$number);
        $number = str_replace("9","۹",$number);
        $number = str_replace("0","۰",$number);
        return $number;
    }
    
public function toEnglishNum($number)
    {
        $number = str_replace("۱","1",$number);
        $number = str_replace("۲","2",$number);
        $number = str_replace("۳","3",$number);
        $number = str_replace("۴","4",$number);
        $number = str_replace("۵","5",$number);
        $number = str_replace("۶","6",$number);
        $number = str_replace("۷","7",$number);
        $number = str_replace("۸","8",$number);
        $number = str_replace("۹","9",$number);
        $number = str_replace("۰","0",$number);
        return $number;
    }
    
public function odd($var)
{
    // returns whether the input integer is odd
    return $var & 1;
}

public function even($var)
{
    // returns whether the input integer is even
    return !($var & 1);
}

public function strpos_all($haystack, $needle_regex)
{
    preg_match_all('/' . $needle_regex . '/', $haystack, $matches, PREG_OFFSET_CAPTURE);
    return array_map(function ($v) {
        return $v[1];
    }, $matches[0]);
}

public function number_getservices(){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=getservice");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function number_getcountry(){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=getcountry");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function number_getinfo($service, $country){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=getinfo&service=$service&country=$country");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    //curl_setopt($ch, CURLOPT_HTTPGET, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function number_get($service, $country, $operator){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=getnum&country=$country&operator=$operator&service=$service");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function number_cancell($method ,$id){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=$method&id=$id");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

public function number_get_code($numId){
    $ch =curl_init("https://api.numberland.ir/v2.php/?apikey=66dd89656b2b89c05588ca7659104b89&method=checkstatus&id=$numId");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


public function remove_emoji($string)
{
    // Match Enclosed Alphanumeric Supplement
    $regex_alphanumeric = '/[\x{1F100}-\x{1F1FF}]/u';
    $clear_string = preg_replace($regex_alphanumeric, '', $string);

    // Match Miscellaneous Symbols and Pictographs
    $regex_symbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clear_string = preg_replace($regex_symbols, '', $clear_string);

    // Match Emoticons
    $regex_emoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clear_string = preg_replace($regex_emoticons, '', $clear_string);

    // Match Transport And Map Symbols
    $regex_transport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clear_string = preg_replace($regex_transport, '', $clear_string);
    
    // Match Supplemental Symbols and Pictographs
    $regex_supplemental = '/[\x{1F900}-\x{1F9FF}]/u';
    $clear_string = preg_replace($regex_supplemental, '', $clear_string);

    // Match Miscellaneous Symbols
    $regex_misc = '/[\x{2600}-\x{26FF}]/u';
    $clear_string = preg_replace($regex_misc, '', $clear_string);

    // Match Dingbats
    $regex_dingbats = '/[\x{2700}-\x{27BF}]/u';
    $clear_string = preg_replace($regex_dingbats, '', $clear_string);

    return $clear_string;
}

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

public function delete_from($table ,$where1=null ,$where2=null){
	$this->db->where("uid",$uid);
	$this->db->delete('telegram_information');
}
public function get_max($table){
    $this->db->select_max('id');
    $result1 = $this->db->get($table);
    return $result1->result();
}

public function auto_increament_Decrease($table, $max){
    $query =("ALTER TABLE `$table` AUTO_INCREMENT = $max");
	return $this->db->query($query);
    
}

public function auto_increament(/*$table,$num*/){
    $query =("ALTER TABLE temp AUTO_INCREMENT = 99");
    $result = $this->db->query($query);

}

public function set_telinfo($data){
$this->db->insert('telegram_information', $data);
}

public function update_token($uid,$data){
	$this->db->where('uid',$uid);
    $this->db->update('telegram_information', $data);
}
public function get_token($url){
	$this->db->where("boturl",$url);
	$result = $this->db->get('telegram_information');
	 return $result->row(0)->tokenkey;
}
public function get_bot_url($uid){
	$this->db->where('uid',$uid);
	$result = $this->db->get('telegram_information');
	 return $result->result();
}
public function get_token_buid($uid){
	$this->db->where("uid",$uid);
	$result = $this->db->get('telegram_information');
	 return $result->row(0)->tokenkey;
}
public function get_group($url){
	$this->db->where("boturl",$url);
	$result = $this->db->get('telegram_information');
	 return $result->row(0)->botgroup;
}
public function get_users_group($groupname){
	$this->db->where("botgroup",$groupname);
	$result = $this->db->get('telegram_information');
	 return $result->result();
}
public function get_group_byuid($uid){
	$this->db->where("uid",$uid);
	$result = $this->db->get('telegram_information');
	 return $result->row(0)->botgroup;
}
public function get_groupuid_byurl($boturl){
	$this->db->where("boturl",$boturl);
	$result = $this->db->get('telegram_information');
	 return $result->row(0)->uid;
}
public function delete_telegram_token($uid){
	$this->db->where("uid",$uid);
	$this->db->delete('telegram_information');
}
public function insert_telegram_table($name){
	$this->load->dbforge();
	$fields = array(
        'name' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
        ),
        'level' => array(
                'type' =>'INT',
                'constraint' => '3',
        ),
        'command' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
        ),
		'func' => array(
			'type' => 'VARCHAR',
                'constraint' => '100',
		),
		'locate' => array(
			'type' => 'VARCHAR',
            'constraint' => '100',			 
		),
		'text' => array(
			'type' => 'VARCHAR',
                'constraint' => '100',
		),
		'isdiynamic'=>array(
			'type' => 'INT',
                'constraint' => '1',
		),
		'material'=>array(
			'type' => 'INT',
                'constraint' => '1',
		)
);
	$this->dbforge->add_field('id');
	$this->dbforge->add_field($fields);
	$this->dbforge->create_table('telebot_'.$name, TRUE);
}
public function drop_telegram_table($name){
	$this->load->dbforge();
	$this->dbforge->drop_table('telebot_'.$name);
}
public function set_telegram_db($tablename,$data){
	$this->db->insert($tablename, $data);
}
public function delete_telegram_db($tablename){
	$this->db->empty_table($tablename);
}
public function get_telegram_bd_locate($tablename,$locatename){
	$this->db->where('locate',$locatename);
		 $result = $this->db->get($tablename);
        return $result->result();
}
public function get_telegram_bd_dymanic($tablename){
	$this->db->where('isdiynamic',1);
 $result = $this->db->get($tablename);
        return $result->result();
}
public function set_user_info($data){
	$this->db->insert("telegram_users_info", $data);
}
public function get_telegram_bd_name($tablename,$name){
	$this->db->where('name',$name);
		 $result = $this->db->get($tablename);
        return $result->result();
}
public function get_telegram_post($uid,$postid){
	$this->db->where('uid',$uid);
	$this->db->where('postid',$postid);
	 $result = $this->db->get("telegram_post_info");
        return $result->result();
}
public function update_telegram_post($uid,$postid,$data){
    $this->db->where('uid',$uid);
	$this->db->where('postid',$postid);
    $this->db->update('telegram_post_info', $data);
}
public function set_telegram_post($data){
	$this->db->insert("telegram_post_info", $data);
	
}
//----------------------------------------

public function get_phone_sell($user_id){
	$this->db->where('telid',$user_id);
	$result = $this->db->get("phone_sell");
    return $result->result();
}
public function set_phone_sell($data){
	$this->db->insert("phone_sell", $data);
	return ($this->db->affected_rows() > 0);
}
public function clear_phone_sell($user_id){
	$this->db->where('telid',$user_id);
	$this->db->delete('phone_sell');
}
public function update_phone_sell($user_id,$data){
	$this->db->where('telid',$user_id);
    $this->db->update('phone_sell', $data);
}
//-----
public function get_phone_sell_services(){
    $result = $this->db->get("phone_sell_services");
    return $result->result();
}
public function get_phone_sell_services_one($id){
    $this->db->where('id',$id);
    $result = $this->db->get("phone_sell_services");
    return $result->result();
}
public function set_phone_sell_services($data){
	$this->db->insert("phone_sell_services", $data);
	return ($this->db->affected_rows() > 0);
}
public function update_phone_sell_services($data){
    $this->db->where('id',1);
    $this->db->update('phone_sell_services', $data);
}
public function set_phone_sell_services_batch($data){
	$this->db->insert_batch("phone_sell_services", $data);
	return ($this->db->affected_rows() > 0);
}
public function update_phone_sell_services_batch($data){
    //$this->db->where('id',1);
    return $this->db->update_batch('phone_sell_services', $data, 'name');
}
//-----
public function get_phone_sell_country(){
    $result = $this->db->get("phone_sell_country");
    return $result->result();
}
public function get_phone_sell_country_one($id){
    $this->db->where('id',$id);
    $result = $this->db->get("phone_sell_country");
    return $result->result();
}
public function set_phone_sell_country($data){
	$this->db->insert("phone_sell_country", $data);
	return ($this->db->affected_rows() > 0);
}
public function set_phone_sell_country_batch($data){
	$this->db->insert_batch("phone_sell_country", $data);
	return ($this->db->affected_rows() > 0);
}
public function update_phone_sell_country_batch($data){
    //$this->db->where('id',1);
    return $this->db->update_batch('phone_sell_country', $data, 'country');
}
//-----------------
public function set_phone_sell_order($data){
	$this->db->insert("phone_sell_order", $data);
	return ($this->db->affected_rows() > 0);
}

public function get_phone_sell_order($user_id, $numId){
    $this->db->where('telid',$user_id);
	$this->db->where('num_id',$numId);
	$result = $this->db->get("phone_sell_order");
    return $result->result();
}

public function clear_phone_sell_order($user_id,$numId){
	$this->db->where('telid',$user_id);
	$this->db->where('num_id',$numId);
	$this->db->delete('phone_sell_order');
}
//---------------
public function set_phone_sell_lang($data){
	$this->db->insert("phone_sell_lang", $data);
	//$this->db->replace('phone_sell_lang', $data);
	return ($this->db->affected_rows() > 0);
}

public function get_phone_sell_lang($user_id){
    $this->db->where('telid',$user_id);
	$result = $this->db->get("phone_sell_lang");
    return $result->result();
}

public function update_phone_sell_lang($user_id,$data){
	$this->db->where('telid',$user_id);
    $this->db->update('phone_sell_lang', $data);
}

public function clear_phone_sell_Lang($user_id){
	$this->db->where('telid',$user_id);
	$this->db->delete('phone_sell_lang');
}
//---------------
public function set_phone_sell_represent($data){
	$this->db->insert("phone_sell_represent", $data);
	return ($this->db->affected_rows() > 0);
}
public function get_phone_sell_represent($user_id){
    $this->db->where('new',$user_id);
	$result = $this->db->get("phone_sell_represent");
    return $result->result();
}
public function clear_phone_sell_represent($user_id){
	$this->db->where('new',$user_id);
	$this->db->delete('phone_sell_represent');
}
//----------------------------------------

public function set_query($data,$qid,$start,$end){
    //$q = "INSERT INTO `inline_query` values ($qid, $start, $end) ON DUPLICATE KEY UPDATE `start` = $start, `end` = $end";
	//$this->db->insert("inline_query", $data);
	//$result = $this->db->query($query);
	
	$this->db->replace('inline_query', $data);
    return $result->result();
	//return ($this->db->affected_rows() > 0);
}
public function get_query($Qid){
	$this->db->where('q_id',$Qid);
	$result = $this->db->get("inline_query");
    return $result->result();
}

public function clear_query($Qid){
	$this->db->where('q_id',$Qid);
	$this->db->delete('inline_query');
}

//----------------------------------------
public function set_groups_users($data){
	$this->db->insert("groups_user", $data);
	return ($this->db->affected_rows() > 0);
}
public function get_groups_users($grid,$user_id){
	$this->db->where('group_id',$grid);
	$this->db->where('user_id',$user_id);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users2($user_id){
	$this->db->where('user_id',$user_id);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users3($grid){
	$this->db->where('group_id',$grid);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users35($grid,$user,$time){
    $this->db->limit(50);
    $this->db->order_by("id", "RANDOM");
	$this->db->where('group_id',$grid);
	$this->db->where('online_time <', $time);
	$this->db->where('user_id !=', $user);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users4($grid,$persia){
    $this->db->having('group_id',$grid);
    $this->db->like('persian_name', $persia);
	//$this->db->select('*')->from('groups_user')->where('group_id', $grid)->like('persian_name',$persia);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users5($start,$end){
    $this->db->where('id <',$end);
    $this->db->where('id >',$start);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function get_groups_users_inactive(){
    $time = time();
    $this->db->limit(10);
    $this->db->order_by("id", "random");
    //$this->db->where("$time - online_time <", 172800);
    $this->db->where("group_id IS NOT NULL", null, false);
	$result = $this->db->get("groups_user");
    return $result->result();
}
public function update_groups_users($grid,$user_id,$data){
    $this->db->where('group_id',$grid);
	$this->db->where('user_id',$user_id);
    $this->db->update('groups_user', $data);
}
public function update_groups_users2($grid,$user_id,$data){
    $this->db->where('group_id',$grid);
	$this->db->where('user_id',$user_id);
    $this->db->update('groups_user', $data);
    return ($this->db->affected_rows() > 0);
}
public function update_groups_users3($user_id,$data){
    //$this->db->where('group_id',$grid);
	$this->db->where('user_id',$user_id);
    $this->db->update('groups_user', $data);
}
public function clear_groups_users($grid,$user_id){
	$this->db->where('group_id',$grid);
	$this->db->where('user_id',$user_id);
	$this->db->delete('groups_user');
}
public function clear_groups_users_group($grid){
	$this->db->where('group_id',$grid);
	$this->db->delete('groups_user');
}
//----------------------------------------
public function set_left_count($data){
	$this->db->insert("left_count", $data);
	
}
public function get_left_count($groupid,$user_id){
	$this->db->where('group_id',$groupid);
	$this->db->where('user_id',$user_id);
	$result = $this->db->get("left_count");
    return $result->result();
}
public function get_left_count_all($groupid){
	$this->db->where('group_id',$groupid);
	//$this->db->where('user_id',$user_id);
	$result = $this->db->get("left_count");
    return $result->result();
}
public function update_left_count($groupid,$user_id,$data){
    $this->db->where('group_id',$groupid);
    $this->db->where('user_id',$user_id);
    $this->db->update('left_count', $data);
}

//----------------------------------------

public function set_procc_stack($data){
	$this->db->insert("procc_stack", $data);
}

public function get_procc_stack_all(){
	//$this->db->where('uid',$user_id);
	$result = $this->db->get("procc_stack");
    return $result->result();
}

public function get_procc_stack_byUser($user_id){
	$this->db->where('uid',$user_id);
	$result = $this->db->get("procc_stack");
    return $result->result();
}

public function get_procc_stack($chatid){
	$this->db->where('chatid',$chatid);
	$result = $this->db->get("procc_stack");
    return $result->result();
}

public function update_procc_stack($chatid,$data){
    $this->db->where('chatid',$chatid);
    $this->db->update('procc_stack', $data);
}

public function update_procc_stack_byId($id,$data){
    $this->db->where('id',$id);
    $this->db->update('procc_stack', $data);
}

public function clear_procc_stack($chatid){
	$this->db->where('chatid',$chatid);
	$this->db->delete('procc_stack');
}

public function get_procc_acc($user_id){
	$this->db->where('uid',$user_id);
	$result = $this->db->get("procc_account");
    return $result->result();
}

public function update_procc_acc($user_id,$data){
    $this->db->where('uid',$user_id);
    $this->db->update('procc_stack', $data);
}
//----------------------------------------
public function set_chek_link($data){
	$this->db->insert("group_link_check", $data);
	
}
public function get_chek_link($groupid){
	$this->db->where('group_id',$groupid);
	 $result = $this->db->get("group_link_check");
        return $result->result();
}
public function update_chek_link($groupid,$data){
    $this->db->where('group_id',$grid);
    $this->db->update('group_link_check', $data);
}
public function clear_chek_link($groupid){
	$this->db->where('group_id',$groupid);
	$this->db->delete('group_link_check');
}
//----------------------------------------
public function get_mobile($cat){
    $this->db->where('category',$cat);
	$result = $this->db->get("mobile");
    return $result->result();
}
public function get_mobile_one($name){
	$this->db->where('name',$name);
	$result = $this->db->get("mobile");
    return $result->result();
}
public function get_mobile_like($name){
	$this->db->like('name', $name);
	$result = $this->db->get("mobile");
    return $result->result();
}
public function get_mobile_like_brand($name){
	$this->db->like('brand', $name);
	$this->db->order_by('price', 'DESC');
	$result = $this->db->get("mobile");
    return $result->result();
}
public function update_mobile($name,$data){
    $this->db->where('name',$name);
    $this->db->update('mobile', $data);
}
public function set_mobile($data){
	$this->db->insert("mobile", $data);
	
}
public function clear_mobile($uid){
	$this->db->where('userid',$uid);
   //$this->db->where('telegramid',$telegramid);
	//$this->db->delete('mobile');
}
public function truncate_mobile(){
	$this->db->truncate('mobile');
}
//----------------------------------------
public function get_telegram_faal($uid){
	$this->db->where('userid',$uid);
	//$this->db->where('time_req',$date);
	 $result = $this->db->get("faal_user");
        return $result->result();
}
public function get_telegram_faal2($num){
	$this->db->where('number',$num);
	$result = $this->db->get("faal_hafez");
        return $result->result();
}
public function update_telegram_faal($uid/*,$date*/,$data){
    $this->db->where('userid',$uid);
    $this->db->update('faal_user', $data);
}
public function set_telegram_faal($data){
	$this->db->insert("faal_user", $data);
}
public function set_telegram_faal2($data){
	$this->db->insert("faal_hafez", $data);
}
public function clear_telegram_faal($uid){
	$this->db->where('userid',$uid);
   //$this->db->where('telegramid',$telegramid);
	$this->db->delete('faal_user');
}
//--------------------------------------------
public function get_viera_group(){
	    //$this->db->where('group_id',$group_id);
	    //$this->db->where('group_name',$group_name);
	    $result = $this->db->get("group_viera_in");
        return $result->result();
}
public function update_viera_group($group_id,$data){
    $this->db->where('group_id',$group_id);
    $this->db->update('group_viera_in', $data);
}
public function set_viera_group($data){
	$this->db->insert("group_viera_in", $data);
	
}
public function clear_viera_group($group_id){
	$this->db->where('group_id',$group_id);
   //$this->db->where('telegramid',$telegramid);
	$this->db->delete('group_viera_in');
}
public function truncate_viera_group(){
	$this->db->truncate('group_viera_in');
}
//--------------------------------------------
public function set_orderpo($data){
	$this->db->insert("orderPo", $data);
	if($this->db->affected_rows() > 0)
    return (true);
}
public function get_orderpo($uid){
    $this->db->where('uid', $uid);
    $result = $this->db->get("orderPo");
    return $result->result();
}
public function update_orderpo($uid){
    $this->db->set('cash', 'cash-10000', FALSE);
    $this->db->where('uid', $uid);
    $this->db->update('orderPo');
}
//--------------------------------------------
/*public function get_viera_delet_list(){
	    $result = $this->db->get("delet_order");
        return $result->result();
}
public function update_viera_delet_list($group_id,$data){
    $this->db->where('group_id',$group_id);
    $this->db->update('delet_order', $data);
}
public function set_viera_delet_list($data){
	$this->db->insert("delet_order", $data);
	
}
public function clear_viera_group($group_id){
	$this->db->where('group_id',$group_id);
	$this->db->delete('delet_order');
}*/

//--------------------------------------------
public function get_telegram_restrict($group_id){
	    $this->db->where('group_id',$group_id);
	    //$this->db->where('user_id',$user_id);
	    $result = $this->db->get("group_user_restricted");
        return $result->result();
}
public function get_telegram_restrict_user($group_id,$idplus){
	    $this->db->where('group_id',$group_id);
	    $this->db->where('idplus',$idplus);
	    $result = $this->db->get("group_user_restricted");
        return $result->result();
}
public function update_telegram_restrict($group_id,$data){
    $this->db->where('group_id',$group_id);
	//$this->db->where('time_req',$date);
    $this->db->update('group_user_restricted', $data);
}
public function set_telegram_restrict($data){
	$this->db->insert("group_user_restricted", $data);
	
}
public function delete_telegram_restrict($group_id,$user_id){
	$this->db->where('group_id',$group_id);
	$this->db->where('user_id',$user_id);
	$this->db->delete('group_user_restricted');
}
//--------------------------------------------
public function get_telegram_video($title,$video_id){
	    $this->db->where('title',$title);
	    $this->db->where('video_id',$video_id);
	    $result = $this->db->get("video");
        return $result->result();
}
public function get_telegram_video_byId($id){
	    $this->db->where('id',$id);
	    $result = $this->db->get("video");
        return $result->result();
}
public function get_telegram_video_like($tag){
	    //$this->db->where('tags',$tag);
	    $this->db->like('tags',$tag);
	    $result = $this->db->get("video");
        return $result->result();
}
public function update_telegram_video($group_id,$data){
    $this->db->where('group_id',$group_id);
	//$this->db->where('time_req',$date);
    $this->db->update('video', $data);
}
public function set_telegram_video($data){
	$this->db->insert("video", $data);
	if($this->db->affected_rows() > 0)
    return (true);
	
}
public function delete_telegram_video($group_id,$user_id){
	$this->db->where('group_id',$group_id);
	$this->db->where('user_id',$user_id);
	$this->db->delete('video');
}
//--------------------------------------------
public function set_video_insta($data){
	$this->db->insert("video_insta", $data);
	if($this->db->affected_rows() > 0)
    return (true);
	
}
public function get_video_insta(){
    $this->db->limit(30);
    //$this->db->order_by("id", "random");
    $this->db->order_by("id", "desc"); 
    $result = $this->db->get("video_insta");
    return $result->result();
}

public function get_video_insta_one($link){
    $this->db->where('insta_link',$link); 
    $result = $this->db->get("video_insta");
    return $result->result();
}

public function get_video_insta_like($where,$like){
    $this->db->limit(30);
    $this->db->order_by("id", "desc");
    $this->db->like($where,$like);
    $result = $this->db->get("video_insta");
    return $result->result();
}

public function update_insta_video($data,$link){
    $this->db->where('insta_link',$link);
    return $this->db->update('video_insta', $data);
}

public function delete_insta_video($link){
	$this->db->where('insta_link',$link);;
	$this->db->delete('video_insta');
	return $this->db->affected_rows();
}

//--------------------------------------------

public function set_video_youtube($data){
	$this->db->insert("video_youtube", $data);
	if($this->db->affected_rows() > 0)
	return $this->db->affected_rows();
    return (true);
	
}

public function get_video_youtube_like($where,$like){
    $this->db->limit(30);
    $this->db->order_by("id", "desc");
    $this->db->like($where,$like);
    $result = $this->db->get("video_youtube");
    return $result->result();
}

//--------------------------------------------
public function set_music_video($data){
	$this->db->insert("music_video", $data);
	if($this->db->affected_rows() > 0)
    return (true);
	
}
public function get_music_video($nsame,$singer){
	$this->db->where('performer',$singer);
	$this->db->where('title',$nsame);
	$this->db->order_by("id", "desc");
	$result = $this->db->get("music_video");
    return $result->result();
}
//--------------------------------------------

public function get_telegram_music_id($id){
    $this->db->where('id',$id);;
    $result = $this->db->get("music_sent");
    return $result->result();
}
public function get_telegram_music_sent_new(){
    //$this->db->where('group_id',$group_id);
    $this->db->where('jadid',"#جدید");
    $result = $this->db->get("music_sent");
    return $result->result();
}
public function get_telegram_music_sent($perf,$tite){
    $this->db->where('title_en',$tite);
    $this->db->where('performer_en',$perf);
    $result = $this->db->get("music_sent");
    return $result->result();
}
public function get_telegram_music_sent_timer(){
    /*$this->db->where('title_en',$tite);
    $this->db->where('performer_en',$perf);
    $result = $this->db->get("music_sent");
    return $result->result();*/
}
public function get_telegram_music_sent_concat($titeMerg,$offset = null){
    //$this->db->where('title_en',$tite);
    //$this->db->where('performer_en',$perf);
    //$result = $this->db->get("music_sent");
    if($offset == null){
        $offset = 0;
    }
    $query =("SELECT * FROM `music_sent` where CONCAT(performer_fa, ' ', title_fa) LIKE '%$titeMerg%' ORDER BY id ASC LIMIT 15 OFFSET $offset");
    $result = $this->db->query($query);
    return $result->result();
}
public function get_telegram_music_sent_limit(){
    $this->db->limit(10);
    $this->db->order_by("id", "desc"); 
    $result = $this->db->get("music_sent");
    return $result->result();
}
public function get_telegram_music_sent_like($lyric,$perform_fa = ""){
	    
	    $this->db->like('performer_fa', $perform_fa);
	    if(strlen($lyric) > 40){
	        
            $this->db->like('lyrics',$lyric);
            
	    }else{
	        $this->db->like('title_fa', $lyric);
	    }
	    //$this->db->where('performer_fa',$perform_fa);
	    $result = $this->db->get("music_sent");
        return $result->result();
}
public function get_telegram_music_sent_max(){
	    $this->db->select_max('id');
	    $result = $this->db->get("music_sent");
        return $result->result();
}
public function get_telegram_music_sent_count(){
	    $co = $this->db->count_all('music_sent');
        return $co;
}
public function get_telegram_music_search_fa($tit_fa,$perf_fa){
	    $this->db->where('title_fa',$tit_fa);
	    $this->db->where('performer_fa',$perf_fa);
	    $result = $this->db->get("music_sent");
        return $result->result();
}

public function get_telegram_music_search_singer($per_fa){
	    //$this->db->where('title_fa',$tit_fa);
	    $this->db->where('performer_fa',$per_fa);
	    $result = $this->db->get("music_sent");
        return $result->result();
}
public function get_telegram_music_search_en($tit_en){
	    $this->db->where('title_en',$tit_en);
	    //$this->db->where('performer_fa',$perf_fa);
	    $result = $this->db->get("music_sent");
        return $result->result();
}
public function get_telegram_music_lastSent($last_sent){
	    //$this->db->where('title_en',$tit);
	    $this->db->where('last_sent',$last_sent);
	    $result = $this->db->get("music_sent");
        return $result->result();
}
public function get_telegram_music_sent_info(){
    $this->db->limit(1);
	$this->db->where('info',"");
    $result = $this->db->get("music_sent");
    return $result->result();
}
public function update_telegram_music_sent_lastSent($data,$mid){
    //$this->db->where('group_id',$group_id);
    $this->db->where('id',$mid);
	//$this->db->where('last_sent',1);
    $this->db->update('music_sent', $data);
}

public function update_telegram_music_sent($data,$perf,$tite){
    $this->db->where('title_en',$tite);
	$this->db->where('performer_en',$perf);
    $this->db->update('music_sent', $data);
}
public function update_telegram_music_sent_fa($data,$perf_fa,$tite_fa){
    $this->db->where('title_fa',$tite_fa);
	$this->db->where('performer_fa',$perf_fa);
    $this->db->update('music_sent', $data);
}
public function update_telegram_music_sent_new($data,$id){
    $this->db->where('id',$id);
	//$this->db->where('performer_fa',$perf_fa);
    $this->db->update('music_sent', $data);
}
public function update_telegram_music_sent_info($data,$fid){
    $this->db->where('file_id',$fid);
    $this->db->update('music_sent', $data);
}
public function set_telegram_music_sent($data){
	$this->db->insert("music_sent", $data);
	
}

public function clear_telegram_music_sent($group_id){
	$this->db->where('group_id',$group_id);
	$this->db->delete('music_sent');
}

public function get_telegram_music_timer(){
	    //$this->db->where('title_en',$tit);
	    $this->db->where('time <',time());
	    $result = $this->db->get("music_timer");
        return $result->result();
}

public function get_music_timer_user($userid){
	    //$this->db->where('title_en',$tit);
	    $this->db->where('uid',$userid);
	    $result = $this->db->get("music_timer");
        return $result->result();
}

public function set_telegram_music_timer($data){
	$this->db->insert("music_timer", $data);
	
}

public function update_music_timer($data,$userid){
    $this->db->where('uid',$userid);
    $this->db->update('music_timer', $data);
    return $this->db->affected_rows();
}

public function clear_telegram_music_timer($user_id){
	$this->db->where('uid',$user_id);
	$this->db->delete('music_timer');
}
//-----------------------------------------------------------

public function set_music($data){
	$this->db->insert("music_sent22", $data);
	
}
public function update_music($data){
    $this->db->where('title_en',"");
	$this->db->where('performer_en',"");
    $this->db->update('music_sent22', $data);
}

//----------------------------------------------------------

public function get_vid_sent_concat($nameAndtitle){
    //$this->db->select('t_vid');
    //$this->db->select('CONCAT(performer, title)');
    //$this->db->where('title',"$nameAndtitle");
    $this->db->order_by("id", "RANDOM");
    $this->db->where("CONCAT(performer, ' ', title) LIKE '%$nameAndtitle%'",NULL,FALSE);
    //$results = $this->db->get()->result();
    $result = $this->db->get("video");
    return $result->result();
}

public function get_vid_by_tag($nameAndtitle){
    $this->db->order_by("id", "RANDOM");
    $this->db->like('tags', $nameAndtitle);
    $result = $this->db->get("video");
    return $result->result();
}
//--------------------------------------------
public function set_poem($data){
	$result = $this->db->insert("poem", $data);
	return $result;
}

public function update_poem($name,$poeter,$data){
    $this->db->where('name',$name);
    $this->db->where('poet',$poeter);
    $this->db->update('poem', $data);
    return $this->db->affected_rows();
}

public function get_poem_one($id){
    $this->db->where('id',$id);
	$result = $this->db->get("poem");
    return $result->result();
}

public function get_by_poeter($poeter){
    $this->db->where('poet',$poeter);
    $this->db->order_by('id', 'RANDOM');
    $this->db->limit(1);
	$result = $this->db->get("poem");
    return $result->result();
}

public function get_by_poeter_match($poeter){
    $query =("SELECT DISTINCT poet FROM (`poem`)
    WHERE MATCH(`poet`) AGAINST('$poeter')");
    $result = $this->db->query($query);
    return $result->result();
}
public function get_by_poeter_like($poeter){
    $this->db->distinct();
    $this->db->limit(1);
    $this->db->like('poet',$poeter);
    $result = $this->db->get("poem");
    return $result->result();
}

public function get_by_tag_like($tag){
    $this->db->distinct();
    $this->db->limit(1);
    $this->db->order_by('id', 'RANDOM');
    $this->db->like('tag',$tag);
    $result = $this->db->get("poem");
    return $result->result();
}

public function get_by_poeter_like_allPoet($poeter){
    $query =("SELECT DISTINCT * FROM (`poem`)
    WHERE MATCH(`poet`) AGAINST('$poeter') ORDER BY RAND() LIMIT 1");
    $result = $this->db->query($query);
    return $result->result();
}

public function get_poem_all_poeter(){
    $this->db->distinct();
    $this->db->select('poet');
	$result = $this->db->get("poem");
    return $result->result();
}

public function get_poem_name($name,$poeter){
    $this->db->where('name',$name);
    $this->db->where('poet',$poeter);
	$result = $this->db->get("poem");
    return $result->result();
}

public function get_poem_max(){
	$this->db->select_max('id');
    $result = $this->db->get('poem');
    return $result->result();
}

public function clear_poem($name,$poeter){
	$this->db->where('name',$name);
    $this->db->where('poet',$poeter);
	$this->db->delete('poem');
}

public function Decrease_id($maxId){
    $query =("ALTER TABLE poem AUTO_INCREMENT = 201");
	$result = $this->db->query($query);
    return $result;
}
//********************************************

public function set_city($data){
	$result = $this->db->insert("iranCity", $data);
	return $result;
}

public function update_city($name_en,$data){
    $this->db->where('name_en',$name_en);
    $this->db->update('iranCity', $data);
    return $this->db->affected_rows();
}

public function get_city(){
    $this->db->where('name_fa',"");
	$result = $this->db->get("iranCity");
    return $result->result();
}

public function clear_city($name_en){
	$this->db->where('name_en',$name_en);
	$this->db->delete('poem');
}

//--------------------------------------------
public function get_telegram_answer(){
	//$this->db->where('group_word',$gw);
	//$this->db->where('question',$quest) ;
	//$this->db->where('time_req',$date);
	 $result = $this->db->get("group_answer");
        return $result->result();
}

public function get_telegram_answer_like($quest){
	    $this->db->like('question', $quest);
	    $result = $this->db->get("group_answer");
        return $result->result();
}

public function set_telegram_answer($data){
	$this->db->insert("group_answer", $data);
	
}

public function update_telegram_answer($group_id,$data){
    $this->db->where('id',$group_id);
	//$this->db->where('time_req',$date);
    $this->db->update('group_answer', $data);
}
//----------------------------------------------
public function get_telegram_answer1($quest){
	//$this->db->where('group_word',$gw);
	$this->db->where('question',$quest) ;
	//$this->db->where('time_req',$date);
	 $result = $this->db->get("group_answer1");
        return $result->result();
}

public function set_telegram_answer1($data){
	$this->db->insert("group_answer1", $data);
	
}

public function update_telegram_answer1($quest,$data){
    $this->db->where('question',$quest);
	//$this->db->where('time_req',$date);
    $this->db->update('group_answer1', $data);
}
public function get_telegram_answer11($quest){
    $query =("SELECT question, answer
FROM group_answer
WHERE MATCH(question) AGAINST('سرت جواب')");
    
    //$this->db->where_in("namad","وتجارت1");
    
    $result = $this->db->query($query);

   
    return $result->result();
}
//-------------------------------------------- game
public function set_game($data){
	$this->db->insert("dart_game", $data);
	
}

public function get_agame($group_id){
    $this->db->where('group_id',$group_id);
	$result = $this->db->get("dart_game");
    return $result->result();
}
public function get_agame_user($group_id,$user_id){
    $this->db->where('group_id',$group_id);
    $this->db->where('gamers',$user_id);
	$result = $this->db->get("dart_game");
    return $result->result();
}
public function update_game($group_id,$data){
    $this->db->where('group_id',$group_id);
	$this->db->where('requester',1);
    $this->db->update('dart_game', $data);
    if($this->db->affected_rows() > 0)
    return (true);
}

//--------------------------------------------

public function set_telegram_data($data){
	$this->db->insert("telegram_data", $data);
	
}

public function update_telegram_data($uid,$telegramid,$type,$data){
	 $this->db->where('uid',$uid);
	$this->db->where('telegramid',$telegramid);
	$this->db->where('type',$type);
    $this->db->update('telegram_data', $data);
}
public function get_telegram_data($uid,$telegramid,$type){
	$this->db->where('uid',$uid);
	$this->db->where('telegramid',$telegramid);
	$this->db->where('type',$type);
	 $result = $this->db->get("telegram_data");
        return $result->result();
}
public function get_telegram_tellid($uid,$telegramid,$type){
	$this->db->where('uid',$uid);
	$this->db->where('telegramid',$telegramid);
	 $result = $this->db->get("telegram_data");
        return $result->result();
}
public function get_telegram_tellid2($id,$uid){
	$this->db->where('tellid',$id);
	$this->db->where('uid',$uid);
	 $result = $this->db->get("telegram_message");
        if(count($result->result()) == 0){
		  return false;
	  }else{
		  return true;
	  }
}
public function clear_telegram_data($uid,$telegramid){
	$this->db->where('uid',$uid);
   $this->db->where('telegramid',$telegramid);
	$this->db->delete('telegram_data');
}
//---------------------------------------------
public function set_Controler($data){
	$this->db->insert("Controler", $data);
}
public function update_Controler($groupid,$data){
	$this->db->where('groupid',$groupid);
    $this->db->update('Controler', $data);
}
public function get_Controler($groupid){
	$this->db->where('groupid',$groupid);
	 $result = $this->db->get("Controler");
    return $result->result();
}
public function clear_Controler($groupid){
	$this->db->where('groupid',$groupid);
	$this->db->delete('Controler');
}
//-------------------------------------------------
public function set_youtube_timer($data){
	$this->db->insert("youtube_timer", $data);
}
public function update_youtube_timer($timer,$data){
	$this->db->where('timer',$timer);
    $this->db->update('youtube_timer', $data);
}
public function get_youtube_timer($time){
	$this->db->where('timer <',$time);
	$result = $this->db->get("youtube_timer");
    return $result->result();
}
public function get_youtube_timer_vid($id){
	$this->db->where('vid_id',$id);
	$result = $this->db->get("youtube_timer");
    return $result->result();
}
public function get_youtube_timer_name($name){
	$this->db->where('name',$name);
	$result = $this->db->get("youtube_timer");
    return $result->result();
}
public function clear_youtube_timer($vid_id){
	$this->db->where('vid_id',$vid_id);
	$this->db->delete('youtube_timer');
}
//-------------------------------------------------

public function set_youtube_timer2($data){
	$this->db->insert("youtube_timer2", $data);
}
public function get_youtube_timer2($url,$chatid){
	$this->db->where('url',$url);
	$this->db->where('chatid',$chatid);
	$result = $this->db->get("youtube_timer2");
    return $result->result();
}
public function update_youtube_timer2($id,$data){
	$this->db->where('vid_id',$id);
    $this->db->update('youtube_timer2', $data);
}
//-------------------------------------------------
public function set_post_sent($data){
	$this->db->insert("post_sent", $data);
}
public function update_post_sent($channel_name,$news_name,$data){
	$this->db->where('channel_name',$channel_name);
	$this->db->where('news_name',$news_name);
    $this->db->update('post_sent', $data);
    return ($this->db->affected_rows() > 0);
}
public function get_post_sent($id){
	$this->db->where('id',$id);
	$result = $this->db->get("post_sent");
    return $result->result();
}

public function get_post_sent1($channel){
	$this->db->where('channel_name',$channel);
	$result = $this->db->get("post_sent");
    return $result->result();
}
//-------------------------------------------------
public function creat_Bo_table($name){
$this->load->dbforge();
	$fields = array(
        'namad' => array(
                'type' => 'VARCHAR',
                'constraint' => '12',
                'unique' => TRUE,
                //'Collation' => 'utf8_unicode_ci',
        ),
        'name' => array(
                'type' =>'VARCHAR',
                'constraint' => '50',
                //'Collation' => 'utf8_unicode_ci',
        ),
        'hajm' => array(
                'type' => 'VARCHAR',
                'constraint' => '40',
        ),
		'pri' => array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'num_sell' => array(
			'type' => 'VARCHAR',
            'constraint' => '40',			 
		),
		'up' => array(
			'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'down'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'end_pr'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'end_change'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'end_percent'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'last_pr'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'last_change'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'last_percent'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'prev_day_pr'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'Market_value'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '40',
		),
		'time_set'=>array(
			    'type' => 'VARCHAR',
                'constraint' => '50',
                //'default' => 'CURRENT_TIMESTAMP',
		),
		'timestamp'=>array(
			    'type' => 'INT',
                'constraint' => '15',
                //'default' => 'CURRENT_TIMESTAMP',
		),
);
	$this->dbforge->add_field('id');
	$this->dbforge->add_field($fields);
	$this->dbforge->create_table($name, TRUE);
}

public function set_Bo_table($table,$data){
	$this->db->insert($table, $data);
}
public function get_Bo_table($name){
    //$this->db->select('id,namad,end_pr,end_percent');
	//$this->db->where('group_id',$gid);
	$result = $this->db->get($name);
    return $result->result();
}
public function get_Bo_namads($table){
    $this->db->select('namad');
	//$this->db->where('namad',$namad);
	$result = $this->db->get($table);
    return $result->result();
}
public function get_Bo_get_join($namad,$query){
    /*$query =("SELECT namad,end_pr,end_percent from zbo1
        where namad = $namad
        UNION All
        SELECT namad,end_pr,end_percent from zbo2
        where namad = $namad");*/
    
    //$this->db->where_in("namad","وتجارت1");
    
    $result = $this->db->query($query);

   
    return $result->result();
}
public function update_Bo_table_date($name,$data){
	$this->db->where('id >',0);
    $this->db->update($name , $data);
}

public function drop_Bo_table($name){
	$this->load->dbforge();
	$this->dbforge->drop_table($name);
}
//==================================================
public function set_post_sent_group($data){
	$this->db->insert("post_sent_group", $data);
}
public function update_post_sent_group($group_id,$data){
	$this->db->where('group_id',$group_id);
    $this->db->update('post_sent_group', $data);
}
public function get_post_sent_group(){
	//$this->db->where('group_id',$gid);
	$result = $this->db->get("post_sent_group");
    return $result->result();
}
public function clear_post_sent_group($group_id){
	$this->db->where('group_id',$group_id);
   //$this->db->where('telegramid',$telegramid);
	$this->db->empty_table('post_sent_group');
}
//-------------------------------------------------
public function set_bad_guy($data){
	$this->db->insert("bad_guys", $data);
}
public function update_bad_guy($uid,$data){
	$this->db->where('userid',$uid);
    $this->db->update('bad_guys', $data);
}
public function get_bad_guy($uid){
	$this->db->where('userid',$uid);
	$result = $this->db->get("bad_guys");
    return $result->result();
}
public function delete_bad_guy($uid){
	$this->db->where('userid',$uid);
	$this->db->delete('bad_guys');
}
public function empty_bad_guy($uid){
	$this->db->where('user_id',$uid);
   //$this->db->where('telegramid',$telegramid);
	$this->db->empty_table('bad_guys');
}

//---------------------------------------------------

public function set_telegram_message($data){
	$this->db->insert("telegram_message", $data);
}
public function set_telegram_join($data){
	$this->db->insert("joinus_message", $data);
}
public function set_telegram_register($data){
	$this->db->insert("register_table", $data);
}
/*public function set_telegram_music($data){
	$this->db->insert("music_info", $data);
}*/
public function update_telegram_register($uid,$tellid,$data){
	 $this->db->where('uid',$uid);
	$this->db->where('tellid',$tellid);
    $this->db->update('register_table', $data);
}
public function update_telegram_message($uid,$tellid,$data){
	 $this->db->where('uid',$uid);
	$this->db->where('tellid',$tellid);
    $this->db->update('telegram_message', $data);
}
public function get_telegram_message($uid){
	$this->db->where('uid',$uid);
	 $result = $this->db->get("telegram_message");
    return $result->result();
}
public function get_telegram_register($uid){
	$this->db->where('uid',$uid);
	//$this->db->where('tellid',$telegramid);
	 $result = $this->db->get("register_table");
        return $result->result();
}
public function get_telegram_score($id,$uid){
	$this->db->where('tellid',$id);
	$this->db->where('uid',$uid);
	
	$result = $this->db->get("telegram_message");
	$result = $result->result();
    return $result[0]->score;
}
public function get_telegram_check($id,$uid){
	$this->db->where('tellid',$id);
	$this->db->where('uid',$uid);
	
	$result = $this->db->get("register_table");
	$result = $result->result();
    return $result[0]->profile_complet_chek;
}
public function get_telegram_message_index($id,$uid){
	$this->db->where('tellid',$id);
	$this->db->where('uid',$uid);
	
	$result = $this->db->get("register_table");
	$result = $result->result();
    return $result[0]->message;
}
public function get_telegram_timestart($id,$uid){
	$this->db->where('tellid',$id);
	$this->db->where('uid',$uid);
	
	$result = $this->db->get("telegram_message");
	$result = $result->result();
    return $result[0]->timestart;
}
public function get_telegram_join($uid){
	$this->db->where('uid',$uid);
	//$this->db->where('tellid',$telegramid);
	 $result = $this->db->get("joinus_message");
        return $result->result();
}
public function get_telegram_album_music($name){
	$this->db->where('album',$name);
	 $result = $this->db->get("music_info");
    return $result->result();
}
public function get_telegram_music($name){
	$this->db->where('music_name',$name);
	 $result = $this->db->get("music_info");
    return $result->result();
}
public function get_telegram_album($name){
	$this->db->where('singer',$name);
	 $result = $this->db->get('music_info');
    return $result->result();
}

public function get_question($qid){
	$this->db->where('id',$qid);
	 $result = $this->db->get('questions');
    return $result->result();
}

public function delete_telegram_message($id){
	$this->db->where('id',$id);
	$this->db->delete('telegram_message');
}
//********************************************************
public function set_temp($data){
	$this->db->insert("temp", $data);
	
}
public function get_temp($id){
	$this->db->where('id',$id);
	 $result = $this->db->get('temp');
    return $result->result();
}
public function update_temp($id,$data){
	$this->db->where('id',$id);
    $this->db->update('temp', $data);
    return ($this->db->affected_rows() > 0);
}
//==================================================
public function get_lock($chatid){
	//$this->db->where('id',$id);
	$this->db->where('group_id',$chatid);
	 $result = $this->db->get('lock_key');
    return $result->result();
}

//==================================================
public function set_caption_image($data){
	$this->db->insert("caption_images", $data);
}
public function delete_caption_image($id,$uid){
	$this->db->where('uid',$uid);
	$this->db->where('id',$id);
	$this->db->delete('caption_images'); 
}
public function get_caption_text($uid,$group_name){
	$this->db->where('uid',$uid);
	$this->db->where('group_name',$group_name);
	$result = $this->db->get("caption_images");
	return $result->result();
}
public function get_caption_by_id($uid,$id){
	$this->db->where('uid',$uid);
	$this->db->where('id',$id);
	$result = $this->db->get("caption_images");
	return $result->result();
}
public function update_caption_by_id($uid,$id,$data){
	$this->db->where('uid',$uid);
	$this->db->where('id',$id);
	$this->db->update('caption_images', $data); 
}
public function get_caption_image($uid,$groupname,$imagename){
	$this->db->where('uid',$uid);
	$this->db->where('group_name',$groupname);
	$this->db->where('imagename',$imagename);
	$result = $this->db->get("caption_images");
	$result = $result->result();
    return $result[0]->text;
	
}
public function get_visited_users($uid,$mon){
	$this->db->where('uid',$uid);
	$this->db->where('mon',$mon);
	$result = $this->db->get("visited_bot");
	$result = $result->result();
    return @$result[0]->number;
}
public function set_visited_users($data){
	$this->db->insert("visited_bot", $data);
}
public function update_visited_users($uid,$mon,$data){
	$this->db->where('uid',$uid);
	$this->db->where('mon',$mon);
	$this->db->update('visited_bot', $data);
}
public function is_visited_users_exist($uid,$mon){
$this->db->where("uid",$uid);
$this->db->where("mon",$mon);
	  $result = $this->db->get('visited_bot');
	  if(count($result->result()) == 0){
		  return false;
	  }else{
		  return true;
	  }
}
}
?>