<?php 

function eedu_portal_broadsheet($args) {
	$class = eedu_portal_get_class_selection($args['class_category']);
	$html = "";
	$html .= eedu_portal_default_paperhead();
    $html .= eedu_portal_make_broadsheet($class['class'], $class['category'], $args['term'], $args['format'], array(), "bootstrap-data-table");
    $html .= "<div class=\"btn-group\">";
	$html .= "<a href=\"print-broadsheet?class=".$class['class']."&category=".$class['category']."&term=".$args['term']."&format=".$args['format']."&media=print\" class=\"btn btn-default popmeup\" data-width=1270 data-height=800>Print</a>";
	$html .= "<a href=\"javaScript:void(0);\" class=\"btn btn-default ajax-action\" data-action-callback=\"eedu_portal_refresh_broadsheet\" data-class=".$class['class']." data-category=\"".$class['category']."\" data-term=".$args['term']." data-callback=\"click\" data-callbackid=\"#search-query-btn\">Refresh Changes</a>";
    $html .= "<a href=\"javaScript:void(0);\" data-action-callback=\"eedu_portal_compile_results\" data-class=\"".$class['class']."\" data-category=\"".$class['category']."\" data-term=\"".$args['term']."\" data-content=\"Are you sure you want to go ahead and compile this result?\" data-format=\"".$args['format']."\" class=\"btn btn-primary ajax-action\">Compile Result</a>";
    $html .= "</div>";
    return $html;
}

function eedu_portal_annual_broadsheet($args) {
	if($args['class'] == "") {
		return "Please Select Class";
	}
	if($args['session'] == "") {
		$args['session'] = get_option("current_academic_session");
	}
	$html = "";
	$html .= eedu_portal_default_paperhead();
	$html .= eedu_portal_make_annual_broadsheet($args['class'], $args['session'], $args['format'], array(), "bootstrap-data-table");
	$html .= "<a href=\"print-annual-broadsheet?class=".$args['class']."&session=".$args['session']."&format=".$args['format']."&media=print\" class=\"btn btn-default popmeup\" data-width=1270 data-height=800>Print</a>";
	$html .= "<a href=\"javaScript:void(0);\" class=\"btn btn-default ajax-action\" data-action-callback=\"eedu_portal_refresh_annual_broadsheet\" data-class=".$args['class']." data-session=".$args['session']." data-callback=\"click\" data-callbackid=\"#search-query-btn\">Refresh Changes</a>";
	return $html;
}

function eedu_portal_gradebook($args) {
	if($args['course'] == "") {
		return "You have not selected any subject";
	}
	$class = eedu_portal_get_class_selection($args['class_category']);
	$students = eedu_portal_get_class_students($class['class'], $class['category'], $args['term']);
	$html = "";
	$table = new table("gradebook", $students);
	$table->grading = new grading;
	$table->grading->root_mode_of_scoring();
	$table->modes = $table->grading->get_mode_of_scoring();
	$table->grades = $table->grading->get_grades();
	$table->existing = db_post_unique(['type' => 'result', 'class' => $class['class'], 'category' => $class['category'], 'course' => $args['course'], 'term' => $args['term']]);
	if($table->existing) {
		$table->results = _unserialize($table->existing['result']);
	}
	$table->table_id = "table";
	$columns = [
		"sn" => "SN",
		"fullname" => "Full Name",
	];
	$dynamic_columns = [
		'total' => "_tf_eedu_portal_get_gradebook_total",
		'grade' => "_tf_eedu_portal_get_gradebook_grade"
	];
	if($table->modes) {
		foreach ($table->modes as $key => $value) {
			$columns[$value['mode_of_scoring']] = "<div class=\"text-center\"><small>".$value['mode_of_scoring']."</small><br />".$value['max']."%</div>";
			$dynamic_columns[$value['mode_of_scoring']] = "_tf_eedu_portal_get_gradebook_input";
		}
	}
	$columns['total'] = "<div class=\"text-center\"><small>Total</small><br />100%</div>";
	$columns['grade'] = "Grade";
	$table->set_display_columns($columns);
	$table->set_dynamic_columns($dynamic_columns);
	$html .= "<form method=\"post\" action=\"contents/plugins/eedu_portal/ajax.php\" id=\"result_sheet_form\">";
	$html .= "<button class=\"btn btn-primary submit pull-right\" id=\"submit-btn1\">Save Entries</button>";
	$html .= eedu_portal_default_paperhead();
	$html .= "<div class=\"text-center\"><strong>".strtoupper(get_class_name($class['class'], $class['category'])." ".get_course_name($args['course'])." ".get_full_term_name($args['term']))."</strong></div><hr />";
	$html .= $table->table_html();
	$html .= "<div>";
	$html .= "<input type=\"hidden\" name=\"action\" value=\"save_gradebook\">";
	$html .= "<input type=\"hidden\" name=\"class\" value=\"".$class['class']."\">";
	$html .= "<input type=\"hidden\" name=\"category\" value=\"".$class['category']."\">";
	$html .= "<input type=\"hidden\" name=\"course\" value=\"".$args['course']."\">";
	$html .= "<input type=\"hidden\" name=\"term\" value=\"".$args['term']."\">";
	$html .= "<input type=\"hidden\" name=\"session\" value=\"".get_term_session($args['term'])."\">";
	$html .= "<button class=\"btn btn-primary submit pull-right\" id=\"submit-btn\">Save Entries</button>";
	$html .= "</div>";
	$html .= "</form>";
	return $html;
}

