<?php
ini_set('display_errors', '0');
class bot
{
    public $token;
    public $chatid;
    public $recmsg;
    public $message_id;
    public $username;
    public $firstname;
    public $lastname;
    public $datamytext;
    public $datachatid;
    public $phone;
    public $exRecmsg;
    public $exRecGlass;
    public $gpFromChatId;
    public $gpFromFirstname;
    public $gpFromLastname;
    public $gpFromUsername;
    public $gpNewMemberChatid;
    public $gpNewMemberFirstname;
    public $gpNewMemberLastname;
    public $gpNewMemberUsername;
    public $gpLeftMemberChatid;
    public $gpLeftMemberFirstname;
    public $gpLeftMemberLastname;
    public $gpLeftMemberUsername;
    public $gpChatTitle;
    public $gpActionType;
    public $gpSecondMemberChatid;
    public $gpSecondMemberFirstname;
    public $gpSecondMemberLastname;
    public $gpSecondMemberUsername;
    public $backKey;
    public $mainKey;
    public $fileidBest;
    public $fileidGood;
    public $fileid;
    public $fileidBad;
    public $fileidVeryBad;
    public $documentFileId;


    function __construct($token, $content)
    {
        $this->token = $token;
        $this->backKeyEn = json_encode(
            array(
                "keyboard" => array(
                    array("🔙 Return")
                ),
                "resize_keyboard" => True
            )
        );


        $this->backKey  = json_encode(
            array(
                "inline_keyboard" => array(
                    array(
                        array("text" => "🔙 بازگشت", "callback_data" => "🔙 بازگشت")
                    ),
                )
            )
        );

        $this->mainKey  = json_encode(
            array(
                "inline_keyboard" => array(
                    array(
                        array("text" => urlencode("موسیقی"), "callback_data" => urlencode("خرید موسیقی")),
                    ),

                    array(
                        array("text" => urlencode("دعا و نیایش"), "callback_data" => urlencode("خرید دعا"))
                    ),
                )
            )
        );



     


        if ($content != '') {
            $update = json_decode($content, true);
            $message = $update["message"];
            $this->recmsg = $message['text'];
            $this->recmsg = str_replace('@teletools_member_counter_bot', '', $this->recmsg);
            $this->message_id = $message['message_id'];
            $this->chatid = $message['chat']['id'];
            $this->username = $message['from']['username'];
            $this->firstname = $message['from']['first_name'];
            $this->lastname = $message['from']['last_name'];
            $this->datamytext = $update["callback_query"]["data"];
            $this->datachatid = $update["callback_query"]["from"]["id"];
            if ($this->chatid == '') {
                $this->chatid = $this->datachatid;
                $this->recmsg = $this->datamytext;
            }
            $this->phone = $message["contact"]["phone_number"];
            $erecmsg = str_replace("/start", "", $this->recmsg);
            $erecmsg = str_replace(" ", "", $erecmsg);
            $exrec = explode("_", $erecmsg);
            $this->exRecmsg = $exrec;
            $this->exRecGlass = explode("a", $this->datamytext);
            ///Group information
            $this->gpFromChatId = $message['from']['id'];
            $this->gpFromFirstname = $message['from']['first_name'];
            $this->gpFromLastname = $message['from']['last_name'];
            $this->gpFromUsername = $message['from']['username'];

            $this->gpNewMemberChatid = $message['new_chat_participant']['id'];
            $this->gpNewMemberFirstname = $message['new_chat_participant']['first_name'];
            $this->gpNewMemberLastname = $message['new_chat_participant']['last_name'];
            $this->gpNewMemberUsername = $message['new_chat_participant']['username'];


            $this->gpLeftMemberChatid = $message['left_chat_participant']['id'];
            $this->gpLeftMemberFirstname = $message['left_chat_participant']['first_name'];
            $this->gpLeftMemberLastname = $message['left_chat_participant']['last_name'];
            $this->gpLeftMemberUsername = $message['left_chat_participant']['username'];
            $this->gpChatTitle = $message['chat']['title'];


            $this->fileidBest = $message['photo'][4]['file_id'];
            $this->fileidGood = $message['photo'][3]['file_id'];
            $this->fileid = $message['photo'][2]['file_id'];
            $this->fileidBad = $message['photo'][1]['file_id'];
            $this->fileidVeryBad = $message['photo'][0]['file_id'];
            $this->documentFileId = $message['document']['file_id'];



            if (isset($message['new_chat_participant']['id']) && $message['new_chat_participant']['id'] == $this->gpFromChatId) {

                $this->gpActionType = 'joined';
                $this->gpSecondMemberChatid = $message['new_chat_participant']['id'];
                $this->gpSecondMemberFirstname = $message['new_chat_participant']['first_name'];
                $this->gpSecondMemberLastname = $message['new_chat_participant']['last_name'];
                $this->gpSecondMemberUsername = $message['new_chat_participant']['username'];
            } elseif (isset($message['new_chat_participant']['id'])) {
                $this->gpActionType = 'added';
                $this->gpSecondMemberChatid = $message['new_chat_participant']['id'];
                $this->gpSecondMemberFirstname = $message['new_chat_participant']['first_name'];
                $this->gpSecondMemberLastname = $message['new_chat_participant']['last_name'];
                $this->gpSecondMemberUsername = $message['new_chat_participant']['username'];
            } elseif (isset($message['left_chat_participant']['id']) && $message['left_chat_participant']['id'] == $this->gpFromChatId) {
                $this->gpActionType = 'left';
                $this->gpSecondMemberChatid = $message['left_chat_participant']['id'];
                $this->gpSecondMemberFirstname = $message['left_chat_participant']['first_name'];
                $this->gpSecondMemberLastname = $message['left_chat_participant']['last_name'];
                $this->gpSecondMemberUsername = $message['left_chat_participant']['username'];
            } elseif (isset($message['left_chat_participant']['id'])) {
                $this->gpActionType = 'removed';
                $this->gpSecondMemberChatid = $message['left_chat_participant']['id'];
                $this->gpSecondMemberFirstname = $message['left_chat_participant']['first_name'];
                $this->gpSecondMemberLastname = $message['left_chat_participant']['last_name'];
                $this->gpSecondMemberUsername = $message['left_chat_participant']['username'];
            }
        }
    }




