<?php 
 header("Access-Control-Allow-Origin: *");
date_default_timezone_set("Africa/Lagos");
function connect(){
$dbc = mysqli_connect("localhost", "bowensta_bowen", "80622BOWen") or die('No server');
	mysqli_select_db($dbc, "bowensta_sshub") or die('No db');
	return $dbc;

}




require "phpmailer/PHPMailerAutoload.php";


if (isset($_SESSION['staff_session'])) {
    $username = $_SESSION['staff_session'];

} else {
    header('Location:../../index.php');
    exit();
}
/*
function authenticate(){
$dbc = connect();
$buino = $_SESSION['staff_session'];
$hma = $_SESSION['username'];
$stat = 0;
 $query = "SELECT * FROM nonacadstaffs WHERE hashedbui='$hma' AND staffsId='$buino'";
 $run = mysqli_query($dbc, $query);
 if(mysqli_num_rows($run) >= 1){
	 $stat = 1;
 }
 return $stat;

}*/

function generatebursaryclearance(){
	
}







function numberofstaff(){
	$dbc =  connect();
	$query1  = "SELECT * FROM staffs";
	$run1 = mysqli_query($dbc, $query1);
	$num = mysqli_num_rows($run1);
	return $num;
}
function numberofstudents(){
	$dbc =  connect();
	$query1  = "SELECT * FROM students";
	$run1 = mysqli_query($dbc, $query1);
	$num = mysqli_num_rows($run1);
	return $num;
}
function numberofstudentsprovost($fac){
	$dbc =  connect();
	$query1  = "SELECT * FROM students WHERE faculty='$fac'";
	$run1 = mysqli_query($dbc, $query1);
	$num = mysqli_num_rows($run1);
	return $num;
}
function numberofstudentspc($dept){
	$dbc =  connect();
	$query1  = "SELECT * FROM students WHERE Departments_DepartmentCode='$dept'";
	$run1 = mysqli_query($dbc, $query1);
	$num = mysqli_num_rows($run1);
	return $num;
}

function numberofmycourses($staffid){
	$dbc =  connect();
	
	$query1  = "SELECT * FROM staff_course_mapping WHERE staff_id='$staffid' ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[2]);
	}
	return $list;
}

function staffunreadmessages($staffid){
	$dbc =  connect();
	$query1  = "SELECT * FROM mails WHERE receiver='$staffid' AND status='0'";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[1]);
	}
	return $list;
}

function allinbox($staffid){
	$dbc =  connect();
	$query1  = "SELECT * FROM mails WHERE receiver='$staffid' ORDER BY timesent DESC ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		$temp = array();
		array_push($temp, $row1[0], $row1[1], $row1[2],$row1[3], $row1[4], $row1[5], $row1[6], $row1[7]);
		array_push($list, $temp);
	}
	return $list;
}
function getmessagesnippet($msg){
	$result = mb_substr($msg, 0, 100);
	$result = $result."...";
	return $result;
}
function getmessagesnippet2($msg){
	$result = mb_substr($msg, 0, 50);
	$result = $result."...";
	return $result;
}

function getfullmail($id){
	$dbc =  connect();
	$query1  = "SELECT * FROM mails WHERE id='$id'";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[1], $row1[2],$row1[3], $row1[4], $row1[5], $row1[6], $row1[7] );
	}
	
	return $list;
}
function changemailstatus($id){
	$dbc = connect();
	mysqli_query($dbc, "UPDATE mails SET status = '1' WHERE id='$id'");
	keeplog("Read Email","Read email with ID-$id");
}

function aboutstaff($staffid){
	$dbc =  connect();
	$query1  = "SELECT * FROM nonacadstaffs WHERE staffsId='$staffid' ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[1], $row1[2], $row1[3], $row1[4], $row1[5], $row1[6], $row1[7], $row1[8], $row1[9], $row1[10], $row1[11], $row1[12], $row1[13], $row1[18], $row1[19], $row1[20]);
	}
	return $list;
}
function coursestoregister($studid, $level, $dept){
	//get all courses to that level
	
	$dbc = connect();
	$query2 = "SELECT * FROM courselevelid WHERE Departments_DepartmentCode = '$dept' AND Level_Levelid='$level' ORDER BY Elective ASC";
	$run2 = mysqli_query($dbc, $query2);
	
	//get carry over courses if exists
	
}

function keeplog($actionname,$message){
	$dbc= connect();
$deviceid = getdeviceip();
	
	mysqli_query($dbc, "INSERT into logs(action,actor,message deviceid) VALUES('$actionname','$username', '$message',  '$deviceid' )");
}

function login($username,$passkey){
	$actionname="login";
	//select username,salt,encryptedText,level? from students
	//try{
		//a>b? c : d
		//if(newstudent){
			//log($actionname,$username,$message);
			//redirect to changePassword($oldpassword,$username,$newpassword,$salt);
		//}
		//else if(notnewstudent){
			//log($actionname,$username,$message);
			//redirect to dashboard();
		//}
	//}
	//catch e{
		//log($actionname,$username,$message);
	//}
}