function eedu_portal_print_results($args) {
	$class = eedu_portal_get_class_selection($args['args']['class_category'] ?? '');
	$post = new post;
	$q = ['term' => $args['args']['term'] ?? ''];
	if(($args['args']['exam'] ?? '') === "Regular") {
		$q['type'] = 'compiled_result';
	} else if (($args['args']['exam'] ?? '') === "Mock") {
		$q['type'] = 'compiled_mock_result';
	}

	if($class['class']) {
		$q['class'] = $class['class'];
	}
	if($class['category']) {
		$q['category'] = $class['category'];
	}
	if(!current_user_can("print_results_without_pin")) {
		$session = Session::getInstance();
		$q['student_id'] = $session->id;
	}
	$res = $post->get_post_by_meta_data($q, "LIKE", false, $args['limit'], $args['offset']);

	if(_count($res) && is_array($res)) {
		$table = new table("results-table", $res);
		$session = Session::getInstance();
		$table->user_id = $session->id;
		$display = [
			'sn' => 'SN',
			'student_id' => 'Name',
			'position' => 'Position',
			'class' => 'Class',
			'last_compiled' => 'Last Compiled',
			'ft_comment' => 'Comment',
			'print' => 'Action'
		];
		$dynamic = [
			'class' => '_tf_eedu_display_student_class',
			'last_compiled' => '_tf_get_date',
			'student_id' => '_tf_get_fullname_id',
			'position' => '_tf_display_position',
			'print' => '_tf_view_print'
		];
		$table->set_display_columns($display);
		$table->set_dynamic_columns($dynamic);
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found";
		$response['continue'] = false;
	}
	$response['container'] = "results-table tbody";
	return apply_filters("eedu_portal_print_results_query_function", $response, $args);
}

function eedu_portal_print_student_results($args) {
	$post = new post;
	$session = Session::getInstance();
	$q = ['type' => ['compiled_result', 'compiled_mock_result'], 'student_id' => $session->id];

	$res = $post->get_post_by_meta_data($q, "LIKE", false, $args['limit'], $args['offset']);

	if(_count($res) && is_array($res)) {
		$table = new table("results-table", $res);
		$session = Session::getInstance();
		$table->user_id = $session->id;
		$display = [
			'sn' => 'SN',
			'student_id' => 'Name',
			'position' => 'Position',
			'class' => 'Class',
			'term' => 'Term',
			'ft_comment' => 'Comment',
			'print' => 'Action'
		];
		$dynamic = [
			'class' => '_tf_eedu_display_student_class',
			'term' => '_tf_eedu_display_full_term_name',
			'student_id' => '_tf_get_fullname_id',
			'position' => '_tf_display_position',
			'print' => '_tf_view_print'
		];
		$table->set_display_columns($display);
		$table->set_dynamic_columns($dynamic);
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found".serialize($q);
		$response['continue'] = false;
	}
	$response['container'] = "results-table tbody";
	return apply_filters("eedu_portal_print_results_query_function", $response, $args);
}