    function inchannel($chatid, $channel)
    {
        $c = curl_init("https://api.telegram.org/bot" . $this->token . "/getChatMember?chat_id=$channel&user_id=$chatid");
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt(... other options you want...)

        curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
        //curl_setopt($c, CURLOPT_RETURNTRANSFER, true);

        $sended = curl_exec($c);

        if (curl_error($c)) {
            die(curl_error($c));
        }

        // Get the status code
        $status = curl_getinfo($c, CURLINFO_HTTP_CODE);

        curl_close($c);
        # sendmessage(urlencode("in $sended"),"80433998",'');
        $update2 = json_decode($sended, true);
        $getinfo = $update2["result"]["status"];


        if ($getinfo == "creator" || $getinfo == "member" || $getinfo == "administrator") {
            return "ok";
        } else {
            return "no";
        }
    }


    function uploadPhoto()
    {
        $fileType = 'pic';
        $fileExtention = '.png';





        if ($this->fileidBest != '') {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->fileidBest;
        } elseif ($this->fileidGood != '') {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->fileidGood;
        } elseif ($this->fileid != '') {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->fileid;
        } 
        elseif ($this->fileidBad != '') {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->fileidBad;
        } elseif ($this->documentFileId != '') {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->documentFileId;
            $fileType = 'video';
            $fileExtention = '.mp4';
        } else {
            $forSend = "https://api.telegram.org/bot" . $this->token . "/getFile?file_id=" . $this->fileidVeryBad;
        }


        // $this->sendmessage(urlencode('Here1'.$forSend), 5803067539 , '');


        $c = curl_init("$forSend");
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
        $sended = curl_exec($c);
        if (curl_error($c))
            die(curl_error($c));
        $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
        curl_close($c);


        $imginfo = json_decode($sended, true);
        $picname = $imginfo['result']['file_path'];

        //$this->sendmessage(urlencode('Here2'.$picname), -1001147215207 , '');

      
        $time = time();
        $thename = "image" . $time . rand(0, 1000);


        $c = curl_init("https://api.telegram.org/file/bot" . $this->token . "/$picname");
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
        $sended = curl_exec($c);
        if (curl_error($c))
            die(curl_error($c));
        $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
        curl_close($c);
       $result= file_put_contents("upload/$thename" . $fileExtention, $sended);

        //$this->sendmessage(urlencode('Here22 )) '."https://api.telegram.org/file/bot" . $this->token . "/$picname"), 80433998 , '');
        //$this->sendmessage(urlencode('Here3'.$picname), 80433998 , '');
        //$this->sendmessage(urlencode('Here4'."upload/$thename" . $fileExtention  . "and : ".$result), 80433998 , '');

        $mypic = "$thename" . $fileExtention;
        return $mypic;


    }