function changePassword($oldpassword,$username,$newpassword,$salt){
	$actionname="changePassword";
	//encryptPassword($newpassword);
	//update students.table ($newpassword) where studentsid is $ussername;
	//log($actionname,$username,$message);
}
function encryptPassword($password,$salt){
	//crypt($type,$salt,$enc,$password);
	//log($actionname,$username,$message);
}
function currentSemester(){
	$month=date('n');
	switch($month){
		case 1: return 0; //first semester
		case 9: return 0; //first semester
		case 10: return 0; //first semester
		case 11: return 0; //first semester
		case 12: return 0; //first semester
		case 2: return 1; //second semester
		case 3: return 1; //second semester
		case 4: return 1; //second semester
		case 5: return 1; //second semester
		case 6: return 1; //second semester
		case 7: return 2; //summer semester
		case 8: return 2; //summer semester
 	}
	
}
function currentSession(){
	$year=date('Y');
	$month=date('n');
	switch($month){
		case 9: return(($year).'/'.($year+1)); //current year and next year
		case 10: return(($year).'/'.($year+1)); //current year and next year
		case 11: return(($year).'/'.($year+1)); //current year and next year
		case 12: return(($year).'/'.($year+1)); //current year and next year
		case 1: return(($year-1).'/'.($year)); //previous year and current year
		case 2: return(($year-1).'/'.($year)); //previous year and current year
		case 3: return(($year-1).'/'.($year)); //previous year and current year
		case 4: return(($year-1).'/'.($year)); //previous year and current year
		case 5: return(($year-1).'/'.($year)); //previous year and current year
		case 6: return(($year-1).'/'.($year)); //previous year and current year
		case 7: return(($year-1).'/'.($year)); //previous year and current year
		case 8: return(($year-1).'/'.($year)); //previous year and current year
 	}
	
}
function assignRole($staffid,$username,$role){
	//username is actor, $staffid is the person whose role is to be changed
	//update staff.table ($role) where staffid=$staffid;
	//$actionname="assignRole";
	//$message="";
	//log($actionname,$username,$message);
}
function registerCourse(){
	/*
	Status: 0 - denied
			1 - approved
			2 - disapproved
	*/
}
function approveCourse(){
	
}

function getallsessions(){
	$dbc = connect();
	$query = "SELECT * FROM sessions ORDER BY session DESC";
	$run = mysqli_query($dbc, $query);
	$list = array();
	while($row = mysqli_fetch_row($run)){
		array_push($list, $row[1]);
	}
	return $list;
}

function getcourseforsession($session, $username){
	$dbc = connect();
	
	$list = array();
	$query = "SELECT * FROM staff_course_mapping WHERE session='$session' AND staff_id='$username'";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[2], $row[4], $row[5]);
		array_push($list, $temp);
	}
	return $list;
}

function getsemester($x){
 
	switch($x){
		case 0: return "First Semester";
		case 1: return "Second Semester";
		case 2: return "Summer Semester";
	}
}

function getcoursetitleandunit($cid){
	$dbc = connect();
	$query = "SELECT  title, Description, UNIT FROM course WHERE CourseID ='$cid'";
	$run = mysqli_query($dbc, $query );
	$list = array();
	while($row = mysqli_fetch_row($run)){
		array_push($list, $row[0],$row[1], $row[2] );
	}
	return $list;
}
function getcoursemodules($courseid, $username, $session){
	$dbc = connect();
	$query = "SELECT * FROM coursemodule WHERE Course_CourseID = '$courseid' AND session = '$session' AND lecturer = '$username'";
	$run = mysqli_query($dbc, $query);
	$list = array();
	while($row = mysqli_fetch_row($run)){
		array_push($list,$row[1]);
	}
	return $list;
}

function getrole($username, $session){
	$dbc = connect();
	$query1 = "SELECT role, level, department, college FROM lecturer_rolemapping WHERE staffid = '$username' AND session='$session'";
	$run = mysqli_query($dbc, $query1);
	$list = array();
	while($row = mysqli_fetch_row($run)){
		array_push($list, $row[0], $row[1], $row[2], $row[3]);
	}
	return $list;
}

function getmystudents($dept, $level){
	$dbc = connect();
	$query = "SELECT firstname, lastname, middlename,StudentsId, sex, phonenumber FROM students WHERE Departments_DepartmentCode='$dept' AND level='$level'";
	$run = mysqli_query($dbc, $query);
	
	$list = array();
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1], $row[2],$row[3], $row[4], $row[5]);
		array_push($list, $temp);
	}
	return $list;
}

function numberofcourseshod($dept){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM course WHERE Departments_DepartmentCode='$dept' ORDER BY level ASC";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1], $row[2], $row[3], $row[5], $row[6], $row[7]);
		array_push($list, $temp);
		
	}
	return $list;
}

function numberoflecturershod($dept){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM staffs WHERE Departments_DepartmentCode='$dept'";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[8], $row[9], $row[10]);
		array_push($list, $temp);
		
	}
	return $list;
}
function numberofprogramsprovost($coll){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM departments WHERE Faculty_FacultyCode1='$coll' ORDER BY DepartmentName ASC";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1]);
		array_push($list, $temp);
		
	}
	return $list;
}
function numberofprogramscolleges(){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM faculty ";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1]);
		array_push($list, $temp);
		
	}
	return $list;
}
function getpc($cid){
	$dbc = connect();
	$curs = currentSession();
	$query = "SELECT  staffid FROM lecturer_rolemapping WHERE department = '$cid' AND role = '2' AND session='$curs'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	try {
		$val = aboutstaff($row[0]);
		
		$txt = $val[0]." ".$val[1]." ".$val[2];
	return $txt;
	}
	catch (Exception $e){
		
	}
}

function getprovost($cid){
	$dbc = connect();
	$curs = currentSession();
	$query = "SELECT  staffid FROM lecturer_rolemapping WHERE college = '$cid' AND role = '1' AND session='$curs'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	try {
		$val = aboutstaff($row[0]);
		
		$txt = $val[0]." ".$val[1]." ".$val[2];
	return $txt;
	}
	catch (Exception $e){
		
	}
}

function numberofcolleges(){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM faculty";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1]);
		array_push($list, $temp);
		
	}
	return $list;
}



function mycoursespersession($staffid, $cur){
	$dbc =  connect();
	
	$query1  = "SELECT * FROM staff_course_mapping WHERE staff_id='$staffid' AND session='$cur' ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[2]);
	}
	return $list;
}

function studcoursesession($cid, $session){
	$dbc =  connect();
	$query = "SELECT * FROM studcourse WHERE session='$session' AND CourseLevelID_CLDID = '$cid' AND course_status='1'";
	$run = mysqli_query($dbc, $query);
	$list = array();
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[1], $row[5], $row[6], $row[7], $row[8]);
		array_push($list, $temp);
	}
	return $list;

}

