<?php
//Set default time
date_default_timezone_set('US/Eastern');
//Config
require 'config.php';
require 'cryptoFunctions.php';
// Autoload our dependencies with Composer
require 'vendor/autoload.php';

// Bootstrap Eloquent ORM
$container = new Illuminate\Container\Container;
$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory($container);
$conn = $connFactory->make($settings);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);
use Illuminate\Database\Query\Expression as raw;

// Create Slim app
$app = new \Slim\Slim();


// Use for very complex queries 
function rawPDO($query, $bindings = null)
{
	$dsn = 'mysql:dbname=' . DBNAME . ';host='.SERVER.';port=3306;charset=utf8';
	try {
	    $db_conn = new PDO($dsn, DBUSER, DBPASS, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
	} catch (PDOException $e) {
	    die('db down');
	}
    $db_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $statement = $db_conn->prepare($query);
    if(is_array($bindings))
        $statement->execute(array_values($bindings));
    else
        $statement->execute();
    return $statement;
}

// Fetch all records from a table for internal or API USE
function fetchRecords($table)
{
	$class = selectClass($table);
	if($table == "students")
		return $class->getStudentsInfo();
	elseif($table == "judges")
		return $class->getJudgesInfo();
	else
		return $class->getAll();
}



function obscureId($id)
{
	return ($id*155.2)*10+9999;
}

function recoverId($id)
{
	return (($id - 9999)/10)/155.2;
}

function fetchOldRecords($table)
{
	$class = selectClass($table);
	if ($table == "students")
		return $class->getOldStudentsInfo();
	elseif ($table == "judges")
		return $class->getOldJudgesInfo();
}

function fetchAllRecords($table)
{
	$class = selectClass($table);
	if ($table == "students")
		return $class->getAllStudentsInfo();
	elseif ($table == "judges")
		return $class->getAllJudgesInfo();
}

// Identify Class and Return it
function selectClass($table)
{
	switch (strtolower($table)) {
		case "judges":
		case "students":
		case "users":
			$class = new Users();
			break;
		case "prospectivejudges":
			$class = new Prospective();
			break;
		case "emailtemplates":
			$class = new Templates();
			break;
		case "judgeinvitations":
			$class = new Invitations();
			break;
		case "judgestudentconflicts":
			$class = new StudentConflicts();
			break;
		case "judgestudentgrade":
			$class = new StudentGrades();
			break;
		case "questions":
			$class = new Questions();
			break;
		case "settings":
			$class = new Settings();
			break;
		case "terms":
			$class = new Terms();
			break;
		case "projects":
			$class = new Projects();
			break;
		case "roles":
			$class = new Roles();
			break;
		case "states":
			$class = new States();
			break;
		case "locations":
			$class = new Locations();
			break;
		case "grades":
			$class = new Grades();
			break;
		default:
			echo "INVALID";
	}
	return $class;
}

function saveRecord($table, $entry, $input)
{
	$entry->fill((array)$input)->save();
	echo $entry->toJson();
}

function updateRecord($table, $entry, $input, $id)
{
	$input = (array)$input;
	//If password is present we encrypt it.
	if(isset($input['pass']))
		$input['pass'] = encrypt_decrypt('encrypt', $input['pass']);

	echo $entry->update($input);;
}


function searchById($table, $id) {
	$class = selectClass($table);
	return $class->getById($id);
}

function countItems($table)
{
	$class = selectClass($table);
	return $class->countItems();
}

//AUTHENTICATION FUNCTIONS
// route middleware for simple API authentication
function authenticate(\Slim\Route $route) {
    $app = \Slim\Slim::getInstance();
    $uid = $app->getEncryptedCookie('SE_________ES');
    if (validateUserKey($uid) === false) 
    {
    	echo '{"response": "qwe122e223ergrew323"}';
    	exit();
    }
    else
    {
    	$app->deleteCookie('SE_________ES');
		$app->setEncryptedCookie('SE_________ES', encrypt_decrypt('encrypt', 'myJudgekey2015'), '60 minutes');
    }
}

function validateUserKey($uid) {
	if ($uid == encrypt_decrypt('encrypt', 'myJudgekey2015')) 
	{
    	return true;
  	} 
  	else 
  	{
    	return false;
  	}
}


// generates a temporary API key using cookies
// call this first to gain access to protected API methods
$app->get('/authenticate/:user/:pass', function ($user, $pass) use ($app) {  
	$check = new Users();
	$result = $check->login($user, encrypt_decrypt('encrypt', $pass));
	if(sizeof($result) == 0)
		echo 0;
	else
	{
		try 
		{
			$app->setEncryptedCookie('SE_________ES', encrypt_decrypt('encrypt', 'myJudgekey2015'), '60 minutes');
			echo $result;
		} 
		catch (Exception $e) 
		{
			$app->response()->status(400);
			$app->response()->header('X-Status-Reason', $e->getMessage());
		}
	}
});
//END AUTHENTICATION FUNCTIONS

$app->put('/api/updateGrades/:judgeid/:studentid/:termid/:questionid', 'authenticate', function($judgeid, $studentid, $termid, $questionid) use ($app)
{
	// get and decode JSON request body
	$table = new Grades();
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	//Get correct entry
	$id = "";
	$entry = (new Grades())->where('judgeid', $judgeid)->where('studentid', $studentid)->where('termid', $termid)->where('questionsid', $questionid);

	$user = (new Users())->getById($judgeid);
	if($user->statesid <= 6)
	{
		$user->statesid = 7;
		$user->update();
	}
	updateRecord($table, $entry, $input, $id);
});

$app->put('/api/update/:table/:id', 'authenticate', function($table, $id) use ($app)
{
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	//Get correct entry
	$entry = searchById($table, $id);
	updateRecord($table, $entry, $input, $id);
});

$app->put('/api/setNewActive', 'authenticate', function() use ($app)
{
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	$table = "terms";
	$id = $input->id;
	//Get correct entry
	try
	{
		$term = (new Terms())->getActiveTerm();
		$term->active = 0;
		$term->update();
	}
	catch (exception $e)
	{

	}


	$entry = searchById($table, $id);
	updateRecord($table, $entry, $input, $id);


});

$app->post('/api/save/judgestudentconflicts', 'authenticate', function () use ($app)
{
	// get and decode JSON request body
	$table = 'judgestudentconflicts';
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);

	//Create a new entry for specified table
	$class = selectClass($table);

	if($table == "terms" && $input->active == 1)
	{
		$active = (new Terms())->getActiveTerm();
		$active->active = 0;
		$active->save();
	}

	//Save to correct table
	saveRecord($table, $class, $input);
});

