<?php 

require_once(dirname(__FILE__)."/pages/upload-external-exam.php");
require_once(dirname(__FILE__)."/pages/mock-exam-broadsheet.php");
require_once(dirname(__FILE__)."/pages/download-external-exam.php");
require_once(dirname(__FILE__)."/pages/mock-result-sheet.php");
require_once(dirname(__FILE__)."/pages/use-mock-result-for-mastersheet.php");
require_once(dirname(__FILE__)."/pages/mock-exam-gradebook.php");
require_once(dirname(__FILE__)."/pages/print-mock-broadsheet.php");

function extexam_make_broadsheet($class, $category, $term, $ext_exam, $columns = array()) {
	$default = [
		"fullname" => "FULL NAME", 
		"scores" => "SCORES", 
		"total" => "TOTAL", 
		"subjects_offered" => "SUBJECTS OFFERED", 
		"average" => "AVERAGE", 
		"position" => "POSITION"
	];
	$columns = array_merge($default, $columns);
	$class_courses = get_class_courses($class, $category, false, true, true);
	$columns_count = (_count($columns) - 1) + (_count($class_courses));

	// get broadsheet
	$broadsheet = extexam_get_broadsheet($class, $category, $term, $ext_exam, $class_courses);
	$html = "";
	$html .= "<table class=\"table table-bordered text-center\"><thead><tr><th colspan=\"".$columns_count."\" class=\"broadsheet-header text-center\">";
	$html .= strtoupper(get_class_name($class, $category)." ".$ext_exam)." BROADSHEET ".get_full_term_name($term);
	$html .= "</th></tr>";
	$html .= "<tr>";
	foreach ($columns as $column => $label) {
		$tag_class = ($column == "fullname" || $column == "student_id") ? "text-left" : "rotate90";
		if($column === "scores") {
			foreach ($class_courses as $course_id => $course_name) {
				$html .= "<th class=\"".$tag_class."\"><span>".$course_name."</span></th>";
			}
		} else {
			$html .= "<th class=\"".$tag_class."\"><span>".$label."</span></th>";
		}
	}
	$html .= "</tr></thead><tbody>";
	if(_count($broadsheet) && is_array($broadsheet)) {
		foreach ($broadsheet as $key => $value) {
			$html .= "<tr>";
			foreach ($columns as $column => $label) {
				$tag_class = ($column == "fullname" || $column == "student_id") ? "text-left" : "";
				if($column === "scores") {
					foreach ($class_courses as $course_id => $course_name) {
						$html .= "<td class=\"".$tag_class."\">".$value['courses'][$course_id]['score']."</td>";
					}
				} else {
					if($column == "average") {
						$value[$column] = round($value[$column]);
					}
					$html .= "<td class=\"".$tag_class."\">".$value[$column]."</td>";
				}
			}
			$html .= "</tr>";
		} // end foreach broadsheet
	}
	$html .= "</tbody></table>";
	return $html;
}

function extexam_get_broadsheet($class, $category, $term, $ext_exam, $class_courses) {
	if($record = get_record("mock_broadsheet_".$ext_exam."_".$class."_".$category."_".$term)) {
		if($record = _unserialize($record)) {
			return $record;
		}
	}
	$post = new post;
	$comment = new ft_comment;
	$students_results = extexam_get_results($class, $category, $term, $ext_exam, $class_courses);
	$broadsheet = [];
	if(!isset($students_results['students'])) {
		return $broadsheet;
	}
	if(!_count($students_results['students'])) {
		return $broadsheet;
	}
	foreach ($students_results['students'] as $student_meta) {
		set_time_limit(60);
		$broadsheet[$student_meta['id']]['fullname'] = get_fullname($student_meta);
		$broadsheet[$student_meta['id']]['student_id'] = strtoupper($student_meta['username']);
		$broadsheet[$student_meta['id']]['total'] = 0;
		$count = 0;
		foreach ($class_courses as $course_id => $course_name) {
			$score = 0;
			if(isset($students_results['results'][$student_meta['id']]['scores'][$course_id])) {
				$score = is_numeric($students_results['results'][$student_meta['id']]['scores'][$course_id]) ? $students_results['results'][$student_meta['id']]['scores'][$course_id] : 0;
				$broadsheet[$student_meta['id']]['courses'][$course_id]['score'] = $score;
				$broadsheet[$student_meta['id']]['courses'][$course_id]['course_name'] = $course_name;
				$count++;
			}
			$broadsheet[$student_meta['id']]['total'] += $score;
		}
		$broadsheet[$student_meta['id']]['subjects_offered'] = $count;
		$broadsheet[$student_meta['id']]['average'] = ($count > 0 && $broadsheet[$student_meta['id']]['total'] > 0) ? $broadsheet[$student_meta['id']]['total']/$count : 0;
		$broadsheet[$student_meta['id']]['comment'] = $comment->get_comment($broadsheet[$student_meta['id']]['average']);
	}
	
	$broadsheet = eedu_portal_positioning($broadsheet);
	$processed = serialize($broadsheet);
	$processed = base64_encode($processed);
	update_record("mock_broadsheet_".$ext_exam."_".$class."_".$category."_".$term, $processed);
	remove_record("mock_prepared_results_".$ext_exam."_".$class."_".$category."_".$term);
	return $broadsheet;
}