    function sendphoto($address, $chatid, $key, $caption)
    {

        $bot_url = "https://api.telegram.org/bot" . $this->token . "/";
        $url = $bot_url . "sendPhoto?caption=$caption&reply_markup=$key&parse_mode=Html&chat_id=" . $chatid;
        $file = '' . 'upload' . '/' . $address;
        $mime = mime_content_type($file);
        $info = pathinfo($file);
        $name = $info['basename'];
        $output = new CURLFile($file, $mime, $name);

        $data = array(
            "photo" => $output,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $error = curl_error($ch);
        }
        curl_close($ch);

        return $result . $error;
    }

    function sendmessage($text, $chatid, $keys)
    {
        $ch = curl_init("https://api.telegram.org/bot" . $this->token . "/sendmessage?chat_id=$chatid&text=$text&parse_mode=HTML&reply_markup=$keys");
        curl_exec($ch);
    }
    function sendFile($address, $text, $chatid, $keys)
    
    {
        $ch = curl_init("https://api.telegram.org/bot6332184574:AAHLvn7liZrMLKuuHDQFXlvB4asjlyUL3zI/sendDocument?document=https://teleaccmanager.telegramtools.io/dev/telegram_member_counter/mamad.xlsx&chat_id=$chatid");
        curl_exec($ch);


        $result2 = file_get_contents("https://api.telegram.org/bot6332184574:AAHLvn7liZrMLKuuHDQFXlvB4asjlyUL3zI/sendDocument?document=https://teleaccmanager.telegramtools.io/dev/telegram_member_counter/mamad.xlsx&chat_id=$chatid");
        print("RESULT 2 : $result2");
    }
    function channel_member_status($chatid, $group_id)
    {
        $c = curl_init("https://api.telegram.org/bot" . $this->token . "/getChatMember?chat_id=$group_id&user_id=$chatid");
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
        $sended = curl_exec($c);
        if (curl_error($c)) {
            die(curl_error($c));
        }
        $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
        curl_close($c);
        $update2 = json_decode($sended, true);
        $getinfo = $update2["result"]["status"];
        return $getinfo;
    }
    function isAdmin($message_from_id, $chatid)
    {
        #checker
        $channel_member_status = $this->channel_member_status($message_from_id, $chatid);
        if (!($channel_member_status == 'creator' || $channel_member_status == 'administrator')) {
            return True;
        }
        #checker

        return False;
    }



    // function copyMessage($chatid, $from_chatid, $message_id)
    // {
    //     $send = "https://api.telegram.org/bot" . $this->token . "/copyMessage?chat_id=$chatid&from_chat_id=$from_chatid&message_id=$message_id=";
    //     $c = curl_init($send);
    //     curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    //     //curl_setopt(... other options you want...)
    //     curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
    //     //curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    //     $sended = curl_exec($c);
    //     if (curl_error($c)) {
    //         die(curl_error($c));
    //     }
    //     $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
    //     curl_close($c);
    //     $decodeData = json_decode($sended, true);
    //     $id_message = $decodeData['result']['message_id'];
    //     return $id_message;
    // }
    function copyMessage($chatid, $from_chatid, $message_id, $key = null)
    {
        $send = "https://api.telegram.org/bot" . $this->token . "/copyMessage";
    
        $data = [
            'chat_id' => $chatid,
            'from_chat_id' => $from_chatid,
            'message_id' => $message_id
        ];
    
        // If reply_markup is provided, add it
        if (!empty($key)) {
            $data['reply_markup'] = $key;
        }
    
        $c = curl_init();
        curl_setopt($c, CURLOPT_URL, $send);
        curl_setopt($c, CURLOPT_POST, true);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($data));  // JSON encoding is required
        curl_setopt($c, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
    
        $sended = curl_exec($c);
        
        if (curl_error($c)) {
            die(curl_error($c));
        }
        
        $status = curl_getinfo($c, CURLINFO_HTTP_CODE);
        curl_close($c);
        
        $decodeData = json_decode($sended, true);
        
        if (isset($decodeData['result']['message_id'])) {
            return $decodeData['result']['message_id'];
        } else {
            return "Error: " . json_encode($decodeData);
        }
    }

