<?php 

function cp_delete_lesson($args) {
	$post = new post;
	$post->drop_post($args['id']);
	return ['status' => true, 'msg' => 'Lesson deleted successfully'];
}

function cp_publish_quiz($args) {
	$session = Session::getInstance();
	$post = new post;
	$quiz_meta = $post->get_post_meta($args['id']);
	if($quiz_meta['status'] !== "published") {
		$post->update_post_meta($args['id'], ['status' => 'published', 'published_by' => $session->id]);
		$stream = new cp_streams;
		$stream->type = "quiz";
		$stream->link = "cp-all-available-quiz";
		$stream->mail_subject = "CLASSROOM PLUS: ".get_class_name($quiz_meta['class'])." ".get_course_name($quiz_meta['course'])." ".strtoupper($quiz_meta['test']);
		$stream->message = $stream->mail_subject." is now published to be available from ".date(_DATE_FORMAT_, $quiz_meta['from'])." to ".date(_DATE_FORMAT_, $quiz_meta['to']).". Please ensure that you write the exam before the takedown time. <br>Time allowed is: ".$quiz_meta['time_allowed']."minutes";
		$stream->class_id = $quiz_meta['class'];
		$stream->subject = $quiz_meta['course'];
		$stream->send_communique(EMAIL, NOTIFICATION);
		$stream->log();
		return ['status' => true, 'msg' => 'Quiz published successfully'];
	} else {
		return ['status' => false, 'msg' => 'Quiz was already published'];
	}
	
}

function cp_delete_question($args) {
	$post = new post;
	$questions = $post->get_post_by_meta_data(['type' => 'cp_quiz_question', 'question' => $args['id']]);
	if(_count($questions)) {
		foreach ($questions as $existing) {
			$quiz_meta = $post->get_post_meta($existing['quiz']);
			if($quiz_meta['to'] >= time()) {
				return ['status' => false, 'msg' => 'Question is linked to an upcoming or ongoing quiz. Question cannot be deleted.'];
			}
		}
	}
	$post->drop_post($args['id']);
	return ['status' => true, 'msg' => 'Question deleted successfully'];
}

function cp_delete_answer($args) {
	$post = new post;
	$quiz_meta = $post->get_post_meta($args['quiz']);
	if(time() > $quiz_meta['to']) {
		return ['status' => false, 'msg' => 'Quiz has already been taken down. You cannot delete user score again.'];
	}
	$answer = db_post_unique(["type" => "cp_write_quiz", "quiz" => $args['quiz'], 'user_id' => $args['id']]);
	if($answer) {
		$post->drop_post($answer['id']);
		admin_log("Deleted ".get_fullname($args['id'])."'s ".get_course_name($quiz_meta['course'])." quiz answer.");
		return ['status' => true, 'msg' => 'Answer deleted successfully'];
	} else {
		return ['status' => false, 'msg' => 'Student don\'t have any recorded answers to this quiz'];
	}
}