function getcourselevelid($course){
	$dbc =  connect();
	$run = mysqli_query($dbc, "SELECT CLDID FROM courselevelid WHERE Course_CourseID = '$course'");
	return mysqli_fetch_row($run)[0];
}

function getgrade($x){

	 
		if($x >= 1 AND $x <= 44){
			return "F";
		}else if($x >= 45 AND $x <= 49){
			return "D";
		}
		else if($x >= 50 AND $x <= 59){
			return "C";
		}else if($x >= 60 AND $x <= 69){
			return "B";
		}else if($x >= 70 AND $x <= 100){
			return "A";
		}
		
		else{
			return "No Value";
		}
		
	
}

function getcurrentcgpa($x){
	return $x;
}


function assigncourse($id, $cid){
	$dbc =connect();
		$cur = currentSession();
		$sem = currentSemester();
	$query1 = "SELECT * FROM staff_course_mapping WHERE course_id= '$cid' AND session='$cur' AND staff_id='$id'";
	$run1 = mysqli_query($dbc, $query1);
	$row = mysqli_num_rows($run1);
	if($row > 0){
		
	}else {

	$query2 = "INSERT INTO staff_course_mapping(staff_id, course_id, session, semester) VALUES ('$id', '$cid', '$cur', '$sem')";
	$run2 = mysqli_query($dbc, $query2);
	keeplog("Assigned Course","Assigned course $cid to $id");
	//return "Done";
	}
	
}

function leveladviser($id, $level, $dept, $fac){
	$dbc =connect();
		$cur = currentSession();
	
	$query2 = "UPDATE lecturer_rolemapping SET role='3', level='$level' WHERE staffid='$id'";
	$run2 = mysqli_query($dbc, $query2);
	keeplog("Assigned Level Adviser","Assigned $level level adviser role to $id");
	return "Done";
	
}


function updateca($courseSrch, $coursesession, $ma, $ca ){
	$dbc =connect();
	$query1 = "UPDATE studcourse SET ca='$ca' WHERE Students_StudentsId = '$ma' AND session = '$coursesession' AND CourseLevelID_CLDID = '$courseSrch' AND ca_status ='Pending'";
	mysqli_query($dbc, $query1);
		keeplog("Updates ca","Updates ca score of Student - $ma course - $courseSrch to value $ca");
}
	function updateexam($courseSrch, $coursesession, $ma, $exam ){
		$dbc =connect();
		$query1 = "UPDATE studcourse SET exam='$exam' WHERE Students_StudentsId = '$ma' AND session = '$coursesession' AND CourseLevelID_CLDID = '$courseSrch' AND exam_status ='Pending'";
		
	mysqli_query($dbc, $query1);
		keeplog("Updates exam","Updates exam score of Student - $ma course - $courseSrch to value $exam");
	}
	
	function submitca($courseSrch, $coursesession, $ma, $ca ){
	$dbc =connect();
	$query1 = "UPDATE studcourse SET ca='$ca', ca_status='Submitted' WHERE Students_StudentsId = '$ma' AND session = '$coursesession' AND CourseLevelID_CLDID = '$courseSrch' AND ca_status ='Pending'";
	mysqli_query($dbc, $query1);
		keeplog("Submits CA ","Submits CA scores to Program Coordinator for  Student - $ma course - $courseSrch  value: $ca");
}
	function submitexam($courseSrch, $coursesession, $ma, $exam ){
		$dbc =connect();
		$query1 = "UPDATE studcourse SET exam='$exam', exam_status='Submitted' WHERE Students_StudentsId = '$ma' AND session = '$coursesession' AND CourseLevelID_CLDID = '$courseSrch' AND exam_status ='Pending'";
	mysqli_query($dbc, $query1);
	keeplog("Submits exam ","Submits exam scores to Program Coordinator for  Student - $ma course - $courseSrch value: $exam");
		
	}