    function unBanMember($chatid, $channelId)
    {
        $send = "https://api.telegram.org/bot" . $this->token . "/unbanChatMember?chat_id=$channelId&user_id=$chatid&only_if_banned=True";
        $sended = file_get_contents($send);
        //print $sended;
    }

    function banMember($chatid, $channelId)
    {
        $send = "https://api.telegram.org/bot" . $this->token . "/banChatMember?chat_id=$channelId&user_id=$chatid";
        $sended = file_get_contents($send);
        //print $sended;
    }


    function getChannelLink($channelId)
    {
        $exTime = time() + 180;
        $ch = curl_init("https://api.telegram.org/bot" . $this->token . "/createChatInviteLink?chat_id=$channelId&member_limit=1");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $result = curl_exec($ch);
        //print('result ' . $result);
        $data = json_decode($result, true);
        //print("THIS DATA  : " . $data['result']['invite_link']);
        $vipChannel = $data['result']['invite_link'];
        if ($vipChannel == "" || $vipChannel == " ") {
             return $result;
        } else {
             return $vipChannel;
        }
    }


    function checkWallet($chatid,$conn){

        
    
        $sql = "select * from users where chatid ='" . $chatid . "' ";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $getter = $stmt->fetchAll();
        $numrowfusers = $stmt->rowCount();
        
    
        
        $sql = "select * from adduser where mainchatid ='" . $chatid . "' ";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $getter = $stmt->fetchAll();
        $numrowfusers = $stmt->rowCount();

        
    
        $myMoneyRial=0;
        $myMoneyUsdt=0;
        $counter=0;

     
        

        foreach($getter as $singleGetter){
    
            
            
            
            $sql = "select * from payments where chatid ='" . $singleGetter['chatid'] . "' ";
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter2 = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            

                
       

            foreach($getter2 as $singleGetter2){

                if($numrow==0){
                
                    continue;
                }
    
                    
                    
                $counter = $counter + 1;
    
                $convertedRial = intval($singleGetter2['rial']);
                $convertedCrypto = intval($singleGetter2['crypto']);
                
                
    
                if($counter>0 and $counter <=5){
    
                    $myMoneyRial = $myMoneyRial + (($convertedRial* 20) / 100);
                    $myMoneyUsdt = $myMoneyUsdt + (($convertedCrypto  * 20) / 100);
                    
                }
    
                elseif($counter>5 and $counter <=10){
                    $myMoneyRial = $myMoneyRial + (($convertedRial* 30) / 100);
                    $myMoneyUsdt = $myMoneyUsdt + (($convertedCrypto  * 30) / 100);
                }
                elseif($counter>10 and $counter <=15){
                    $myMoneyRial = $myMoneyRial + (($convertedRial * 40) / 100);
                    $myMoneyUsdt = $myMoneyUsdt + (($convertedCrypto  * 40) / 100);
                }
                elseif($counter>15 ){
                    $myMoneyRial = $myMoneyRial + (($convertedRial * 50) / 100);
                    $myMoneyUsdt = $myMoneyUsdt + (($convertedCrypto  * 50) / 100);
                }
    
            }
            
            }

    
        
        $money = [ "rial" => $myMoneyRial, 
                   "crypto" => $myMoneyUsdt ];
            
    return $money;

    }


    function sendDocument($chatId, $documentPath){

        
        
        $url = "https://api.telegram.org/bot" . $this->token . "/sendDocument?chat_id=$chatId";
        
        $postFields = array(
            'chat_id' => $chatId,
            'document' => new CURLFile(realpath($documentPath))
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type:multipart/form-data"
        ));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $output = curl_exec($ch);
        
        if ($output === FALSE) {
            echo "cURL Error: " . curl_error($ch);
        }
        
        curl_close($ch);
        

    }

    function sendinfo($fileid,$chatid,$key,$caption,$method,$type){

        $encodedCaption = urlencode($caption);

        $send = "https://api.telegram.org/bot" . $this->token . "/$method?chat_id=$chatid&$type=$fileid&reply_markup=$key&caption=$encodedCaption&parse_mode=HTML";
        $sended = file_get_contents($send);

        return $sended;
        print$sended;
    
    
    }
}
