<?php
ob_start();

$API_KEY = '632497513:AAFRXljcay6Zs461is21alWvNgO_xXGnQEQ';
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);
    }
}

//// DB
$servername = "localhost";
$username = "biaradi1_pop";
$password = "SametPishr0";
$dbname = "biaradi1_pop";
$conn = new mysqli($servername, $username, $password, $dbname);
// END DB


function SendMessage($chatid,$text){
    bot('sendMessage',[
        'chat_id'=>$chatid,
        'text'=>$text,
    ]);
}

function SendAction($chat_id, $action){
	bot('sendchataction',[
	'chat_id'=>$chat_id,
	'action'=>$action
	]);
	}
	

function keyboard_maker($array){
    $counter = 0;
    $keyboard = [];
    while($row = $array[$counter]){
        $keyboard[$counter] = [['text' => $row]];
        $counter++;
    }
    return $keyboard;
}


function find_rank($array , $value){
    $counter = 0;
    foreach($array as $index){
        $counter++;
        if ( strval($index) == strval($value) )
            return $counter;
    }
        
}

function make_max($array,$parsed_json_score_sheet,$grade){
    foreach ($parsed_json_score_sheet as $key => $value){
        foreach($value as $rank){
            if($rank["object"] == "STUDENT")
                array_push($array,strval($rank[$grade]));
        }
    }
    rsort($array);
    return $array;
}

## Telegram Variables ##
$admins = [315799454,757232871];
$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;
$document = $message->document;
$first_name = $message->from->first_name;
$last_name = $message->from->last_name;
$username = $message->from->username;
$text = $message->text;
$file = $update->message->document->file_id;
## Telegram Variables ##


## MySQL Variables ##
$sql = "SELECT * FROM users WHERE chat_id = $from_id ";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$row_fname = $row["fname"];
$row_lname = $row["lname"];
$row_student_number = $row["student_number"];
$row_password = $row["password"];
$row_has_student_number = $row["has_student_number"];
$row_has_password = $row["has_password"];
$row_sending = $row["sending"];
## MySQL Variables ##

## Log ##
$new_log = "[" ."[".$from_id."]"."[".$username."]"."[".$first_name.' '.$last_name."]"."[".$text."]"."]";
$log_file = 'log.txt';
$old_logs = file_get_contents($log_file);
file_put_contents($log_file,$new_log ."\n".$old_logs);
## Log ##




if($text == '/start'){
    if($result->num_rows == 0){ // if new user --> sign him up
        $signUp = "INSERT INTO users (fname, lname, chat_id , student_number , password , has_student_number , has_password,sending)VALUES ('$first_name', '$last_name', '$from_id' , '0' , '0' , '0' , '0','0')";
        $conn->query($signUp);
        SendMessage($chat_id,'شماره دانشجویی خود را وارد کنید : ');
    }
    
    if($result->num_rows != 0){ // if enter /start for second time --> tell him his current student number
        bot('sendmessage',[
        	'chat_id'=>$chat_id,
        	'text'=>"شما هم اکنون با شماره دانشجویی $row_student_number وارد شده اید.\n گزینه مورد نظر خود را از کیبورد ربات وارد کنید : ",
            'parse_mode'=>'MarkDown',
        	'reply_markup'=>json_encode([
        	    'resize_keyboard'=>true,
        	    'one_time_keyboard'=>true,
        	    'keyboard'=>[[['text' => 'نمایش لیست افراد کلاس' ]],[['text' => 'ارسال پیام']]],
        	])  
    	]);
    }
}

else if($row_has_student_number == '0' && $row_has_password == '0'){
    $signUp = "UPDATE users SET student_number='$text' , has_student_number = '1' WHERE chat_id='$from_id' ";
    $conn->query($signUp);
    SendMessage($chat_id,"شماره دانشجویی شما ثبت شد.\nلطفا رمز عبور خود را وارد نمایید : ");
}

else if($row_has_student_number == '1' && $row_has_password == '0'){
    $signUp = "UPDATE users SET password='$text' , has_password = '1' WHERE chat_id='$from_id' ";
    $conn->query($signUp);
    SendMessage($chat_id,"رمز عبور شما ثبت شد. لطفا دوباره /start کنید!");
}