$app->post('/api/save/:table', 'authenticate', function ($table) use ($app)
{
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);

	//Create a new entry for specified table
	$class = selectClass($table);

	if($table == "terms" && $input->active == 1)
	{
		$active = (new Terms())->getActiveTerm();
		$active->active = 0;
		$active->save();
	}

	//Save to correct table
	saveRecord($table, $class, $input);
});

$app->post('/api/importJudges', 'authenticate', function() use ($app)
{
	ini_set("auto_detect_line_endings", "1");
	$term = (new Terms())->getActiveTerm();
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$body = preg_replace('/\r\n|\n\r|\n|\r/', PHP_EOL, $body);
	//$body = str_replace('^p', PHP_EOL, $body);
	$lines = explode(PHP_EOL, $body);
	$numimpoted = 0;
	$numskipped = 0;
	$uskipped = "";
	foreach ($lines as $line) {
		$row = str_getcsv($line);
		if($row[0] != null && $row[1] != null && $row[2] != null)
		{
			$user = (new Users())->where('email', $row[0])->first();

			$judge = new Users();
			$judge->fname = $row[1];
			$judge->lname = $row[2];
			$judge->email = $row[0];
			$judge->termid = $term->id;
			$judge->statesid = 1;
			$judge->roleid = 2;
			$judge->projectid = 0;
			$judge->locationid = 0;

			if($user == null)
			{
				$judge->save();
				$numimpoted++;
			}
			else if($user->termid != $term->id)
			{
				if(($user->roleid == 2 && $user->stateid != 12) || ($user->roleid == 1))
				{
					$judge->save();
					$numimpoted++;
				}
				else
				{
					$numskipped++;
					$uskipped .= $judge->fname." ".$judge->lname."\n";
				}
			}
			else
			{
				$numskipped++;
				$uskipped .= $judge->fname." ".$judge->lname."\n";
			}
		}
	}
	echo "Imported: ".$numimpoted."\nSkipped: ".$numskipped."\nJudges Skipped: \n".$uskipped;
});

