<?php

defined('BASEPATH') or exit('No direct script access allowed');

use Nilambar\NepaliDate\NepaliDate;

require_once 'vendor/autoload.php';


class Teacher extends CI_Controller
{

	private $nepaliDateObject;
	private $nepali_current_date;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Teacher_model');
		$this->load->model('Admin_model');
		$this->load->helper('url');
		$this->load->library('email');
		$this->load->helper('common_helper');
		// date_default_timezone_set("Asia/Kolkata");
		date_default_timezone_set("Asia/Kathmandu");

		$this->nepaliDateObject = new NepaliDate();
		$this->nepali_current_date = cuurentNepaliDate($this->nepaliDateObject);
	}

	public function index()
	{
		//if(!isset($_SESSION['teacher_id'])){
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/header', $data);
		$this->load->view('teacher/login');
		$this->load->view('teacher/footer');
		/*  }
	     else
	     redirect(base_url().'Teacher/dashboard');*/
	}

	public function teacher_login()
	{
		$uname = $this->input->post('email');
		$pwd = $this->input->post('password');
		if ($this->Teacher_model->login($uname, $pwd)) {
			if (isset($_POST['remember_me']) && $_POST['remember_me'] == 'on') {
				//set 0 instead of time to remove the cookie once the browser is closed
				setcookie("username", $_POST["email"], time() + 86400); 	//86400 seconds in a day
				setcookie("password", $_POST["password"], time() + 86400);
				setcookie("rem_me", 'On', time() + 86400);
			} else {
				if (isset($_COOKIE['username'])) {
					unset($_COOKIE['username']);
					setcookie('username', '');
				}
				if (isset($_COOKIE['password'])) {
					unset($_COOKIE['password']);
					setcookie('password', '');
				}
				if (isset($_COOKIE['rem_me'])) {
					unset($_COOKIE['rem_me']);
					setcookie('rem_me', '');
				}
			}

			$teacher_info = $this->Teacher_model->login($uname, $pwd);
			//getting values from database
			$teacher_id = $teacher_info->id;
			$teacher_role = $teacher_info->role;
			$teacher_rights = $teacher_info->rights;
			$teacher_email = $teacher_info->email;
			$teacher_name = $teacher_info->teacher_name;
			//create required sessions
			$this->session->set_userdata('teacher_id', $teacher_id);
			$this->session->set_userdata('teacher_role', $teacher_role);
			$this->session->set_userdata('teacher_rights', $teacher_rights);
			$this->session->set_userdata('teacher_email', $teacher_email);
			$this->session->set_userdata('teacher_name', $teacher_name);
			echo '1';
		} else {
			echo '0';
		}
	}

	public function convert()
	{


		$date = $this->nepaliDateObject->getDetails('2077', '1', '1', 'bs');
		test_view_array($date);
		// echo date('d-m-Y', strtotime($start));
	}

	public function teacher_logout()
	{
		$this->session->sess_destroy();
		redirect(base_url() . 'Teacher');
	}

	public function dashboard()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		if (isset($_SESSION['teacher_id'])) {
			$data['currentURL'] = current_url();
			// print_r($data['currentURL']);
			// die();
			$tid = $_SESSION['teacher_id'];
			$tname = $_SESSION['teacher_name'];
			//$data['classes'] = $this->Teacher_model->get_myClasses($tid,'');
			//  print_r($data['classes']);

			$nowMonth = date('m', strtotime($this->nepali_current_date));
			$nowYear = date('Y', strtotime($this->nepali_current_date));
			$nowDay = date('d', strtotime($this->nepali_current_date));

			$obj = new NepaliDate();

			// Convert BS to AD.
			$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
			$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];
			$presentDay = strtolower(date('l', strtotime(date('Y-m-d H:i:s'))));

			$currentDate = date('Y-m-d', strtotime($this->nepali_current_date));

			$teacher_subjects = $this->Teacher_model->get_table_info('classroom_teacher_subject', array('teacher_id' => $_SESSION['teacher_id']), '', "ASC");

			$data['subjects'] = array();
			$count = 0;
			foreach ($teacher_subjects as $key => $value) {

				$sql = "Select sd.subject_id, sd.id as session_id, sd.start, sd.day, sd.duration,sd.start_link, sd.join_link, cs.start_date,cs.end_date,c.id as classroom_id,c.classroom_name, s.subject_name, s.subject_icon from classroom_teacher_subject cts
				inner join classroom_session cs on cts.classroom_id = cs.classroom_id
				inner join session_details sd on cs.id = sd.session_id
				inner join subject s on s.id = sd.subject_id
				inner join classroom c on c.id = $value[classroom_id]
				inner join batch b on cs.batch_id = b.id
				WHERE s.id = $value[subject_id] 
				AND (cts.teacher_id = $_SESSION[teacher_id] 
				AND cts.classroom_id = $value[classroom_id])
				AND LOWER(sd.day) = '$presentDay' 
				AND	('$currentDate' between cs.start_date and cs.end_date)
				AND (cs.is_active = 'yes' AND s.is_active = 'yes' AND c.is_active = 'yes') GROUP BY sd.id";

				$session_results = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);
				// echo $this->db->last_query();exit;
				if (!empty($session_results)) {

					foreach ($session_results as $key2 => $value2) {

						$data['subjects'][$count] = array(
							'subject_id' => $value2['subject_id'],
							'session_id' => $value2['session_id'],
							'start' => $value2['start'],
							'start_date' => $value2['start_date'],
							'end_date' => $value2['end_date'],
							'classroom_id' => $value2['classroom_id'],
							'classroom_name' => $value2['classroom_name'],
							'subject_name' => $value2['subject_name'],
							'subject_icon' => $value2['subject_icon'],
							'duration' => $value2['duration'],
							'start_link' => $value2['start_link'],
							'day' => $value2['day']
						);

						$count++;
					}
				}
			}

			usort($data['subjects'], function ($item1, $item2) {
				return $item1['start'] <=> $item2['start'];
			});
			//get logo
			$data['school_info'] = $this->Admin_model->get_logo_from_setting();
			$this->load->view('teacher/teacher-header', $data);
			$this->load->view('teacher/teacher-leftmenu', $data);

			$this->load->view('teacher/dashboard', $data);
			$this->load->view('teacher/teacher-footer');
		}
	}


	public function teacher_test_exams()
	{
		if (isset($_SESSION['teacher_id'])) {
			$data['currentURL'] = current_url();
			//get logo
			$data['school_info'] = $this->Admin_model->get_logo_from_setting();
			$this->load->view('teacher/teacher-header', $data);
			$this->load->view('teacher/teacher-leftmenu', $data);
			$this->load->view('teacher/teacher-test-exams');
			$this->load->view('teacher/teacher-footer');
		}
	}

	public function teacher_grades()
	{
		if (isset($_SESSION['teacher_id'])) {
			$data['currentURL'] = current_url();
			//get logo

			$sql = "SELECT cst.teacher_id, cst.classroom_id, cr.id as course_name, cr.course_name, c.classroom_name from classroom_teacher_subject cst inner join classroom c on cst.classroom_id = c.id inner JOIN course cr ON cr.id = c.course_id WHERE cst.teacher_id = '" . $_SESSION['teacher_id'] . "' GROUP BY c.classroom_name, cr.course_name order by c.id";
			$data['result'] = $this->Teacher_model->get_table_info('teacher_subjects', '', $sql);

			$data['school_info'] = $this->Admin_model->get_logo_from_setting();
			$this->load->view('teacher/teacher-header', $data);
			$this->load->view('teacher/teacher-leftmenu', $data);
			$this->load->view('teacher/teacher-grades');
			$this->load->view('teacher/teacher-footer');
		}
	}



	public function add_edit_classroom($crid = NULL)
	{
		// if(isset($_SESSION['admin_id'])){
		$data['crid'] = $crid;
		$cid = '';
		$data['currentURL'] = current_url();
		//get logo
		$data['logo'] = $this->Admin_model->get_logo();
		//get menu list
		$data['menulist'] = $this->Admin_model->get_adminMenu();
		if ($crid > 0) {
			$data['detail'] = $this->Admin_model->get_classroom($crid);
		}
		$data['course'] = $this->Admin_model->get_course($cid);
		/*    $this->load->view('admin/header',$data);
    	    $this->load->view('admin/add-edit-classroom');
    	    $this->load->view('admin/footer');*/
		// }
	}

	// Shankar code start from here //

	public function teacher_assignment()
	{
		if (isset($_SESSION['teacher_id'])) {
			$data['currentURL'] = current_url();

			$tid = $_SESSION['teacher_id'];
			$tname = $_SESSION['teacher_name'];

			$data['classes'] = $this->Teacher_model->get_course($tid);

			$data['school_info'] = $this->Admin_model->get_logo_from_setting();
			$this->load->view('teacher/teacher-header', $data);
			$this->load->view('teacher/teacher-leftmenu');
			$this->load->view('teacher/teacher-assignment');
			$this->load->view('teacher/teacher-footer');
		}
	}

	public function create_assignment()
	{
		if (isset($_SESSION['teacher_id'])) {
			$tid = $_SESSION['teacher_id'];



			if (isset($_POST)) {
				$due_date = $this->input->post('due_date');
				$title = $this->input->post('c_title');
				$remark = $this->input->post('c_remark');
				$subject_id = $this->input->post('Sub');
				$cls_id = $this->input->post('classroom_id');

				$data = array(
					'classroom_id' => $cls_id,
					'teacher_id' => $tid,
					'subject_id' => $subject_id,
					'title' => $title,
					'remark' => $remark,
					'due_date' => $due_date,
					'created_on' => $this->nepali_current_date
				);

				$result = $this->Teacher_model->create_assignment($data);

				if ($result) {
					$this->session->set_flashdata('success', 'Assignment Created Successfully');

					redirect(base_url() . 'teacher/assignment_cls/' . $cls_id . '/' . $result);
				}



				echo json_encode($data);
			}
		}
	}


	public function assignment_class()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');


		$data['currentURL'] = current_url();

		$tid = $_SESSION['teacher_id'];
		$tname = $_SESSION['teacher_name'];
		$classroom_id = $this->uri->segment(3);
		$asgn_id = $this->uri->segment(4);
		$m = $this->uri->segment(5);
		$year = $this->uri->segment(6);
		if ($m < 10) {
			$month = '0' . $m;
		} else {
			$month = $m;
		}

		if (isset($_POST['submit'])) {

			$query = $this->db->query('select id from assignment where assignment.id IN ( select assignment_id from assignments_uploaded where assignment_id =' . $_POST['assignment_id'] . ' )');

			if ($query->num_rows() > 0) {
				$this->session->set_flashdata('danger', str_replace('%s', "Assignment", ALREADY_ASSIGNED_MSG));
			} else {
				$update = $this->db->delete('assignment', array('id' => $_POST['assignment_id']));
				$this->session->set_flashdata('success', str_replace('%s', "Assignment", THE_DELETE_SUCCESS_MSG));
			}

			$data['subjects'] = $this->Teacher_model->get_subjects($tid, $_POST['classroom_id']);
			$data['assignment'] = $this->Teacher_model->get_assignments($tid, $_POST['classroom_id']);
		} else {

			$data['subjects'] = $this->Teacher_model->get_subjects($tid, $classroom_id);
			$data['assignment'] = $this->Teacher_model->get_assignments($tid, $classroom_id, $asgn_id, $month, $year);
		}


		$allStudtentArray = array();

		foreach ($data['assignment'] as $key => $value) {

			$assignmentData = $this->Teacher_model->uploaded_assignment($value['student_id'], $value['asgn_id']);
			if ($assignmentData) {
				$overdue = false;
				if ($assignmentData[0]['uploaded_date'] > $value['due_date'])
					$overdue = true;
				array_push($allStudtentArray, array(
					'title'				=> $value['title'],
					'subject_name'		=> $value['subject_name'],
					'remark'			=> $value['remark'],
					'due_date'			=> $value['due_date'],
					'teacher_name'		=> $value['teacher_name'],

					'student_name' 		=> $value['student_name'],
					'student_id' 		=> $value['student_id'],
					'asgn_id' 			=> $value['asgn_id'],
					'uploaded_date' 	=> $assignmentData[0]['uploaded_date'],
					'overdue'			=> $overdue ? $overdue : false,
					'flag' 				=> $assignmentData[0]['Flag'],
					'uploaded_id'		=> $assignmentData[0]['id'],
					'uploaded_remark'	=> $assignmentData[0]['remark'] ? $assignmentData[0]['remark'] : 2
				));
			} else {
				array_push($allStudtentArray, array(
					'title'				=> $value['title'],
					'subject_name'		=> $value['subject_name'],
					'remark'			=> $value['remark'],
					'due_date'			=> $value['due_date'],
					'teacher_name'		=> $value['teacher_name'],

					'student_name' 		=> $value['student_name'],
					'student_id' 		=> $value['student_id'],
					'asgn_id' 			=> $value['asgn_id'],
					'overdue'			=> false,
					'uploaded_remark'	=> 1
				));
			}
		}

		$data['main_assignment'] = $allStudtentArray;
		$data['list_assignments_all'] = $this->Teacher_model->list_of_assignments($tid, $classroom_id, $month, $year);

		$list_students = array();
		foreach ($data['list_assignments_all'] as $key => $value) {
			$assignmentData = $this->Teacher_model->uploaded_assignment(0, $value['assignment_id']);

			if ($assignmentData) {

				array_push($list_students, array(
					'assignment_id'		=> $value['assignment_id'],
					'classroom_id'		=> $value['classroom_id'],
					'teacher_id'		=> $value['teacher_id'],
					'subject_id'		=> $value['subject_id'],
					'title'				=> $value['title'],

					'remark' 			=> $value['remark'],
					'due_date' 			=> $value['due_date'],
					'subject_name' 		=> $value['subject_name'],
					'teacher_name' 		=> $value['teacher_name'],
					'classroom_name' 	=> $value['classroom_name'],
					'flag' 				=> $assignmentData[0]['Flag'],
					'uploaded_remark'	=> $assignmentData[0]['remark'] ? $assignmentData[0]['remark'] : 2
				));
			} else {
				array_push($list_students, array(
					'assignment_id'		=> $value['assignment_id'],
					'classroom_id'		=> $value['classroom_id'],
					'teacher_id'		=> $value['teacher_id'],
					'subject_id'		=> $value['subject_id'],
					'title'				=> $value['title'],

					'remark' 			=> $value['remark'],
					'due_date' 			=> $value['due_date'],
					'subject_name' 		=> $value['subject_name'],
					'teacher_name' 		=> $value['teacher_name'],
					'classroom_name' 	=> $value['classroom_name'],
					'flag' 				=> 0,
					'uploaded_remark'	=> 1
				));
			}
		}

		$data['list_assignments'] = $list_students;
		$data['month'] = $year ? $year . '-' . $month : date('Y-m', strtotime($this->nepali_current_date));

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teachers-assignments-class', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function teachers_assignments_review()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		$data['currentURL'] = current_url();

		$tid = $_SESSION['teacher_id'];
		$tname = $_SESSION['teacher_name'];

		$asgn_id = $this->uri->segment(3);
		$student_id = $this->uri->segment(4);


		$data['assignment'] = $this->Teacher_model->show_student_assignment($asgn_id, $student_id);

		$std_folder = $student_id . '_' . $asgn_id;
		$file_extensions = array('jpg', 'png', 'jpeg');
		$img = array();
		if (is_dir("student_assignment/" . $std_folder . '/')) {
			$files = scandir("student_assignment/" . $std_folder . '/');
			for ($i = 0; $i < count($files); $i++) {
				if ($files[$i] != '.' && $files[$i] != '..') {
					$file = pathinfo($files[$i]);
					$extension = $file['extension'];

					if (in_array($extension, $file_extensions)) {
						$img[$i] = "student_assignment/$std_folder/$files[$i]";
					}
				}
			}
		}

		$data['images'] = $img ? $img : '';



		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teachers-assignments-review', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function upload_assignment()
	{

		if (isset($_SESSION['teacher_id'])) {

			if (isset($_POST)) {

				$student_upload_id = $this->input->post('uploaded_id');

				$data = array(
					'remark' => $this->input->post('remark'),
					'Flag' => 1,
					'modified' => $this->nepali_current_date
				);
				$res = $this->Teacher_model->upload_assignment($data, $student_upload_id);

				if ($res) {

					$this->session->set_flashdata('success', 'Remark added successfully');
					redirect(base_url() . 'teacher/assignment_cls/' . $this->input->post('classroom_id') . '/' . $this->input->post('assignment_id'));
				}
			}
		}
	}
	//shankar code end here

	// Notification Controllers - 14-10-2021

	public function teacher_notification()
	{
		if (isset($_SESSION['teacher_id'])) {

			$date = date('Y-m-d', strtotime($this->nepali_current_date));

			$time = strtotime($date);
			$month = date("m", $time);
			$year = date("Y", $time);

			$currDate = $year . '-' . $month;

			$dateArr = array('month' => $month, 'year' => $year);

			$data['date'] = $currDate;

			$id = $_SESSION['teacher_id'];

			$sql = $this->Teacher_model->getTeachersNotification($id, $dateArr);

			if (!$sql) {
				$data['currentURL'] = current_url();
				//get logo
				$data['school_info'] = $this->Admin_model->get_logo_from_setting();
				$this->load->view('teacher/teacher-header', $data);
				$this->load->view('teacher/teacher-leftmenu', $data);
				$this->load->view('teacher/teacher-notification', $data);
				$this->load->view('teacher/teacher-footer');
			} else {
				$data['result'] = $sql;
				$data['currentURL'] = current_url();
				//get logo
				$data['school_info'] = $this->Admin_model->get_logo_from_setting();
				$this->load->view('teacher/teacher-header', $data);
				$this->load->view('teacher/teacher-leftmenu', $data);
				$this->load->view('teacher/teacher-notification', $data);
				$this->load->view('teacher/teacher-footer');
			}
		}
	}

	public function ajax_displayNotificationByDate()
	{

		$json = $this->input->post('dateArr');
		$data = json_decode($json);
		$dateArr = array('month' => $data[1], 'year' => $data[0]);

		$sql = $this->Teacher_model->getTeachersNotification($_SESSION['teacher_id'], $dateArr);

		if ($sql == false) {
			$json = json_encode('failed');
			echo $json;
		} else {
			$notifyArr = array();

			foreach ($sql as $row) {
				$originalDate = $row['created_at'];
				$newDate = date("d-m-Y", strtotime($originalDate));
				$newTime = date("h:i", strtotime($originalDate));

				$holder = '';


				$holder = '<div class="content-exam-box-one">';
				$holder .= 		'<div class="content-box-one-inner">';
				$holder .= 			'<div class="content-right-side">';
				$holder .= 				"<h6 class='exs-notif-title'>" .  $row['notification_title'] . "</h6>";
				$holder .=			'</div>';
				$holder .=		'</div>';

				$holder .=		'<div class="content-mid-text">';
				$holder .= 			"<p class='exs-notif-desc'>" .  $row['description'] . "</p>";
				$holder .=		'</div>';

				$holder .=		'<div class="content-last-sec">';
				$holder .=			'<li><b>Date : <span class="exs-notif-date">' . $newDate . '</span></b></li>';
				$holder .=			'<li><b>Time : <span class="exs-notif-time">' . $newTime . '</span></b></li>';
				$holder .=			'<li><input type="button" onClick="displaySelectedNotification(event,' . $row["notification_id"] . ')" value="view details" class="view-detail-notify"></li>';
				$holder .=			'</div>';
				$holder .= '</div>';

				array_push($notifyArr, $holder);
			}

			$json = json_encode($notifyArr);
			echo $json;
		}
	}

	public function ajax_getNotificationDescription()
	{
		$id = $this->input->post('notifid');

		$sql = $this->Admin_model->getSingleNotification($id);

		if ($sql) {
			echo json_encode($sql);
		} else {
			echo json_encode('failed');
		}
	}

	public function ajax_hide_notification_msg()
	{
		$id = $this->input->post('notifid');

		$update_read = $this->Admin_model->notification_update_read($id);

		if (!$update_read)
			echo json_encode('failed');
		else
			echo json_encode('success');
	}

	// Notification Controllers - 14-10-2021

	// Exam Controllers - 20-10-2021 - Afras Khan

	public function test_exam()
	{

		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		if (!file_exists(APPPATH . 'views/teacher/test-exam.php'))
			show_404();

		//classroom Query 
		// $sql = "SELECT t.teacher_id, t.classroom_id, c.id as classroom_table_id, c.classroom_name FROM teacher_subjects t INNER JOIN classroom c on t.classroom_id = c.id WHERE t.teacher_id = '".$_SESSION['teacher_id']."' AND (t.classroom_id = c.id AND t.teacher_id = c.teacher_id)";

		$sql = "SELECT cst.teacher_id, cst.classroom_id, cr.id as course_name, c.classroom_name as course_name from classroom_teacher_subject cst inner join classroom c on cst.classroom_id = c.id inner JOIN course cr ON cr.id = c.course_id WHERE cst.teacher_id = '" . $_SESSION['teacher_id'] . "' GROUP BY c.classroom_name, cr.course_name order by c.id";
		$data['result'] = $this->Teacher_model->get_table_info('teacher_subjects', '', $sql);


		$data['currentURL'] = current_url();
		//get logo
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/test-exam', $data);
		$this->load->view('teacher/teacher-footer');
	}

	// Exam Controllers - 20-10-2021 - Afras Khan

	// Teacher Attendence - 31-10-2021 - Afras Khan

	public function teacher_attendance()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		if (!file_exists(APPPATH . 'views/teacher/teacher-attendance.php'))
			show_404();

		if (isset($_SESSION['teacher_id'])) {
			$data['currentURL'] = current_url();


			$query = "SELECT cst.teacher_id, cst.classroom_id, cr.id as course_name, c.classroom_name , c.id  from classroom_teacher_subject cst inner join classroom c on cst.classroom_id = c.id inner JOIN course cr ON cr.id = c.course_id WHERE cst.teacher_id = '" . $_SESSION['teacher_id'] . "' GROUP BY c.classroom_name, cr.course_name order by c.id";

			$sql = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $query);
			// dd($sql);
			// $classroom_where_clause = '';
			// foreach ($sql as $key => $value) {

			// 	if ($key == 0) {
			// 		$classroom_where_clause .= "id = '$value[classroom_id]'";
			// 	} else {
			// 		$classroom_where_clause .= " OR id = '$value[classroom_id]'";
			// 	}
			// }


			// $data['teacher_classes'] = $this->Teacher_model->get_table_info('classroom', $classroom_where_clause);
			$data['teacher_classes'] = $sql;
			// dd($data['teacher_classes']);
			$data['school_info'] = $this->Admin_model->get_logo_from_setting();
			$this->load->view('teacher/teacher-header', $data);
			$this->load->view('teacher/teacher-leftmenu', $data);
			$this->load->view('teacher/teacher-attendance');
			$this->load->view('teacher/teacher-footer');
		}
	}

	public function teacher_attendance_subjects($cid)
	{

		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		if (!file_exists(APPPATH . 'views/teacher/teachers-attendance-subjects.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['classroom_id'] = $cid;

		$nowMonth = date('m', strtotime($this->nepali_current_date));
		$nowYear = date('Y', strtotime($this->nepali_current_date));
		$nowDay = date('d', strtotime($this->nepali_current_date));

		$obj = new NepaliDate();

		// Convert BS to AD.
		$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
		$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];
		$data['pday'] = $presentDay = strtolower(date('l', strtotime($currConvDate)));


		// $data['pday'] = $presentDay = strtolower(date('l', strtotime($this->nepali_current_date)));

		$data['complete_curr_date'] = $this->nepali_current_date;
		$data['cur_date'] = $currentDate = date('Y-m-d', strtotime($this->nepali_current_date));

		$sql = "Select sd.subject_id, sd.id as session_id, sd.start as start_time, cs.start_date,cs.end_date,c.id as classroom_id,c.classroom_name, s.subject_name, s.subject_icon,b.b_name, b.id as batch_id from classroom_teacher_subject cts
    		inner join classroom_session cs on cts.classroom_id = cs.classroom_id
    		inner join session_details sd on cs.id = sd.session_id
    		inner join subject s on s.id = sd.subject_id
    		inner join classroom c on c.id = $cid
    		inner join batch b on cs.batch_id = b.id
    		WHERE cts.teacher_id = $_SESSION[teacher_id] 
    		AND cts.classroom_id = $cid 
    		AND cts.subject_id = sd.subject_id
    		AND LOWER(sd.day) = '$presentDay' AND
    		('$currentDate' between cs.start_date and cs.end_date) 
    		AND (cs.is_active = 'yes' AND s.is_active = 'yes' AND c.is_active = 'yes') GROUP BY sd.id";

		$data['subjects'] = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);

		foreach ($data['subjects'] as $key => $value) {
			$data['subjects'][$key]['attendance_date'] = $currentDate . ' ' . date('H:i:s', strtotime($value['start_time']));
		}

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teachers-attendance-subjects');
		$this->load->view('teacher/teacher-footer');
	}


	public function teacher_attendance_list()
	{

		if (count($_POST) == 0) {
			$this->session->set_flashdata('failed', "Please select one classroom");
			redirect(base_url() . 'teacher/teacher_attendance');
		}

		$cid = (int)$this->input->post('classroom_id');
		$subject_id = (int)$this->input->post('subject_id');
		$session_id = (int)$this->input->post('session_id');
		$class_date = $this->input->post('class_date');
		$class_time = $this->input->post('class_time');
		$batch_id = $this->input->post('batch_id');


		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		if (!file_exists(APPPATH . 'views/teacher/teacher-attendance-list.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['class_time'] = date('Y-m-d H:i a', strtotime($class_time));
		$data['classroom_id'] = $cid;
		$data['class_date'] = $class_date;
		$data['subject_id'] = $subject_id;
		$data['session_id'] = $session_id;
		$data['batch_id'] = $batch_id;
		$subjecQuery = $this->db->get_where('subject', array('id' => $data['subject_id'], 'is_active' => 'yes'))->row_array();
		$data['sub_name'] = $subjecQuery['subject_name'];

		$classQuery = $this->db->get_where('classroom', array('id' => $data['classroom_id'], 'is_active' => 'yes'))->row_array();
		$data['class_name'] = $classQuery['classroom_name'];



		// Check if data is present in student_attendance table
		$sql = "Select * from student_attendence where classroom_id = $data[classroom_id] AND subject_id = $data[subject_id] AND DATE(attendence_date) = '" . date('Y-m-d', strtotime($class_date)) . "'  AND session_id = $data[session_id]";
		$check_if_record_exists = $this->Teacher_model->get_table_info('student_attendence', '', $sql);

		// if data is present, then its a update proceess else insert process
		$data['status'] = empty($check_if_record_exists) ? 'Insert' : 'Update';


		// if its update process, assigning attendance data into a variable
		if ($data['status'] == 'Update') {
			$data['existing_attendence'] = $check_if_record_exists;
		}

		// Select Student Id's from student_batch 
		$query = "SELECT * FROM student_batch WHERE classroom_id = '$data[classroom_id]' AND is_active = 'yes' AND batch_id = $batch_id";

		if ($data['status'] == 'Update') {
			$query = "SELECT * FROM student_batch sb INNER JOIN student_attendence sa on sb.student_id = sa.student_id WHERE sb.classroom_id = '$data[classroom_id]' AND is_active = 'yes' AND sb.batch_id = $batch_id";
		}


		$student_ids = array_column($this->Teacher_model->get_table_info('student_batch', '', $query), 'student_id');

		// If there are Ids Go inside this IF condition else Empty classroom with no students
		if (!empty($student_ids)) {

			$student_where_clause = '';

			foreach ($student_ids as $key => $value) {
				if ($key == 0) {
					$student_where_clause .= "id = '$value'";
				} else {
					$student_where_clause .= " OR id = '$value'";
				}
			}



			$stud_sql = "Select * from students where $student_where_clause ORDER by name";

			// Fetch students names from student ids
			// $data['students_list'] = $this->Teacher_model->get_table_info('students', '',$stud_sql);
			$student_list = $this->Teacher_model->get_table_info('students', '', $stud_sql);
			foreach ($student_list as $key => $value) {

				$roll = $this->db->order_by('id', 'DESC')->get_where('student_batch', array('student_id' => $value['id'], 'batch_id' => $value['batch_id']))->row_array();
				(!empty($roll)) ? $student_list[$key]['roll_no'] = $roll['roll_no'] : 0;
			}

			usort($student_list, function ($item1, $item2) {
				return $item1['roll_no'] <=> $item2['roll_no'];
			});

			$data['students_list'] = $student_list;

			if (count($_POST) > 0 && isset($_POST['studentid'])) {

				unset($_POST['markAll']);

				$insertData = array();


				$class_time = $this->input->post('class_time');
				$class_date = $this->input->post('class_date');
				$classroom_id = $this->input->post('classroom_id');
				$subject_id = $this->input->post('subject_id');
				$session_id = $this->input->post('session_id');
				$student_ids = $this->input->post('studentid');
				$student_name = $this->input->post('studentname');
				$attendance_data = $this->input->post('attendance');
				$status = $this->input->post('status');


				if ($data['status'] == 'Update') {


					$queryFlag = true;
					foreach ($student_ids as $key => $value) {

						$updateData = array();
						$updateData = [
							'status' => $attendance_data[$key],
							'modified' => date('Y-m-d H:i:s')
						];

						$whereClause = array(
							'student_id' => $value,
							'classroom_id' => $data['classroom_id'],
							'subject_id' => $data['subject_id'],
							'session_id' => $data['session_id'],
							'DATE(attendence_date)' => date('Y-m-d', strtotime($class_date))
						);



						$updateQuery = $this->Teacher_model->add_edit_student_attendance($updateData, $data['status'], $whereClause);

						if (!$updateQuery) {
							$queryFlag = false;
							return false;
						}
					}

					// $updateQuery = $this->Teacher_model->add_edit_student_attendance($updateData, $data['status'], $data['subject_id']);

					if (!$queryFlag) {
						$this->session->set_flashdata('failed', str_replace('%s', "Student's Attendance", THE_UPDATE_ERROR_MSG));
						redirect(base_url() . "teacher/attendance-subjects/$classroom_id");
					} else {
						$this->session->set_flashdata('success', str_replace('%s', "Student's Attendance", THE_UPDATE_SUCCESS_MSG));
						redirect(base_url() . "teacher/attendance-subjects/$classroom_id");
					}
				} else {


					echo $class_date;
					foreach ($attendance_data as $key => $value) {
						$insertData[] = array(
							'student_id' => $student_ids[$key],
							'classroom_id' => $classroom_id,
							'subject_id' => $subject_id,
							'session_id' => $data['session_id'],
							'attendence_date' => date('Y-m-d H:i:s', strtotime($class_date)),
							'status' => $value
						);
					}

					$insertQuery = $this->Teacher_model->add_edit_student_attendance($insertData, $data['status']);



					if (!$insertQuery) {
						$this->session->set_flashdata('failed', str_replace('%s', "Student's Attendance", THE_ADD_ERROR_MSG));
						redirect(base_url() . "teacher/attendance-subjects/$classroom_id");
					} else {
						$this->session->set_flashdata('success', str_replace('%s', "Student's Attendance", THE_ADD_SUCCESS_MSG));
						redirect(base_url() . "teacher/attendance-subjects/$classroom_id");
					}
				}
			}
		}


		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teacher-attendance-list');
		$this->load->view('teacher/teacher-footer');
	}

	public function ajax_get_teacher_sessions_from_date()
	{

		$date = $this->input->post('dateval');

		$cid = $this->input->post('classroom_id');

		$date = date('Y-m-d', strtotime($date));

		$nowMonth = date('m', strtotime($date));
		$nowYear = date('Y', strtotime($date));
		$nowDay = date('d', strtotime($date));

		$obj = new NepaliDate();

		// Convert BS to AD.
		$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
		$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];
		$day = strtolower(date('l', strtotime($currConvDate)));

		// $day = strtolower(date('l', strtotime($date)));

		$sql = "Select sd.subject_id, sd.id as session_id, sd.start as start_time, cs.start_date,cs.end_date,c.id as classroom_id,c.classroom_name, s.subject_name, s.subject_icon,b.b_name, b.id as batch_id from classroom_teacher_subject cts
    		inner join classroom_session cs on cts.classroom_id = cs.classroom_id
    		inner join session_details sd on cs.id = sd.session_id
    		inner join subject s on s.id = sd.subject_id
    		inner join batch b on cs.batch_id = b.id
    		inner join classroom c on c.id = $cid
    		WHERE cts.teacher_id = $_SESSION[teacher_id] 
    		AND cts.classroom_id = $cid 
    		AND cts.subject_id = sd.subject_id
    		AND LOWER(sd.day) = '$day' AND
    		(DATE('$date') between cs.start_date and cs.end_date) 
    		AND (cs.is_active = 'yes' AND s.is_active = 'yes' AND c.is_active = 'yes') GROUP BY sd.id";

		$data = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);

		foreach ($data as $key => $value) {
			$data[$key]['attendance_date'] = $date . ' ' . date('H:i:s', strtotime($value['start_time']));
		}


		if (!empty($data)) {

			$sessions = '<div class="class-head">';
			$sessions .= 	'<h3 class="common-heading"><span>' . date("d/m/Y", strtotime($date)) . '</span></h3> ';
			$sessions .= '</div>';
			$sessions .= '<div class="upcoming-cover">';

			foreach ($data as $key => $value) {
				$sessions .= '<form action="' . base_url() . 'teacher/students-attendance-list" method="POST">';
				$sessions .= '<input type="hidden" name="classroom_id" value="' . $value['classroom_id'] . '">';
				$sessions .= '<input type="hidden" name="subject_id" value="' . $value['subject_id'] . '">';
				$sessions .= '<input type="hidden" name="class_date" value="' . $value['attendance_date'] . '">';
				$sessions .= '<input type="hidden" name="session_id" value="' . $value['session_id'] . '">';
				$sessions .= '<input type="hidden" name="class_time" value="' . date('h:i a', strtotime($value['start_time'])) . '">';
				$sessions .= '<input type="hidden" name="batch_id" value="' . $value['batch_id'] . '">';
				$sessions .= '<div class="upcoming-tab">';
				$sessions .= '<img src="' . base_url() . 'assets_admin/images/icons/' . $value['subject_icon'] . '">';
				$sessions .= '<div class="upcoming-subject">';
				$sessions .= '<h4>' . $value['subject_name'] . '</h4>';
				$sessions .= '<p><span>' . $value['classroom_name'] . '</span><div style="font-size : 12px">' . $value['b_name'] . '</div></p>';
				$sessions .= '</div>';
				$sessions .= '<div class="upcoming-date">';
				$sessions .= '<span>' . ucfirst($day) . ', ' . date('h:i a', strtotime($value['start_time'])) . '</span>';
				$sessions .= '<div class="mark-btn-wrap"><button type="submit" class="join-class-btn">Mark</button></div></div></div></form>';
			}

			echo $sessions;
		} else {
			echo 'failed';
		}
	}

	// Teacher Attendence - 31-10-2021 - Afras Khan

	// view syllabus of teacher - shankar 01-11-21
	public function teacher_syllabus()
	{
		if (isset($_SESSION['teacher_id']))
			$data['currentURL'] = current_url();

		$data['currentURL'] = current_url();
		//get logo

		$tid = $_SESSION['teacher_id'];
		$data['get_syllabus'] = $this->Teacher_model->get_syllabus($tid);

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teachers-syllabus', $data);
		$this->load->view('teacher/teacher-footer');
	}


	//exam -Add/Edit in teacher flow on 01-11-21
	public function exam_questions($clsroom_id)
	{
		if (isset($_SESSION['teacher_id']))
			$data['currentURL'] = current_url();


		$data['currentURL'] = current_url();
		//get logo

		$tid = $_SESSION['teacher_id'];
		$get_questions = $this->Teacher_model->view_all_exam_details($tid, $clsroom_id);
		$exam_data = array();


		if ($get_questions != '' && isset($get_questions)) {
			foreach ($get_questions as $key => $val) {
				$get_total_count = $this->Teacher_model->get_count_questions_details($val['id']);
				$nowMonth = date('m', strtotime($val['exam_date']));
				$nowYear = date('Y', strtotime($val['exam_date']));
				$nowDay = date('d', strtotime($val['exam_date']));

				$obj = new NepaliDate();

				// Convert BS to AD.
				$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
				$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];

				$currConvDate = date('Y-m-d', strtotime('-1 day', strtotime($currConvDate)));

				$ConDar = $obj->convertAdToBs(date('Y', strtotime($currConvDate)), date('m', strtotime($currConvDate)), date('d', strtotime($currConvDate)));

				array_push($exam_data, array(
					'exam_id' 			=> $get_total_count['exam_id'],
					'tot_mark' 			=> $get_total_count['sum(question_mark)'],
					'id'				=> $val['id'],
					'classroom_id'		=> $val['classroom_id'],
					'course_id'			=> $val['course_id'],
					'exam_date'			=> $val['exam_date'],
					'exam_starttime'	=> $val['exam_starttime'],
					'exam_endtime'		=> $val['exam_endtime'],
					'e_name'			=> $val['e_name'],
					'subject_icon'		=> $val['subject_icon'],
					'classroom_name'	=> $val['classroom_name'],
					'subject_name'		=> $val['subject_name'],
					'total_marks'		=> $val['total_marks'],
					'Ndate'				=> date('Y-m-d', strtotime($this->nepali_current_date)),
					'checker_date'		=> $ConDar['year'] . '-' . $ConDar['month'] . '-' . $ConDar['day']

				));
			}
		}

		$data['get_questions'] = $exam_data;

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teacher-test-exams', $data);
		$this->load->view('teacher/teacher-footer');
	}


	public function add_edit_exam_questions()
	{
		if (isset($_SESSION['teacher_id']))
			$data['currentURL'] = current_url();

		$e_id = $this->uri->segment(3);
		$cls_rm_id = $this->uri->segment(4);

		$data['currentURL'] = current_url();

		$tid = $_SESSION['teacher_id'];
		$data['exam_id'] = $e_id;
		$data['classroom_id'] = $cls_rm_id;


		$data['get_questions'] = $this->Teacher_model->get_all_questions($e_id);
		// $data['get_exam_question'] = $this->Teacher_model->get_all_questions_details($exam_que_id='', $e_id);
		$exam_date = $data['get_questions']['exam_date'];
		$nowMonth = date('m', strtotime($exam_date));
		$nowYear = date('Y', strtotime($exam_date));
		$nowDay = date('d', strtotime($exam_date));

		$obj = new NepaliDate();

		// Convert BS to AD.
		$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
		$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];

		$currConvDate = date('Y-m-d', strtotime('-1 day', strtotime($currConvDate)));

		$ConDar = $obj->convertAdToBs(date('Y', strtotime($currConvDate)), date('m', strtotime($currConvDate)), date('d', strtotime($currConvDate)));
		$checkDate = $ConDar['year'] . '-' . $ConDar['month'] . '-' . $ConDar['day'];
		if (strtotime($checkDate) <= strtotime(date('Y-m-d', strtotime($this->nepali_current_date)))) {
			$data['date_checker'] = 1;
		} else {
			$data['date_checker'] = 0;
		}

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/Teacher-flow-exam-correction-mc', $data);
		$this->load->view('teacher/teacher-footer');
	}

	function get_exam_question_details($e_id)
	{
		$get_questions = $this->Teacher_model->get_all_questions($e_id);
		// $get_questions ='';

		echo json_encode($get_questions);
	}

	function add_edit_question_details($exam_que_id)
	{
		$get_exam_details = $this->Teacher_model->get_all_questions_details($exam_que_id);
		// if ($exam_que_id != '') {
		// 	$data['get_total_count'] = $this->Teacher_model->get_count_questions_details($e_id, $exam_que_id);
		// }  		
		// print_r($get_exam_details);
		// exit();
		echo json_encode($get_exam_details);
	}


	function add_edit_question_details_save()
	{

		$tid = $_SESSION['teacher_id'];
		$exam_questions_id = ($_POST['exam_que_id'] != '') ? $_POST['exam_que_id'] : '';


		if (isset($_FILES['file']['name'])) {

			$filename = $_FILES['file']['name'];

			if (!is_dir('content-Test-Image')) {
				mkdir('./content-Test-Image', 0777, true);
			}

			$location = "content-Test-Image/" . $filename;

			$imageFileType = pathinfo($location, PATHINFO_EXTENSION);
			$imageFileType = strtolower($imageFileType);

			/* Valid extensions */
			$valid_extensions = array("jpg", "jpeg", "png");

			$response = 0;
			/* Check file extension */
			if (in_array(strtolower($imageFileType), $valid_extensions)) {
				/* Upload file */
				if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
					$response = $location;
				}
			}
		}
		$image_name = '';
		if (isset($_FILES['file']['name'])) {
			$image_name = $response;
		}

		$insert_data = array(
			'exam_id' => $_POST['exam_id'],
			'subject_id' => $_POST['subject_id'],
			'teacher_id' => $tid,
			'question_type_id' => $_POST['question_type_id'],
			'question_name'  => $_POST['question_name'],
			'option_a' => $_POST['option_a'],
			'option_b' => $_POST['option_b'],
			'option_c' => $_POST['option_c'],
			'option_d' => $_POST['option_d'],
			'correct_answer' => $_POST['multiple_answer'] ? $_POST['multiple_answer'] : $_POST['tf_answer'],
			'question_mark' => $_POST['question_mark'],
			'image' => $image_name ? $image_name : '',
		);


		$id = $this->Teacher_model->add_questions_details($insert_data, $exam_questions_id);

		echo json_decode($id);
	}

	public function tick_marks_data_view()
	{
		$get_total_count = $this->Teacher_model->get_count_questions_details($_POST['exam_id'], $_POST['marks'], $_POST['count']);

		if ($_POST['count'] == 1) {
			$exam_data = array();
			foreach ($get_total_count as $k => $v) {

				array_push($exam_data, array(
					'exam_id' => $v['exam_id'],
					'count_mark' => $v['count(question_mark)'],
					'que_mark' => $v['question_mark'],
				));
			}

			echo json_encode($exam_data);
		} else {
			echo json_decode($get_total_count['count(question_mark)']);
		}
	}

	//end code for Test/Exam on 10-11-21

	// Teacher's Calendar - 09-11-2021 - Afraskhan

	public function teacher_calender()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		if (!file_exists(APPPATH . 'views/teacher/teachers-attendance-subjects.php'))
			show_404();

		$data['currentURL'] = current_url();

		$nowMonth = date('m', strtotime($this->nepali_current_date));
		$nowYear = date('Y', strtotime($this->nepali_current_date));
		$nowDay = date('d', strtotime($this->nepali_current_date));

		$obj = new NepaliDate();

		// Convert BS to AD.
		$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
		$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];
		$presentDay = strtolower(date('l', strtotime($currConvDate)));
		// $presentDay = strtolower(date('l', strtotime($this->nepali_current_date)));


		$query = "Select cts.* from classroom_teacher_subject cts inner join classroom c on c.id = cts.classroom_id where cts.teacher_id = '$_SESSION[teacher_id]' AND c.is_active='yes'";

		$teacher_subjects = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $query);
		$data['cur_date'] = $currentDate = date('Y-m-d', strtotime($this->nepali_current_date));
		// test_view_array($teacher_subjects);
		$data['subjects'] = array();
		$count = 0;
		foreach ($teacher_subjects as $key => $value) {

			$sql = "Select sd.subject_id, sd.id as session_id, sd.start, sd.day, sd.duration,sd.start_link, sd.join_link, cs.start_date,cs.end_date,c.id as classroom_id,c.classroom_name, s.subject_name, s.subject_icon,b.b_name from classroom_teacher_subject cts
    			inner join classroom_session cs on cts.classroom_id = cs.classroom_id
    			inner join session_details sd on cs.id = sd.session_id
    			inner join subject s on s.id = sd.subject_id
    			inner join classroom c on c.id = $value[classroom_id]
    			inner join batch b on cs.batch_id = b.id
    			WHERE s.id = $value[subject_id] 
    			AND (cts.teacher_id = $_SESSION[teacher_id] 
    			AND cts.classroom_id = $value[classroom_id])
    			AND LOWER(sd.day) = '$presentDay' 
    			AND	('$currentDate' between cs.start_date and cs.end_date) 
    			AND (cs.is_active = 'yes' AND s.is_active = 'yes' AND c.is_active = 'yes') GROUP BY sd.id ";

			$session_results = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);



			if (!empty($session_results)) {

				foreach ($session_results as $key2 => $value2) {

					$data['subjects'][$count] = array(
						'subject_id' => $value2['subject_id'],
						'session_id' => $value2['session_id'],
						'start' => $value2['start'],
						'start_date' => $value2['start_date'],
						'end_date' => $value2['end_date'],
						'classroom_id' => $value2['classroom_id'],
						'classroom_name' => $value2['classroom_name'],
						'subject_name' => $value2['subject_name'],
						'subject_icon' => $value2['subject_icon'],
						'duration' => $value2['duration'],
						'start_link' => $value2['start_link'],
						'day' => $value2['day'],
						'batch_name' => $value2['b_name']
					);

					$count++;
				}
			}
		}
		usort($data['subjects'], function ($item1, $item2) {
			return $item1['start'] <=> $item2['start'];
		});
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/teacher-calendar');
		$this->load->view('teacher/teacher-footer');
	}

	public function ajax_get_teacher_calendar_from_date()
	{
		$date = $this->input->post('dateval');

		$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

		$nowMonth = date('m', strtotime($date));
		$nowYear = date('Y', strtotime($date));
		$nowDay = date('d', strtotime($date));

		$obj = new NepaliDate();

		// Convert BS to AD.
		$nowArr = $obj->convertBsToAd($nowYear, $nowMonth, $nowDay);
		$currConvDate = $nowArr['year'] . '-' . $nowArr['month'] . '-' . $nowArr['day'];
		$day = strtolower(date('l', strtotime($currConvDate)));

		// $day = strtolower(date('l', strtotime($date)));

		$query = "Select cts.* from classroom_teacher_subject cts inner join classroom c on c.id = cts.classroom_id where cts.teacher_id = '$_SESSION[teacher_id]' AND c.is_active='yes'";

		$teacher_subjects = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $query);

		$data = array();
		$count = 0;
		foreach ($teacher_subjects as $key => $value) {

			$sql = "Select sd.subject_id, sd.id as session_id, sd.start, sd.day, sd.duration,sd.start_link, sd.join_link, cs.start_date,cs.end_date,c.id as classroom_id,c.classroom_name, s.subject_name, s.subject_icon,b.b_name from classroom_teacher_subject cts
    			inner join classroom_session cs on cts.classroom_id = cs.classroom_id
    			inner join session_details sd on cs.id = sd.session_id
    			inner join subject s on s.id = sd.subject_id
    			inner join classroom c on c.id = $value[classroom_id]
    			inner join batch b on cs.batch_id = b.id
    			WHERE s.id = $value[subject_id] 
    			AND (cts.teacher_id = $_SESSION[teacher_id] 
    			AND cts.classroom_id = $value[classroom_id])
    			AND LOWER(sd.day) = '$day' 
    			AND	(DATE('$date') between cs.start_date and cs.end_date) 
    			AND (cs.is_active = 'yes' AND s.is_active = 'yes' AND c.is_active = 'yes') GROUP BY sd.id";

			$session_results = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);

			if (!empty($session_results)) {

				foreach ($session_results as $key2 => $value2) {

					$data[$count] = array(
						'subject_id' => $value2['subject_id'],
						'session_id' => $value2['session_id'],
						'start' => $value2['start'],
						'start_date' => $value2['start_date'],
						'end_date' => $value2['end_date'],
						'classroom_id' => $value2['classroom_id'],
						'classroom_name' => $value2['classroom_name'],
						'subject_name' => $value2['subject_name'],
						'subject_icon' => $value2['subject_icon'],
						'duration' => $value2['duration'],
						'start_link' => $value2['start_link'],
						'day' => $value2['day'],
						'batch_name' => $value2['b_name']
					);

					$count++;
				}
			}
		}
		usort($data, function ($item1, $item2) {
			return $item1['start'] <=> $item2['start'];
		});
		if (empty($data)) {
			echo 'failed';
		} else {

			$sessions = '<div class="class-head">';
			$sessions .= 	'<h3 class="common-heading"><span>' . date('d/m/Y', strtotime($date)) . '</span></h3> ';
			$sessions .= '</div>';
			$sessions .= '<div class="upcoming-cover">';

			foreach ($data as $key => $value) {

				$pday =  date("l");
				$sessionDay = $value['day'];

				$s = $value['start'];
				// $s = "15:03";
				$p = date("H:i");

				$mins  = (strtotime($s) - strtotime($p)) / 60;

				$duration = $value['duration'];
				$end = date('H:i', strtotime($s) + ($duration * 60));

				$now = new Datetime("now");
				$begintime = new DateTime($s);
				$endtime = new DateTime($end);



				$sessions .= '<div class="upcoming-tab upcoming-classes-tab next-class">';
				$sessions .= '<div class="class-Sec">';
				$sessions .= '<h4 class="mb-3">' . $value['classroom_name'] . '</h4>';
				$sessions .= '<img class="mb-1" src="' . base_url() . 'assets_admin/images/icons/' . $value['subject_icon'] . '"></div>';
				$sessions .= '<div class="class-det"><div class="class-det-head">';
				$sessions .= '<h5>' . $value["subject_name"] . '</h5>';
				$sessions .= '<div class="class-time"><div class="time">';
				$sessions .= '<i class="far fa-clock"></i><span>' . $value['duration'] . ' min</span>';
				$sessions .= '</div></div></div>';
				$sessions .= '<p>' . $value['batch_name'] . '</p>';
				if (strtolower($pday) === strtolower($sessionDay) && ($now >= $begintime && $now <= $endtime) && $date == date('Y-m-d', strtotime($this->nepali_current_date))) {
					$sessions .= '<div class="start-btn-wrap">';
					$sessions .= '<a class="join-class-btn" href="' . $value['start_link'] . '" target="_blank">Start</a>';
					$sessions .= '</div>';
				} else {
					$sessions .= '<p class="mt-3"><b>' . date('h:i a', strtotime($s)) . '</b></p>';
				}
				$sessions .= '</div></div>';
			}

			echo $sessions;
		}
	}

	// Teacher's Calendar End - 09-11-2021 - Afraskhan


	// Teacher Test/Exam Evaluation Start - 11-11-21 - Shankar

	public function exam_evaluation()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$data['currentURL'] = current_url();

		$tid = $_SESSION['teacher_id'];

		$sql = 'select e_name,exam_id,exam_date
    		FROM questions, exam
    		WHERE teacher_id = ' . $tid . ' 
    		AND exam_id = exam.id
    		GROUP BY exam_id
    		ORDER BY exam_date DESC';

		$data['session_results'] = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);

		foreach ($data['session_results'] as $key => $value) {
			$returnaArr = get_complete_BS_date_info($this->nepaliDateObject, $value['exam_date']);
			$data['session_results'][$key]['bs_date'] = $returnaArr['F'] . '-' . $returnaArr['Y'];
		}

		// test_view_array($data['session_results']);

		// echo "<pre>";print_r($data['session_results']);exit();

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/TF-evaluation-details', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function get_exam_subject_details($exam_id)
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$data['currentURL'] = current_url();
		$tid = $_SESSION['teacher_id'];
		$query = 'select q.id as question_id,e_name, subject_name, subject_id, teacher_name, subject_icon, q.exam_date
    		from questions q, exam e,subject s, teacher t
    		where q.teacher_id = ' . $tid . ' 
    		and q.exam_id =  ' . $exam_id . ' 
    		and q.teacher_id = t.id
    		and s.id = q.subject_id
    		and e.id = q.exam_id
    		ORDER by exam_date DESC';
		$query_result = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $query);

		echo json_encode($query_result);
	}

	public function exam_question_evaluation()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$data['currentURL'] = current_url();

		$question_id = $this->uri->segment(3);
		$data['questions_id'] = $question_id;
		$query = $this->db->query('select questions.*, e_name from questions,exam where questions.id =' . $question_id . ' and exam_id = exam.id');
		$questions_data = $query->row_array();

		foreach ($questions_data as $key => $value) {
			if ($key == 'exam_date') {
				$returnaArr = get_complete_BS_date_info($this->nepaliDateObject, $value);
				$questions_data['bs_date'] = $returnaArr['F'] . '-' . $returnaArr['Y'];
			}
		}

		$data['questions_details'] = $questions_data;
		$sections = explode(",", $questions_data['section_id']);

		$data_array = array();
		for ($i = 0; $i < count($sections); $i++) {

			$q_one = $this->db->query('SELECT s.id as student_id, s.name, q.id as questions_id 
    				FROM questions q
    				INNER JOIN classroom c ON q.course_id = c.course_id  
    				INNER JOIN student_batch sb ON c.id = sb.classroom_id
    				INNER JOIN students s ON sb.student_id = s.id AND sb.batch_id = s.batch_id			            
    				WHERE q.id =' . $question_id . '  
    				AND c.course_id =' . $questions_data['course_id'] . ' 
    				AND c.section_id =' . $sections[$i] . '
    				GROUP BY s.id
    				');

			$query_result1 = $q_one->result_array();

			if (count($query_result1) > 0) {
				foreach ($query_result1 as $key => $value) {

					$appeared_exam = $this->db->query('
    						select exams_id as exam_ans_id,created,review, status from exam_answers where exams_id = ' . $value['questions_id'] . ' AND student_id =' . $value['student_id'] . ' limit 1');
					$ans_query = $appeared_exam->row_array();


					if (isset($ans_query)) {

						array_push($data_array, array(
							'exam_ans_id'	=> $ans_query['exam_ans_id'],
							'date_of_exam'	=> $ans_query['created'],
							'status'		=> $ans_query['status'],
							'student_name'	=> $value['name'],
							'student_id'	=> $value['student_id'],
							'appeared'		=> 'yes',
						));
					} else {
						array_push($data_array, array(

							'student_name'	=> $value['name'],
							'student_id'	=> $value['student_id'],
							'appeared'		=> 'no',
						));
					}
				}
			}
		}


		$data['students_data']	= $data_array;

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/TF-evaluation-action', $data);
		$this->load->view('teacher/teacher-footer');
	}


	public function exam_question_evaluation_paper()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$data['currentURL'] = current_url();

		$question_id = $this->uri->segment(3);
		$student_id = $this->uri->segment(4);

		$get_Data = $this->db->query('select q.*, subject_name, e_name from questions q, subject s, exam e where q.id =' . $question_id . ' AND q.subject_id = s.id and q.exam_id = e.id');
		$data['exam_data'] = $get_Data->row_array();

		$query = $this->db->query('
    			SELECT  ea.*,eq.subject_id, eq.question_type_id, eq.question_name,eq.option_a,eq.option_b,eq.option_c,eq.option_d,eq.correct_answer,eq.question_mark,eq.image 
    			FROM exam_questions eq
    			LEFT JOIN exam_answers ea ON ea.exams_id = eq.exam_id 			            			            
    			WHERE eq.exam_id =' . $question_id . ' 
    			AND ea.student_id = ' . $student_id . '
    			AND eq.exam_id = ea.exams_id
    			AND eq.id = ea.exam_questions_id
    			GROUP by eq.question_name,ea.id
    			ORDER BY eq.id asc
    			');

		$data['questions_data'] = $query->result_array();

		$data['questions_id'] = $question_id;

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/TF-evaluation-qn1', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function get_questionsAndAnswerEvaluation()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$examAnsid = $_POST['exam_answer_id'];
		$marks = $_POST['marks'];

		$query = $this->db->query('
    			SELECT  eq.question_mark 
    			FROM exam_questions eq, exam_answers ea

    			WHERE ea.id =' . $examAnsid . ' 
    			AND ea.exam_questions_id = eq.id
    			');
		$data = $query->row_array();

		if ($marks <= $data['question_mark']) {

			$this->db->set('review', $marks);
			$this->db->set('modified', $this->nepali_current_date);
			$this->db->where('id', $examAnsid);
			$this->db->update('exam_answers');

			echo 1;
		} else {
			echo 0;
		}
	}

	public function teacher_review_status()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}
		$data['currentURL'] = current_url();

		$exams_id = $_POST['exams_id'];
		$student_id = $_POST['student_id'];
		$status = $_POST['status'];

		$data = array(
			'status' => $status + 1,
			'modified' => $this->nepali_current_date
		);


		$this->db->trans_start();
		$this->db->where('student_id', $student_id);
		$this->db->where('exams_id', $exams_id);
		$this->db->update('exam_answers', $data);
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			//false
			redirect(base_url() . 'teacher/evaluate-questions/' . $exams_id);
		} else {
			//true
			// if ($status == 1) {

			$query = $this->db->query(' select sum(review) as totalMarks from exam_answers where student_id =' . $student_id . ' AND exams_id=' . $exams_id);
			$get_marks_student = $query->row_array();

			$student_marks_tot = $get_marks_student['totalMarks'];


			$tot_mark_query = $this->db->query(' select  subject_id,total_marks from questions where id=' . $exams_id);
			$tot_mark = $tot_mark_query->row_array();

			$actual_marks = $tot_mark['total_marks'];

			if ($student_marks_tot == 0) {
				$scored_percentage = 0;
			} else {
				$scored_percentage = round(($student_marks_tot * (100 / $actual_marks)), 2);
			}



			$grade = student_grade_show($scored_percentage);

			$batch_id_query = $this->db->query('select student_batch.id from student_batch, students where students.id =' . $student_id . ' and students.batch_id = student_batch.batch_id and students.id = student_batch.student_id and students.is_active = "yes"');
			$student_batch_id = $batch_id_query->row_array();

			$insert_data = array(
				'student_id'		=> $student_id,
				'exams_id'			=> $exams_id,
				'subject_id'		=> 	$tot_mark['subject_id'],
				'total_marks'		=>	$actual_marks,
				'get_marks'			=>	$student_marks_tot,
				'grades_id'			=>	$grade['id'],
				'student_batch_id'	=>	$student_batch_id['id'],
			);

			$check_data = $this->db->query('select * from student_exam_results where student_id=' . $student_id . ' and exams_id=' . $exams_id . ' and subject_id=' . $tot_mark['subject_id']);

			if ($check_data->num_rows() == 0) {
				$this->db->insert('student_exam_results', $insert_data);
				$result_id = $this->db->insert_id();
				if ($result_id) {
					redirect(base_url() . 'teacher/evaluate-questions/' . $exams_id);
				}
			} else {
				$this->db->trans_start();
				$this->db->where('student_id', $student_id);
				$this->db->where('exams_id', $exams_id);
				$this->db->where('subject_id', $tot_mark['subject_id']);
				$this->db->update('student_exam_results', $insert_data);
				$this->db->trans_complete();
				redirect(base_url() . 'teacher/evaluate-questions/' . $exams_id);
			}
		}
	}

	// Teacher Test/Exam Evaluation End - 11-11-21 - Shankar 

	//Teacher Grade 

	public function teacher_grade_deatils()
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}

		$data['currentURL'] = current_url();

		$classroom_id = $this->uri->segment(3);

		$tid = $_SESSION['teacher_id'];

		$sql = 'select e_name,exam_id,exam_date, classroom.id as classroom_id
    		FROM questions, exam, classroom
    		WHERE teacher_id = ' . $tid . ' 
    		AND classroom.id = ' . $classroom_id . '
    		AND classroom.course_id = questions.course_id
    		AND exam_id = exam.id
    		GROUP BY exam_id
    		ORDER BY exam_date DESC';

		$data['session_results'] = $this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql);

		foreach ($data['session_results'] as $key => $value) {
			$returnaArr = get_complete_BS_date_info($this->nepaliDateObject, $value['exam_date']);
			$data['session_results'][$key]['bs_date'] = $returnaArr['F'] . '-' . $returnaArr['Y'];
		}

		// test_view_array($data['session_results']);

		$data['classroom_id'] = $classroom_id;

		// echo "<pre>";print_r($data['session_results']);exit();

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/TF-grade-exam-details', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function get_datewises_exam_details($classroom_id, $date)
	{
		if (!isset($_SESSION['teacher_id'])) {
			redirect(base_url() . 'teacher');
		}
		$tid = $_SESSION['teacher_id'];

		$sql = 'select e_name,exam_id,exam_date, classroom.id as classroom_id
    		FROM questions, exam, classroom
    		WHERE teacher_id = ' . $tid . ' 
    		AND classroom.id = ' . $classroom_id . '
    		AND classroom.course_id = questions.course_id
    		AND exam_id = exam.id
    		AND DATE_FORMAT(questions.exam_date,"%Y-%m") >="' . $date . '" 
    		GROUP BY exam_id
    		ORDER BY exam_date DESC';

		echo json_encode($this->Teacher_model->get_table_info('classroom_teacher_subject', '', $sql));
		// echo $this->db->last_query();
		// echo $date;
	}





	//teacher reset password start here

	public function teacher_reset_view()
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/header', $data);

		$this->load->view('teacher/teacher-reset');
		$this->load->view('teacher/footer');
	}

	public function fp_check_is_emailid_valid()
	{
		$emailId = $_POST['email'];

		$query = $this->db->get_where('teacher', array('email' => $emailId));

		if (!empty($query->row_array())) {
			echo ('success');
		} else {
			echo ('failure');
		}
	}

	public function send_email_reset_password()
	{

		if ($_POST) {
			$url =  str_replace("reset-email", "create-password", current_url());
			$emailId = $_POST['teacherID'];
			$query = $this->db->get_where('teacher', array('email' => $emailId));
			$teacher_name = $query->row_array();

			$base_url = str_replace("index.php/teacher/send_email_reset_password", "", current_url());

			$mail_url = urlsafe_b64encode($emailId);

			$replace_url = $url . '/' . $mail_url;

			$approve_data = array(
				"teachername" => $teacher_name['teacher_name'],
				"reset_link" => $replace_url,
				"baseurl" => $base_url
			);
			$approve_data['school_info'] = $this->Admin_model->get_logo_from_setting();

			$msg = $this->load->view('reset_password_email_teacher', $approve_data, TRUE);

			$this->load->config('email');
			$from = $this->config->item('smtp_user');
			$this->email->from($from);
			$this->email->set_newline("\r\n");
			$this->email->to($emailId);
			//$this->email->to('shankar@erisn.com');


			$this->email->subject('Reset Password');
			$this->email->message($msg);

			if ($this->email->send()) {
				$this->session->set_flashdata('success', 'A mail has been sent to your Email-Id, Please check and reset your password');
				redirect(base_url() . 'teacher/teacher-reset');
			} else {
				$this->session->set_flashdata('failed', "Mailer Error: " . $this->email->print_debugger());
				redirect(base_url() . 'teacher/teacher-reset');
			}
		} else {
			redirect(base_url() . 'teacher', 'refresh');
		}
	}


	public function teacher_create_password($emailId)
	{
		$decode_mail = urlsafe_b64decode($emailId);
		$query = $this->db->get_where('teacher', array('email' => $decode_mail));

		if (!empty($query->row_array())) {
			$data['teacher_data'] = $query->row_array();
		} else {
			$data['teacher_data'] =  '0';
		}

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('teacher/header', $data);
		$this->load->view('teacher/teacher-new-password', $data);
		$this->load->view('teacher/footer');
	}

	public function change_teacher_password()
	{
		if ($_POST) {
			$data = array(
				'password' => base64_encode($_POST['password'])
			);
			$this->db->where('id', $_POST['teacher_id']);
			$this->db->where('email', $_POST['teacher_email']);

			$this->db->update('teacher', $data);
			$this->db->trans_complete();
			if ($this->db->trans_status() === FALSE) {
				$this->session->set_flashdata('danger', str_replace('%s', 'Password', THE_ADD_ERROR_MSG));
			} else {
				$this->session->set_flashdata('success', str_replace('%s', 'Password', THE_UPDATE_SUCCESS_MSG));
			}

			redirect(base_url() . 'teacher');
		} else {
			redirect(base_url() . 'teacher', 'refresh');
		}
	}

	public function update_link_active()
	{
		$storedURL = $this->input->post('link');
		$_SESSION['active_old_link'] = $storedURL;
	}

	public function changeTeacher_password()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		$data['currentURL'] = current_url();

		//get logo
		$data['logo'] = $this->Admin_model->get_logo();
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();

		$data['title'] = 'Change Password';
		if (count($_POST) > 0) {

			$data = array(
				'password' => base64_encode($_POST['password']),
				'modified_on' => $this->nepali_current_date
			);


			$this->db->where('id', $_SESSION['teacher_id']);
			$this->db->update('teacher', $data);
			$this->db->trans_complete();
			if ($this->db->trans_status() === FALSE) {
				$this->session->set_flashdata('danger', str_replace('%s', 'Password', THE_ADD_ERROR_MSG));
				redirect(base_url() . 'teacher/teacher-change-password');
			} else {
				$this->session->set_flashdata('success', str_replace('%s', 'Password', THE_UPDATE_SUCCESS_MSG));
				redirect(base_url() . 'teacher/teacher-change-password');
			}

			exit();
		}
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu', $data);
		$this->load->view('teacher/change-password', $data);
		$this->load->view('teacher/teacher-footer');
	}

	public function leaves()
	{
		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		$data['currentURL'] = current_url();

		//get logo
		$data['logo'] = $this->Admin_model->get_logo();
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();

		$teacher_id = (string)$_SESSION['teacher_id'];

		$sql = "SELECT s.name,c.classroom_name,la.* from leave_applications la 
    		INNER JOIN students s on s.id = la.student_id
    		INNER JOIN student_batch sb on s.id = sb.student_id AND sb.batch_id = s.batch_id
    		INNER JOIN classroom c on c.id = sb.classroom_id
    		WHERE JSON_CONTAINS(la.teacher_id, '[$teacher_id]')";

		$data['leaves'] = $leaves = $this->Teacher_model->get_table_info('leave_applications', '', $sql);
		// dd($leaves);
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu');
		$this->load->view('teacher/leaves');
		$this->load->view('teacher/teacher-footer');
	}

	public function view_leave($id)
	{

		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		$data['currentURL'] = current_url();

		//get logo
		$data['logo'] = $this->Admin_model->get_logo();
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$data['leave_id'] = $id;
		$leave = $this->Teacher_model->get_table_info('leave_applications', array('id' => $id));

		if (empty($leave)) {
			$this->session->set_flashdata('failed', 'There is no leave application with the given Id');
			redirect(base_url() . 'teacher/leaves');
		} else {
			$name = '';
			foreach ($leave as $key => $value) {
				$teacher_ids = json_decode($value['teacher_id']);
				foreach ($teacher_ids as $index => $ele) {
					$teacher_name = $this->db->get_where('teacher', array('id' => $ele))->row();
					if (!empty($teacher_name)) {
						if (!$name) {
							$name = $teacher_name->teacher_name;
							$leave[$key]['teacher_name'] = $name;
						} else {
							$name .= ', ' . $teacher_name->teacher_name;
							$leave[$key]['teacher_name'] = $name;
						}
					} else {
						if (!$name) {
							$name = 'unknown teacher';
							$leave[$key]['teacher_name'] = $name;
						} else {
							$name .= ', unknown teacher ';
							$leave[$key]['teacher_name'] = $name;
						}
					}
				}
			}
			$data['leave'] = $leave;
		}
		// dd($data['leave']);
		$this->load->view('teacher/teacher-header', $data);
		$this->load->view('teacher/teacher-leftmenu');
		$this->load->view('teacher/single_leave');
		$this->load->view('teacher/teacher-footer');
	}

	public function ar_leave_application()
	{

		if (!isset($_SESSION['teacher_id']))
			redirect(base_url() . 'teacher');

		if (count($_POST) == 0) {
			$this->session->set_flashdata('failed', 'Please select a valid leave application');
			redirect(base_url() . 'teacher/leaves');
		}

		$id = $this->input->post('id');

		if (isset($_POST['rejected_msg'])) {

			$data['status'] = 'Rejected';
			$data['rejected_msg'] = $this->input->post('rejected_msg');
			$data['modified'] = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));
			$leave = $this->Teacher_model->update_table($id, $data, 'leave_applications');

			if ($leave) {
				$this->session->set_flashdata('success', 'Leave has been successfully rejected');
				redirect(base_url() . 'teacher/leaves');
			} else {
				$this->session->set_flashdata('failed', 'Please try again later!');
				redirect(base_url() . 'teacher/leaves');
			}
		} else {
			$data['status'] = 'Approved';
			$data['modified'] = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));
			$leave = $this->Teacher_model->update_table($id, $data, 'leave_applications');

			if ($leave) {
				$this->session->set_flashdata('success', 'Leave has been successfully approved');
				redirect(base_url() . 'teacher/leaves');
			} else {
				$this->session->set_flashdata('failed', 'Please try again later!');
				redirect(base_url() . 'teacher/leaves');
			}
		}
	}
}