<?php




    function keyGen($mykeys)
    {

        $getter = explode(",", $mykeys);


        $row_count = sizeof($getter);
        $numa = -1;
        $i = 0;
        $fara = 0;
        $counter = -1;
        foreach ($getter as $getter2) {
            
              
              
            $fara = $fara + 1;
            $counter = $counter + 1;

            $character[] = urlencode($getter2);
            $i = $i + 1;
            if ($i == 2) {
                
                   
                $numa = $numa + 1;
                $summerkey[$numa] = $character;
                unset($character);
                $i = 0;
            }


            if ($row_count % 2 == 1 && $row_count == ($counter + 1)) {
                $numa = $numa + 1;

                $summerkey[$numa] = $character;
            }
        }



        $key = json_encode(array("keyboard" => $summerkey, "resize_keyboard" => true));

        return $key;
    }


    function keyGenGlass($mykeys)
    {

        $getter = explode(",", $mykeys);


        $row_count = sizeof($getter);
        $numa = -1;
        $i = 0;
        $fara = 0;
        $counter = -1;
        foreach ($getter as $getter2) {
            $fara = $fara + 1;
            $counter = $counter + 1;

            $glassKey['callback_data'] = urlencode($getter2);
            $glassKey['text'] = urlencode($getter2);

            $character[] = $glassKey;
            unset($glassKey);
            $i = $i + 1;
            if ($i == 2) {
                $numa = $numa + 1;
                $summerkey[$numa] = $character;

                unset($character);
                $i = 0;
            }


            if ($row_count % 2 == 1 && $row_count == ($counter + 1)) {
                $numa = $numa + 1;

                $summerkey[$numa] = $character;
            }
        }



        $key = json_encode(array("inline_keyboard" => $summerkey));

        return $key;
    }
    function copyMessage($chatid, $from_chatid, $message_id)
    {
        $send = "https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/copyMessage?chat_id=$chatid&from_chat_id=$from_chatid&message_id=$message_id&protect_content=true";


        $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));
        }

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

        curl_close($c);



        $decodeData = json_decode($sended, true);
        $id_message = $decodeData['result']['message_id'];

        print $sended;


        return $id_message;
    }


    // copyMessage($chatid,$chatid,767);