define('FILE_ENCRYPTION_BLOCKS', 100000);
function encryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);
    $iv = openssl_random_pseudo_bytes(16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        // Put the initialzation vector to the beginning of the file
        fwrite($fpOut, $iv);
        if ($fpIn = fopen($source, 'rb')) {
            while (!feof($fpIn)) {
                $plaintext = fread($fpIn, 16 * FILE_ENCRYPTION_BLOCKS);
                $ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                // Use the first 16 bytes of the ciphertext as the next initialization vector
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $ciphertext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
function decryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        if ($fpIn = fopen($source, 'rb')) {
            // Get the initialzation vector from the beginning of the file
            $iv = fread($fpIn, 16);
            while (!feof($fpIn)) {
                $ciphertext = fread($fpIn, 16 * (FILE_ENCRYPTION_BLOCKS + 1)); // we have to read one block more for decrypting than for encrypting
                $plaintext = openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                // Use the first 16 bytes of the ciphertext as the next initialization vector
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $plaintext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
function getgcmarray($cid){
	$dbc = connect();
	$curs = currentSession();
	$query = "SELECT Students_StudentsId FROM studcourse WHERE CourseLevelID_CLDID = '$cid' AND session='$curs'";
	$list = array();
	while($row = mysqli_fetch_row($run)){
		
		array_push($list, $row[0]);
		
	}
	return $list;
}


function alert($message){
	return "<div class='alert alert-success alert-dismissible fade in' style='top:0; margin-top: -50px; width:40%; float: right; '>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>$message</strong>
  </div>";
}
function alert2($message){
	return "<div class='alert alert-success alert-dismissible fade in' >
    <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
    <strong>$message</strong>
  </div>";
}

function getmailattachments($id){
	$dbc = connect();
	$run1 = mysqli_query($dbc, "SELECT attachment FROM mails WHERE id='$id'");
	$row = mysqli_fetch_row($run1);
	return $row[0];
}

function getroledetails($rid){
	$dbc = connect();
	$run1 = mysqli_query($dbc, "SELECT roletitle FROM roles WHERE id='$rid'");
	$row = mysqli_fetch_row($run1);
	return $row[0];
	
}

function numberofcoursesassign($dept, $level){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM courselevelid WHERE Departments_DepartmentCode='$dept' AND Level_Levelid='$level'";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[0], $row[1], $row[2], $row[3], $row[5], $row[6], $row[7], $row[4]);
		array_push($list, $temp);
		
	}
	return $list;
}

function getcoursetolecturer($cid){
	$dbc = connect();
	$curs = currentSession();
	$query = "SELECT staff_id FROM `staff_course_mapping` WHERE `course_id` = '$cid' AND `session`='$curs'";
	$run = mysqli_query($dbc, $query);
	$list = array();
	while($row = mysqli_fetch_row($run)){
		$tet = aboutstaff($row[0]);
		$temp = array();
		array_push($temp, $tet[0], $tet[1], $tet[2], $tet[3], $tet[9], $row[0]);
		array_push($list, $temp);
		
	}
	return $list;
}

function checkifcourseisassigned($cid, $stid){
	$dbc = connect();
	$curs = currentSession();
	$query = "SELECT * FROM `staff_course_mapping` WHERE `course_id` = '$cid' AND `session`='$curs' AND staff_id='$stid'";
	$run = mysqli_query($dbc, $query);
	$num = mysqli_num_rows($run);
	if($num > 0){
		return 1;
	}else{
		return 0;
	}	
}

function deletecourse($cid, $staff_id){
	$dbc = connect();
	$curs = currentSession();
	$query = "DELETE FROM `staff_course_mapping` WHERE `staff_id`='$staff_id'  AND `course_id` ='$cid' AND `session` ='$curs' ";
	$run = mysqli_query($dbc, $query);
	
	keeplog("Remove ","Removes course form Lecturer $staff_id ");
	
	

}

function changeexam($cid, $sess, $val){
	$dbc = connect();
	
	$query = "UPDATE studcourse SET exam_status='$val' WHERE `session`='$sess'  AND `CourseLevelID_CLDID` ='$cid'";
	$run = mysqli_query($dbc, $query);
	keeplog("Updates exam  status","Updates exam status to $val");
	return $query;
}

function changeca($cid, $sess, $val){
	$dbc = connect();
	
	$query = "UPDATE studcourse SET ca_status='$val' WHERE `session`='$sess'  AND `CourseLevelID_CLDID` ='$cid'";
	$run = mysqli_query($dbc, $query);
	keeplog("Updates CA  status","Updates CA status to $val");
	return $query;
}


function getexamfiles($cid, $sess){
	$dbc = connect();
	$list = array();
	$query = "SELECT * FROM exfiles WHERE coursemodule='$cid' AND session='$sess'";
	$run = mysqli_query($dbc, $query);
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[1], $row[2], $row[3], $row[4], $row[5], $row[7], $row[9]);
		array_push($list, $temp);
		
	}
	return $list;
}
function aboutstudent($staffid){
	$dbc =  connect();
	$query1  = "SELECT * FROM students WHERE StudentsId='$staffid' ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		array_push($list, $row1[0], $row1[1], $row1[2], $row1[3], $row1[4], $row1[5], $row1[6], $row1[7], $row1[8], $row1[9], $row1[10], $row1[11], $row1[12], $row1[13], $row1[14]);
	}
	keeplog("Student Profile","Checks profile of student: $staffid");
	return $list;
}

function studcourse($sid, $sess, $sem){
	$dbc =  connect();
	$query1  = "SELECT * FROM studcourse WHERE Students_StudentsId='$sid' AND session='$sess' AND semester='$sem'";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		$temp = array();
		array_push($temp, $row1[2], $row1[5], $row1[6], $row1[11], $row1[0] , $row1[11]);
		array_push($list, $temp);
	}
	return $list;
}

function previoussession($x){
	
	$set = currentSession();
	$set1 = substr($set,0,4);
	$set2 = substr($set,5,8);
	$set1 = $set1 - $x;
	$set2 = $set2 - $x;
	$pset = $set1."/".$set2;
	return $pset;
}
function getcourse($course){
	$dbc =  connect();
	$query = "SELECT Course_CourseID FROM courselevelid WHERE CLDID = '$course'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	$list = getcoursetitleandunit($row[0]);
	array_push($list, $row[0]);
	return $list;

}
function coursewgp($unit, $grade){
	if($grade == "A"){
		return $unit * 5;
	}else if($grade == "B"){
		return $unit * 4;
	}else if($grade == "C"){
		return $unit * 3;
	}else if($grade == "D"){
		return $unit * 2;
	}else if($grade == "E"){
		return $unit * 1;
	}else if($grade == "F"){
		return $unit * 0;
	}
	
	
}

function coursegradepoint($grade){
	switch($grade){
		case "A": return 5;
		case "B": return 4;
		case "C": return 3;
		case "D": return 2;
		case "E": return 1;
		case "F": return 0;
		
	}
}

function getlastseen($username){
	$dbc = connect();
	$run = mysqli_query($dbc, "SELECT lastseen FROM logs WHERE actor='$username' AND action='Logout' ORDER BY actiontime DESC LIMIT 1");
	$row= mysqli_fetch_row($run);
	
	$dt = date("Y-m-d - H:i:s", $row[0]);
	return $dt;
}

function updatecoursestatus($cid, $action){
	$dbc = connect();
	if($action == "approve"){
		mysqli_query($dbc, "UPDATE studcourse SET course_status='1' WHERE StudCourseID='$cid'");
	keeplog("Student Course","Approves $cid ");
	}else{
		mysqli_query($dbc, "DELETE FROM studcourse WHERE StudCourseID='$cid'");
		keeplog("Student Course","Disapproves $cid ");
	}
}