$app->post('/api/updateQM', 'authenticate', function() use ($app)
{
	$term = (new Terms())->getActiveTerm();
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	var_dump($input);
	foreach ($input as $item) {
		$question = (new Questions())->getById($item->id);
		$question->text = $item->text;
		$question->value = $item->value;
		$question->enabled = $item->enabled;
		$question->order = $item->order;
		$question->update();
	}
	//$input = $body;
});

$app->post('/api/saveQM', 'authenticate', function() use ($app)
{
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	var_dump($input);
	foreach ($input as $item) {
		$question = new Questions();
		$question->text = $item->text;
		$question->value = $item->value;
		$question->enabled = $item->enabled;
		$question->order = $item->order;
		$question->save();
	}

});

$app->post('/api/deleteQM', 'authenticate', function() use ($app)
{
	$term = (new Terms())->getActiveTerm();
	// get and decode JSON request body
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	$question = (new Questions())->getById($input->id);
	$question->delete();
});

$app->get('/api/deleteTemplate/:id', 'authenticate', function ($id) use ($app) {
	$row = (new Templates())->getById($id);
	$row->delete();
	echo $row;
});

$app->post('/api/saveUser', 'authenticate', function() use ($app)
{
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	//var_dump($input);
	if(isset($input->id)) $user = (new Users())->getById($input->id);
	else $user = (new Users());
	if($input->pass == "") { $input->pass = $user->pass;}
	$user->email = $input->email;
	$user->fname = $input->fname;
	$user->lname = $input->lname;
	$user->title = $input->title;
	if($user->pass != $input->pass) { $user->pass = encrypt_decrypt('encrypt', $input->pass);}
	$user->affiliation = $input->affiliation;
	$user->termid = $input->termid;
	$user->roleid = intval($input->roleid);
	$user->projectid = $input->projectid;
	$user->statesid = $input->statesid;
	$user->locationid = $input->locationid;
	if(isset($input->id)) $result = $user->update();
	else $result = $user->save();
	echo '{"result":"'.$result.'","fname":"'.$user->fname.'","lname":"'.$user->lname.'","id":"'.$user->id.'"}';
});

$app->post('/api/deleteUser', 'authenticate', function() use ($app)
{
	$request = $app->request();
	$body = $request->getBody();
	$input = json_decode($body);
	$user = (new Users())->getById($input->id);
	echo $user->delete();
});

// Get All Records from a table in JSON
//$app->get('/api/getAll/:table', function($table) use ($app)
$app->get('/api/getAll/:table', 'authenticate', function ($table) use ($app)
{
	echo fetchRecords($table);
});

$app->get('/api/getQM', 'authenticate', function () use ($app)
{
	echo (new Questions())->orderBy('enabled', 'DESC')->orderBy('order')->get();
});

$app->get('/api/getCurrent/questions', 'authenticate', function () use ($app)
{
	echo (new Questions())->where('enabled', '1')->orderBy('order')->get();
});

