<?php
ob_start();


//// DB
$servername = "localhost";
$username = "biaradi1_chdb";
$password = "SametPishr0";
$dbname = "biaradi1_chdb";

$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "DELETE FROM users WHERE chat_id = 0";
$result = $conn->query($sql);
$sql = "DELETE FROM users WHERE online_time = 0";
$result = $conn->query($sql);


///// DB End

$API_KEY = '787481346:AAFgiqd0K-VE7IALDIrAFnF8vZcGDinvrs4';
require_once dirname(__FILE__) . '/jdatetime.class.php';
$date = new jDateTime(true, true, 'Asia/Tehran');
define('API_KEY',$API_KEY);
function bot($method,$datas=[]){
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    if(curl_error($ch)){
        var_dump(curl_error($ch));
    }else{
        return json_decode($res);
    }
}
function SendMessage($chatid,$text,$parsmde,$keyboard,$message_id){
    bot('sendMessage',[
        'chat_id'=>$chatid,
        'text'=>$text,
        'parse_mode'=>$parsmde,
        'reply_markup'=>$keyboard,
        'message_id'=>$message->message_id
    ]);
}
function SendPhoto($chatid,$photo,$keyboard,$caption){
    bot('SendPhoto',[
        'chat_id'=>$chatid,
        'photo'=>$photo,
        'caption'=>$caption,
        'reply_markup'=>$keyboard
    ]);
}
function SendAudio($chatid,$audio,$keyboard,$caption,$sazande,$title){
    bot('SendAudio',[
        'chat_id'=>$chatid,
        'audio'=>$audio,
        'caption'=>$caption,
        'performer'=>$sazande,
        'title'=>$title,
        'reply_markup'=>$keyboard
    ]);
}
function SendDocument($chatid,$document,$caption){
    bot('SendDocument',[
        'chat_id'=>$chatid,
        'document'=>$document,
        'caption'=>$caption,
    ]);
}
function SendVoice($chatid,$voice,$keyboard,$caption){
    bot('SendVoice',[
        'chat_id'=>$chatid,
        'voice'=>$voice,
        'caption'=>$caption,
        'reply_markup'=>$keyboard
    ]);
}
function SendVideo($chat_id, $video, $caption){
    bot('SendVideo',[
        'chat_id'=>$chat_id,
        'video'=>$video,
        'caption'=>$caption
    ]);
}

function SendAction($chat_id, $action){
	bot('sendchataction',[
	'chat_id'=>$chat_id,
	'action'=>$action
	]);
	}
	
function Forward($berekoja,$azchejaei,$kodompayam)
{
bot('ForwardMessage',[
'chat_id'=>$berekoja,
'from_chat_id'=>$azchejaei,
'message_id'=>$kodompayam
]);
}

function is_sticker($message){
    if ($message->sticker == true)
        return true;
    return false;
}  


function SendSticker($chatid,$sticker,$keyboard){
	bot('SendSticker',[
	'chat_id'=>$chatid,
	'sticker'=>$sticker,
	]);
}

function setChatPhoto($chat_id,$photo){
	bot('setChatPhoto',[
	'chat_id'=>$chat_id,
	'photo'=>"http://www.myfaza2music.net/wp-content/uploads/2019/01/938-AlirezaPouya-MojezeyeEshgh.jpg",
	]);
}

function getFile($file_id){
    bot('getFile',[
        'file_id' => $file_id,
    ]);
}

function mentionAll(){
    $servername = "localhost";
    $username = "biaradi1_chdb";
    $password = "SametPishr0";
    $dbname = "biaradi1_chdb";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "SELECT* FROM users";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $out = '';
        while($row = $result->fetch_assoc()) {
            //<a href="tg://user?id=123456789">inline mention of a user</a>
            $row_chat_id = $row["chat_id"];
            $row_name = $row["fname"];
            $row_link = "\"tg://user?id=$row_chat_id\"";
            $data = "<a href=$row_link>$row_name</a>";
            $out .= $data."\n";
         }
         $conn->close();
         return $out;
    }
}


## Developed by : @erfaansabouri ##

