<?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 = $_POST;
		unset($args['action']);
		$user = new user;
		$post = new post;
		$support = new support(['software_engineer', 'super_admin']);

		switch ($_POST['action']) {
			case 'create_course_outline':
				$args['type'] = 'cp_course_outline';
				$args['status'] = 'active';
				$material = [
					'ref' => $args['ref'],
					'class' => $args['class'],
					'course' => $args['course'],
					'type' => 'cp_lesson_material',
					'status' => 'active',
					'material-title' => 'Note Attachment: '.$args['topic']
				];
				unset($args['ref']);
				$res = $post->add_post($args);
				if($res) {
					$stream = new cp_streams;
					$stream->type = "lesson";
					$stream->link = "cp-view-lesson?id=".$res;
					$stream->mail_subject = "CLASSROOM PLUS: NEW LESSON PUBLISHED BY ".get_fullname($session->id);
					$stream->message = "A new lesson topic \"".$args['topic']."\" was published under ".get_class_name($args['class'])." ".get_course_name($args['course']);
					$stream->class_id = $args['class'];
					$stream->subject = $args['course'];
					$stream->send_communique(EMAIL, NOTIFICATION);
					$stream->log();
				}
				$files = get_upload_library_files( $material['ref'] );
				if($files && $res) {
					set_time_limit(60);
					$material['lesson_id'] = $res;
					$res = $post->add_post($material);
					if($res) {
						cp_generate_material_ref($session->id);
						$stream = new cp_streams;
						$stream->type = "material";
						$stream->link = "cp-view-material?id=".$res;
						$stream->mail_subject = "CLASSROOM PLUS: LEARNING MATERIAL ADDED BY ".get_fullname($session->id);
						$stream->message = "A learning material was added to Lesson topic \"".$args['topic']."\". This lesson can be found under ".get_class_name($args['class'])." ".get_course_name($args['course']);
						$stream->class_id = $args['class'];
						$stream->subject = $args['course'];
						$stream->send_communique(EMAIL, NOTIFICATION);
						$stream->log();
					}
				}
				$response['error'] = 0;
				$response['msg'] = 'Lesson added successfully';
				echo json_encode($response);
				exit();
				break;

			case 'edit_course_outline':
				$res = $post->update_post_meta($args['id'], $args);
				if($res) {
					$stream = new cp_streams;
					$stream->type = "lesson";
					$stream->link = "cp-view-lesson?id=".$args['id'];
					$stream->mail_subject = "CLASSROOM PLUS: LESSON EDITED BY ".get_fullname($session->id);
					$stream->message = "Lesson topic \"".$args['topic']."\" was edited. This lesson can be found under ".get_class_name($args['class'])." ".get_course_name($args['course']);
					$stream->class_id = $args['class'];
					$stream->subject = $args['course'];
					$stream->send_communique(EMAIL, NOTIFICATION);
					$stream->log();
				}
				$response['error'] = 0;
				$response['msg'] = 'Lesson updated successfully';
				echo json_encode($response);
				exit();
				break;

			case 'cp_get_lessons':
				$lessons = $post->get_post_by_meta_data(['type' => 'cp_course_outline', 'term' => $args['term'], 'course' => $args['course'], 'class' => $args['class']]);
				$sorting = new sorting;
				$lessons = $sorting->sort_by_meta_value($lessons, "week");
			    $table = new table("lessons-table", $lessons);
			    $table->set_display_columns([
			        // "sn" => "SN",
			        "week" => "Week",
			        "period" => "Period",
			        "topic" => "Topic"
			    ]);
			    $table->set_action_links([
			        "View" => "cp-view-lesson",
			        "Edit" => "cp-edit-lesson",
			        "Delete" => false
			    ]);
			    $table->set_action_access([
			        "View" => "cp_view_lesson",
			        "Edit" => "cp_edit_lesson",
			        "Delete" => "cp_delete_lesson"
			    ]);
			    $table->set_action_callback([
			        "View" => false,
			        "Edit" => false,
			        "Delete" => "cp_delete_lesson"
			    ]);
			    $table->set_action_args([
			        "View" => ["id" => "id"],
			        "Edit" => ["id" => "id"],
			        "Delete" => ["id" => "id", "callback" => "cp_get_lessons", "callbackid" => "#display-lessons"]
			    ]);
			    $response['lesson_table'] = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case 'cp_get_quiz':
				$current_session = get_option("current_academic_session");
				$term = db_post_unique(['type' => 'academic_term', 'order' => $args['term'], 'acsession' => $current_session]);
				if($term) {
					$quiz = $post->get_post_by_meta_data(['type' => 'cp_quiz', 'term' => $term['id'], 'course' => $args['course'], 'class' => $args['class']]);
				    $table = new table("lessons-table", $quiz);
				    $table->set_display_columns([
				        "posted_on" => "Date",
				        "test" => "Test",
				        "term" => "Term",
				        "from" => "Starts",
				        'to' => "Ends",
				        "time_allowed" => "Time Allowed"
				    ]);
				    $table->set_dynamic_columns([
				        "term" => "_tf_eedu_display_term_name",
				        "from" => "_tf_get_date",
				        'to' => "_tf_get_date",
				        "time_allowed" => "_tf_cp_display_time_allowed"
				    ]);
				    $table->set_action_links([
				        "Manage" => "cp-manage-quiz",
				        "Edit" => "cp-edit-quiz",
				        "Delete" => false
				    ]);
				    $table->set_action_access([
				        "Manage" => "cp_manage_quiz",
				        "Edit" => "cp_edit_quiz",
				        "Delete" => "cp_delete_quiz"
				    ]);
				    $table->set_action_callback([
				        "Manage" => false,
				        "Edit" => false,
				        "Delete" => "cp_delete_quiz"
				    ]);
				    $table->set_action_popup([
				        "Edit" => true
				    ]);
				    $table->set_action_args([
				        "Manage" => ["id" => "id"],
				        "Edit" => ["id" => "id", "width" => 700, "height" => 500],
				        "Delete" => ["id" => "id", "callback" => "cp_get_lessons", "callbackid" => "#display-lessons"]
				    ]);
				    $response['quiz_table'] = $table->table_html();
				}
				
				echo json_encode($response);
				exit();
				break;

			case 'attach_lesson_material':
				$uploads = get_upload_library_files( $args['ref'] );
				if(!$uploads) {
					$response['msg'] = "You have not attached any file";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				if(db_post_unique(['type' => 'cp_lesson_material', 'ref' => $args['ref']])) {
					$response['msg'] = "You have already uploaded this material";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$lesson = $post->get_post_meta($args['lesson_id']);
				$args['class'] = $lesson['class'];
				$args['course'] = $lesson['course'];
				$args['type'] = 'cp_lesson_material';
				$args['status'] = 'active';
				$res = $post->add_post($args);
				if($res) {
					cp_generate_material_ref($args['lesson_id']);
					$stream = new cp_streams;
					$stream->type = "material";
					$stream->link = "cp-view-material?id=".$res;
					$stream->mail_subject = "CLASSROOM PLUS: LEARNING MATERIAL ADDED BY ".get_fullname($session->id);
					$stream->message = "A learning material was added to Lesson topic \"".$lesson['topic']."\". This lesson can be found under ".get_class_name($args['class'])." ".get_course_name($args['course']);
					$stream->class_id = $args['class'];
					$stream->subject = $args['course'];
					$stream->send_communique(EMAIL, NOTIFICATION);
					$stream->log();
					$response['msg'] = "You have successfully published the material";
					$response['error'] = 0;
				} else {
					$response['msg'] = "Something went wrong";
					$response['error'] = 1;
				}
				
				echo json_encode($response);
				exit();
				break;

			case "edit_lesson_material":
				$uploads = get_upload_library_files( $args['ref'] );
				if(!$uploads) {
					$response['msg'] = "You have not attached any file";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$res = $post->update_post_meta($args['id'], $args);
				$response['msg'] = "You have successfully updated the material";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'attach_lesson_material_link':
				if(db_post_unique(['type' => 'cp_lesson_material', 'material-url' => $args['material-url']])) {
					$response['msg'] = "You have already uploaded this material";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$lesson = $post->get_post_meta($args['lesson_id']);
				$args['class'] = $lesson['class'];
				$args['course'] = $lesson['course'];
				$args['type'] = 'cp_lesson_material_link';
				$args['status'] = 'active';
				$res = $post->add_post($args);
				if($res) {
					$stream = new cp_streams;
					$stream->type = "material";
					$stream->link = "cp-view-material?id=".$res;
					$stream->mail_subject = "CLASSROOM PLUS: LEARNING LINK ADDED BY ".get_fullname($session->id);
					$stream->message = "A learning link was added to Lesson topic \"".$lesson['topic']."\". This lesson can be found under ".get_class_name($args['class'])." ".get_course_name($args['course']);
					$stream->class_id = $args['class'];
					$stream->subject = $args['course'];
					$stream->send_communique(EMAIL, NOTIFICATION);
					$stream->log();
					$response['msg'] = "You have successfully published the material";
					$response['error'] = 0;
				} else {
					$response['msg'] = "Something went wrong";
					$response['error'] = 1;
				}
				
				echo json_encode($response);
				exit();
				break;

			case "cp_get_materials":
				$materials = $post->get_post_by_meta_data(['type' => ['cp_lesson_material', 'cp_lesson_material_link'], 'lesson_id' => $args['lesson_id'], 'status' => 'active']);
				$table = new table("materials-table", $materials);
			    $table->set_display_columns([
			        "sn" => "SN",
			        "material-title" => "Title",
			        // "material-description" => "Description",
			        "download_link" => "Download Links"
			    ]);
			    $table->set_dynamic_columns([
			    	"download_link" => "cp_download_link"
			    ]);
		    	$table->set_action_links([
		    		"Reading & Discussion" => "cp-view-material",
			        "Edit Material" => "cp-edit-material",
			        "Remove Material" => false
			    ]);
			    $table->set_action_access([
			    	"Reading & Discussion" => 'cp_view_material',
			        "Edit Material" => "cp_edit_material",
			        "Remove Material" => "deactivate_post"
			    ]);
			    $table->set_action_callback([
			    	"Reading & Discussion" => false,
			        "Edit Material" => false,
			        "Remove Material" => "deactivate_post"
			    ]);
			    $table->set_action_args([
			    	"Reading & Discussion" => ["id" => "id"],
			        "Edit Material" => ["id" => "id"],
			        "Remove Material" => ["id" => "id"]
			    ]);
			    $response['display_html'] = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case 'create_quiz':
				if(db_post_unique(['type' => 'cp_quiz', 'class' => $args['class'], 'course' => $args['course'], 'term' => $args['term'], 'test' => $args['test']])) {
					$response['msg'] = "The specified quiz has already been added for the term";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$args['solve_online'] = isset($args['solve_online']) ? (int) $args['solve_online'] : 0;
				$args['shuffle_questions'] = isset($args['shuffle_questions']) ? (int) $args['shuffle_questions'] : 0;
				$args['from'] = strtotime($args['from']);
				$args['to'] = strtotime($args['to']);
				$args['type'] = 'cp_quiz';
				$args['added_by'] = $session->id;
				$args['status'] = 'draft';
				$post->add_post($args);
				$response['msg'] = "Quiz was added successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'edit_quiz':
				$args['solve_online'] = isset($args['solve_online']) ? (int) $args['solve_online'] : 0;
				$args['shuffle_questions'] = isset($args['shuffle_questions']) ? (int) $args['shuffle_questions'] : 0;
				$args['from'] = strtotime($args['from']);
				$args['to'] = strtotime($args['to']);
				$args['type'] = 'cp_quiz';
				$args['last_updated_by'] = $session->id;
				$post->update_post_meta($args['id'], $args);
				$response['msg'] = "Quiz was updated successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "add_objective_question":
				if(!isset($args['option'])) {
					$response['msg'] = "Please add options";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				if(!isset($args['correct_option'])) {
					$response['msg'] = "Please indicate the correct option";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				set_time_limit(150);
				unset($args['new']);
				$quiz = $args['quiz'];
				if(isset($args['compulsory'])) {
					$compulsory = (int) $args['compulsory'];
					unset($args['compulsory']);
				} else {
					$compulsory = 0;
				}
				unset($args['quiz']);
				$args['option'] = serialize($args['option']);
				$args['type'] = "cp_question_bank";
				$args['question_type'] = 'objective';
				$res = $post->add_post($args);
				if($res) {
					$result = cp_add_quiz_question($quiz['id'], $res, $compulsory);
					$response['msg'] = "Question added successfully ".$result["msg"];
					$response['error'] = 0;
				} else {
					$response['msg'] = "Something went wrong";
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

			case "cp_get_question_bank":
					$bank = cp_get_question_bank($args['class'], $args['course']);
					$table = new table("lessons-table", $bank);
				    $table->set_display_columns([
				        "posted_on" => "Date",
				        "question" => "Question",
				        "question_type" => "Question Type"
				    ]);
				    $table->set_action_links([
				        "Add to quiz" => "cp-add-question",
				        "Edit" => "cp-edit-question",
				        "Delete" => false
				    ]);
				    $table->set_action_access([
				        "Add to quiz" => "cp_add_question",
				        "Edit" => "cp_edit_question",
				        "Delete" => "cp_delete_question"
				    ]);
				    $table->set_action_callback([
				        "Add to quiz" => false,
				        "Edit" => false,
				        "Delete" => "cp_delete_question"
				    ]);
				    $table->set_action_args([
				        "Add to quiz" => ["id" => "id"],
				        "Edit" => ["id" => "id"],
				        "Delete" => ["id" => "id", "callback" => "getQuestionBank", "callbackid" => "#question-bank"]
				    ]);
				    $table->set_action_condition([
				        "Add to quiz" => ["cp_add_to_quiz" => ["quiz" => $args["quiz"]]]
				    ]);
				    $response['display_html'] = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "cp_get_grading":
					$students = $user->get_user_by_meta_data(['role' => 'student', 'status' => 'active', 'class' => $args['class']]);
					$table = new table("students-table", $students);
					$table->table_id = "students-table-table";
					$table->quiz = $args['quiz'];
				    $table->set_display_columns([
				        "sn" => "SN",
				        "fullname" => "Name",
				        "objective" => "Objective"
				    ]);
				    $table->set_dynamic_columns([
				        "objective" => "_tf_cp_get_objective_question_score"
				    ]);
				    $table->set_action_links([
				        "Delete" => false
				    ]);
				    $table->set_action_access([
				        "Delete" => "cp_delete_answer"
				    ]);
				    $table->set_action_callback([
				        "Delete" => "cp_delete_answer"
				    ]);
				    $table->set_action_args([
				        "Delete" => ["id" => "id", "quiz" => $args['quiz'], "callback" => "getGrading", "callbackid" => "#grading"]
				    ]);
				    $response['display_html'] = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "write_quiz":
				$args['end_time'] = time();
				$args['user_id'] = $session->id;
				$args['type'] = "cp_write_quiz";
				if(isset($args['objective'])) {
					$args['correct'] = 0;
					$args['wrong'] = 0;
					foreach ($args['objective'] as $key => $value) {
						if($key === $value) {
							$args['correct']++;
						} else $args['wrong']++;
					}
					$args['skipped'] = $args['number_of_questions'] - $args['correct'] - $args['wrong'];
					$args['objective'] = serialize($args['objective']);
					$args['obj_question'] = serialize($args['obj_question']);
				}
				if($existing = db_post_unique(["type" => "cp_write_quiz", "user_id" => $session->id, "quiz" => $args['quiz']])) {
					$post->update_post_meta($existing['id'], $args);
				} else {
					$post->add_post($args);
				}
				$response['msg'] = "Quiz submitted successfully";
				$response['error'] = 0;
				$response['args'] = $args;
				echo json_encode($response);
				exit();
				break;

			case "cp_init_quiz":
				$args['user_id'] = $session->id;
				$args['type'] = "cp_write_quiz";
				if($existing = db_post_unique(["type" => "cp_write_quiz", "user_id" => $session->id, "quiz" => $args['quiz']])) {
					$post->update_post_meta($existing['id'], $args);
				} else {
					$post->add_post($args);
				}
				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);
				break;
		}
		// json_encode($response);
	}

endif;