function getFromChatid($id_message ,$conn ){
    $conn = connectd();
    $stmt = $conn->prepare("SELECT * FROM file_data where message_id='" . $id_message . "' ");

    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $getter2 = $stmt->fetchAll();
    $numrow = $stmt->rowCount();
    $from_chat_id = $getter2[0]['from_chat_id'];

    return $from_chati_id;
}

    function checkProducts($chatid, $recmsg)
    {
        $conn = connectd();
        $stmt = $conn->prepare("SELECT * FROM products where cate=\"$recmsg\" ");
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $result = $stmt->fetchAll();
        $numrow = $stmt->rowCount();




        if ($numrow == 0) {
            return $numrow;
        }
        $toSend = '';





        foreach ($result as $singelProduct) {




            $id_message1 = $singelProduct["id_message1"];
            $id_message2 = $singelProduct["id_message2"];
            $id_message3 = $singelProduct["id_message3"];
            $id_message4 = $singelProduct["id_message4"];
            $id_message5 = $singelProduct["id_message5"];
            $id_message6 = $singelProduct["id_message6"];
            $id_message7 = $singelProduct["id_message7"];
            $id_message8 = $singelProduct["id_message8"];
            $id_message9 = $singelProduct["id_message9"];
            $id_message10 = $singelProduct["id_message10"];




            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message1\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message1);


            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message2\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message2);


            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message3\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message3);


            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message4\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message4);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message5\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message5);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message6\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message6);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message7\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message7);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message8\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message8);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message9\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message9);

            $stmt = $conn->prepare("SELECT * FROM file_data where message_id=\"$id_message10\" ");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $getter = $stmt->fetchAll();
            $numrow = $stmt->rowCount();
            $from_chat_id = $getter[0]['from_chat_id'];

            copyMessage($chatid, $from_chat_id, $id_message10);
        }

        return 'ok';
    }


    function searchProducts($chatid, $recmsg)
    {
        $conn = connectd();
        $stmt = $conn->prepare("SELECT * FROM products where name LIKE '%" . $recmsg . "%' ");
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $result = $stmt->fetchAll();
        $numrow = $stmt->rowCount();




        if ($numrow == 0) {
            return $numrow;
        }
        $toSend = '';





        foreach ($result as $singelProduct) {



            $name = $singelProduct["name"];
            $info = $singelProduct["info"];
            $photo = $singelProduct["photo"];
            $price = $singelProduct["price"];
            $toSend = "
$name

$info
 
 قیمت : $price
            
            ";

            if ($photo == '') {

                sendmessage(urlencode($toSend), $chatid, '');
            } else {
                $result = sendphoto($photo, $chatid, '', urlencode($toSend));
            }
        }

        return 'ok';
    }



    function checkwords($chatid, $recmsg)
    {
        $conn = connectd();
        $exrecmsg = explode("/", $recmsg);


        $stmt = $conn->prepare("SELECT * FROM layertwo where mykey='$recmsg' ");
        $stmt->execute();

        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

        $k = $stmt->fetchAll();
        $mykeys = $k[0]["myarakeys"];
        $answer = $k[0]["answer"];
        $ispic = $k[0]["ispic"];
        $picture = $k[0]["picture"];


        $numrow = $stmt->rowCount();


        if ($numrow == 0) {
            $numrow = checkProducts($chatid, $recmsg);
        }







        if ($numrow == '0') {


            sendmessage(urlencode("دستور شما رو متوجه نشدم !"), $chatid, $key);
        } else {



            foreach ($k as $themyorder) {

                $mykeys = $themyorder["myarakeys"];
                $answer = $themyorder["answer"];
                $ispic = $themyorder["ispic"];
                $picture = $themyorder["picture"];
                $key_type = $themyorder["key_type"];

                print("qw");


                $txt = urlencode("$answer");

                $numrow = $stmt->rowCount();

                if ($mykeys == "" || $mykeys == " ") {
                    // $key = json_encode(array("hide_keyboard" =>True));
                    $key = "";
                } else {


                    if ($key_type == 'glass') {
                        $key = keyGenGlass($mykeys);
                    } else {
                        $key = keyGen($mykeys);
                    }
                }
                
                
                
                     //sendmessage($txt.urlencode("$txt Key is "), $chatid, '');
                     
                     

                if ($ispic == "pic") {
                    sendphoto($picture, $chatid, $key, "");
                } elseif ($ispic == "pdf") {
                    $result = senddoc($picture, $chatid, $key, '');
                } elseif ($ispic == "video") {
                    sendvideo($picture, $chatid, $key);
                }
                sendmessage($txt, $chatid, $key);
            }
        }
    }








    function ifnewuserinsert($chatid, $username, $name, $family, $conn, $myphone, $recmsg)
    {
        $conn = connectd();

        $sql = "select * from user where chatid=\"$chatid\"  ";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $numrow = $stmt->rowCount();

        if ($numrow == 0) {
            $sql = "insert into user (chatid,username,name,family) values (\"$chatid\",\"$username\",\"$name\",\"$family\")";
            $conn->exec($sql);
        }
    }


    function getChannelLink($channelId)
    {
        $exTime = time() + 180;
        $ch = curl_init("https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/createChatInviteLink?chat_id=$channelId&member_limit=1&expire_date=$exTime");
        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 inchannel($chatid, $channel)
    {
        $c = curl_init("https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/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);
        
        $update2 = json_decode($sended, true);
        $getinfo = $update2["result"]["status"];


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

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

        $encodedCaption = urlencode($caption);

        $send = "https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/$method?chat_id=$chatid&$type=$fileid&reply_markup=$key&caption=$encodedCaption&parse_mode=HTML";
        $sended = file_get_contents($send);
        print$sended;
    
    
    }

    function sendVideo($chatID, $videoPath, $caption) {
        $apiUrl = "https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/sendVideo";
    
        $postData = array(
            'chat_id' => $chatID,
            'video' => new CURLFile($videoPath),
            'caption' => $caption
        );
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if ($response === false) {
            echo "cURL Error: " . curl_error($ch);
        } else {
            echo "Video sent successfully!";
        }
        curl_close($ch);
    }
    
    
    
    
    function sendmessage($text, $chatid, $keys)
    {

        // $send = "https://api.telegram.org/bot7342242097:AAEbsheB984xDy2vK_mN31Heo7I1NA7yZo4/sendmessage?chat_id=$chatid&text=$text&parse_mode=Html&reply_markup=$keys&protect_content=false";
        $send = "https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/sendmessage?chat_id=$chatid&text=$text&parse_mode=Html&reply_markup=$keys";


        $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));
        }

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

        curl_close($c);



        $decodeData = json_decode($sended, true);
        $id_message = $decodeData['result']['message_id'];

        print $sended;


        return $id_message;
    }