$app->get('/api/getProjectFilter/:id', 'authenticate', function ($id) use ($app)
{
	$term = (new Terms())->getActiveTerm()->id;
	$users = (new Users())->where('projectid', $id)->where('termid', $term)->get();
	$result = '';
	foreach($users as &$user)
	{
		$result .= $user->fname . " " . $user->lname ."|";
	}
	$result = substr($result, 0, strlen($result) - 1);
	echo $result;
});

$app->get('/api/getAll/:table/:type','authenticate', function ($table, $type) use ($app) {
	switch ($type)
	{
		case "old":
			echo fetchOldRecords($table);
			break;
		case "all":
			echo fetchAllRecords($table);
			break;
		case "current":
			echo fetchRecords($table);
			break;
		default:
			break;
	}
});

$app->get('/api/count/:table', 'authenticate', function($table) use ($app)
{
	echo countItems($table);
});

$app->get('/api/getGradesFilter/:id', 'authenticate', function($id) use ($app)
{
	$term = (new Terms())->getActiveTerm();
	$grades = new Grades();
	$grades->where('studentid', id)->where('termid', $term)->get();
	echo $grades->where('studentid', id)->where('termid', $term)->get();
});

$app->get('/api/getGrade/:student/:judge', 'authenticate', function($student, $judge) use ($app)
{
	$term = (new Terms())->getActiveTerm();
	$grades = new Grades();
	echo $grades->where('studentid', $student)->where('termid', $term->id)->where('judgeid', $judge)->get();
});


$app->get('/api/invite/:table/:id', function($table, $id) use ($app)
{
	$realId = recoverId($id);
	echo json_encode(searchById($table, $realId));
});

$app->get('/api/delete/:table/:id', 'authenticate', function($table, $id) use ($app)
{
	try
	{
		$term = (new Terms())->getById($id);
		$term->delete();
		echo 1;
	}
	catch(exception $e)
	{
		echo 0;
	}

});

$app->get('/api/get/:table/:id', 'authenticate', function($table, $id) use ($app)
{
	echo json_encode(searchById($table, $id));
});

$app->get('/api/getStudentsInfo/', 'authenticate', function() use ($app)
{
	$students = new Users();
	echo $students->getStudentsInfo();
});

$app->get('/api/getGradesInfo/', 'authenticate', function() use ($app)
{
	$grades = new Grades();
	echo $grades->getGradesInfo();
});

$app->get('/api/toggleGrade/:id', 'authenticate', function($id) use ($app)
{
	$grade = (new Grades())->where('id', $id)->first();
	switch($grade->accepted)
	{
		case 0:
			$grade->accepted = 1;
			break;
		case 1:
			$grade->accepted = 2;
			break;
		case 2:
			$grade->accepted = 0;
			break;
	}

	echo $grade->update();
});

$app->get('/api/getJudgesInfo/', 'authenticate',function() use ($app)
{
	$students = new Users();
	echo $students->getJudgesInfo();
});

$app->get('/api/getFullJudgesInfo/:termid/:statename', 'authenticate', function ($termid, $statename) use ($app) {
	$judges = new Users();
	echo $judges->getFullJudgesInfo($termid, $statename);
});

$app->get('/api/getFullStudentsInfo/:termid/:statename', 'authenticate', function ($termid, $statename) use ($app) {
	$students = new Users();
	echo $students->getFullStudentsInfo($termid, $statename);
});

$app->get('/api/getAllUsers/', 'authenticate', function() use ($app)
{
	$students = new Users();
	echo $students->select(new raw("*, id as value, CONCAT(fname, ' ', lname) as label"))->get();
});

$app->get('/api/getEmailTemplatesInfo/', 'authenticate', function () use ($app) {
	$emailTemplates = new Templates();
	echo $emailTemplates->getEmailTemplatesInfo();
});

$app->get('/api/getProjectsInfo/', 'authenticate', function () use ($app) {
	$projects = new Projects();
	echo $projects->projectStats();
});

