<?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 'upload_external_exam':
				$args['exam'] = strtolower($args['exam']);
				$path = ABSPATH.UPLOADFOLDER.'/External Examinations/'.str_replace('/', '-', $args['exam']).'/'.date('Y', time()).'/';
				$save_as = get_fullname($args['student_id']).$args['student_id'];
				$res = UploadFile($_FILES, 'upload-file', $path, ['image/jpeg','image/gif','image/png','application/pdf','image/x-eps'], 5000000, $save_as);
				if($res[0] != 0) {
					$response['msg'] = $res[1];
					$response['error'] = 1;
				} else {
					$args['file'] = $response['file'] = str_replace(ABSPATH, "", $res[1]);
					$args['type'] = 'external_exam';
					$existing = $post->get_post_by_meta_data(['student_id' => $args['student_id'], 'type' => 'external_exam', 'exam' => $args['exam']]);
					if(_count($existing)) {
						$existing_id = $existing[0]['id'];
						$res1 = $post->update_post_meta($existing_id, $args);
						if($res1) {
							$info = "Your ".$args['exam']." result has just been updated on the school portal.";
							inform_user($args['student_id'], $info, "EXPENSE APPROVED", get_option("home_url"), EMAIL, NOTIFICATION);
							$info = "Admin updated ".get_fullname($args['student_id'])." ".$args['exam']." result";
							admin_log($info);
							$response['error'] = 0;
							$response['msg'] = "Result updated successfully";
						} else {
							$response['error'] = 0;
							$response['msg'] = "Result updated successfully";
						}
					} else {
						$res1 = $post->add_post($args);
						if($res1) {
							$user->update_user_meta($args['student_id'], [strtolower($args['exam']) => $res1]);
							$info = "Your ".$args['exam']." result has just been uploaded on the school portal.";
							inform_user($args['student_id'], $info, "EXPENSE APPROVED", get_option("home_url"), EMAIL, NOTIFICATION);
							$info = "Admin uploaded ".get_fullname($args['student_id'])." ".$args['exam']." result";
							admin_log($info);
							$response['error'] = 0;
							$response['msg'] = "Result uploaded successfully";
						} else {
							$response['error'] = 1;
							$response['msg'] = "Something went wrong during updating";
						}
					}
					
				}
				echo json_encode($response);
				exit();
				break;

			case 'delete_external_exam':
				$student_meta = $user->get_user_meta($args['studentid']);
				$exam_meta = $post->get_post_meta($student_meta[$args['exam']]);
				$res = $user->update_user_meta($student_meta['id'], [$args['exam'] => ""]);
				$post->drop_post($exam_meta['id']);
				unlink(ABSPATH.$exam_meta['file']);
				$response['error'] = 0;
				$response['msg'] = "Result deleted successfully";
				echo json_encode($response);
				exit();
				break;

			case 'get_class_courses':
				$response['courses'] = get_class_courses($args['class_id'], $args['category_id']); 
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			// deprecating
			case 'upload_mock_exam':
				$res = update_mock_exam_result($args);
				if($res) {
					$response['msg'] = 'Result saved successfully';
					$response['error'] = 0;
				} else {
					$response['msg'] = 'No records found';
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

			case 'mock_for_mastersheet':
				$args['type'] = 'mock_for_mastersheet';
				$check = $args;
				unset($check['ext_exam']);
				if($existing = db_post_unique($check)) {
					$post->update_post_meta($existing['id'], $args);
					$response['msg'] = 'This result is already used in mastersheet';
					$response['error'] = 1;
				} else {
					$post->add_post($args);
				}
				eedu_portal_reset_annual_broadsheet($args['class'], $args['term']);
				$response['msg'] = 'Done';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'get_mock_for_mastersheet':
				$response['res'] = $post->get_post_by_meta_data(['type' => 'mock_for_mastersheet']);
				if(_count($response['res'])) {
					foreach ($response['res'] as $key => &$value) {
						$term_meta = $post->get_post_meta($value["term"]);
						$value['class_name'] = get_class_name($value['class']);
						$value['term_name'] = $term_meta['term_name']." [".get_session_name($term_meta['acsession'])."]";
					}
				}
				echo json_encode($response);
				exit();
				break;

			// deprecating
			case 'compile_result':
				ignore_user_abort(true);
				ini_set('max_execution_time', 300);

				// dynamically query students
			    if(promotion_done_in_session($args['session'])) {
			        $students = array();
			        if($args['category'] == "all") {
			        	$_students = get_students_in_class($args['session'], $args['term'], $args['class']);
			        	$_students = root_std_arr_catlevel($_students);
			        } else $_students = get_students_in_class($args['session'], $args['term'], $args['class'], $args['category']);
			        if(_count($_students)) {
			            foreach ($_students as $key => $student_id) {
			                $students[] = $user->get_user_meta($student_id);
			            }
			        }
			    } else {
			        $students = get_class_students(['class_id' =>$args['class'], 'category_id' =>$args['category']]);
			    }
			    // dynamically query students
				  
				$std_count = _count($students);
				$use_pin = get_option('use_pins_to_access_results');
				if($std_count) {
				    if($args['category'] == 'all') {
				      $class_courses = get_extended_course_mapping($args['class']);
				      $results = $post->get_post_by_meta_data(['type' => 'mock_exam', 'exam' => $args['ext_exam'], 'class' => $args['class'], 'session' => $args['session'], 'term' => $args['term']]);
				      if(_count($results)) {
				        foreach($results as $key => $result_meta) {
				          if(!in_array($result_meta['course'], $class_courses)) {
				            unset($results[$key]);
				          }
				        }
				      }
				    } else {
				      $results = $post->get_post_by_meta_data(['type' => 'mock_exam', 'exam' => $args['ext_exam'], 'class' => $args['class'], 'category' => $args['category'], 'session' => $args['session'], 'term' => $args['term']]);
				      $course_mapping = get_option("course_mapping");
				      if(isset($course_mapping[$args['class']][$args['category']]) && _count($results)) {
				        foreach($results as $key => $result_meta) {
				          if(!in_array($result_meta['course'], $course_mapping[$args['class']][$args['category']])) {
				            unset($results[$key]);
				          }
				        }
				      }
				    }
				    $response['xsxs_res'] = $results;
				    $response['results'] = prepare_mock_result($results);
				    $response['courses'] = $class_courses;
				    $response['students'] = $students;
				    $response['args'] = $args;
				    $response['use_pin'] = $use_pin;
				    $response['std_count'] = $std_count;
				    // foreach ($students as $key => $value) {
				    //   compile_mock_result($value['id'], $args['session'], $args['term'], $args['class'], $args['category'], $std_count, $results[$value['id']], $args['ext_exam'], $use_pin);
				    // }
				    $info = get_class_name($args['class'], $args['category'])." ".get_term_name($args['term'])." ".get_session_name($args['session'])." mock ".$args['ext_exam']." result was compiled successfully";
				    // // inform_admins($info);
				    admin_log($info);
				    $response['error'] = 0;
					$response['msg'] = get_class_name($args['class'], $args['category'])." ".$args['ext_exam']." mock result is ready to be compiled";
				} else {
					$response['error'] = 1;
					$response['msg'] = "No student in category";
				}
				echo json_encode($response);
				exit();
				break;

			case 'compile_student_result':
				$res = compile_mock_result($args['student'], $args['session'], $args['term'], $args['class'], $args['category'], $args['std_count'], $args['student_result'], $args['ext_exam'], $args['use_pin']);
				echo json_encode($response);
				exit();
				break;

			case 'save_gradebook':
				$args['scores'] = serialize($args['result']);
				$args['scores'] = base64_encode($args['scores']);
				$args['type'] = 'mock_exam_gradebook';
				$args['status'] = get_option('auto_verify_results') ? 'verified' : 'in process';
				$existing = $post->get_post_by_meta_data(['type' => 'mock_exam_gradebook', 'class' => $args['class'], 'category' => $args['category'], 'course' => $args['course'], 'term' => $args['term'], 'exam' => $args['exam']]);
				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';
				}
				ext_exam_reset_broadsheet($args['class'], $args['category'], $args['term'], $args['exam']);
				ext_exam_reset_broadsheet($args['class'], "", $args['term'], $args['exam']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			default:
				# code...
				break;
		}
		// json_encode($response);
	}

endif;