else if($text == '/resetme'){
    $signUp = "UPDATE users SET student_number='0' , password='0' , has_password='0' , has_student_number = '0' WHERE chat_id='$from_id' ";
    $conn->query($signUp);
    SendMessage($chat_id,"اطلاعات شما به حالت پیشفرض بازگشت!\nلطفا شماره دانشجویی خود را دوباره وارد کنید : ");
}

else if($text == "بازگشت⤴️"){
    bot('sendmessage',[
        	'chat_id'=>$chat_id,
        	'text'=>"گزینه مورد نظر خود را از کیبورد ربات وارد کنید : ",
            'parse_mode'=>'MarkDown',
        	'reply_markup'=>json_encode([
        	    'resize_keyboard'=>true,
        	    'one_time_keyboard'=>true,
        	    'keyboard'=>[[['text' => 'نمایش لیست افراد کلاس' ]],[['text'=>'ارسال پیام']]],
        	])  
    	]);
}

elseif($text == 'نمایش لیست افراد کلاس'){
    
    $names = [];
    array_push($names , 'بازگشت⤴️');
    $score_sheet_json = file_get_contents("scoresheet.json");
    $score_sheet_json_decode = json_decode($score_sheet_json, true);
    foreach ($score_sheet_json_decode as $key => $value){
        foreach($value as $student){
            $fullname = $student["SName"].' '.$student["SFName"];
            if($fullname != ' ')
                array_push($names , $fullname);
      
        }
    }
    array_push($names , 'بازگشت⤴️');
    $list_of_names = keyboard_maker($names);
    
    bot('sendmessage',[
    	'chat_id'=>$chat_id,
    	'text'=>"لطفا از بین اسامی زیر نام خود را انتخاب کنید : ",
        'parse_mode'=>'MarkDown',
    	'reply_markup'=>json_encode([
    	    'resize_keyboard'=>true,
    	    'one_time_keyboard'=>true,
    	    'keyboard'=>$list_of_names,
    	])  
	]);
}




elseif($text == '/getlog' &&  in_array($from_id,$admins) != false){
    bot('SendDocument',[
        'chat_id'=>$chat_id,
        'document'=>new CURLFile("log.txt"),
     ]);
}

elseif(isset($message->document) &&  in_array($from_id,$admins) != false && $message->document->file_name == 'reasons.json'){
    $document = $message->document;
    $file = $document->file_id;
    $get = bot('getfile',['file_id'=>$file]);
    $path = $get->result->file_path;
    file_put_contents('reasons.json',file_get_contents('https://api.telegram.org/file/bot'.$API_KEY.'/'.$path));
    SendMessage($chat_id,"reasons DB Upgraded Successfully!");
}

elseif(isset($message->document) &&  in_array($from_id,$admins) != false && $message->document->file_name == 'scoresheet.json'){
    $document = $message->document;
    $file = $document->file_id;
    $get = bot('getfile',['file_id'=>$file]);
    $path = $get->result->file_path;
    

    
    file_put_contents('scoresheet.json',file_get_contents('https://api.telegram.org/file/bot'.$API_KEY.'/'.$path));
    SendMessage($chat_id,"scoresheet DB Upgraded Successfully!");
}



elseif($text == 'ارسال پیام'){
    $sendingQuery = "UPDATE users SET sending='1' WHERE chat_id='$from_id' ";
    $conn->query($sendingQuery);
    SendMessage($chat_id,"لطفا پیام خود را ارسال کنید : ");
}

elseif($row_sending == '1'){
    bot('ForwardMessage',[
        'chat_id'=>315799454,//757232871
        'from_chat_id'=>$chat_id,
        'message_id'=>$message_id
    ]);
    bot('ForwardMessage',[
        'chat_id'=>757232871,//757232871
        'from_chat_id'=>$chat_id,
        'message_id'=>$message_id
    ]);
    SendMessage($chat_id,'پیام شما ارسال شد.');
    $sendingQuery = "UPDATE users SET sending='0' WHERE chat_id='$from_id' ";
    $conn->query($sendingQuery);
    
}