$app->get('/api/getProjectsSInfo/', 'authenticate', function () use ($app) {
	$projects = new Projects();
	echo $projects->studentsStats();
});

$app->get('/api/loadStudents/', 'authenticate', function() use ($app)
{
	$students = new Users();
	echo $students->loadStudents();
});

$app->get('/api/getAdminHome/', 'authenticate', function() use ($app)
{
	$students = new Users();
	echo $students->getAdminHome();
});

$app->get('/api/test', 'authenticate', function () use ($app)
{
	$stugrades = (new Grades())->where('termid', 5)->where('active', 1)->where('graded', 0)->groupBy('studentid')->count();
	$students = (new Grades())->where('termid', 5)->where('active', 1)->where('graded', 0)->groupBy('studentid')->get();
	echo $stugrades.$students;
});

$app->get('/api/pendingGrade/', 'authenticate', function() use ($app)
{
	$term = (new Terms())->sendActiveTerm();
	$students = new Students();
	$stucount = (new Grades())->where('termid', $term->id)->get()->count();
	$stugrades = (new Grades())->where('termid', $term->id)->where('graded', 1)->get()->count();
	echo $stucount - $stugrades;
});

$app->get('/api/getActiveTerm', 'authenticate', function() use ($app)
{
	echo (new Terms())->getActiveTerm();
});

$app->get('/api/getStudentsJudge/:judgeId', 'authenticate', function($judgeId) use ($app)
{
	$students = new Grades();
	echo $students->getCurrentAssignments($judgeId);
});

$app->get('/api/getStudentHome/:id', 'authenticate', function($id) use ($app)
{
	$term = (new Terms())->getActiveTerm();
	$students = (new Users())->getById($id);
	$grades = (new Grades());
	$grade = $grades
		->select(new raw("*, AVG(value) as valueg"))
		->where('termid', $term->id)
		->where('active', 1)
		->where('graded', 1)
		->where('accepted', 1)
		->where('studentid', $id)
		->groupBy('questionsid')
		->get();

	$sum2 = 0;
	$sum = 0;
	foreach($grade as &$gr)
	{
		$sum += $gr->valueg;
		$sum2++;
	}

	if($term->studentscangrades == 1)
	{
		echo json_encode([
			"grade" => (($sum2 != 0) ? $sum : 'Pending') ,
			"max" => (new Questions())->where('enabled', 1)->sum('value')
		]);
	}
	else{
		echo json_encode([
			"grade" => 'Pending',
			"max" => (new Questions())->where('enabled', 1)->sum('value')
		]);
	}
});


