<?php 

// session_start();

require_once("../../../config.php");
require_once("../../../app/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']);

		switch ($_POST['action']) {

			case 'add_candidate':
				$profile_picture = $args['imagebase64'];
				unset($args['imagebase64']);
				$args['role'] = 'candidate';
				$args['status'] = 'inactive';
				$n1_phone = trim_array(explode(",", $args['n1_phone']));
				if(_count($n1_phone)) {
					foreach ($n1_phone as $key => &$value) {
						$value = internationalize_phone_number($value);
					}
				}
				$args['n1_phone'] = implode(", ", $n1_phone);
				$args['promotion'] = 0;
				$args['username'] = $args['password'] = get_next_username();
				$response = $user->register_user($args);
				if($response['error'] == 0) {
					$path = ABSPATH.UPLOADFOLDER.'/'.$response['user_id'].'/profile-picture/';
					if($profile_picture != '') {
						$res = upload_base64_image($profile_picture, 'profile_picture', $path, $_FILES);
						if($res[0] == 1) {
							$user->update_user_meta($response['user_id'], ['profile_picture' => str_replace(ABSPATH, '', $res[1])]);
						}
					}
				}
				echo json_encode($response);
				exit();
				break;

			case 'add_entrance_exam_subject':
				if(!db_post_unique(['subject_name' => $args['subject_name'], 'type' => 'ent_subject'])) {
					$args['type'] = 'ent_subject';
					$args['classes_involved'] = serialize($args['classes_involved']);
					$res = $post->add_post($args);
					if($res) {
						$response['msg'] = "You have successfully added a new subject to the subject list!";
						$response['error'] = 0;
						echo json_encode($response);
						exit();
						break;
					} else {
						$response['msg'] = "Oops, Something went wrong!";
						$response['error'] = 1;
						echo json_encode($response);
						exit();
						break;
					}
				}
				$response['msg'] = "Oops! Subject name is not unique, consider editing the existing subject!";
				$response['error'] = 1;
				echo json_encode($response);
				exit();
				break;

			case 'get_ent_subjects':
				$response['subjects'] = $post->get_post_by_meta_data(['type' => 'ent_subject']);
				if(_count($response['subjects'])) {
					foreach ($response['subjects'] as $key => &$value) {
						$subj_involved = unserialize($value['classes_involved']);
						if(_count($subj_involved)) {
							foreach($subj_involved as &$subj) {
								$subj = get_class_name($subj);
							}
						}
						$value['classes_involved'] = implode(", ", $subj_involved);
					}
				}
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_class_subjects':
				$response['subjects'] = get_entrance_exam_subjects($args['class_id']);
				echo json_encode($response);
				exit();
				break;

			case 'upload_ent_exam':
				if($existing = db_post_unique(['type' => 'entrance_exam_result', 'adm_class' => $args['adm_class'], 'adm_term' => $args['adm_term']])) {
					$score = unserialize($existing['score']);
					if(_count($args['score'])) {
						foreach ($args['score'] as $candidate => $value) {
							$score[$candidate] = $value;
						}
					}
					$args['score'] = serialize($score);
					$post->update_post_meta($existing['id'], $args);
					$response['msg'] = "Examination scores updated successfully";
					$response['error'] = 0;
					echo json_encode($response);
					exit();
				} else {
					$args['type'] = 'entrance_exam_result';
					$args['score'] = serialize($args['score']);
					$post->add_post($args);
				}
				$response['msg'] = "Examination scores added successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "offer_admission":
				$adm_term_meta = $post->get_post_meta($args['term_of_admission']);
				$args['status'] = 'active';
				$args['promotion'] = 1;
				$args['class'] = $args['class_of_admission'];
				$id = $args['student_id'];
				unset($args['student_id']);
				if(time() >= $adm_term_meta['term_begins']) {
					//place in class
					$args['category'] = get_next_category($args['gender'], $args['class_of_admission'], 'student');
					$args['role'] = 'student';
				} else {
					//place in waiting list
					$args['category'] = get_next_category($args['gender'], $args['class_of_admission'], 'fresher');
					$args['role'] = 'fresher';
				}
				$user->update_user_meta($id, $args);
				$response['msg'] = "You have successfully admitted the student";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "set_registration_fee":
				$args['type'] = 'registration_fee';
				$args['status'] = 'ok';
				$meta = $args;
				if($args['gender'] === 'Both') {
					$args['gender'] = ['Male', 'Female'];
				} else {
					$args['gender'] = [$args['gender']];
				}
				foreach($args['gender'] as $key => $gender) {
					$meta['gender'] = $gender;
					$existing = db_post_unique(['type' => 'registration_fee', 'adm_term' => $meta['adm_term'], 'gender' => $meta['gender'], 'adm_class' => $meta['adm_class'], 'cat' => $meta['cat']]);
					if($existing) {
						$post->update_post_meta($existing['id'], $meta);
					} else $post->add_post($meta);
				}
				$response['msg'] = "Done";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "get_registration_fee":
				if($args['gender'] === "Both") {
					$args['gender'] = ["Male", "Female"];
				}
				$existing = db_post_unique(['type' => 'registration_fee', 'adm_term' => $args['adm_term'], 'gender' => $args['gender'], 'adm_class' => $args['adm_class'], 'cat' => $args['cat']]);
				$response['registration_fee'] = $existing ? $existing['amount'] : "";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "get_fee_data":
				$fee_meta = $post->get_post_meta($args['id']);
				$response['affected_students'] = rf_get_affected_students($fee_meta, $args['session']);
				$response['paid'] = rf_get_student_that_paid($fee_meta, $args['session']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "check_result":
				$sorting = new sorting;
				$candidates = $user->get_user_by_meta_data(['role' => 'candidate', 'surname' => "%".$args['surname']."%"]);
				$candidates = array_merge($candidates, $user->get_user_by_meta_data(['role' => 'fresher', 'surname' => "%".$args['surname']."%"]));
				$exam = $post->get_post_by_meta_data(['type' => 'entrance_exam_result']);
				$exam = $sorting->sort_by_meta_value($exam, 'adm_term', 'desc');
				$res = array();
				if(_count($candidates) && count) {
					foreach ($candidates as $key => $candidate) {
						$i = 0;
						$found = false;
						do {
							$score = unserialize($exam[$i]['score']);
							if(isset($score[$candidate['id']])) {
								$candidate_score = array();
								if(_count($score[$candidate['id']])) {
									foreach ($score[$candidate['id']] as $key => $value) {
										$subject_meta = $post->get_post_meta($key);
										$candidate_score[$subject_meta["subject_name"]] = $value;
									}
								}
								$res[] = ['candidate' => $candidate, 'exam' => $exam[$i], 'score' => $candidate_score];
								$found = true;
							}
							$i++;
						} while(isset($exam[$i]) && !$found);
					}
				}
				if(_count($res)) {
					$response['res'] = $res;
					$response['error'] = 0;
				} else {
					$response['args'] = $args;
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

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

endif;