function eedu_portal_print_myresults($args) {
	$class = eedu_portal_get_class_selection($args['args']['class_category']);
	$post = new post;
	$q = ['type' => ['compiled_result', 'compiled_mock_result'], 'student_id' => $args['args']['student_id']];

	$res = $post->get_post_by_meta_data($q, "LIKE", false, $args['limit'], $args['offset']);

	if(_count($res) && is_array($res)) {
		$table = new table("results-table", $res);
		$session = Session::getInstance();
		$table->user_id = $session->id;
		$display = [
			'sn' => 'SN',
			'student_id' => 'Name',
			'class' => 'Class',
			'term' => 'Term',
			'status' => 'Status',
			'print' => 'Action'
		];
		$dynamic = [
			'class' => '_tf_eedu_display_student_class',
			'status' => '_tf_ucwords',
			'student_id' => '_tf_get_fullname_id',
			'term' => '_tf_eedu_display_term_name',
			'print' => '_tf_view_print'
		];
		$table->set_display_columns($display);
		$table->set_dynamic_columns($dynamic);
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found";
		$response['continue'] = false;
	}
	$response['container'] = "results-table tbody";
	return apply_filters("eedu_portal_print_results_query_function", $response, $args);
}

function eedu_portal_promotion_order($args) {
	if($args['class'] == "") {
		return "You have not selected any subject";
	}
	$courses = get_class_courses($args['class'], false, false, true, false); 
	if(_count($courses)) {
		foreach ($courses as $key => &$value) {
			$value = ["course_name" => $value];
			$value['id'] = $key;
		}
	} else {
		return "No subject was assigned to this class";
	}
	$html = "";
	$table = new table("promotion_order_table", $courses);
	$post = new post;
	$average = 0;
	$table->promotion_order = db_post_unique(['type' => 'promotion_order', 'class' => $args['class']]);
	if($table->promotion_order) {
		$table->promotion_order['condition'] = _unserialize($table->promotion_order['condition']);
		$average = $table->promotion_order['average'];
	}
	$table->table_id = "table";
	$table->table_class = "table table-bordered";
	$columns = [
		"course_name" => "Subject Name",
		"remove" => "",
		"must_pass" => "<div class=\"text-center\">Must Pass</div>",
		"optional1" => "<div class=\"text-center\">Optional 1</div>",
		"optional2" => "<div class=\"text-center\">Optional 2</div>",
		"optional3" => "<div class=\"text-center\">Optional 3</div>"
	];
	$dynamic_columns = [
		'must_pass' => "_tf_eedu_portal_po_must_pass",
		'optional1' => "_tf_eedu_portal_po_optional1",
		'optional2' => "_tf_eedu_portal_po_optional2",
		'optional3' => "_tf_eedu_portal_po_optional3",
		'remove' => "_tf_eedu_portal_po_remove"
	];
	$table->set_display_columns($columns);
	$table->set_dynamic_columns($dynamic_columns);
	$html .= "<form method=\"post\" action=\"contents/plugins/eedu_portal/ajax.php\" id=\"promotion_order_form\">";
	// $html .= "<button class=\"btn btn-primary submit pull-right\" id=\"submit-btn1\">Save Entries</button>";
	$html .= "<div class=\"text-center\"><strong>".strtoupper(get_class_name($args['class']))." PROMOTION ORDER</strong></div><hr />";
	$html .= $table->table_html();
	$html .= "<div>";
	$html .= "Total Average Must Be Above: <input type=\"text\" id=\"average\" class=\"numbers-only\" name=\"average\" value=\"".$average."\" required> %";
	$html .= "<input type=\"hidden\" name=\"action\" value=\"save_promotion_order\">";
	$html .= "<input type=\"hidden\" name=\"class\" value=\"".$args['class']."\">";
	$html .= "<button class=\"btn btn-primary submit pull-right\" id=\"submit-btn\">Save Entries</button>";
	$html .= "</div>";
	$html .= "</form>";
	return $html;
}

