<?php 

// session_start();

require_once("../../../config.php");
require_once("../../../app/functions.php");
require_once("../../../app/table-functions.php");
// require_once("../../../app/includes/phpmailer/class.phpmailer.php");
spl_autoload_register(function($class_name) {
	$file = "../../../app/classes/class-".$class_name.".php";
	if (file_exists($file)) {
		include $file;
	}
});

require_once("../plugins.php");
$plugins = new plugins();
$plugins->load();

$session = Session::getInstance();


if ($_SERVER["REQUEST_METHOD"] == "POST") :

	if(isset($_POST['action'])){
		$response = array();
		$args = sanitize($_POST);
		unset($args['action']);
		$user = new user;
		$post = new post;
		$support = new support(['software_engineer', 'super_admin', 'admin']);

		switch ($_POST['action']) {

			case 'forget':
				$usermeta = get_user_meta($args['username']);
				if($usermeta) {
					$otp = generate_otp($usermeta['id']);
					$response['user_id'] = $usermeta['id'];
					if($otp[1] && $otp[2]->status == 'OK') {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your email and phone number. Enter the pin in the field above. Pin expires in 15 minutes';
					} else if($otp[1] && $otp[2]->errno) {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your email. Enter the pin in the field above. Pin expires in 15 minutes';
					} else if(!$otp[1] && $otp[2]->status == 'OK') {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your phone number. Enter the pin in the field above. Pin expires in 15 minutes';
					} else {
						$response['error'] = 1;
						$response['msg'] = 'Sorry, email and text message could not be sent. Password could not be retrived';
					}
				} else {
					$response['error'] = 1;
					$response['msg'] = 'Staff number or student ID do not match any of our records';
				}
				echo json_encode($response);
				exit();
				break;

			case 'verifyotp':
				$verify = verifyotp($args['otp'], $args['user_id']);
				if($verify) {
					$authe = SHA1(rand(9999999999, 9999999999999));
					$loggon_key = SHA1(time(). SALT);
					$user->update_user_meta($args['user_id'], array('loggon_key' => $loggon_key, 'authe' => $authe));
					$session->id = $args['user_id'];
					$session->key = $loggon_key;
					$response['authe'] = $authe;
					$response['error'] = 0;
					$response['msg'] = 'Thank you for verifying your account ownership. You can now change your password.';
				} else {
					$response['error'] = 1;
					$response['msg'] = 'You entered a wrong pin';
				}
				echo json_encode($response);
				exit();
				break;

			case 'add_class':
				$args['type'] = 'class';
				if(db_post_unique(['type' => 'class', 'class_name' => $args['class_name']])) {
					$response['error'] = 1;
					$response['msg'] = 'Class name is not unique';
					echo json_encode($response);
					exit();
				}
				if(db_post_unique(['type' => 'class', 'order' => $args['order']])) {
					$response['error'] = 1;
					$response['msg'] = 'Order is not unique';
					echo json_encode($response);
					exit();
				}
				if($post->add_post($args)) {
					$response['error'] = 0;
					$response['msg'] = $args['class_name'].' Class Added Successfully';
					echo json_encode($response);
					exit();
				}
				break;

			case 'add_category':
				$args['type'] = 'category';
				if(db_post_unique(['type' => 'category', 'category_name' => $args['category_name']])) {
					$response['error'] = 1;
					$response['msg'] = 'Category name is not unique';
					echo json_encode($response);
					exit();
				}
				if(db_post_unique(['type' => 'category', 'order' => $args['order']])) {
					$response['error'] = 1;
					$response['msg'] = 'Order is not unique';
					echo json_encode($response);
					exit();
				}
				if($post->add_post($args)) {
					$response['error'] = 0;
					$response['msg'] = $args['class_name'].' Category Added Successfully';
					echo json_encode($response);
					exit();
				}
				break;

			case 'edit_class':
				if($existing = db_post_unique(['type' => 'class', 'class_name' => $args['class_name']])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Class name is not unique';
						echo json_encode($response);
						exit();
					}
				}
				if($existing = db_post_unique(['type' => 'class', 'order' => $args['order']])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Order is not unique';
						echo json_encode($response);
						exit();
					}
				}
				$post->update_post_meta($args['id'], $args);
				eedu_portal_reset_class_name($args['id']);
				$response['error'] = 0;
				$response['msg'] = 'Done';
				echo json_encode($response);
				exit();
				break;

			case 'edit_category':
				if($existing = db_post_unique(['type' => 'category', 'category_name' => $args['category_name']])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Category name is not unique';
						echo json_encode($response);
						exit();
					}
				}
				if($existing = db_post_unique(['type' => 'category', 'order' => $args['order']])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Order is not unique';
						echo json_encode($response);
						exit();
					}
				}
				$post->update_post_meta($args['id'], $args);
				eedu_portal_reset_category_name($args['id']);
				$response['error'] = 0;
				$response['msg'] = $args['category_name'].' Category updated Successfully';
				echo json_encode($response);
				exit();
				break;

			case 'add_courses':
				$args['type'] = 'course';
				if(course_name_exists($args['course_name'])) {
					$response['error'] = 1;
					$response['msg'] = $args['course_name'].' Course Exists';
					echo json_encode($response);
					exit();
				}
				if($post->add_post($args)) {
					$response['error'] = 0;
					$response['msg'] = $args['course_name'].' Course Added Successfully';
					echo json_encode($response);
					exit();
				}
				break;

			case 'add_subject_branch':
				$args['type'] = 'subject_branch';
				if(db_post_unique(['type' => 'subject_branch', 'course_name' => trim($args['course_name'])])) {
					$response['error'] = 1;
					$response['msg'] = $args['course_name'].' Branch Exists';
					echo json_encode($response);
					exit();
				}
				if($post->add_post($args)) {
					$response['error'] = 0;
					$response['msg'] = $args['course_name'].' Branch Added Successfully';
					echo json_encode($response);
					exit();
				}
				break;

			case 'edit_subject_branch':
				$args['type'] = 'subject_branch';
				if($existing = db_post_unique(['type' => 'subject_branch', 'course_name' => trim($args['course_name'])])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = $args['course_name'].' Branch Exists';
						echo json_encode($response);
						exit();
					}
				}
				$post->update_post_meta($args['id'], $args);
				$response['error'] = 0;
				$response['msg'] = $args['course_name'].' Branch Updated Successfully';
				echo json_encode($response);
				exit();
				break;

			case "get_subject_branch":
				$rows = $post->get_post_by_meta_data(['type' => 'subject_branch']);
				$table = new table("branch-table", $rows);
			    $table->set_display_columns([
			        "sn" => "SN",
			        "course_name" => "Branch Name",
			        "course_id" => "Linked Course/Subject"
			    ]);
			    $table->set_dynamic_columns([
			    	"course_id" => "_tf_eedu_get_course_name"
			    ]);
			    $table->set_action_links([
		    		"Edit" => "edit-subject-branch"
			    ]);
			    $table->set_action_access([
			    	"Edit" => 'edit_subject_branch'
			    ]);
			    $table->set_action_callback([
			    	"Edit" => false
			    ]);
			    $table->set_action_args([
			    	"Edit" => ["id" => "id"]
			    ]);
			    $response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "get_courses":
				$rows = $post->get_post_by_meta_data(['type' => 'course']);
				$table = new table("course-table", $rows);
			    $table->set_display_columns([
			        "sn" => "SN",
			        "course_name" => "Subject Name",
			        "course_code" => "Subject Code",
			        "course_type" => "Type"
			    ]);
			    $table->set_action_links([
		    		"Edit" => "edit-course"
			    ]);
			    $table->set_action_access([
			    	"Edit" => 'edit_course'
			    ]);
			    $table->set_action_callback([
			    	"Edit" => false
			    ]);
			    $table->set_action_args([
			    	"Edit" => ["id" => "id"]
			    ]);
			    $response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case 'edit_course':
				if($existing = db_post_unique(['type' => 'course', 'course_name' => trim($args['course_name'])])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = $args['course_name'].' Course Exists';
						echo json_encode($response);
						exit();
					}
				}
				$post->update_post_meta($args['id'], $args);
				$response['error'] = 0;
				$response['msg'] = $args['course_name'].' Course Updated Successfully';
				echo json_encode($response);
				exit();
				break;

			case 'assign_courses':
				$courses = $args['courses'];
				update_option('course_mapping', $courses);
				$response['error'] = 0;
				$response['msg'] = $args['class'].' Courses Mapped Successfully';
				eedu_portal_reset_class_courses();
				echo json_encode($response);
				exit();
				break;

			case 'category_mapping':
				$categories = $args['categories'];
				$formated = [];
				if(_count($categories) > 0) {
					foreach ($categories as $class => $category) {
						foreach ($category as $key => $value) {
							if($value == 'on')
								$formated[$class][] = $key;
						}
					}
				}
				update_option('category_mapping', $formated);
				$response['error'] = 0;
				$response['msg'] = $args['class'].' Categories Mapped Successfully';
				echo json_encode($response);
				exit();
				break;

			case 'assign_teachers':
				$teacher_mapping = get_option("teacher_mapping");
				$teacher_mapping[$args['class']][$args['category']] = $args['teacher'];
				update_option('teacher_mapping', $teacher_mapping);
				// update_option('form_teacher_mapping', $args['formteacher']);
				$response['error'] = 0;
				$response['msg'] = 'Teachers Assigned Successfully';
				echo json_encode($response);
				exit();
				break;

			case 'assign_form_teachers':
				update_option('form_teacher_mapping', $args['form_teacher']);
				$response['error'] = 0;
				$response['msg'] = 'Form Teachers Assigned Successfully';
				echo json_encode($response);
				exit();
				break;


			case 'add_student':
				$args['promotion'] = 1;
				$args['gender'] = display_gender($args['gender']);
				$n1_phone = trim_array(explode(",", $args['n1_phone']));
				$args['state_reg_number'] = trim($args['state_reg_number']);
				$args['state_reg_number'] = strtoupper($args['state_reg_number']);
				if($args['state_reg_number'] !== "") {
					if($existing = db_user_unique(['state_reg_number' => $args['state_reg_number']])) {
						$response['msg'] = get_fullname($existing)." in ".get_class_name($existing['class'], $existing['category'])." has already been assigned the state reg number ".$args['state_reg_number'];
						$response['error'] = 1;
						echo json_encode($response);
						exit();
					}
				}
				if(_count($n1_phone)) {
					foreach ($n1_phone as $key => &$value) {
						$value = internationalize_phone_number($value);
					}
				}
				$args['n1_phone'] = implode(", ", $n1_phone);
				$n2_phone = trim_array(explode(",", $args['n2_phone']));
				if(_count($n2_phone)) {
					foreach ($n2_phone as $key => &$value) {
						$value = internationalize_phone_number($value);
					}
				}
				$args['n2_phone'] = implode(", ", $n2_phone);
				$n3_phone = trim_array(explode(",", $args['n3_phone']));
				if(_count($n3_phone)) {
					foreach ($n3_phone as $key => &$value) {
						$value = internationalize_phone_number($value);
					}
				}
				$args['n3_phone'] = implode(", ", $n3_phone);
				$args['status'] = 'active';
				$response = $user->register_user($args);
				if($result['error'] == 0) {
					update_students_id_in_class($args['class'], $args['category']);
				}
				echo json_encode($response);
				exit();
				break;

			case 'edit_student_profile':
				$profile_picture = $args['imagebase64'];
				$args['gender'] = display_gender($args['gender']);
				unset($args['imagebase64']);
				$folder = '/'.$args['id'].'/profile-picture/';
				$args = process_croppie_upload($args, "profile_picture", $_FILES, $folder, $response);
				$args['state_reg_number'] = trim($args['state_reg_number']);
				$args['state_reg_number'] = strtoupper($args['state_reg_number']);
				if($args['state_reg_number'] !== "") {
					if($existing = db_user_unique(['state_reg_number' => $args['state_reg_number']])) {
						if($existing['id'] !== $args['id']) {
							$response['msg'] = get_fullname($existing)." in ".get_class_name($existing['class'], $existing['category'])." has already been assigned the state reg number ".$args['state_reg_number'];
							$response['error'] = 1;
							echo json_encode($response);
							exit();
						}
						
					}
				}
				if(isset($args['n1_phone'])) {
					$args['n1_phone'] = internationalize_phone_number($args['n1_phone']);
				}
				if(isset($args['n2_phone'])) {
					$args['n2_phone'] = internationalize_phone_number($args['n2_phone']);
				}
				if(isset($args['n3_phone'])) {
					$args['n3_phone'] = internationalize_phone_number($args['n3_phone']);
				}
				if(isset($args['phone'])) {
					$args['phone'] = internationalize_phone_number($args['phone']);
				}
				if($user->update_user_meta($args['id'], $args)) {
					update_students_id_in_class($args['class']);
					$response['msg'] = 'Student record updated successfully';
					$response['error'] = 0;	
				} else {
					$response['msg'] = 'No changes was made';
					$response['error'] = 1;	
				}
				echo json_encode($response);
				exit();
				break;

			case 'add_staff':
				$args['phone'] = internationalize_phone_number($args['phone']);
				$args['gender'] = display_gender($args['gender']);
				$args['role'] = 'teacher';
				if(get_option('email_activation') == 'email_activation') {
					$args['status'] = 'inactive';
				} else $args['status'] = 'active';
				$response = $user->register_user($args);
				echo json_encode($response);
				exit();
				break;

			case 'other_logo':
				unset($args['imagebase64']);
				$folder = 'customization/other_logo/';
				$args = process_croppie_upload($args, "other_logo", $_FILES, $folder, $response);
				update_option('other-logo', $args['other_logo']);
				$response['msg'] = 'Settings updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'school_settings':
				$absolute_average = ($args['absolute_average'] == 1) ? 1 : 0;
				update_option('absolute_average', $absolute_average);
				update_option('email_activation', $args['email_activation']);
				update_option('sch_ministry', $args['sch_ministry']);
				update_option('sch_ministry_branch', $args['sch_ministry_branch']);
				update_option('pref_name_for_principal', $args['pref_name_for_principal']);
				update_option('pref_name_for_form_teacher', $args['pref_name_for_form_teacher']);
				update_option('pref_name_for_class_prefect', $args['pref_name_for_class_prefect']);
				update_option('sch_abbr', $args['sch_abbr']);
				update_option('school_principal', $args['school_principal']);
				update_option('mtp', $args['mtp']);
				update_option('mcr', $args['mcr']);
				update_option('sch_logo_width', $args['sch_logo_width']);
				update_option('sch_logo_height', $args['sch_logo_height']);
				update_option('extra_activities', explode(',', $args['extra_activities']));
				update_option('grades', explode('\r\n', $args['grades']));
				update_option('mode_of_scoring', explode('\r\n', $args['mode_of_scoring']));
				update_option('behaviours_skills', explode(',', $args['behaviours_skills']));
				update_option('behaviour_rating', explode(',', $args['behaviour_rating']));
				update_option('behaviours_skills_caption', $args['behaviours_skills_caption']);
				update_option('rating_key', explode('\r\n', $args['rating_key']));
				update_option('default_comment', explode('\r\n', $args['default_comment']));
				update_option('rating_key_caption', $args['rating_key_caption']);
				update_option('promotion_interval', $args['promotion_interval']);
				update_option('role_names', explode('\r\n', $args['role_names']));
				$use_pins_to_access_results = ($args['use_pins_to_access_results'] == 1) ? 1 : 0;
				update_option('use_pins_to_access_results', $use_pins_to_access_results);
				$auto_verify_results = ($args['auto_verify_results'] == 1) ? 1 : 0;
				update_option('auto_verify_results', $auto_verify_results);
				$include_attendance_report_in_result = ($args['include_attendance_report_in_result'] == 1) ? 1 : 0;
				update_option('include_attendance_report_in_result', $include_attendance_report_in_result);
				$auto_comment_on_result = ($args['auto_comment_on_result'] == 1) ? 1 : 0;
				update_option('auto_comment_on_result', $auto_comment_on_result);
				$auto_comment_on_annual = ($args['auto_comment_on_annual'] == 1) ? 1 : 0;
				update_option('auto_comment_on_annual', $auto_comment_on_annual);
				$print_with_paperhead = ($args['print_with_paperhead'] == 1) ? 1 : 0;
				update_option('print_with_paperhead', $print_with_paperhead);
				update_option('current_academic_term', $args['term']);
				$term_meta = $post->get_post_meta($args['term']);
				update_option('current_academic_session', $term_meta['acsession']);
				// section database
				do_action('save_more_school_settings_field', $args);

				$response['msg'] = 'Settings updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_db_sections':
				$all = (isset($args['all'])) ? $args['all'] : true;
				$response['deactivate'] = base64_encode("deactivate_post");
				$response['activate'] = base64_encode("activate_post");
				$response['sections'] = get_db_sections($all);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'add_db_section':
				$section_field = get_option("section_field");
				if(!db_section_field_name_is_valid($section_field)) {
					$response['error'] = 1;
					$response['msg'] = 'Please set up the section field first. If not empty, use a unique field name';
					echo json_encode($response);
					exit();
				}
				if(!db_section_name_unique($args['section_name'], $section_field)) {
					$response['error'] = 1;
					$response['msg'] = 'Database section name is not unique';
					echo json_encode($response);
					exit();
				}
				$args['type'] = $section_field;
				$args['status'] = 'active';
				$post->add_post($args);
				$response['msg'] = "Database Section added successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'schedule_school_event':
				$start = strtotime($args['start'].' '.$args['starttime']);
				$end = strtotime($args['end'].' '.$args['endtime']);
				mark_calendar($args['event_title'], $start, $end);
				$response['msg'] = 'Schedule recorded successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'update_school_event':
				$start = strtotime($args['start'].' '.$args['starttime']);
				$end = strtotime($args['end'].' '.$args['endtime']);
				$post->update_post_meta($args['id'], ['start' => $start, 'end' => $end, 'event' => $args['event_title']]);
				$response['msg'] = 'Schedule updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'edit_timetable':
				$timetable = get_option('timetable');
				$timetable[$args['class']][$args['category']] = $args['period'];
				update_option('timetable', $timetable);
				$response['msg'] = 'Timetable updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'save_gradebook':
				$args['result'] = serialize($args['result']);
				$args['result'] = base64_encode($args['result']);
				$args['type'] = 'result';
				$args['status'] = get_option('auto_verify_results') ? 'verified' : 'in process';
				$existing = $post->get_post_by_meta_data(['type' => 'result', 'class' => $args['class'], 'category' => $args['category'], 'course' => $args['course'], 'term' => $args['term'], 'session' => $args['session']]);
				if(_count($existing) > 0) {
					$id = array_shift($existing)['id'];
					$post->update_post_meta($id, $args);
					$response['e'] = $existing;
					$response['pId'] = base64_encode($id);
					$response['msg'] = 'Done';
				} else {
					$id = $post->add_post($args);
					$response['pId'] = base64_encode($id);
					$response['msg'] = 'Done';
				}
				eedu_portal_reset_broadsheet($args['class'], $args['category'], $args['term']);
				eedu_portal_reset_broadsheet($args['class'], "", $args['term']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'edit_psychometrics':
				foreach ($args as $student_id => $psy) {
					$psy = serialize($psy);
					$user->update_user_meta($student_id, ['psychometrics' => $psy]);
				}
				$response['msg'] = 'Data updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'ft_comment':
				if(_count($args['comment']) > 0) :
				foreach ($args['comment'] as $student_id => $comment) {
					$student_meta = $user->get_user_meta($student_id);
					$existing = isset($student_meta['position']) && is_serialized($student_meta['position']) ? unserialize($student_meta['position']) : array();
					$existing[$args['term']]['ft_comment'] = $comment;
					$promote = ($args['promotion'][$student_id] == 1) ? 1 : 0;
					$user->update_user_meta($student_id, ['position' => serialize($existing), 'promotion' => $promote]);
				}
				// $response['args'] = $args;
				$response['msg'] = 'Comments updated successfully';
				$response['error'] = 0;
				else :
					$response['msg'] = 'No records to update';
					$response['error'] = 1;
				endif;
				echo json_encode($response);
				exit();
				break;

			case 'edit_curriculum':
				foreach ($args['curriculum'] as $sn => $cur) {
					if($cur['timeline'] != '' && $cur['topic'] == '') {
						$response['msg'] = 'Please fill out the topic for '.$cur['timeline'].' period';
						$response['error'] = 1;
						echo json_encode($response);
						exit();
					}
					if($cur['timeline'] == '' && $cur['topic'] != '') {
						$response['msg'] = 'Please fill out timeline for '.$cur['topic'];
						$response['error'] = 1;
						echo json_encode($response);
						exit();
					}
					if($cur['timeline'] == '' && $cur['topic'] == '') {
						unset($args['curriculum'][$sn]);
					}
				}
				if(_count($args['curriculum']) < 1) {
					$response['msg'] = 'You did not make any Entry';
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$args['curriculum'] = serialize($args['curriculum']);
				$curriculum = get_option('curriculum');
				if(!$curriculum) 
					$curriculum = [];
				$curriculum[$args['term']][$args['class']][$args['category']][$args['course']] = $args['curriculum'];
				update_option('curriculum', $curriculum);
				$response['msg'] = 'Curriculum updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'edit_academic_term':
				$term_meta = $post->get_post_meta($args['id']);
				$session_name = get_session_name($term_meta['acsession']);
				$args['term_begins'] = (isset($args['term_begins']) && $args['term_begins'] != "") ? strtotime($args['term_begins']) : 0;
				$args['term_ends'] = (isset($args['term_ends']) && $args['term_ends'] != "") ? strtotime($args['term_ends']) : 0;
				$args['startup_test_starts'] = (isset($args['startup_test_starts']) && $args['startup_test_starts'] != "") ? strtotime($args['startup_test_starts']) : 0;
				$args['startup_test_ends'] = (isset($args['startup_test_ends']) && $args['startup_test_ends'] != "") ? strtotime($args['startup_test_ends']) : 0;
				$args['midterm_test_starts'] = (isset($args['midterm_test_starts']) && $args['midterm_test_starts'] != "") ? strtotime($args['midterm_test_starts']) : 0;
				$args['midterm_test_ends'] = (isset($args['midterm_test_ends']) && $args['midterm_test_ends'] != "") ? strtotime($args['midterm_test_ends']) : 0;
				$args['midterm_break_starts'] = (isset($args['midterm_break_starts']) && $args['midterm_break_starts'] != "") ? strtotime($args['midterm_test_starts']) : 0;
				$args['midterm_break_ends'] = (isset($args['midterm_break_ends']) && $args['midterm_break_ends'] != "") ? strtotime($args['midterm_break_ends']) : 0;
				$args['exam_starts'] = (isset($args['exam_starts']) && $args['exam_starts'] != "") ? strtotime($args['exam_starts']) : 0;
				$args['exam_ends'] = (isset($args['exam_ends']) && $args['exam_ends'] != "") ? strtotime($args['exam_ends']) : 0;
				$args['next_term_begins'] = (isset($args['next_term_begins']) && $args['next_term_begins'] != "") ? strtotime($args['next_term_begins']) : 0;
				$post->update_post_meta($args['id'], $args);
				$response['msg'] = 'Academic Term Updated Successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'change_password':
				if(!isset($session->id)) {
					$response['msg'] = 'Invalid submission';
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				if(! $user->user_login($session->id, $args['current_password'])) {
					$response['msg'] = 'Your current password is incorrect';
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				unset($args['current_password']);
				unset($args['retype_password']);
				if ($user->update_user_meta($session->id, $args)) {
					$response['msg'] = 'Your password was changed successfully';
					$response['error'] = 0;
					echo json_encode($response);
					exit();
				}
				$response['msg'] = 'Your password is still the same as the former one';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'change_password2':
				if(!isset($session->id)) {
					$response['msg'] = 'Invalid submission';
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$args['authe'] = '';
				unset($args['retype_password']);
				if ($user->update_user_meta($session->id, $args)) {
					$response['msg'] = 'Your password was changed successfully';
					$response['error'] = 0;
					echo json_encode($response);
					exit();
				}
				$response['msg'] = 'Your password is still the same as the former one';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_site_logo':
				$response['logo'] = get_option("company-logo");
				$response['desc'] = get_option("company_name");
				echo json_encode($response);
				exit();
				break;

			case 'edit_user_profile':
				$profile_picture = $args['imagebase64'];
				$args['gender'] = display_gender($args['gender']);
				unset($args['imagebase64']);
				$folder = $args['id'];
				$path = ABSPATH.UPLOADFOLDER.'/'.$folder.'/profile-picture/';
				if($profile_picture != '') {
					$res = upload_base64_image($profile_picture, 'profile_picture', $path, $_FILES);
					if($res[0] == 1) {
						$args['profile_picture'] = str_replace(ABSPATH, '', $res[1]);
					}
				}
				$args['phone'] = internationalize_phone_number($args['phone']);
				$res = $user->update_user_meta($args['id'], $args);
				if($res) {
					$info = "Your profile has just been updated";
					$home_url = get_option("home_url");
					inform_user($args['id'], $info, "PROFILE UPDATE", $home_url."profile", EMAIL, NOTIFICATION);
					if(current_user_can('admin') && $session->id != $args['id']) {
						$info = $args['surname']." ".$args['other_names'].": Profile updated";
						admin_log($info);
					}
				}
				$response['msg'] = 'Profile updated successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'nominate_class_prefect':
				$prefect_mapping = get_option('prefect_mapping');
				foreach ($args['prefect'] as $class => $prefect) {
					$prefect_mapping[$class] = $prefect;
				}
				update_option('prefect_mapping', $prefect_mapping);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'mark_attendance':
				$option = "attendance_".$args['term']."_".$args['class'];
				update_option($option, $args['att']);
				$response['msg'] = "Attendance register saved";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'promotion_order':
				update_option('promotion_order', $args['promotionorder']);
				$response['msg'] = "Your settings have been saved";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'upload_signature':
				$folder = $args['id'].'/signature/';
				$args = process_croppie_upload($args, "signature", $_FILES, $folder, $response);
				$user->update_user_meta($args['id'], $args);
				$response['msg'] = "Your settings have been saved";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_session':
				$term_meta = $post->get_post_meta($args['term']);
				$response['session'] = $term_meta['acsession'];
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'reassign_students':
				foreach ($args['category'] as $student_id => $category_id) {
					$user->update_user_meta($student_id, ['category' => $category_id]);
				}
				update_students_id_in_class($args['class']);
				$response['msg'] = 'Students successfully reassigned';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_class_courses':
				if($args['fulloption']) {
					$response['courses'] = get_class_courses($args['class_id'], $args['category_id'], false, false); 
				} else $response['courses'] = get_class_courses($args['class_id'], $args['category_id']); 
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_class_subjects':
				$class_selection = eedu_portal_get_class_selection($args['selection']);
				if($args['fulloption']) {
					$response['courses'] = get_class_courses($class_selection['class'], $class_selection['category'], false, false); 
				} else $response['courses'] = get_class_courses($class_selection['class'], $class_selection['category']); 
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'update_students_in_class':
				$term = (isset($args['term']) && (int) $args['term'] > 0 )? $args['term'] : false;
				$session = (isset($args['session']) && (int) $args['session'] > 0) ? $args['session'] : false;
				$category = (isset($args['category']) && (int) $args['category'] > 0) ? $args['category'] : false;
				update_students_id_in_class($args['class'], false, $term, $session);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_ac_sessions':
				$response['current'] = get_option("current_academic_session");
				$response['acsessions'] = $post->get_post_by_meta_data(['type' => 'academic_session']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'new_academic_session':
				$existing = $post->get_post_by_meta_data(['type' => 'academic_session', 'session_name' => $args['session_name']]);
				if(_count($existing)) {
					$response['error'] = 1;
					$response['msg'] = "Academic session name already exists";
					echo json_encode($response);
					exit();
				}
				$args['type'] = "academic_session";
				$args['posted_on'] = strtotime($arg['posted_on']);
				$post->add_post($args);
				$response['msg'] = "Academic Session Added Successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'add_new_term':
				$args['term_name'] = ucwords($args['term_name']);
				$session_name = get_session_name($term_meta['acsession']);
				$existing = $post->get_post_by_meta_data(['type' => 'academic_term', 'term_name' => $args['term_name'], 'acsession' => $args['acsession']]);
				if(_count($existing)) {
					$response['error'] = 1;
					$response['msg'] = "Academic term name already exists within the session ".get_session_name($args['acsession']);
					echo json_encode($response);
					exit();
				}
				$tstart = $tend = $ststart = $stend = $mtstart = $mtend = $mbstart = $mbend = $estart = $eend = 0;
				
				if($args['term_begins'] != '') :
					$tstart = strtotime($args['term_begins']);
					$tend = strtotime($args['term_ends']);
				endif;

				if($args['startup_test_starts'] != '') :
					$ststart = strtotime($args['startup_test_starts']);
					$stend = strtotime($args['startup_test_ends']);
				endif;

				if($args['midterm_test_starts'] != '') :
					$mtstart = strtotime($args['midterm_test_starts']);
					$mtend = strtotime($args['midterm_test_ends']);
				endif;

				if($args['midterm_break_starts'] != '') :
					$mbstart = strtotime($args['midterm_break_starts']);
					$mbend = strtotime($args['midterm_break_ends']);
				endif;

				if($args['exam_starts'] != '') :
					$estart = strtotime($args['exam_starts']);
					$eend = strtotime($args['exam_ends']);
				endif;

				$meta = [
					'order' => $args['order'],
					'term_begins' => (int) $tstart,
					'term_ends' => (int) $tend,
					'term_name' => $args['term_name'],
					'next_term_begins' => (int) strtotime($args['next_term_begins']),
					'startup_test_starts' => (int) $ststart,
					'startup_test_ends' => (int) $stend,
					'midterm_test_starts' => (int) $mtstart,
					'midterm_test_ends' => (int) $mtend,
					'midterm_break_starts' => (int) $mbstart,
					'midterm_break_ends' => (int) $mbend,
					'exam_starts' => (int) $estart,
					'exam_ends' => (int) $eend,
					'acsession' => $args['acsession'],
					'type' => 'academic_term'
				];

				$id = $post->add_post($meta);

				if($args['term_begins'] != '') :
					$ttag = 'resumptiondate'.$id;
					$tevent = 'School resumes for '.$args['term_name'].' '.$session_name;
					mark_calendar($tevent, $tstart, $tend, $ttag);
				endif;

				if($args['startup_test_starts'] != '') :
					$sttag = 'startuptest'.$id;
					$stevent = 'Start up test for '.$args['term_name'].' '.$session_name;
					mark_calendar($stevent, $ststart, $stend, $sttag);
				endif;

				if($args['midterm_test_starts'] != '') :
					$mttag = 'midtermtest'.$id;
					$mtevent = 'Midterm test for '.$args['term_name'].' '.$session_name;
					mark_calendar($mtevent, $mtstart, $mtend, $mttag);
				endif;

				if($args['midterm_break_starts'] != '') :
					$mbtag = 'midtermbreak'.$id;
					$mbevent = 'Midterm break for '.$args['term_name'].' '.$session_name;
					mark_calendar($mbevent, $mbstart, $mbend, $mbtag);
				endif;

				if($args['exam_starts'] != '') :
					$etag = 'exam'.$id;
					$eevent = 'End of Term Examination for '.$args['term_name'].' '.$session_name;
					mark_calendar($eevent, $estart, $eend, $etag);
				endif;
				$response['msg'] = "Academic Term Added Successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "remove_post_item":
				$post->drop_post($args['id']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "get_category_mapping":
				$sorting = new sorting;
				$response['classes'] = $post->get_post_by_meta_data(['type' => 'class']);
				$response['classes'] = $sorting->sort_by_meta_value($response['classes'], 'order', 'ASC');
				$response['categories'] = $post->get_post_by_meta_data(['type' => 'category']);
				$response['categories'] = $sorting->sort_by_meta_value($response['categories'], 'order', 'ASC');
				$response['category_mapping'] = get_option("category_mapping");
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'promote_checker':
				$user->update_user_meta($args['student_id'], ['promotion' => $args['promotion']]);
				exit();
				break;

			case 'get_promotion_order':
				$response['promotion_order'] = get_option('promotion_order');
				if(_count($response['promotion_order'])) {
					foreach($response['promotion_order'] as $key => &$value) {
						$value = [$value, get_class_name($value)];
					}
				}
				echo json_encode($response);
				exit();
				break;

			//deprecating
			case 'promote_class_students':
				$session_name = get_session_name($args['session']); //graduation year
				$students = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active', 'class' => $args['class']]);
				if(_count($students) > 0) :
					foreach ($students as $student_meta) {
						promote_student($student_meta, $session_name);
					}
				endif;
				$response['class_promoted_to'] = get_next_class($args['class'], false);
				$response['class_name'] = get_class_name($args['class']);
				$response['c'] = $args['class'];
				$response['next_class'] = get_next_class($args['class'], true);
				echo json_encode($response);
				exit();
				break;

			case 'promote_waiting_list':
				$students = $user->get_user_by_meta_data(['role' => 'fresher', 'status' => 'active']);
				if(_count($students)) {
					foreach ($students as $student_meta) {
						$user->update_user_meta($student_meta["id"], ["role" => "student", 'last_promoted' => time(), 'promotion' => 1]);
					}
				}
				echo json_encode($response);
				exit();
				break;

			case 'close_promotion':
				$post->update_post_meta($args['session'], ['promotion' => 1]);
				echo json_encode($response);
				exit();
				break;

			// case 'school_population':
			// 	$classes = $post->get_post_by_meta_data(['type' => 'class']);
			// 	$res = array();
			// 	if(_count($classes)) {
			// 		foreach ($classes as $key => $class_meta) {
			// 			// students in the class
			// 			$all_students = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active', 'class' => $class_meta['id']]);
			// 			$male = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active', 'class' => $class_meta['id'], 'gender' => ['male', 'm']]);
			// 			$female = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active', 'class' => $class_meta['id'], 'gender' => ['female', 'f']]);
			// 			$res[$class_meta['class_name']]["class_name"] = $class_meta['class_name'];
			// 			$res[$class_meta['class_name']]["students"]["male"] = _count($male);
			// 			$res[$class_meta['class_name']]["students"]["female"] = _count($female);
			// 			$res[$class_meta['class_name']]["students"]["unknown"] = _count($all_students) - (_count($male) + _count($female));
			// 		}
			// 	}
			// 	$response['res'] = $res;
			// 	echo json_encode($response);
			// 	exit();
			// 	break;

			case 'get_classes_for_analytics':
				$response['classes'] = $post->get_post_by_meta_data(['type' => 'class'], 'LIKE', true);
				$response['category'] = $post->get_post_by_meta_data(['type' => 'category'], 'LIKE', true);
				$response['category_mapping'] = get_option('category_mapping');
				$students = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active']);
				if(_count($students)) {
					foreach ($students as $key => $student_meta) {
						if(isset($response['students'][$student_meta['class']][$student_meta['category']])) {
							$response['students'][$student_meta['class']][$student_meta['category']]++;
						} else $response['students'][$student_meta['class']][$student_meta['category']] = 1;
						$gender = display_gender($student_meta['gender']);
						if(isset($response['gender'][$student_meta['class']][$student_meta['category']][$gender])) {
							$response['gender'][$student_meta['class']][$student_meta['category']][$gender]++;
						} else $response['gender'][$student_meta['class']][$student_meta['category']][$gender] = 1;
					}
				}
				echo json_encode($response);
				exit();
				break;

			case 'refreshlist':
				$people = (function_exists('get_bulk_receivers')) ? get_bulk_receivers($args['people']) : alt_get_bulk_receivers($args['people']);
				force_update_students_id_in_class($args['class'], $args['category'], $people, $args['term'], $args['session'], true);
				$response['error'] = 0;
				$response['msg'] = 'List refreshed successfully';
				echo json_encode($response);
				exit();
				break;

			case 'addtolist':
				$people = (function_exists('get_bulk_receivers')) ? get_bulk_receivers($args['people']) : alt_get_bulk_receivers($args['people']);
				force_update_students_id_in_class($args['class'], $args['category'], $people, $args['term'], $args['session'], false);
				$response['error'] = 0;
				$response['msg'] = 'Students added to list successfully';
				echo json_encode($response);
				exit();
				break;

			case 'remove_student_from_class':
				remove_student_id_from_class($args['class'], $args['category'], $args['studentid'], $args['term'], $args['session']);
				echo json_encode($response);
				exit();
				break;

			case 'return_student_to_class':
				return_student_id_to_class($args['class'], $args['category'], $args['studentid'], $args['term'], $args['session']);
				echo json_encode($response);
				exit();
				break;

			case 'get_students_in_class':
				$students = array();
				$_students = get_students_in_class($args['session'], $args['term'], $args['class'], $args['category']);
				$notstudents = array();
				$_notstudents = get_students_not_in_class($args['session'], $args['term'], $args['class'], $args['category']);
				if(_count($_students)) {
					foreach ($_students as $key => $student_id) {
						$student_meta = $user->get_user_meta($student_id);
						$student_meta['classname'] = get_class_name($student_meta['class'], $student_meta['category']);
						$student_meta['studentphoto'] = get_user_image($student_meta);
						$student_meta['gender'] = display_gender($student_meta['gender']);
						$response['students'][] = $student_meta;
					}
				}
				if(_count($_notstudents)) {
					foreach ($_notstudents as $key => $student_id) {
						$student_meta = $user->get_user_meta($student_id);
						$student_meta['classname'] = get_class_name($student_meta['class'], $student_meta['category']);
						$student_meta['studentphoto'] = get_user_image($student_meta);
						$student_meta['gender'] = display_gender($student_meta['gender']);
						$response['notstudents'][] = $student_meta;
					}
				}
				$sorting = new sorting;
				$response['notstudents'] = $sorting->sort_by_meta_value($response['notstudents'], 'surname', 'asc');
				$response['students'] = $sorting->sort_by_meta_value($response['students'], 'surname', 'asc');
				echo json_encode($response);
				exit();
				break;

			case 'apply_minimum_subject':
				$args['type'] = 'minimum_subject';
				$check = $args;
				unset($check['minimum_subject']);
				if($res = db_post_unique($check)) {
					$post->update_post_meta($res['id'], $args);
					$response['msg'] = 'You have successfully updated minimum subject for the class and term';
					$response['error'] = 0;
				} else {
					$post->add_post($args);
					$response['msg'] = 'You have successfully added minimum subject for the class and term';
					$response['error'] = 0;
				}
				echo json_encode($response);
				exit();
				break;

			case 'get_minimum_subject':
				$all_class = $post->get_post_by_meta_data(['type' => 'class'], 'LIKE', true);
				$all_category = $post->get_post_by_meta_data(['type' => 'category'], 'LIKE', true);
				$all_academic_term = $post->get_post_by_meta_data(['type' => 'academic_term'], 'LIKE', true);
				$all_academic_session = $post->get_post_by_meta_data(['type' => 'academic_session'], 'LIKE', true);
				$response['minimum_subject'] = $post->get_post_by_meta_data(['type' => 'minimum_subject']);
				if(_count($response['minimum_subject'])) {
					foreach ($response['minimum_subject'] as $key => &$value) {
						$value['class_name'] = $all_class[$value['class']]['class_name'];
						$value['category_name'] = $all_category[$value['category']]['category_name'];
						$value['term_name'] = $all_academic_term[$value['term']]['term_name'];
						$value['session_name'] = $all_academic_session[$all_academic_term[$value['term']]['acsession']]['session_name'];
					}
				}
				echo json_encode($response);
				exit();
				break;

			case 'get_latest_users':
				$student_roles = ['student', 'fresher', 'candidate', 'alumni'];
				if($args['role'] === 'staff') {
					$role = get_system_roles($student_roles);
				} else {
					$role = $student_roles;
				}
				$q = ['role' => $role];
				$people = $user->get_user_by_meta_data($q, "LIKE", false, 20, 0, 'user_id', $order = 'DESC');
				$table = new table($args['role']."-table", $people);
				$table->set_display_columns([
					"sn" => "SN",
					"fullname" => "Fullname",
					"class" => "Class",
					"date_created" => "Reg. Date"
				]);
				$table->set_dynamic_columns([
					'class' => '_tf_eedu_display_student_class'
				]);
				$response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case 'process_result_checker':
				$student_meta = $user->get_user_meta($args['user_id'], 'user_id');
				if(!$student_meta) {
					$response['error'] = 1;
					$response['msg'] = 'Student ID is Incorrect';
					echo json_encode($response);
					exit();
				}
				// if(trim(strtolower($student_meta['surname'])) != trim(strtolower($args['surname']))) {
				// 	$response['error'] = 1;
				// 	$response['msg'] = 'Surname does not match the student ID';
				// 	echo json_encode($response);
				// 	exit();
				// }
				if(isset($args['mock']) && $args['mock'] == "mock" && trim($args['ext_exam']) == "") {
					$response['error'] = 1;
					$response['msg'] = 'Please specify the mock exam';
					echo json_encode($response);
					exit();
				}
				$resultPin = new resultPin;
				$pin_meta = $resultPin->verify_pin($args['pin']);
				if(!$pin_meta) {
					$response['error'] = 1;
					$response['msg'] = 'Sorry, you provided an incorrect pin';
					echo json_encode($response);
					exit();
				}
				// pin has not been used
				$result_search_options = ['type' => 'compiled_result', 'term' => $args['term'], 'student_id' => $student_meta['id']];
				if(isset($args['mock']) && $args['mock'] == "mock") {
					$result_search_options['type'] = 'compiled_mock_result';
					$result_search_options['exam'] = $args['ext_exam'];
					$response['link'] = 'mock-result-sheet';
				} else {
					$response['link'] = 'result-sheet';
				}
				if($pin_meta['valid'] == 1) {
					$result = db_post_unique($result_search_options);
					if(!$result) {
						$response['error'] = 1;
						$response['msg'] = 'Sorry, student has no termly result for the specified term.';
						echo json_encode($response);
						exit();
					} else {
						if($result['status'] == "unlocked" && isset($result['pin'])) {
							$response['error'] = 1;
							$response['msg'] = 'Sorry, the result for the selected term is already tied to another pin.';
							echo json_encode($response);
							exit();
						} else {
							$post->update_post_meta($result['id'], ['status' => 'unlocked', 'pin' => $pin_meta['id']]);
							$resultPin->update_pin_meta($pin_meta['id'], ['valid' => 0, 'result' => $result['id']]);
						}
					}
				} else {
					// pin has either been used or invalid
					$result = $post->get_post_meta($pin_meta['result']);
					if(!$result || $result['student_id'] != $student_meta['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Sorry, the pin that you provided is invalid.';
						echo json_encode($response);
						exit();
					} else {}

				}

				$response['error'] = 0;
				$response['msg'] = 'Result found. Please wait to be redirected.';
				$response['result'] = $result['id'];
				$response['token'] = new_token();
				// user login
				$loggon_key = SHA1(time(). SALT);
				$login_meta = (isset($student_meta['login_meta'])) ? unserialize($student_meta['login_meta']) : array();
				$login_meta = [
					'last_login' => time(),
					'loggon_key' => $loggon_key,
					'state' => 'online'
				];
				$login_meta = serialize($login_meta);
				unset($session->menu);
				$user->update_user_meta($student_meta['id'], array('loggon_key' => $loggon_key, 'login_meta' => $login_meta));
				$session->id = $student_meta['id'];
				$session->key = $loggon_key;
				// user login

				echo json_encode($response);
				exit();
				break;

			case "result_checker_get_user":
				$res = $user->get_user_meta($args['selector']);
				if($res) {
					$class = get_student_class_in_term($res["id"], $args['term']);
					$response = "<span class=\"alert-success pt-2 pb-2 d-block pr-2 pl-2\">Name: ".get_fullname($res)."</br>";
					// $response .= "Class: ".$class['class_name']."</span>";
				} else $response = "<em class=\"alert-warning pt-2 pb-2 d-block pr-2 pl-2\">Student is not yet found!</em>";
				echo json_encode($response);
				exit();
				break;

			case "load_class_list":
				$term_meta = $post->get_post_meta($args['term']);
				if(promotion_done_in_session($term_meta['acsession'])) {
					$section = $term_meta['acsession'];
					$students = array();
					$args['class'] = (isset($args['class']) && $args['class'] !== "") ? $args['class'] : false;
					$args['category'] = (isset($args['category']) && $args['category'] !== "") ? $args['category'] : false;
					$_students = get_students_in_class($section, $args['term'], $args['class'], $args['category']);
					if(_count($_students)) {
						foreach ($_students as $key => $student_id) {
							$students[] = $user->get_user_meta($student_id);
						}
					}
				} else {
					$query = ['role' => 'student', 'status' => 'active'];
					if(isset($args['category']) && $args['category'] !== "") {
						$query['category'] = $args['category'];
					}
					if(isset($args['class']) && $args['class'] !== "") {
						$query['class'] = $args['class'];
					}
					$students = $user->get_user_by_meta_data($query);
				}
				$table = new table("students-table", $students);
				$display = [
					'sn' => 'SN',
					'fullname' => 'Name',
					'username' => 'Student ID',
					'profile_picture' => 'Photo',
					'gender' => 'Sex',
					'class' => 'Class',
					'n1_fullname' => 'Parents',
					'n1_phone' => 'Parent Contact'
				];
				$dynamic = [
					'class' => '_tf_eedu_display_student_class'
				];
				$table->set_display_columns($display);
				$table->set_dynamic_columns($dynamic);
				$table->set_action_links(['Profile' => 'student-profile']);
				$table->set_action_access(['Profile' => 'view_student']);
				$table->set_action_args(['Profile' => ['id' => 'id']]);
				$response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			// deprecating
			case "load_compiled_results":
				$sorting = new sorting;
			    $term_meta = $post->get_post_meta($args['term']);
				
			    if($args['class'] !== 'all') {
			        $output = $post->get_post_by_meta_data(['type' => 'compiled_result', 'term' => $args['term'], 'session' => $term_meta['acsession'], 'class' => $args['class'], 'category' => $args['category']]);
			        if(!_count($output)) {
			            $output = $post->get_post_by_meta_data(['type' => 'compiled_result', 'term' => $args['term'], 'session' => $term_meta['acsession'], 'class' => $args['class']]);
			        }
			    } else {
			        $output = $post->get_post_by_meta_data(['type' => 'compiled_result', 'term' => $args['term'], 'session' => $term_meta['acsession']]);
			    }

				$output = $sorting->sort_by_meta_value($output, 'position', 'asc');

				$table = new table("results-table", $output);

				$display = [
					'sn' => 'SN',
					'student_id' => 'Name',
					'position' => 'Position',
					'class' => 'Class',
					'last_compiled' => 'Last Compiled',
					'ft_comment' => 'Comment',
					'print' => ''
				];
				$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);

				$response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			// deprecating
			case "edit_single_ft_comment":
				$post->update_post_meta($args['id'], ["ft_comment" => $args['comment'], "ft_custom_comment" => $args['comment']]);
				echo json_encode($args['comment']);
				exit();
				break;

			case "save_promotion_order":
				$args['type'] = "promotion_order";
				$args['condition'] = serialize($args['condition']);
				$args['condition'] = base64_encode($args['condition']);
				if($existing = db_post_unique(['type' => 'promotion_order', 'class' => $args['class']])) {
					$post->update_post_meta($existing['id'], $args);
				} else {
					$post->add_post($args);
				}
				$response['msg'] = "Done";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "maintain_students_in_class":
				$class = eedu_portal_get_class_selection($args['class_category']);
				$people = eedu_portal_get_class_students($class['class'], $class['category']);
				force_update_students_id_in_class($args['to_class'], $args['to_category'], $people, $args['to_term'], $args['to_session'], false);
				$response['msg'] = "Done";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "get_next_student_id":
				$response = get_next_username(true);
				echo json_encode($response);
				exit();
				break;

			default:
				$response['error'] = 1;
				$response['msg'] = 'You have not created a module to process this form submission';
				echo json_encode($response);
				exit();
				break;

		}
		// json_encode($response);
	}

endif;