$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$data = $update->callback_query->data;
$from_id = $message->from->id;
$chat_id = $message->chat->id;
$message_id = $message->message_id;
$message_id2 = $update->callback_query->message->message_id;

$sticker = $message->sticker;
$document = $message->document;
$entit = $message->entities;
$first_name = $message->from->first_name;
$last_name = $message->from->last_name;
$username = $message->from->username;
$text = $message->text;
$video = $update->message->video->file_id;
$voice = $update->message->voice->file_id;
$file = $update->message->document->file_id;
$music = $update->message->audio->file_id;
$rpto = $update->message->reply_to_message->forward_from->id;
$type = $update->message->chat->type;
$flag = file_get_contents("flag.txt");
$flag2 = file_get_contents("flag2.txt");
$self_done = false;
## Developed by : @erfaansabouri ##
$rand = rand(1,100);







//5 shanbe ha
if($flag == 1 && date("l") != "Thursday")
    file_put_contents("flag.txt",0);

if($flag == 0 && date("l") == "Thursday"){
    $day = $date->date("l");
    $out = "امروز"." $day "."سلفففففففففففففففففففففف";
    SendMessage($chat_id,mentionAll().PHP_EOL.$out,"HTML");
    file_put_contents("flag.txt",1);
}


// jome ha
if($flag2 == 1 && date("l") != "Friday")
    file_put_contents("flag2.txt",0);

if($flag2 == 0 && date("l") == "Friday"){
    $day = $date->date("l");
    $out = "امروز"." $day "."سلف بگیرید";
    SendMessage($chat_id,mentionAll().PHP_EOL.$out,"HTML");
    file_put_contents("flag2.txt",1);
}



if(stristr($text,"self")!= false || stristr($text,"سلف")!= false){
    bot('pinChatMessage',[
	'chat_id'=>$chat_id,
	'message_id'=>$message_id,
	]);
    SendMessage($chat_id,mentionAll().PHP_EOL."سلف بگیرید","HTML");
}

// Check connection
if ($conn->connect_error) {
    SendMessage($chat_id,$conn->connect_error);
    die("Connection failed: " . $conn->connect_error);
}


$sql = "SELECT chat_id,fname,lname FROM users WHERE chat_id = $from_id ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $path = "/home1/biaradi1/public_html/bots/chappe/users";
    $files = scandir($path);
    for($i = 0 ; $i<=count($files) ; $i++){
        if($files[$i] == "$from_id.txt"){
            $lines = file_get_contents(users."/$from_id.txt");
            $lines_a = file(users."/$from_id.txt");
            $online_time = round((strlen($lines) - 1)/60);
            $sent_msg = count($lines_a) - 1;
            break;
        }
        
    }
    while($row = $result->fetch_assoc()){
        $sql3 = "UPDATE users SET online_time='$online_time', sent_msg = '$sent_msg' WHERE chat_id='$from_id'";
        if ($conn->query($sql3) === TRUE);
    }
} 

else{
    $sql = "INSERT INTO users (fname, lname, username , chat_id)VALUES ('$first_name', '$last_name', '$username' , '$from_id')";
    $conn->query($sql);
}


if($text == '/all'){
    $sql = "SELECT * FROM users ORDER BY online_time DESC";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $out = '';
        $magham = 1;
        while($row = $result->fetch_assoc()) {
            $row_chat_fname = $row["fname"];
            $row_chat_online_time = $row["online_time"];
            $row_chat_sent_msg = $row["sent_msg"];
            $data = "📊 $row_chat_fname Status: \n⏱ Online Time : $row_chat_online_time Min.\n"."📩 Sent Message : $row_chat_sent_msg PM.";
            $out .="\n\n$magham - $data";
            $magham++;
         }
         SendMessage($chat_id,$out);
    }
}



if(($type == 'private' && is_sticker($message)) && ($chat_id == 315799454 || $chat_id == 748289829)){
    bot('SendSticker',[
	'chat_id'=>-1001306185954,
	'sticker'=>$sticker->file_id,
	]);
}