function eedu_portal_stud_in_class($args) {
	$current = get_option("current_academic_term");
	$class = eedu_portal_get_class_selection($args['class_category']);
	$students = eedu_portal_get_class_students($class['class'], $class['category'], $args['term']);
	$table = new table("stud_in_class", $students);
	$table->term = $args['term'];
	$table = apply_filters("eedu_stud_in_class_table", $table, $args);
	$columns = [
		"sn" => "SN",
		"fullname" => "Name",
		"class" => "Current Class"
	];
	$columns = apply_filters("eedu_stud_in_class_columns", $columns, $args);
	$dynamic = [
		"class" => "_tf_eedu_display_student_class"
	];
	$dynamic = apply_filters("eedu_stud_in_class_dynamic_columns", $dynamic, $args);
	$table->set_display_columns($columns);
	$table->set_dynamic_columns($dynamic);
	if($args['term'] !== $current) {
		$session = get_term_session($args['term']);
		$table->set_action_links([
			"Remove" => false
		]);
		$table->set_action_callback([
			"Remove" => "eedu_portal_remove_student_from_class"
		]);
		$table->set_action_access([
			"Remove" => "eedu_portal_remove_student_from_class"
		]);
		$table->set_action_args([
			"Remove" => [
				"studentid" => "id", 
				"class" => $class['class'],
				"category" => $class['category'],
				"term" => $args['term'],
				"session" => $session,
				"callback" => "click",
				"callbackid" => "#search-query-btn"
			]
		]);
	}
	$html = "<div class=\"row mb-4\">
			<div class=\"col-md-12\">
		        <div class=\"card\">
		            <div class=\"card-header\">
		                <strong class=\"card-title\">ACTIVE</strong>";
	if(current_user_can("maintain_students_in_class")) {
		$html .= "<a href=\"maintain-students-in-class?class=".$class['class']."&category=".$class['category']."&term=".$args['term']."&session=".$session."\" class=\"pull-right popmeup\" data-width=700 data-height=280 data-onreturncb=\"click\" data-onreturncbid=\"#search-query-btn\" style=\"font-size: 15px;letter-spacing: 0.1px;word-spacing: 0.5px;background: #eee;cursor: pointer;\">PULL FROM CURRENT TERM</a>";
	}
	$html .= "</div><div class=\"card-body\">";
	$html .= $table->table_html();                
	$html .= "</div>
	            	        </div>
	            	    </div>
	                </div>";

	if(($args['term'] !== $current) && current_user_can('eedu_portal_remove_student_from_class')) {
		$sorting = new sorting;
		$user = new user;
		$students = get_students_not_in_class($session, $args['term'], $class['class'], $class['category']);
		foreach ($students as $key => &$student_id) {
			$student_id = $user->get_user_meta($student_id);
		}
		$students = $sorting->sort_by_meta_value($students, "surname");
		$table = new table("stud_not_in_class", $students);
		$table = apply_filters("eedu_stud_not_in_class_table", $table, $args);
		$columns = [
			"sn" => "SN",
			"fullname" => "Name",
			"class" => "Current Class"
		];
		$columns = apply_filters("eedu_stud_not_in_class_columns", $columns, $args);
		$dynamic = [
			"class" => "_tf_eedu_display_student_class"
		];
		$dynamic = apply_filters("eedu_stud_not_in_class_dynamic_columns", $dynamic, $args);
		$table->set_display_columns($columns);
		$table->set_dynamic_columns($dynamic);
		$table->set_action_links([
			"Restore" => false
		]);
		$table->set_action_callback([
			"Restore" => "eedu_portal_restore_student_to_class"
		]);
		$table->set_action_access([
			"Restore" => "eedu_portal_remove_student_from_class"
		]);
		$table->set_action_args([
			"Restore" => [
				"studentid" => "id", 
				"class" => $class['class'],
				"category" => $class['category'],
				"term" => $args['term'],
				"session" => $session,
				"callback" => "click",
				"callbackid" => "#search-query-btn"
			]
		]);
		$html .= "<div class=\"row\">
				<div class=\"col-md-12\">
			        <div class=\"card\">
			            <div class=\"card-header\">
			                <strong class=\"card-title\">REMOVED</strong>
			            </div>
			            <div class=\"card-body\">";
		$html .= $table->table_html();                
		$html .= "</div>
		            	        </div>
		            	    </div>
		                </div>";
	}

	return $html;
}