function checkapprovedcourses($sid, $sess, $sem){
	$dbc = connect();
	$query = "SELECT * FROM studcourse WHERE Students_StudentsId = '$sid' AND session='$sess' AND $sem='0' AND course_status='0'";
	$run = mysqli_query($dbc, $query);
	$num = mysqli_num_rows($run);
	return $num;
}
function checkapprovedcourses2($sid, $sess, $sem){
	$dbc = connect();
	$query = "SELECT * FROM studcourse WHERE Students_StudentsId = '$sid' AND session='$sess' AND $sem='0' AND course_status='1'";
	$run = mysqli_query($dbc, $query);
	$num = mysqli_num_rows($run);
	return $num;
}

function getstudsta($stid, $sess, $sem){
	
	$list = studcourse($stid, $sess, $sem);
	$numc = 0;
	$numcre = 0;
	foreach($list as $li){
		if($li[5] == 1){
			$numc++;
			$numcre += getcoursetitleandunit((getcourse($li[0])[3]))[2];
		
			
		}
	}
return "$numc courses - $numcre credits";
}


function numstudcoursesreg($level, $dept, $sem){
	$sess = currentSession();
	$mystudents = getmystudents($dept, $level);
	$regstud = 0;
	$nregstud = 0;
	foreach($mystudents as $student){
	$sid = $student[3];
	
	$app = checkapprovedcourses2($sid, $sess, $sem);

	if($app != 0){
		
		$regstud++;
		}
	
	
	
	}
	return $regstud;
}
function numstudcoursesnonreg($level, $dept, $sem){
	$sess = currentSession();
	$mystudents = getmystudents($dept, $level);
	$regstud = 0;
	$nregstud = 0;
	foreach($mystudents as $student){
	$sid = $student[3];
	
	$app = checkapprovedcourses($sid, $sess, $sem);
	
		if($app != 0){
		$regstud++;
		}
	
	
	
	
	}
	return $regstud;
}

function mailstudentcourse($stid, $message){
	$dbc = connect();
	$query = "SELECT email FROM students WHERE StudentsId = '$stid'";
	$run = mysqli_query($dbc, $query);
	$row =  mysqli_fetch_row($run);
	$email = $row[0];
	
	



	$to   = $email;
    $from = 'bowenapp@sshubapp.com';
    $name = 'Bowen University';
    $subj = 'Course Registration Approval Status';
    $msg = $message;
    
    $error=smtpmailer($to,$from, $name ,$subj, $msg);

return $error;

}




function getdeviceip(){
	// Get real visitor IP behind CloudFlare network
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
              $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
              $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}



function smtpmailer($to, $from, $from_name, $subject, $body)
    {
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; 
 
        $mail->SMTPSecure = 'ssl'; 
        $mail->Host = 'sshubapp.com';
        $mail->Port = 465;  
        $mail->Username = 'bowenapp@sshubapp.com';
        $mail->Password = '80622FUNbi';   
   
   //   $path = 'reseller.pdf';
   //   $mail->AddAttachment($path);
   
        $mail->IsHTML(true);
        $mail->From="bowenapp@sshubapp.com";
        $mail->FromName=$from_name;
        $mail->Sender=$from;
        $mail->AddReplyTo($from, $from_name);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AddAddress($to);
        if(!$mail->Send())
        {
            $error ="Please try Later, Error Occured while Processing... If Error Persists, Please Contact Directorate of Digital Services";
            return $error; 
        }
        else 
        {
            $error = "Thanks You !! Memo Sent Successfully";  
            return $error;
        }
    }
    
    function sendnotification($course, $typ){
	$title = 'Bowen University';

	$body = "You have a new $typ for $course. Click for more";
	 
	 $dateSent= date("Y-m-d h:i:sa");
	$clid = getcourselevelid($course);
	$gcms = getgcm($clid);
	
	$conn = connect();
	//pick from db
	define('GOOGLE_API_KEY', 'AAAA-4qulbs:APA91bGBRWCq8g1hiEwfvYLyYiCRr-y7HU8dm05ABKkxEoipmyEGx5Z4GYsHhihXmHXKtxkX3R6WatISaiRj7n3nCP2dtliH0Edh1X19FbJXtWkhSI4FrWb7-19yGbCKBKKl1YNI5MwP');
	  $message = array('title' => $title,'body'=>$body,'date'=>$dateSent,'type'=>'1');
        $notification = array('title' => $title,'body'=>$body,'date'=>$dateSent);
        $pushStatus = sendPushNotification($gcms, $message,$notification);
	return $pushStatus;
	 
	}
	
	
	
	function sendPushNotification($registration_ids, $message,$notification) {
            // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';
		$fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
            'priority'=> 'high',
            'notification'=> $notification,
        );
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();
 
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
		curl_setopt($ch,CURLOPT_SSLVERSION,6);
       // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
 
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        // Close connection
        curl_close($ch);
		return $result;
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function getgcm($course){
		$dbc = connect();
		$curss = currentSession();
		$query = "SELECT Students_StudentsId FROM studcourse WHERE 	CourseLevelID_CLDID = '$course' AND session='$curss' AND course_status = '1'";
		$run = mysqli_query($dbc, $query);
		$gcms = array();
		while($row = mysqli_fetch_row($run)){
			$query2 = "SELECT gcm_device_token FROM students WHERE StudentsId='$row[0]'";
			$run2 = mysqli_query($dbc, $query2);
			while($row2 = mysqli_fetch_row($run2)){
				array_push($gcms, $row2[0]);
			}
			
		}
return $gcms;
		}
    
    
    
    function allsent($staffid){
	$dbc =  connect();
	$query1  = "SELECT * FROM mails WHERE sender='$staffid' ORDER BY timesent DESC ";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row1 = mysqli_fetch_row($run1)){
		$temp = array();
		array_push($temp, $row1[0], $row1[1], $row1[2],$row1[3], $row1[4], $row1[5], $row1[6], $row1[7]);
		array_push($list, $temp);
	}
	return $list;
}
function getcoursename($code){
    $dbc = connect();
    $query = "SELECT DepartmentName FROM departments WHERE DepartmentCode ='$code'";
    $run = mysqli_query($dbc, $query);
    $row = mysqli_fetch_row($run);
    return $row[0];
}