//     function sendmessage($text, $chatid, $keys)
// {
//     $send = "https://api.telegram.org/bot7342242097:AAEbsheB984xDy2vK_mN31Heo7I1NA7yZo4/sendmessage?chat_id=$chatid&text=$text&parse_mode=Html&reply_markup=$keys&protect_content=true";

//     $c = curl_init($send);
//     curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($c, CURLOPT_FOLLOWLOCATION, 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);

//     $decodeData = json_decode($sended, true);
//     $id_message = $decodeData['result']['message_id'];

//     print $sended;

//     return $id_message;
// }



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

        $bot_url = "https://api.telegram.org/bot7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0/";
        $url = $bot_url . "sendPhoto?caption=$caption&reply_markup=$key&chat_id=" . $chatid. "&protect_content=true";
        $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 senddoc($address, $chatid, $key, $caption)
    {



        $bot_url = "https://api.telegram.org/bot7342242097:AAEbsheB984xDy2vK_mN31Heo7I1NA7yZo4/";
        $url = $bot_url . "sendDocument?caption=$caption&reply_markup=$key&chat_id=" . $chatid . "&protect_content=true";
        $file = '' . 'upload' . '/' . $address;
        $mime = mime_content_type($file);
        $info = pathinfo($file);
        $name = $info['basename'];
        $output = new CURLFile($file, $mime, $name);

        $data = array(
            "document" => $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;


  
    }

    //sendphoto('elite-badge.png','80433998','','');




    // function sendvideo($address, $chatid, $key)
    // {

    //     $bot_url = "https://api.telegram.org/bot7070296577:AAEzhKgIwG09prOqjtS9W63NCbNJQSRl4-E/";
    //     $url = $bot_url . "sendvideo?chat_id=" . $chatid. "&protect_content=true";
    //     $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,
    //         array(
    //             "video" => "@" . "upload/" . $address,
    //         )
    //     );
    //     curl_setopt($ch, CURLOPT_INFILESIZE, filesize("upload/" . $address));
    //     $output = curl_exec($ch);
    //     print $output;
    // }

function getNumAdd($chatid,$conn){
    $sql = "select * from adduser where mainchatid ='" . $chatid . "' ";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $getter = $stmt->fetchAll();
    $numrow = $stmt->rowCount();
    return$numrow;
}
function checkWallet($chatid,$conn){
    $sql = "select * from user where chatid ='" . $chatid . "' ";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $getter = $stmt->fetchAll();
    $numrowfusers = $stmt->rowCount();
    $money_used=$getter[0]['money_used'];

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


    $myMoney=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();
   
        if($numrow==0){
continue;
        }
        $counter+=1;

        if($counter>0 and $counter <=5){
            $myMoney = $myMoney + (($getter2[0]['amount'] * 20) / 100);
        }
        elseif($counter>5 and $counter <=10){
            $myMoney = $myMoney + (($getter2[0]['amount'] * 30) / 100);
        }
        elseif($counter>10 and $counter <=15){
            $myMoney = $myMoney + (($getter2[0]['amount'] * 40) / 100);
        }
        elseif($counter>15 ){
            $myMoney = $myMoney + (($getter2[0]['amount'] * 50) / 100);
        }
        
    }

    $myMoney=$myMoney - $money_used;
    return $mymoney;
}

?>