//returns an array of results and students
function extexam_get_results($class, $category, $term, $ext_exam, $class_courses) {
	if($record = get_record("mock_prepared_results_".$ext_exam."_".$class."_".$category."_".$term)) {
		return $record;
	}
	$post = new post;
	$user = new user;
	$gradebooks = [];
	$exam_query = ['type' => 'mock_exam', 'exam' => $ext_exam, 'term' => $term, 'class' => $class];
	$temp = "old";
	if($category) {
		$gradebooks = $post->get_post_by_meta_data(["type" => "mock_exam_gradebook", "exam" => $ext_exam, "class" => $class, "category" => $category, "term" => $term]);
		if(_count($gradebooks)) {
			$temp = "new";
		}
		$exam_query['category'] = $category;
	} else {
		$gradebooks = $post->get_post_by_meta_data(["type" => "mock_exam_gradebook", "exam" => $ext_exam, "class" => $class, "term" => $term]);
		if(_count($gradebooks)) {
			$temp = "new";
		}
	}
	if($temp === "new") {
		$results['students'] = eedu_portal_get_class_students($class, $category, $term);
		if(empty($results['students'])) {
			$results = extexam_prepare_mock_result_new($gradebooks, $class, $term, $ext_exam, true);
		} else {
			$results['results'] = extexam_prepare_mock_result_new($gradebooks, $class, $term, $ext_exam);
		}
	} else {
		$results = $post->get_post_by_meta_data($exam_query);
		$results = extexam_prepare_mock_result_old($results, $class, $term, $ext_exam);
	}
	update_record("mock_prepared_results_".$ext_exam."_".$class."_".$category."_".$term, $results);
	return $results;
}

function extexam_prepare_mock_result_old($results, $class, $term, $ext_exam) {
	$user = new user;
	$post = new post;
	$temp = [];
	$output = [];
	$gradebooks = [];
	if(_count($results)) {
		foreach($results as $result) {
			set_time_limit(80);
			if(!isset($temp[$result['student_id']])) {
				$student = $user->get_user_meta($result['student_id']);
				if($student) {
					$temp[$result['student_id']]['id'] = $student['id'];
					$temp[$result['student_id']]['username'] = $student['username'];
					$temp[$result['student_id']]['surname'] = $student['surname'];
					$temp[$result['student_id']]['other_names'] = $student['other_names'];
				}
			}
			$gradebooks[$result['category']][$result['course']][$result['student_id']] =  $result['score'];
			$check = trim($result['score']);
			if($check !== "" && strtolower($check) !== "x") {
				$output['results'][$result['student_id']]['scores'][$result['course']] = $result['score'];
			}
		}
		if(_count($gradebooks)) {
			foreach ($gradebooks as $category => $courses) {
				foreach ($courses as $course => $scores) {
					set_time_limit(80);
					if(!db_post_unique(["type" => "mock_exam_gradebook", "exam" => $ext_exam, "class" => $class, "category" => $category, "course" => $course, "term" => $term])) {
						$args = [
							"type" => "mock_exam_gradebook",
							"exam" => $ext_exam,
							"class" => $class,
							"category" => $category,
							"course" => $course,
							"term" => $term,
							"scores" => serialize($scores),
							"status" => "verified"
						];
						$post->add_post($args); //saves gradebook
					}
					
				}
				ext_exam_reset_broadsheet($class, $category, $term, $ext_exam);
			}
		}
	}
	$output['students'] = $temp;
	return $output;
}

function extexam_prepare_mock_result_new($gradebooks, $class, $term, $ext_exam, $get_students = false) {
	$output = [];
	$user = new user;
	if(_count($gradebooks)) {
		foreach($gradebooks as $gradebook) {
			set_time_limit(80);
			$scores = _unserialize($gradebook['scores']);
			foreach ($scores as $student_id => $score) {
				if($get_students) {
					if(!isset($output['students'][$student_id])) {
						$output['students'][$student_id] = $user->get_user_meta($student_id);
					}
					$check = trim($score);
					if($check !== "" && strtolower($check) !== "x") {
						$output['results'][$student_id]['scores'][$gradebook['course']] = $score;
					}
				} else {
					$check = trim($score);
					if($check !== "" && strtolower($check) !== "x") {
						$output[$student_id]['scores'][$gradebook['course']] = $score;
					}
				}
			}
		}
	}
	return $output;
}

function ext_exam_reset_broadsheet($class, $category, $term, $ext_exam) {
	remove_record("mock_broadsheet_".$ext_exam."_".$class."_".$category."_".$term);
	remove_record("mock_prepared_results_".$ext_exam."_".$class."_".$category."_".$term);
	remove_record("class_courses_".$class."_".$category."_merged");
	remove_record("class_courses_".$class."_".$category."_expanded");
	$category = false;
	remove_record("mock_broadsheet_".$ext_exam."_".$class."_".$category."_".$term);
	remove_record("mock_prepared_results_".$ext_exam."_".$class."_".$category."_".$term);
	eedu_portal_reset_annual_broadsheet($class, $term);
}