function getcoursefaculty($code){
    $dbc = connect();
    $query = "SELECT FacultyName FROM faculty WHERE FacultyCode ='$code'";
    $run = mysqli_query($dbc, $query);
    $row = mysqli_fetch_row($run);
    return $row[0];
}

function cookiemail($username){
    $dbc = connect();
    $query = "SELECT `email` FROM staffs WHERE `staffsId` = '$username'";
    $run = mysqli_query($dbc, $query);
    $row = mysqli_fetch_row($run);
    
    $to   = $row[0];
    $from = 'bowenapp@sshubapp.com';
    $name = 'Bowen University';
    $subj = 'Security Check';
    $msg = "Good day. We realised another device just logged into your portal. Please contact the Directorate of Digital Services if there is a security threat else ignore this message. Thanks";
    
    $error=smtpmailer($to,$from, $name ,$subj, $msg);
    return $error;
}
function deletecoursefromlevel($id, $id2){
    $dbc = connect();
    $sess = currentSession();
    $query1 = "SELECT `CLDID` FROM `courselevelid` WHERE `Course_CourseID` = '$id' AND Departments_DepartmentCode='$id2' AND session = '$sess'";
    $run1 = mysqli_query($dbc, $query1);
    $row1 = mysqli_fetch_row($run1);
    $cid = $row1[0];
    
    
    $query2 = "DELETE FROM `studcourse` WHERE `ca` IS NULL AND `exam` IS NULL AND `CourseLevelID_CLDID` = '$cid'";
     mysqli_query($dbc, $query2);
    $query3 = "DELETE FROM `courselevelid` WHERE `CLDID` = '$cid'";
        mysqli_query($dbc, $query3);
        
    
    
    
    return "Delete Successful";
 
}

function editcourse($cid, $title, $des, $unit){
    $dbc = connect();
    $query1 = "UPDATE `course` SET `title`='$title',`Description`='$des',`UNIT`='$unit' WHERE `CourseID`='$cid'";
    mysqli_query($dbc, $query1);
}




function getcoursequiz($cid){
		
		$dbc = connect();
		$list2 = array();
			$query = "SELECT * FROM `quiz` WHERE `module_id`='$cid'";
			$run = mysqli_query($dbc, $query);
			while($row = mysqli_fetch_row($run)){
			$temp = array();
			array_push($temp, $row[0],$row[1],$row[2],$row[3], $row[7] );
			array_push($list2, $temp);
			}
		

	return $list2;

	}
	
	function getquizquestion($cid){
		$dbc = connect();
		$list = array();
		$query = "SELECT * FROM questions WHERE quiz_ID='$cid'";
		$run = mysqli_query($dbc, $query);
		while($row = mysqli_fetch_row($run)){
			$temp = array();
			array_push($temp, $row[0],$row[1],$row[2],$row[3],$row[4], $row[5], $row[6], $row[7]);
			array_push($list, $temp);
		}
		
		return $list;
	}
	function checkquiz($cid){
		$dbc = connect();
		$query = "SELECT * FROM questions WHERE quiz_ID='$cid'";
		$run = mysqli_query($dbc, $query);
		$row = mysqli_num_rows($run);
		return $row;
	}
	
	
	function encryptresult($data){
		$token = $data;
		$cipher_method = 'aes-128-ctr';
		$enc_key = "thisis!salt.for?bowen/uni#for&result!`processing+.?";
		$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
		$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
		return $crypted_token;
	}
	
	function decryptresult($crypted_token){
		list($crypted_token, $enc_iv) = explode("::", $crypted_token);;
		$cipher_method = 'aes-128-ctr';
		$enc_key = "thisis!salt.for?bowen/uni#for&result!`processing+.?";
		$token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
		return $token;
	}
	
	function getsignature($sid){
		$dbc = connect();
		
		$query = "SELECT * FROM `signatures` WHERE `staffid`='$sid'";
		$run = mysqli_query($dbc, $query);
		if($row = mysqli_fetch_row($run)){
			return $row[2];
		}else{
			return Null;
		}
		
	}
	
	function getlevels($dept){
		$dbc = connect();
		
		$query = "SELECT levels FROM `departments` WHERE `DepartmentCode`='$dept'";
		$run = mysqli_query($dbc, $query);
		$row =  mysqli_fetch_row($run);
		return $row[0];
		
		
		
	}
	
	function savememo($username, $receivers, $message, $title){
		$dat =  date("d-M-Y H:i:s"); 
		$dbc = connect();
$query = "INSERT INTO `memo`(`sender`, `receiver`, `message`, `title`, `time`) VALUES ('$username', '$receivers', '$message', '$title', '$dat')";
mysqli_query($dbc, $query);

return "$query";
		
		
		
		
	}
	
	function getinmemo($user){
		$dbc = connect();
		$query = "SELECT * FROM memo WHERE receiver='$user' ORDER BY id DESC";
		$run = mysqli_query($dbc, $query);
		$list = array();
		while($row = mysqli_fetch_row($run)){
			$temp = array();
			array_push($temp, $row[0], $row[1], $row[2], $row[4], $row[5]);
			array_push($list, $temp);
		}
		return $list;
	}
	
	function insertsignature($path, $user){
		$dbc = connect();
		$query = "INSERT INTO `signatures`(`staffid`, `signature`) VALUES ('$user', '$path')";
		mysqli_query($dbc, $query);
	}
	
	function getmemo($id){
		$dbc = connect();
		$query = "SELECT * FROM memo WHERE id='$id' ORDER BY id DESC";
		$run = mysqli_query($dbc, $query);
		$row = mysqli_fetch_row($run);
		mysqli_query($dbc, "UPDATE memo SET status='1' WHERE id='$id'");
		
		return $row;
		
	}
	function getsentmemo($user){
		$dbc = connect();
		$query = "SELECT * FROM memo WHERE sender='$user' ORDER BY id DESC";
		$run = mysqli_query($dbc, $query);
		$list = array();
		while($row = mysqli_fetch_row($run)){
			$temp = array();
			array_push($temp, $row[0], $row[1], $row[2], $row[4], $row[5]);
			array_push($list, $temp);
		}
		return $list;
	}
	
		function numberofmemo($user){
	    	$dbc = connect();
		$query = "SELECT id FROM memo WHERE sender='$user' AND status='0'";
		$run = mysqli_query($dbc, $query);
		$num = mysqli_num_rows($run);
		return $num;
		
	}
	
	function changememostatus($id){
	    $dbc = connect();
		$query = "UPDATE memo status='0' WHERE id='$id'";
		$run = mysqli_query($dbc, $query);
		

	    
	}
	
	function checklead($lec, $cid){
	    $dbc = connect();
	    $sess = currentSession();
	    $sem = currentSemester();
	    $query= "SELECT status FROM `staff_course_mapping` WHERE `staff_id`='$lec' AND `course_id` = '$cid' AND `session` = '$sess' AND `semester` = '$sem'";
	    $run = mysqli_query($dbc, $query);
	    while($row = mysqli_fetch_row($run)){
	        if($row[0] == 1){
	            return "Lead Lecturer";
	        }else{
	            return "Support Lecturer";
	        }
	    }
	   
	}
	
	function assignleadrole($lec, $cid){
	    $dbc = connect();
	    $sess = currentSession();
	    $sem = currentSemester();
	   
	    $query= " UPDATE `staff_course_mapping` SET status='0' WHERE `course_id` = '$cid' AND `session` = '$sess' AND `semester` = '$sem'";
	    $run = mysqli_query($dbc, $query);
	    
	    $query= " UPDATE `staff_course_mapping` SET status='1' WHERE `staff_id`='$lec' AND `course_id` = '$cid' AND `session` = '$sess' AND `semester` = '$sem'";
	    $run = mysqli_query($dbc, $query);
	    return mysqli_error($dbc);
	    
	}