$app->get('/api/assignStudents/:judgeId', function($judgeId) use ($app)
{
	$questions = (new Questions())->getActiveQuestions();
	$term = (new Terms())->getActiveTerm()['id'];
	$conflicts = (new StudentConflicts())->getConflicts($judgeId);
	$studentsPerJudge = (new Terms())->getActiveTerm()['studentsperjudge'];
	$newStudents = rawPDO("SELECT users.id,grades.judgeid, COUNT(studentid) AS 'total'
					FROM grades
					RIGHT JOIN users
					ON grades.studentid=users.id
					WHERE users.roleid = 1 && users.termid = '".$term."'
					GROUP BY users.id
					ORDER BY total, RAND()")->fetchAll();

	$counter = 0;
	foreach ($newStudents as $keyS => $valueS) 
	{
		if($counter == $studentsPerJudge)
			break;

		$conflict = false;
		foreach ($conflicts as $keyC => $valueC) 
		{
			if($valueC['studentid'] == $valueS['id'])
			{
				$conflict = true;
				break;
			}
		}

		if(!$conflict)
		{
			foreach ($questions as $keyQ => $valueQ) 
			{
				$input = array();
				$input['judgeid'] = $judgeId;
				$input['studentid'] = $valueS['id'];
				$input['questionsid'] = $valueQ['id'];
				$input['termid'] = $term;
				$input['active'] = 1;
				$input['value'] = $valueQ['value'];
				saveRecord('grades', new Grades(), $input);
			}
			$counter++;
		}
	}
	$judge = (new Users())->getById($judgeId);
	$judge->statesid = 5;
	$judge->update();

});

$app->get('/api/sendEmail/:id/:templateId', 'authenticate', function ($id, $templateId) use ($app) {
	$users = (new Users())->getById($id);
	$uemail = $users->email;
	$template = (new Templates())->getById($templateId);
	$tsubject = $template->subject;

	$sent = new EmailsSent();
	$sent->userid = $id;
	$sent->to = $uemail;
	$sent->sent = date('Y-m-d H:i:s');
	$sent->emailtemplateid = $templateId;
	$sent->termid = (new Terms())->getActiveTerm()->id;
	$sent->save();

	$tbody = $template->getEmailBody($id, $templateId, true, $uemail, $sent->id);
	$tsub = $template->getEmailSubject($id, $templateId, true, $uemail, $sent->id);
	$result = mail($uemail, $tsub, $tbody,
		"From: Masoud Sadjadi <sadjadi@cs.fiu.edu>\r\nMIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n");

	echo '{"email":"' . $uemail . '","result":"' . $result . '"}';
});

$app->get('/api/sendEmailNoId/:email/:templateId', function ($email, $templateId) use ($app) {
	$id = null;
	$exist = (new Users())->where('email', $email)->first();
	$mailInDB = 0;

	if($exist != null)
	{
		$mailInDB = 1;
		$users = $exist;
		$uemail = $users->email;
		$id = $users->id;
		$template = (new Templates())->getById($templateId);
		$tsubject = $template->subject;

		$sent = new EmailsSent();
		$sent->userid = $id;
		$sent->to = $uemail;
		$sent->sent = date('Y-m-d H:i:s');
		$sent->emailtemplateid = $templateId;
		$sent->termid = (new Terms())->getActiveTerm()->id;
		$sent->save();

		$tbody = $template->getEmailBody($id, $templateId, true, $uemail, $sent->id);
		$tsub = $template->getEmailSubject($id, $templateId, true, $uemail, $sent->id);

		$result = mail($uemail, $tsub, $tbody,
			"From: Masoud Sadjadi <sadjadi@cs.fiu.edu>\r\nMIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n");

		echo '{"email":"' . $uemail . '","result":"' . $result . '","inDB":"' . $mailInDB . '"}';
	}
	else
	{
		$uemail = $email;
		$template = (new Templates())->getById($templateId);
		$tsubject = $template->subject;

		$sent = new EmailsSent();
		$sent->userid = 0;
		$sent->to = $uemail;
		$sent->sent = date('Y-m-d H:i:s');
		$sent->emailtemplateid = $templateId;
		$sent->termid = (new Terms())->getActiveTerm()->id;
		$sent->save();

		$tbody = $template->getEmailBody($id, $templateId, true, $uemail, $sent->id);
		$tsub = $template->getEmailSubject($id, $templateId, true, $uemail, $sent->id);

		$user = (new Users())->where('email', $email)->first();
		if($user != null)
		{
			$sent->userid = $user->id;
			$sent->update();
		}

		$result = mail($uemail, $tsub, $tbody,
			"From: Masoud Sadjadi <sadjadi@cs.fiu.edu>\r\nMIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n");



		echo '{"email":"' . $uemail . '","result":"' . $result . '","inDB":"' . $mailInDB . '"}';
	}

});

$app->get('/api/getPreview/:id/:templateId', 'authenticate', function ($id, $templateId) use ($app) {
	$users = (new Users())->getById($id);
	$template = (new Templates())->getById($templateId);
	$tbody = $template->getEmailBody($id, $templateId, false, null, null);
	echo $tbody;
});

$app->get('/api/getPreviewSub/:id/:templateId', 'authenticate', function ($id, $templateId) use ($app) {
	$users = (new Users())->getById($id);
	$template = (new Templates())->getById($templateId);
	$tsub = $template->getEmailSubject($id, $templateId, false, null, null);
	echo $tsub;
});

//Let the app be at the root
$app->get('/', function() use ($app)
{
	$app->render('main.html');
});

//Let the app be at the root
$app->get('/sessionExpired', function() use ($app)
{
	$app->render('main.html');
});

// Email Incoming Judges
$app->get('/emailInvite/:judgeid/:sentId', function($judgeid, $sentId) use ($app)
{
	$id = recoverId($judgeid);
	$judge = (new Users())->getById($id);
	if($judge != null) {
		if ($judge->statesid == 2) {
			$judge->statesid = 4;
			$judge->update();
		}
	}
	$app->render('newJudge.php', array('judgeid' => $judgeid, $sentId));
});

// Email Reject Judges
$app->get('/emailReject/:userid/:sentId', function($userid, $sentId) use ($app)
{
	$id = recoverId($userid);
	$judge = (new Users())->getById($id);
	if($judge != null) {
		$judge->statesid = 3;
		$judge->update();
	}
	$app->render('reject.php', array('userid' => $userid));
});

// Email Reject Judges
$app->get('/emailRemove/:userid/:sentId', function($userid, $sentid) use ($app)
{
	$id = recoverId($userid);
	$judge = (new Users())->getById($id);
	if($judge != null)
	{
		$judge->statesid = 12;
		$judge->update();
	}

	
	$app->render('remove.php', array('userid' => $userid));
});

// Delete current assignment and suffle all the students between all the judges
$app->get('/shuffleStudents/:id', 'authenticate', function($id) use ($app)
{
	$check = (new Users())->idadmin((int)$id);
	if(!$check)
		exit("INVALID");
	$grades = (new Grades())->truncate();
	$term = (new Terms())->getActiveTerm()['id'];
	$judges = (new Users())->where('statesid', '>=', 5)->where('statesid', '<>', 13)->where('roleid', 2)->where('termid', $term)->get();

	foreach ($judges as $key => $value)
	{
		$questions = (new Questions())->getActiveQuestions();
		$term = (new Terms())->getActiveTerm()['id'];
		$conflicts = (new StudentConflicts())->getConflicts($value['id']);
		$studentsPerJudge = (new Terms())->getActiveTerm()['studentsperjudge'];
		$newStudents = rawPDO("SELECT users.id,grades.judgeid, COUNT(studentid) AS 'total'
						FROM grades
						RIGHT JOIN users
						ON grades.studentid=users.id
						WHERE users.roleid = 1 && users.termid = '".$term."'
						GROUP BY users.id
						ORDER BY total, RAND()")->fetchAll();

		$counter = 0;
		foreach ($newStudents as $keyS => $valueS) 
		{
			if($counter == $studentsPerJudge)
				break;

			$conflict = false;
			foreach ($conflicts as $keyC => $valueC) 
			{
				if($valueC['studentid'] == $valueS['id'])
				{
					$conflict = true;
					break;
				}
			}

			if(!$conflict)
			{
				foreach ($questions as $keyQ => $valueQ) 
				{
					$input = array();
					$input['judgeid'] = $value['id'];
					$input['studentid'] = $valueS['id'];
					$input['questionsid'] = $valueQ['id'];
					$input['termid'] = $term;
					$input['active'] = 1;
					$input['value'] = $valueQ['value'];
					saveRecord('grades', new Grades(), $input);
				}
				$counter++;
			}
		}
		$judge = (new Users())->getById($value['id']);
		$judge->statesid = 5;
		$judge->update();
	}
});

// Password reset Route
$app->get('/forgotPass/:userid/:sentId', function($userid, $sentid) use ($app)
{
	$app->render('forgotPass.php', array('userid' => $userid));
});

$app->run();