if($text != "/me" && $text != "chape" && $text != "/all" && $text != "Chape" && $text != "چپه" && $text != '/news') {  
    $myfile = fopen("users/".$from_id.".txt", "a");
    fwrite($myfile, $text."\n");
    fclose($myfile);
}
if($text == "/me"){
    $sql = "SELECT * FROM users WHERE chat_id=$from_id";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $row_chat_fname = $row["fname"];
            $row_chat_online_time = $row["online_time"];
            $row_chat_sent_msg = $row["sent_msg"];
            bot('sendMessage',[
            'chat_id'=>$chat_id,
            'parse_mode' =>'html',
            'text'=>"📊 <b>$row_chat_fname Status</b>: \n⏱ <b>Online Time :</b>".$row_chat_online_time." Min.\n📩 <b>Sent Message :</b>" .$row_chat_sent_msg. " PM.\nUp to now:\n" .$date->date("l j F Y H:i"),
            'message_id'=>$message->message_id
            ]);
         }
    }
}

function getLineWithString($fileName, $str , $container) {
    $lines = file(users."/$fileName");
    foreach ($lines as $lineNumber => $line) {
        if (stristr($line, $str) !== false) {
            array_push($container , $line);
        }
    }
    if(count($container) > 0)
        return $container;
}


if($rand % 5 == 0){
    
    
    $servername2 = "localhost";
    $username2 = "biaradi1_lines";
    $password2 = "SametPishr0";
    $dbname2 = "biaradi1_lines";
    
    $conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
    mysqli_set_charset($conn2,"utf8");
    $cword = count(explode(" ",$text));
    $to_search = explode(" ",$text)[rand(0,$cword-1)];
    $sql_search = "SELECT * FROM liness WHERE value LIKE '%$to_search%' ORDER BY RAND() LIMIT 1"; 
    $result_search = $conn2->query($sql_search);
    
    $sql_add_new = "INSERT INTO liness (value)VALUES ('$text')";
    $conn2->query($sql_add_new);
    
    
    if ($result_search->num_rows > 0) {
        while($row2 = $result_search->fetch_assoc()) {
            bot('sendMessage',[
            'chat_id'=>$chat_id,
            'parse_mode' =>'html',
            'text'=>$row2["value"],
            'message_id'=>$message_id,
            'reply_to_message_id' => $message->message_id
            ]);
         }
    }
    $conn2->close();

    /*
    $user_file = file(users."/$res");
    $random_line = rand(0,count($user_file)-1);
    
    $path2 = dirname(__FILE__) ."/users";
    $files2 = scandir($path2);
    $random_file2 = rand(3,10);
    $res2 = $files2[$random_file2];
    preg_replace( "/\r|\n/", "", $res2 );
    $user_file2 = file(users."/$res2");
    $random_line2 = rand(0,count($user_file2)-1);
    bot('sendMessage',[
        'chat_id'=>-1001306185954,
        'text'=>str_replace("\n", ' ', $user_file[$random_line].' '.$user_file2[$random_line2]),
        'message_id'=>$message->message_id,
    ]);
    
    */

}   

/*
function getAllLine($fileName , $container) {
    
    $servername2 = "localhost";
    $username2 = "biaradi1_lines";
    $password2 = "SametPishr0";
    $dbname2 = "biaradi1_lines";
    
    $conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
    mysqli_set_charset($conn2,"utf8");
    $lines = file(users."/$fileName");
    foreach ($lines as $lineNumber => $line) {
        $container++;
        $sql2 = "INSERT INTO liness (value)VALUES ('$line')";
        $conn2->query($sql2);
    }
    $conn2->close();

    return $container;
}


if($text == 'run'){
    
    $path = dirname(__FILE__) ."/users";
    $files = scandir($path);
    $container = [];
    for($i=2 ; $i<12 ; $i++){
        $res = $files[$i];
        preg_replace( "/\r|\n/", "", $res );
        $container = getAllLine($res, 0);
        bot('sendMessage',[
            'chat_id'=>$chat_id,
            'text'=>$container,
            'message_id'=>$message->message_id,
        ]);
    }
}

*/
$conn->close();


unlink("error_log");
?>