function getcourseforexam($dept, $level, $sem, $session){
		$dbc = connect();
		$query = "SELECT * FROM courselevelid WHERE Departments_DepartmentCode='$dept' AND Level_Levelid='$level' AND ";
	}

function buildca($clid, $ma, $ca){
	$dbc = connect();
	$query = "SELECT `ca` FROM `studcourse` WHERE `Students_StudentsId` = '$ma' AND `CourseLevelID_CLDID` ='$clid'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	$rel = $row[0];
	if($rel == NULL){
		$result = array();
		array_push($result, $ca);
		$relt = json_encode($result);
		$val = encryptresult($relt);
		
	}else{
		$dep = decryptresult($rel);
		$result = json_decode($dep);
		if(end($result) != $ca){
			array_push($result, $ca);
			$relt = json_encode($result);
		}else{
			$relt = json_encode($result);
		}
		$val = encryptresult($relt);
		
	}
return $val;	
}

function buildexam($clid, $ma, $ca){
	$dbc = connect();
	$query = "SELECT `exam` FROM `studcourse` WHERE `Students_StudentsId` = '$ma' AND `CourseLevelID_CLDID` ='$clid'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	$rel = $row[0];
	if($rel == NULL){
		$result = array();
		array_push($result, $ca);
		$relt = json_encode($result);
		$val = encryptresult($relt);
		
	}else{
		$dep = decryptresult($rel);
		$result = json_decode($dep);
		if(end($result) != $ca){
			array_push($result, $ca);
			$relt = json_encode($result);
		}else{
			$relt = json_encode($result);
		}
		$val = encryptresult($relt);
		
	}
return $val;	
}

function lookupcourse($coursecode, $dept){
	$dbc = connect();
	$query = "SELECT * FROM `course` WHERE `CourseID` ='$coursecode' AND `Departments_DepartmentCode` = '$dept'";
	$run = mysqli_query($dbc, $query);
	if(mysqli_num_rows($run) > 0){
		return true;
	}else{
		return false;
	}
	
}
function numberofstudentsexam($dept, $level){
	$dbc =  connect();
	$query1  = "SELECT * FROM students WHERE Departments_DepartmentCode='$dept' AND level='$level'";
	$run1 = mysqli_query($dbc, $query1);
	$list = array();
	while($row = mysqli_fetch_row($run1)){
		array_push($list, $row[0]);
	}
	return $list;
}
function checkcourseresult($matric, $course){
	$dbc = connect();
	//check if student has complete payment else proceed to the following 

	$query = "SELECT `ca`, `exam`, `ca_status`, `exam_status` FROM `studcourse` WHERE CourseLevelID_CLDID= '$course' AND Students_StudentsId='$matric' ";
	$run = mysqli_query($dbc, $query);
	if(mysqli_num_rows($run) > 0){
	while($row = mysqli_fetch_row($run)){
		if($row[2] >= 3 AND $row[3] >= 3){
			if($ca = decryptresult($row[0]) AND $exam = decryptresult($row[1])){
			$ca = json_decode($ca);
			$exam = json_decode($exam);
			
			$total = end($ca)+end($exam);
			$grade = getgrade($total);
		return "$total"."$grade";
		}else{
			return "RNA";
		}
		}else{
			return "RNA";
		}
	}
	}else{
		return "NR";
	}
	
	
}

function approvelevelresult($dept, $level, $x){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	
	
	$query = "INSERT INTO `approvedresult`(`dept`, `level`, `session`, `status`, `semester`) VALUES ('$dept','$level','$sess','$x', '$sem')";
	
	$run = mysqli_query($dbc, $query);
	if(mysqli_affected_rows($run) <= 0){
		$query = "UPDATE `approvedresult` SET status ='$x' WHERE dept = '$dept'  AND level ='$level' AND session ='$sess' AND semester ='$sem'";
	
	$run = mysqli_query($dbc, $query);
	}
	
	
}
function updatelevelresult($dept, $level, $x){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$query = "UPDATE `approvedresult` SET `status`='$x' WHERE dept = '$dept' AND level = '$level' AND session ='$sess' AND `semester`='$sem'";
	
	mysqli_query($dbc, $query);
	return $query;
	
}