else{
    $json_file_score_sheet = file_get_contents("scoresheet.json");
    $parsed_json_score_sheet = json_decode($json_file_score_sheet, true);
    
    $json_file_reasons = file_get_contents("reasons.json");
    $parsed_json_reasons = json_decode($json_file_reasons, true);
    
    $valid_user = 0;
    
    //get student score sheet row
    foreach ($parsed_json_score_sheet as $key => $value){
        foreach($value as $student_score_sheet){
            if($text == $student_score_sheet["SName"].' '.$student_score_sheet["SFName"] && (($row_student_number == $student_score_sheet["StdNo"] && $row_password == $student_score_sheet["password"]) || in_array($from_id,$admins) != false))
            {
                $valid_user = 1;
                break;
            }
                    
            elseif($text == $student_score_sheet["SName"].' '.$student_score_sheet["SFName"] && ($row_student_number != $student_score_sheet["StdNo"] && $row_password == $student_score_sheet["password"]) )
                bot('sendMessage',[
                    'chat_id'=>$chat_id,
                    'text'=>"شماره دانشجویی وارد شده مطابقت ندارد.\nبرای تعویض اکانت دستور /resetme را وارد نمایید.",
                ]);
            elseif($text == $student_score_sheet["SName"].' '.$student_score_sheet["SFName"] && ($row_student_number == $student_score_sheet["StdNo"] && $row_password != $student_score_sheet["password"]) )
                bot('sendMessage',[
                    'chat_id'=>$chat_id,
                    'text'=>"رمز عبور وارد شده مطابقت ندارد.\nبرای تعویض اکانت دستور /resetme را وارد نمایید.",
                ]);
            elseif($text == $student_score_sheet["SName"].' '.$student_score_sheet["SFName"] && ($row_student_number != $student_score_sheet["StdNo"] && $row_password != $student_score_sheet["password"]) )
                bot('sendMessage',[
                    'chat_id'=>$chat_id,
                    'text'=>"شما به اطلاعات دیگران دسترسی ندارید 😊",
                ]);
            
        }
        
    }
    
    //get student reasons row
    foreach ($parsed_json_reasons as $key => $value){
        foreach($value as $student_reasons){
            if($text == $student_reasons["SName"].' '.$student_reasons["SFName"] && (($row_student_number == $student_reasons["StdNo"] && $row_password == $student_reasons["password"]) || in_array($from_id,$admins) != false))
                break;
        }
    }
    
    $ps1 = [];
    $ps1 = make_max($ps1 , $parsed_json_score_sheet , "PS1");
    
    $ps2 = [];
    $ps2 = make_max($ps2 , $parsed_json_score_sheet , "PS2");
    
    $qz1 = [];
    $qz1 = make_max($qz1 , $parsed_json_score_sheet , "QZ1");
    
    $qz2 = [];
    $qz2 = make_max($qz2 , $parsed_json_score_sheet , "QZ2");
    
    $qz3 = [];
    $qz3 = make_max($qz2 , $parsed_json_score_sheet , "QZ3");
    
    $hw1 = [];
    $hw1 = make_max($hw1 , $parsed_json_score_sheet , "HW1 AVG");
    
    $pacman = [];
    $pacman = make_max($pacman , $parsed_json_score_sheet , "Pacman");
    
    $ps8 = [];
    $ps8 = make_max($ps8 , $parsed_json_score_sheet , "PS8");
    
    $hw2 = [];
    $hw2 = make_max($hw2 , $parsed_json_score_sheet , "HW2 AVG");
    
    $hw3 = [];
    $hw3 = make_max($hw3 , $parsed_json_score_sheet , "HW3 AVG");
    
    $final = [];
    $final = make_max($final , $parsed_json_score_sheet , "FSCB");
    
    if(!empty($student_score_sheet["Pacman Bonus"]))
        $pacman_bonus = $student_score_sheet["Pacman Bonus"];
    else
        $pacman_bonus = 0;
    if($valid_user == 1){
        if($student_score_sheet["GSection"] == 1)
            $section = 'یک شنبه ها ساعت 16 تا 18';
        elseif($student_score_sheet["GSection"] == 2)
            $section = 'یک شنبه ها ساعت 18 تا 20';
        else
            $section = 'نا مشخص';
        SendMessage($chat_id,
                            "نام و نام خانوادگی : ".$student_score_sheet["SName"].' '.$student_score_sheet["SFName"]
                            .PHP_EOL.
                            "شماره دانشجویی : ".$student_score_sheet["StdNo"]

                            .PHP_EOL
                            .PHP_EOL
                            ."📊 Total grading report : \n\n"
                            
                            ."🆕 Total RAW: ".$student_score_sheet["FRS"]."/3".PHP_EOL
                            ."🆕 Total REPORTED : ".$student_score_sheet["FSCB"]."/3".PHP_EOL
                            ."🆕 Total RANK :  ".find_rank($final,$student_score_sheet["FSCB"]).PHP_EOL.PHP_EOL
                            
                            ."🔘 Problem Set 1: ".$student_score_sheet["PS1"]."%"." ( rank ".find_rank($ps1,$student_score_sheet["PS1"])." )".PHP_EOL
                            ."🔘 Problem Set 2: ".$student_score_sheet["PS2"]."%"." ( rank ".find_rank($ps2,$student_score_sheet["PS2"])." )".PHP_EOL
                            ."🔘 Problem Set 8: ".$student_score_sheet["PS8"]."%"." ( rank ".find_rank($ps8,$student_score_sheet["PS8"])." )".PHP_EOL.PHP_EOL
                            
                            ."🔘 Homework 1 : ".$student_score_sheet["HW1 AVG"]."%"." ( rank ".find_rank($hw1,$student_score_sheet["HW1 AVG"])." )".PHP_EOL
                            ."🔘 Homework 2 : ".$student_score_sheet["HW2 AVG"]."%"." ( rank ".find_rank($hw2,$student_score_sheet["HW2 AVG"])." )".PHP_EOL
                            ."🔘 Homework 3 : ".$student_score_sheet["HW3 AVG"]."%"." ( rank ".find_rank($hw3,$student_score_sheet["HW3 AVG"])." )".PHP_EOL.PHP_EOL
                            
                            ."🔘 Quiz 1: ".$student_score_sheet["QZ1"]."%"." ( rank ".find_rank($qz1,$student_score_sheet["QZ1"])." )".PHP_EOL
                            ."🔘 Quiz 2: ".$student_score_sheet["QZ2"]."%"." ( rank ".find_rank($qz2,$student_score_sheet["QZ2"])." )".PHP_EOL
                            ."🔘 Quiz 3: ".$student_score_sheet["QZ3"]."%"." ( rank ".find_rank($qz3,$student_score_sheet["QZ3"])." )".PHP_EOL.PHP_EOL
                            
                            ."🔘 Pacman Project: ".$student_score_sheet["Pacman"]." + $pacman_bonus"."%"." ( rank ".find_rank($pacman,$student_score_sheet["Pacman"])." )".PHP_EOL.PHP_EOL
                            
                            ."🔘 Midterm Bonus: ".$student_score_sheet["BonusMidterm"].PHP_EOL.PHP_EOL
                            
                            
                            
                            
                            );
        
        /*
        
        📈 Problem Set 1 grading report : ".PHP_EOL.(htmlentities($student_reasons["PS1"])).PHP_EOL.PHP_EOL.
                            "📈 Problem Set 2 grading report : ".PHP_EOL.(htmlentities($student_reasons["PS2"])).PHP_EOL.PHP_EOL.
                            "📈 Quiz 1 grading report : ".PHP_EOL.(("Q1 : \n".$student_score_sheet["QZ1Q1"].PHP_EOL.$student_reasons["QZ1Q1"].PHP_EOL."Q2 :".PHP_EOL.$student_score_sheet["QZ1Q2"].PHP_EOL.$student_reasons["QZ1Q2"])).PHP_EOL.PHP_EOL
                            
                            
        
        
        
        SendMessage($chat_id,
                            "📈 HW 3 grading report :"
                            .PHP_EOL.
                            "Q1 : ".$student_score_sheet["HW3Q1"]."%".PHP_EOL."Reasons : ".$student_reasons["HW3Q1"]
                            .PHP_EOL.
                            "Q2 : ".$student_score_sheet["HW3Q2"]."%".PHP_EOL."Reasons : ".$student_reasons["HW3Q2"]
                            .PHP_EOL.
                            "Q3 : ".$student_score_sheet["HW3Q3"]."%".PHP_EOL."Reasons : ".$student_reasons["HW3Q3"]
                            .PHP_EOL.
                            "Q4 : ".$student_score_sheet["HW3Q4"]."%".PHP_EOL."Reasons : ".$student_reasons["HW3Q4"]
                            .PHP_EOL.
                            "Q5 : ".$student_score_sheet["HW3Q5"]."%".PHP_EOL."Reasons : ".$student_reasons["HW3Q5"]
                        
                            
                            );
                     */       
                            
        
                            
        
    
    }

}



$conn->close();
unlink("error_log");
?>