<?php
/*
@Diaco_0910
@Sang_Penghancur
*/
set_time_limit(0);
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 300);
if (!file_exists("config.php") or !file_exists("Cr.php")) {
    die(":)");
}
require_once("config.php");
require_once("Cr.php");
function getreq($sname, $type = "get") {
    $url = senddata(address."/login.php?apphash=0&appid=0&phone=$sname&l=none&c=0&info=$type&p=none");
    return json_decode($url,true);
}
function get_rams(){
      $fh = fopen('/proc/meminfo','r');
  $mem = 0;
  while ($line = fgets($fh)) {
    $pieces = array();
    if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
      $mem = $pieces[1];
      break;
    }
  }
  fclose($fh);
  return $mem; 
}
function get_server_memory_usage(){

    $free = shell_exec('free');
    $free = (string)trim($free);
    $free_arr = explode("\n", $free);
    $mem = explode(" ", $free_arr[1]);
    $mem = array_filter($mem);
    $mem = array_merge($mem);
    $memory_usage = $mem[2]/$mem[1]*100;

    return $memory_usage;
}
function get_server_cpu_usage(){

    $load = sys_getloadavg();
    return $load[0];

}
function senddata($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    return curl_exec($ch);
    curl_close($ch);
}
function SendReq($method, $parameters = []) {
    $url = 'https://api.telegram.org/bot'.API_KEY.'/'.$method.'?';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    return json_decode(curl_exec($ch), true);
    curl_close($ch);
}
function generateRandomString($length = 10) {
    $characters = microtime(true).'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.uniqid();
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function forExec($array) {
    $a = [];
    if (empty($array) or is_null($array)) {
        return $array;
    }
    foreach ($array as $key => $value) {
        $a[$key[0] == ":" ? $key : ":".$key] = $value;
    }
    return $a;
}
function getCoulmn($db, $dbname, $cloumn = "*", $where = null) {
    $query = "";
    if (!is_null($where) && is_array($where)) {
        $cs = null;
        $count = count($where) - 1;
        foreach ($where as $key => $value) {
            static $i = 0;
            $cs .= " ".$key[0] == ":" ? ltrim($key, ":") : $key." = :".$key.($i < $count ? " AND" : "");
            $i++;
        }
        $query = "SELECT {$cloumn} FROM `{$dbname}` WHERE ".$cs;
    } else {
        $query = "SELECT {$cloumn} FROM `{$dbname}`";
    }
    $st = $db->prepare($query);
    $f = forExec($where);
    $st->execute($f);
    unset($f, $query, $cs);
    return $cloumn == "*" ? $st->fetchAll(PDO::FETCH_ASSOC) : ($st->fetch()[$cloumn] ?? false);
}
function deleteDir($path) {
    if (empty($path)) { 
        return false;
    }
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}
try {
    $update = json_decode(file_get_contents('php://input'), true);
    $inlineQuery = isset($update['inline_query']['query']) ? $update['inline_query']['query'] : null;
    $inlineQueryId = isset($update['inline_query']['id']) ? $update['inline_query']['id'] : null;
    $inlineQueryFromId = isset($update['inline_query']['from']['id']) ? $update['inline_query']['from']['id'] : null;
    $msgss = isset($update['message']) ? $update['message'] : null;
    $from_id = isset($msgss['from']['id']) ? $msgss['from']['id'] : null;
    $chat_id = isset($msgss['chat']['id']) ? $msgss['chat']['id'] : null;
    $mid = isset($msgss['message_id']) ? $msgss['message_id'] : null;
    $message = isset($msgss['text']) ? $msgss['text'] : null;
    $callBackData = isset($update['callback_query']['data']) ? $update['callback_query']['data'] : null;
    $callBackId = isset($update['callback_query']['id']) ? $update['callback_query']['id'] : null;
    $callBackFromId = isset($update['callback_query']['from']['id']) ? $update['callback_query']['from']['id'] : null;
    $callBackChatId = isset($update['callback_query']['chat']['id']) ? $update['callback_query']['chat']['id'] : $callBackFromId;
    $callBackMsgId = isset($update['callback_query']['inline_message_id']) ? $update['callback_query']['inline_message_id'] : null;
    $callBackMsgId2 = isset($update['callback_query']['message']['message_id']) ? $update['callback_query']['message']['message_id'] : null;
    $from_id = !is_null($callBackFromId) ? $callBackFromId : $from_id;
    $db = new PDO("mysql:host=".hostname.";dbname=".dbname, dbuser, dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'"));
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    createTable($db);
    if (in_array($from_id, admins)) {
        
        if ($message == "/start" or $message == "برگشت") {
            $db->exec("UPDATE `manager` SET step='none'");
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "به ربات مولتی اکانت دیاکو کورد خوش 😶برای ادامه یکی از گزینه های زیر را انتخاب کنید. 
@Diaco_0910
@Sang_Penghancur
@Sang_Penghancur",
                'reply_to_message_id' => $mid,
                'reply_markup' => json_encode(['resize_keyboard' => true, 'keyboard' => [[['text' => "پنل مدیریت ربات ها"]], [['text' => "ساخت ربات"]],[["text"=>"مشخصات سرور"]]]])
            ]);
            return;
        }
        if (preg_match("/^(run)\s+(.+)$/is", $message, $match)) {
            try {
                ob_start();
                eval($match[2].'?>');
                $run = ob_get_contents();
                ob_end_clean();
            }catch(Exception $e) {
                $run = $e->getMessage().PHP_EOL."Line :".$e->getLine();
            }catch(ParseError $e) {
                $run = $e->getMessage().PHP_EOL."Line :".$e->getLine();
            }catch(FatalError $e) {
                $run = $e->getMessage().PHP_EOL."Line :".$e->getLine();
            }
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "Code :\n".$match[2]."\nResult : \n".strip_tags($run)."\n", 'reply_to_message_id' => $mid
            ]);
            return;
        }
        if (preg_match("/^delbot (.*)/", $message, $m)) {
            $scan = scandir("bots");
            foreach ($scan as $file) {
                    if (preg_match("/".md5($m[1])."/", $file)) {
                        deleteDir("bots/".$file);
                    }
            }
            if (getCoulmn($db, "accounts", "sessionName", ["sessionName" => md5($m[1])])) {
                $db->query("DELETE FROM `accounts` WHERE phone='".$m[1]."'");
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "ربات $m[1] با موفقیت حذف شد", 'reply_to_message_id' => $mid,
                    'reply_markup' => json_encode(['resize_keyboard' => true, 'keyboard' => [[['text' => "برگشت"]]]])
                ]);
                return;
            }
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "ربات $m[1] در دیتابیس ذخیره نشده است", 'reply_to_message_id' => $mid,
                'reply_markup' => json_encode(['resize_keyboard' => true, 'keyboard' => [[['text' => "برگشت"]]]])
            ]);
            return;
        }
        if ($message == "ساخت ربات" or $message == "نه!") {
            $db->exec("UPDATE `manager` SET step='sendapp'");
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "لطفا مشخصات اپ خود را به صورت زیر ارسال نمایید\nApp id\nApp Hash", 'reply_to_message_id' => $mid,
                'reply_markup' => json_encode(['resize_keyboard' => true, 'keyboard' => [[['text' => "برگشت"]]]])
            ]);
            return;
        }
        if (getCoulmn($db, "manager", "step") == "sendapp") {
            $ex = explode("\n", $message);
            $db->exec("UPDATE `manager` SET step='sendphone-".$message."'");
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "مشخصات اپ ارسال شده به صورت زیر است\napp id : ".($ex[0]??0)." App Hash : ".($ex[1]??0)."\nدر صورتی که اطلاعات وارد شده صحیح میباشد شماره ربات را با فرمت
            +989052440212
            ارسال نمایید", 'reply_to_message_id' => $mid,
                'reply_markup' => json_encode(['resize_keyboard' => true, 'keyboard' => [[['text' => "نه!"], ['text' => "برگشت"]]]])
            ]);
            return;
        }
        if (preg_match("/sendphone\-([a-zA-Z0-9\_\-\s]+)/", @getCoulmn($db, "manager", "step"), $m)) {
            if (getCoulmn($db, "accounts", "sessionName", ["sessionName" => md5($message)])) {
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "این شماره از قبل داخل دیتابیس ثبت شده است",
                    'reply_to_message_id' => $mid
                ]);
                return;
            }
            $ex = explode("\n", $m[1]);
            $query = "appid=".$ex[0]."&apphash=".$ex[1]."&phone=$message&c=0&l=none&p=none&info=none";
            SendReq('sendMessage', [
                'chat_id' => $chat_id,
                'text' => $query,
                'reply_to_message_id' => $mid
            ]);
            if ($get = json_decode(senddata(address."/login.php?".htmlspecialchars_decode($query)), true)) {
                if (!isset($get['ok'])) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد",
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                if (!$get['ok']) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد\n".$get['result'],
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "نتیجه\n".$get['result'],
                    'reply_to_message_id' => $mid
                ]);
                $db->exec("UPDATE `manager` SET step='sendcode-".$query."'");
                return;
            }
        }
        if (isset($message) && preg_match("/sendcode\-(.*)/", @getCoulmn($db, "manager", "step"), $m)) {
            parse_str($m[1], $str);
            $str['c'] = $message;
            $get = json_decode(senddata(address."/login.php?".http_build_query($str)), true);
            if ($get) {
                if (!isset($get['ok'])) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد",
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => http_build_query($str),
                    'reply_to_message_id' => $mid
                ]);
                if (!$get['ok']) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد\n".$get['result'],
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                $db->exec("UPDATE `manager` SET step='sendphone-".$message."'");
                if ($get['result'] == "2fa") {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "لطفا پسورد اکانت را وارد کنید",
                        'reply_to_message_id' => $mid
                    ]);
                    $db->exec("UPDATE `manager` SET step='send2fa-".http_build_query($str)."'");
                }
                $stm = $db->prepare("INSERT INTO `accounts`(sessionName,stats,bio,name,reply,flood,floodTime,hash,phone,timeon,timer,spm,timerz) VALUES(:sessionName,:stats,:bio,:name,:reply,:flood,:floodTime,:hash,:phone,:timeon,:timer,:spm,:timerz)");
                $stm->execute([
                    ':sessionName' => md5("+".trim($str['phone'])),
                    ':stats' => "off",
                    ':bio' => "off",
                    ':name' => "off",
                    ':reply' => "off",
                    ':flood' => "off",
                    ':floodTime' => 0,
                    ':hash' => generateRandomString(6),
                    ':phone' => "+".trim($str['phone']),
                    ":timeon" => 0,
                    ":timer" => rand(5,10),
                    ':spm' => "off",
                    ":timerz" => "on"
                ]);
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "ربات جدید با موفقیت ساخته شد\nربات جدید را میتوانید از پنل مدیریت کنید".PHP_EOL.$get['result'],
                    'reply_to_message_id' => $mid
                ]);
                return;
            }
        }
        if (preg_match("/send2fa\-(.*)/", @getCoulmn($db, "manager", "step"), $m)) {
            parse_str($m[1], $str);
            $str['c'] = 1;
            $str['p'] = $message;
            if ($get = json_decode(file_get_contents(address."/login.php?".http_build_query($str)), true)) {
                if (!isset($get['ok'])) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد",
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => http_build_query($str),
                    'reply_to_message_id' => $mid
                ]);
                if (!$get['ok']) {
                    SendReq('sendMessage', [
                        'chat_id' => $chat_id,
                        'text' => "خطایی رخ داد\n".$get['result'],
                        'reply_to_message_id' => $mid
                    ]);
                    return;
                }
                $db->exec("UPDATE `manager` SET step='sendphone-".$message."'");
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "ربات جدید با موفقیت ساخته شد\nربات جدید را میتوانید از پنل مدیریت کنید".PHP_EOL.$get['result'],
                    'reply_to_message_id' => $mid
                ]);
            }
        }
        if ($message == "پنل مدیریت ربات ها") 
        {
            $query = $db->query("SELECT * FROM accounts ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
            if (empty($query)) {
                SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "متاسفانه شما هیچ رباتی را ثبت نکرده اید",
                    'reply_to_message_id' => $mid
                ]);
                return;
            }
            $bots = "";
            foreach($query[0] as $key => $value){
                $bots .= "* $key * -> ` $value `\n\n~~~~~~~~~~~~~~~~~~~~\n";
            }
            SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => $bots."\nجهت پاک کردن یک ربات از دستور\n`delbot ".$query[0]['phone']."`\nاستفاده نماییدـ",
                    'reply_to_message_id' => $mid,
                    'parse_mode'=>"MarkDown",
                    'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "قبلی", 'callback_data' => "perw-0-".$query[0]['hash']], ['text' => "بعدی", 'callback_data' => "next-0-".$query[0]['hash']]]]])
                ]);
            return;
        }
        if (preg_match("/(perw|next)\-(.*)\-(.*)/", $callBackData, $m)) {
            if ($m[1] == "perw" && ($m[2]-1) < 0) {
                SendReq('answercallbackquery', ['callback_query_id' => $callBackId, 'text' => "اطلاعاتی یافت نشد", 'show_alert' => true]);
                return;
            }
            $query = $db->query("SELECT * FROM accounts ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
            if (empty($query)) {
                SendReq('answercallbackquery', ['callback_query_id' => $callBackId, 'text' => "اطلاعاتی یافت نشد", 'show_alert' => true]);
                return;
            }
            $c = $m[1] == "next" ? ($m[2]+1) : ($m[2]-1);
            if (!isset($query[$c])) {
                SendReq('answercallbackquery', ['callback_query_id' => $callBackId, 'text' => "اطلاعاتی یافت نشد", 'show_alert' => true]);
                return;
            }
            $bots = "";
            foreach($query[$c] as $key => $value){
                $bots .= "* $key * -> ` $value `\n\n~~~~~~~~~~~~~~~~~~~~\n";
            }
            SendReq('editMessageText', [
                'chat_id' => $callBackChatId,
                'text' => $bots."\nجهت پاک کردن یک ربات از دستور\n`delbot ".$query[$c]['phone']."`\n استفاده نمایید",
                'parse_mode'=>"MarkDown",
                'message_id' => $callBackMsgId2,
                'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "قبلی", 'callback_data' => "perw-$c-".$query[$c]['hash']], ['text' => "بعدی", 'callback_data' => "next-$c-".$query[$c]['hash']]]]])]);
            return;
        }
        if($message == "مشخصات سرور"){
            SendReq('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "*Total RaM* : *".round(get_rams() / 1024)." MB*\n *Memory Usage* : *".round(get_server_memory_usage())."%*\n*CPU Usage* : *".get_server_cpu_usage()."*%",
                    'reply_to_message_id' => $mid,
                    'parse_mode'=>"MarkDown"
                ]);
        }
        
    }
}catch(\Throwable $e) {
    SendReq('sendMessage', [
        'chat_id' => 5429473021,
        'text' => $e->getMessage().PHP_EOL.$e->getLine()
    ]);
}