function qcheck($dept, $level){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$query = "SELECT status FROM approvedresult WHERE dept='$dept' AND level='$level' AND session='$sess' AND semester='$sem'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	if(mysqli_num_rows($run) > 0){
		if($row[0] == 0){
			return true;
		}else{
			return false;
		}
	}else if(mysqli_num_rows($run) == 0) {
		return true;
	}
	
}

function senatecheck($dept, $level){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$query = "SELECT status FROM approvedresult WHERE dept='$dept' AND level='$level' AND	session='$sess' AND semester='$sem'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	if(mysqli_num_rows($run) > 0){
		if($row[0] >= 1){
			return true;
		}else{
			return false;
		}
	}
	
}

function senatecheckbuttons($dept, $level){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$query = "SELECT status FROM approvedresult WHERE dept='$dept' AND level='$level' AND	session='$sess' AND semester='$sem'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	if(mysqli_num_rows($run) > 0){
		if($row[0] == 1 OR $row[0] == 2){
			return true;
		}else{
			return false;
		}
	}
	
}

function pcavailable($dept, $cid){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$prequery = "SELECT * FROM delibrate WHERE type='Programme' AND cat='$dept' AND item='$cid' AND status = '1' AND session='$sess' AND semester='$sem'";
	$run = mysqli_query($dbc, $prequery);
	
	if(mysqli_num_rows($run) <= 0){
		 $queryu = "UPDATE delibrate SET status='0' WHERE type='Programme' AND cat='$dept' AND session='$sess'  AND semester='$sem'";
		mysqli_query($dbc, $queryu);
		
		
		$query = "INSERT INTO `delibrate`(`type`, `cat`, `item`, `status`, `session`, `semester`) VALUES ('Programme', '$dept', '$cid', '1', '$sess', '$sem')";
		mysqli_query($dbc, $query);
		
	}
	
	
}


function sendcomments($message, $cid){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$date = date("d/m/Y H:i:s");
	$lecid = getcoursetolecturer2($cid);
	$username = $_SESSION['staff_session'];
	foreach($lecid as $lid){
	$query = "INSERT INTO `disapprovedcomments`(`cid`, `comments`, `session`, `semester`, `status`, `sender`, `receiver`, `datesent`) VALUES ('$cid', '$message', '$sess', '$sem', '0', '$username', '$lid[5]', '$date')";
	$run = mysqli_query($dbc, $query);
	}
	
	
}


function checkexamcommentsformeandoutput($cid){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$username = $_SESSION['staff_session'];
	$query = "SELECT * FROM disapprovedcomments WHERE receiver='$username' AND cid='$cid' ORDER BY datesent ASC";
	$run = mysqli_query($dbc, $query);
	$list = array();
	if(mysqli_num_rows($run) > 0){
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[2], $row[8]);
		array_push($list, $temp);
	}
	return $list;
	}else{
		return 0;
	}

	
}
function checkexamcommentsviewandoutput($cid){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$username = $_SESSION['staff_session'];
	$query = "SELECT * FROM disapprovedcomments WHERE cid='$cid'";
	$run = mysqli_query($dbc, $query);
	if(mysqli_num_rows($run) > 0){
		return true;
	}else{
		return false;
	}

	
}


function getlasttwo($at){
	$t = count($at);
	$t--;
	
	$current = $at[$t];
	$t--;
	$previous = $at[$t];
	$list = array($previous, $current);
	return $list;
}

function checkexamcommentspreviewandoutput($cid){
	$dbc = connect();
	$sess = currentSession();
	$sem = currentSemester();
	$username = $_SESSION['staff_session'];
	$query = "SELECT * FROM disapprovedcomments WHERE cid='$cid' AND sender='$username' ORDER BY datesent ASC";
	$run = mysqli_query($dbc, $query);
	$list = array();
	if(mysqli_num_rows($run) > 0){
	while($row = mysqli_fetch_row($run)){
		$temp = array();
		array_push($temp, $row[2], $row[8], $row[7]);
		array_push($list, $temp);
	}
	return $list;
	}else{
		return 0;
	}

	
}

function getcoursesummary($grade, $cid, $det){
	$gradecount = 0;
	foreach($det as $dat){
		$dat[1] = decryptresult($dat[1]);
		$temp = json_decode($dat[1]);
		
		$dat[2] = decryptresult($dat[2]);
		$temp = json_decode($dat[2]);
		
		$temp1 = json_decode($dat[1]);
		$temp1 = end($temp1);
		
		$temp2 = json_decode($dat[2]);
		$temp2 = end($temp2);
		
		
		if(getgrade($temp1 + $temp2) == $grade){
			$gradecount++;
		}
	}
	
	return $gradecount;
}

function gennumstud(){
    $dbc = connect();
    $query = "SELECT * FROM students";
    $run = mysqli_query($dbc, $query);
    $num = mysqli_num_rows($run);
    
    return $num;
    
}

function numberofhostel($gender){
    $dbc = connect();
    $query = "SELECT * FROM hostels WHERE type ='$gender'";
    $run = mysqli_query($dbc, $query);
    $list = array();
    while($row = mysqli_fetch_row($run)){
        array_push($list, $row[1]);
    }
    
    return $list;
    
}
function numberofstudentshostel($hostel){
    $dbc = connect();
    $query = "SELECT * FROM students WHERE hostel_name='$hostel'";
    $run = mysqli_query($dbc, $query);
    $num = mysqli_num_rows($run);
    return $num;
}

function getunit($username){
	$dbc = connect();
	$query = "SELECT * FROM nonacadstaffs WHERE staffsId ='$username'";
	$run = mysqli_query($dbc, $query);
	$row = mysqli_fetch_row($run);
	$unit = $row[12];
	$query = "SELECT * FROM units WHERE unitcode='$unit'";
	$run = mysqli_query($dbc, $query);
	$uname = mysqli_fetch_row($run)[2];
	return $uname;
}

?>

