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

use Nilambar\NepaliDate\NepaliDate;

require_once 'vendor/autoload.php';

class Student extends CI_Controller
{
	private $nepaliDateObject;
	private $nepali_current_date;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Student_model');
		$this->load->model('Admin_model');
		$this->load->library('paypal_lib');
		$this->load->helper(array('form', 'url'));
		$this->load->library('email');
		$this->load->library('Ciqrcode');
		$this->load->helper('common_helper');
		$this->load->database();
		date_default_timezone_set('Asia/Kathmandu');
		// date_default_timezone_set("Asia/Kolkata");
		$this->nepaliDateObject = new NepaliDate();
		$this->nepali_current_date = cuurentNepaliDate($this->nepaliDateObject);
	}

	public function index()
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('student/header', $data);
		$this->load->view('student/login', $data);
		$this->load->view('student/footer', $data);
	}

	public function admission_process()
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('student/header', $data);
		$this->load->view('student/admission-process');
		$this->load->view('student/footer');
	}

	public function admission()
	{
		$data['courses'] = $this->Student_model->get_courses();
		//shankar code

		//end shankar code
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$CI = &get_instance();
		$mainListDb = $CI->load->database('schoolSetting', TRUE);
		$data['batch'] = $this->db->query("SELECT * FROM batch where id = " . $data['school_info']['batch_id'])->result_array();
		$data['provinces'] = $mainListDb->query('SELECT * FROM provinces')->result_array();
		$this->load->view('student/header', $data);
		$this->load->view('student/admission', $data);
		$this->load->view('student/footer');
	}

	// 	public function student_reset()
	// 	{
	// 	    $this->load->view('student/header');
	// 	    $this->load->view('student/student-reset');
	// 	    $this->load->view('student/footer');
	// 	}

	public function student_login()
	{
		$uname = $this->input->post('email');
		$pwd = $this->input->post('password');
		//echo md5($pwd);
		//	print_r($this->input->post());
		if ($this->Student_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', '');
				}
			}

			$student_info = $this->Student_model->login($uname, $pwd);
			//getting values from database
			$student_id = $student_info->id;
			$student_email = $student_info->email;
			$student_name = $student_info->name;
			$student_payment = $student_info->payment_status;
			$student_status = $student_info->is_active;
			//create required sessions
			$this->session->set_userdata('student_id', $student_id);
			$this->session->set_userdata('student_email', $student_email);
			$this->session->set_userdata('student_name', $student_name);
			if ($student_status == 'yes') {
				echo '1';
			}
		} else {
			echo '0';
		}
	}

	public function student_logout()
	{
		$this->session->sess_destroy();
		redirect(base_url() . 'Student', 'refresh');
	}

	public function dashboard()
	{

		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$student_id = $_SESSION['student_id'];
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$data['subject_names'] = $this->my_classes_Function();

			//assignment 
			$month = date('m', strtotime($this->nepali_current_date));
			$year = date('Y', strtotime($this->nepali_current_date));

			$curr_naepali_date = $this->nepali_current_date;

			$data['list_assignmet'] = $this->Student_model->get_assignment_list($student_id, '', $month, $year);

			// attendence data

			$sql = "Select sb.student_id, sb.classroom_id, c.course_id as course_id, cs.subject_id as subject_id, s.subject_name as subject_name, s.subject_icon as icon from students std inner join student_batch sb on std.id = sb.student_id AND std.batch_id = sb.batch_id inner join classroom c on sb.classroom_id = c.id inner join course_subjects cs on c.course_id = cs.course_id inner join subject s on s.id = cs.subject_id WHERE std.id = $student_id";

			$data['attendece_subject_names'] = $this->Student_model->get_table_info('student_batch', '', $sql);

			$data['count'] = [];
			foreach ($data['attendece_subject_names'] as $key => $value) {


				$countSql = "SELECT student_id, count(*) as total_count, SUM(CASE when STATUS = 'present' then 1 else 0 end) AS present_count FROM `student_attendence` where student_id = '$student_id' AND subject_id = '$value[subject_id]' AND classroom_id = '$value[classroom_id]'";
				$data['count'][] = $this->db->query($countSql)->row_array();
			}

			//student grades

			$query_examId = $this->db->query('select q.exam_id from questions q, student_exam_results ses where ses.student_id=' . $student_id . ' and  ses.exams_id = q.id and date_format(ses.created,"%y-%m-%d") <=' . date('Y-m-d', strtotime($curr_naepali_date)) . ' order by q.exam_id desc limit 1');

			$exam_id = $query_examId->row_array();

			if ($exam_id) {
				$query_grade = $this->db->query(' SELECT e_name,q.exam_date, subject_name, q.total_marks, passing_marks, get_marks ,grade_name, name
					FROM student_exam_results ser
					INNER JOIN grades g ON ser.grades_id = g.id
					INNER JOIN questions q ON q.id = ser.exams_id
					INNER JOIN subject s ON s.id = q.subject_id                
					INNER JOIN students st on st.id = ser.student_id AND st.course = q.course_id
					INNER JOIN student_batch sb on sb.id = ser.student_batch_id AND sb.student_id = st.id AND sb.batch_id = sb.batch_id
					INNER JOIN exam e ON e.id = q.exam_id
					WHERE q.exam_id = ' . $exam_id['exam_id'] . '
					AND ser.student_id = ' . $student_id . '
					GROUP BY subject_name');

				$data['student_results'] = $query_grade->result_array();
			} else {
				$data['student_results'] = FALSE;
			}

			//echo"<pre>";print_r($data['student_results']);exit();
			$this->load->view('student/header', $data);
			$this->load->view('student/dashboard');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function attendance_detail()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$this->load->view('student/header', $data);
			$this->load->view('student/attendance-detail');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function my_calendar_old()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$pday = trim(date("l"));

			$data['classes'] = $this->Student_model->get_mydayClasses($_SESSION['student_id'], $pday);

			if (!empty($data['classes'])) {
				$k = 0;
				foreach ($data['classes'] as $c) {

					$res = $this->Student_model->get_teacher($c['subject_id'], $c['classroom_name']);
					//    print_r($res);
					$student_sess[$k]['teacher_name']   = $res[0]['teacher_name'];
					$student_sess[$k]['photo']          = $res[0]['photo'];
					$student_sess[$k]['classroom_name'] = $c['classroom_name'];
					$student_sess[$k]['subject_id']     = $c['subject_id'];
					$student_sess[$k]['subject_name']   = $c['subject_name'];
					$student_sess[$k]['subject_icon']   = $c['subject_icon'];
					$student_sess[$k]['start']          = $c['start'];
					$student_sess[$k]['duration']       = $c['duration'];
					$student_sess[$k]['id']             = $c['id'];
					$student_sess[$k]['join_link']      = $c['join_link'];
					$student_sess[$k]['day']            = $c['day'];
					$k++;
				}
			} else {
				$student_sess = '';
			}

			//  print_r($student_sess);
			$data['student_sess'] = $student_sess;
			$this->load->view('student/header', $data);
			$this->load->view('student/my-calendar');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function calenderSessions()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			if (($this->input->post('dateval'))) {
				$t = 	 $this->input->post('dateval');
				$day = strtotime($t);
				$pday = trim(date('l', $day));
			}


			$data['classes'] = $this->Student_model->get_mydayClasses($_SESSION['student_id'], $pday);
			if (!empty($data['classes'])) {
				$k = 0;
				foreach ($data['classes'] as $c) {

					$res = $this->Student_model->get_teacher($c['subject_id'], $c['classroom_name']);
					//    print_r($res);
					$student_sess[$k]['teacher_name']   = $res[0]['teacher_name'];
					$student_sess[$k]['photo']          = $res[0]['photo'];
					$student_sess[$k]['classroom_name'] = $c['classroom_name'];
					$student_sess[$k]['subject_id']     = $c['subject_id'];
					$student_sess[$k]['subject_name']   = $c['subject_name'];
					$student_sess[$k]['subject_icon']   = $c['subject_icon'];
					$student_sess[$k]['start']          = $c['start'];
					$student_sess[$k]['duration']       = $c['duration'];
					$student_sess[$k]['id']             = $c['id'];
					$student_sess[$k]['join_link']      = $c['join_link'];
					$student_sess[$k]['day']            = $c['day'];
					$k++;
				}
			} else {
				$student_sess = '';
			}
			$data['student_sess'] = $student_sess;
			$data['day'] = $t;
			$this->load->view('student/my-calendar-session', $data);
		} else {
			redirect(base_url() . 'Student');
		}
	}



	public function my_assignments()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$this->load->view('student/header', $data);
			$this->load->view('student/my-assignments');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	//Start code of Up- Coming Test/Exams 08-11-21 - Shankar

	public function my_tests_exams()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$data['upcoming_exam_data'] = $this->Student_model->upcoming_Test_or_Exams($_SESSION['student_id']);

			$data['nepali_curr_date'] = $this->nepali_current_date;

			$student_data = array();
			if (isset($data['upcoming_exam_data']) || !empty($data['upcoming_exam_data'])) {

				foreach ($data['upcoming_exam_data'] as $key => $val) {

					$query = $this->db->query('select student_id, exams_id as questions_id from exam_answers where student_id =' . $_SESSION['student_id'] . ' and exams_id = ' . $val['question_id'] . ' group by student_id, exams_id');

					$count_mark = $this->db->query('select sum(question_mark) as tot_marks from exam_questions where exam_id =' . $val['question_id'])->row_array();



					if ($query->num_rows() > 0) {

						$exam_attempt = $query->row_array();

						array_push($student_data, array(
							'questions_id'		=> $val['question_id'],
							'exam_id'			=> $val['exam_id'],
							'e_name'			=> $val['e_name'],
							'classroom_id'		=> $val['classroom_id'],
							'classroom_name'	=> $val['classroom_name'],
							'subject_id'		=> $val['subject_id'],
							'subject_name'		=> $val['subject_name'],
							'exam_date'			=> $val['exam_date'],
							'exam_starttime'	=> $val['exam_starttime'],
							'exam_endtime'		=> $val['exam_endtime'],
							'total_marks'		=> $val['total_marks'],
							'attempt' 			=> 'yes',
							'counting_mark'		=> $count_mark['tot_marks'] ? $count_mark['tot_marks'] : '',
						));
					} else {

						array_push($student_data, array(
							'questions_id'		=> $val['question_id'],
							'exam_id'			=> $val['exam_id'],
							'e_name'			=> $val['e_name'],
							'classroom_id'		=> $val['classroom_id'],
							'classroom_name'	=> $val['classroom_name'],
							'subject_id'		=> $val['subject_id'],
							'subject_name'		=> $val['subject_name'],
							'exam_date'			=> $val['exam_date'],
							'exam_starttime'	=> $val['exam_starttime'],
							'exam_endtime'		=> $val['exam_endtime'],
							'total_marks'		=> $val['total_marks'],
							'attempt' 			=> 'No',
							'counting_mark'		=> $count_mark['tot_marks'] ? $count_mark['tot_marks'] : '',
						));
					}
				}
			}

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

			$data['exams_data'] = $student_data;

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

			$this->load->view('student/header', $data);
			$this->load->view('student/my-tests-exams');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}


	public function view_test_detail()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();

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

			$data['exams_data'] = $this->Student_model->upcoming_Test_or_Exams($_SESSION['student_id'], $exam_question_Id);


			$this->load->view('student/header', $data);
			$this->load->view('student/view-test-detail');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function question_paper()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$data['exam_question_Id'] = $this->uri->segment(3);
			$data['student_id'] =  $_SESSION['student_id'];

			$data['exams_data'] = $this->Student_model->upcoming_Test_or_Exams($_SESSION['student_id'], $this->uri->segment(3));

			$this->load->view('student/header', $data);
			$this->load->view('student/question-paper');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}


	public function getAllQues()
	{
		$id = $_SESSION['student_id'];
		$exam_question_id = $this->input->post('test_id');

		$questions = $this->Student_model->get_allQuestions($exam_question_id);
		print_r(json_encode($questions));
	}

	public function submit_exam_answer()
	{
		$id = $_SESSION['student_id'];
		$ans_array_json = $this->input->post('ans_array');

		if ($this->Student_model->storeAnswer($ans_array_json, $id)) {
			echo '1';
		}
	}


	//End code of Up- Coming Test/Exams 10-11-21 - Shankar

	public function my_grades()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();

			$query = $this->db->query('SELECT exam.e_name, questions.course_id, questions.exam_date,questions.exam_id
				FROM exam , questions , classroom, student_batch , students
				WHERE students.id = ' . $_SESSION['student_id'] . ' 
				AND student_batch.student_id = students.id
				AND students.batch_id = student_batch.batch_id  
				AND student_batch.classroom_id = classroom.id
				AND classroom.course_id = questions.course_id
				AND questions.exam_id = exam.id
				GROUP BY questions.course_id, exam.e_name
		   		ORDER BY exam_date desc');

			$data['exam_details'] = $query->result_array();
			if (!empty($data['exam_details'])) {
				$bs_date_info = get_complete_BS_date_info($this->nepaliDateObject, $data['exam_details'][0]['exam_date']);
				$data['exam_details'][0]['bs_date'] = $bs_date_info['F'] . '-' . $bs_date_info['Y'];
			}

			$this->load->view('student/header', $data);
			$this->load->view('student/my-grades');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function view_grade_detail()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$exam_id = $this->uri->segment(3);
			$query = $this->db->query(' SELECT e_name,q.exam_date, subject_name, q.total_marks, passing_marks, get_marks ,grade_name, name
				FROM student_exam_results ser
				INNER JOIN grades g ON ser.grades_id = g.id
				INNER JOIN questions q ON q.id = ser.exams_id
				INNER JOIN subject s ON s.id = q.subject_id                
				INNER JOIN students st on st.id = ser.student_id
				INNER JOIN exam e ON e.id = q.exam_id
				WHERE q.exam_id = ' . $exam_id . '
				AND ser.student_id = ' . $_SESSION['student_id'] . '
				GROUP BY subject_name');

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

			if (!empty($data['student_results'])) {
				$bs_date_info = get_complete_BS_date_info($this->nepaliDateObject, $data['student_results'][0]['exam_date']);
				$data['student_results'][0]['bs_date'] = $bs_date_info['F'] . '-' . $bs_date_info['Y'];
			}


			$this->load->view('student/header', $data);
			$this->load->view('student/view-grade-detail');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	// 	public function my_notifications()
	// 	{
	// 	    if(isset($_SESSION['student_id'])){
	// 	        $this->load->helper('url');
	//             $data['currentURL'] = current_url();
	// 	        $data['menulist'] = $this->Student_model->get_studentMenus();
	// 	        $this->load->view('student/header',$data);
	//     	    $this->load->view('student/my-notifications');
	//     	    $this->load->view('student/footer');
	// 	    }else{
	// 	        redirect(base_url().'Student');
	// 	    }
	// 	}

	public function settings()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$this->load->view('student/header', $data);
			$this->load->view('student/settings');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}
	//shankar code of Student Syllybus Models start - 29-10-2021
	public function my_syllabus()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$data['student_syllabus'] = $this->Student_model->get_student_syllabus($_SESSION['student_id']);
			$this->load->view('student/header', $data);
			$this->load->view('student/my-syllabus');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}
	//shankar code of Student Syllybus Models end - 29-10-2021
	public function my_profile()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$this->load->view('student/header', $data);
			$this->load->view('student/my-profile');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function addedit_apllication()
	{

		$this->load->helper('url');
		$this->load->helper(array('form', 'url'));

		$config['upload_path'] = 'assets_student/application/';
		$config['allowed_types'] = 'gif|jpg|png';
		$this->load->library('upload', $config);
		$this->upload->initialize($config);
		$data['currentURL'] = current_url();
		$data['sinfo'] = $_POST;



		if (!$this->upload->do_upload('photo')) {
			$data['photo'] = "No-Image.jpg";
		} else {
			$photo = array('upload_data' => $this->upload->data());
			//   print_r($photo);
			$data['photo'] = $photo['upload_data']['file_name'];
		}
		if (!$this->upload->do_upload('school')) {
			$data['school'] = "No-Image.jpg";
		} else {
			$school = array('upload_data' => $this->upload->data());
			$data['school'] = $school['upload_data']['file_name'];
		}

		if (!$this->upload->do_upload('exam')) {
			$data['exam'] = "No-Image.jpg";
		} else {
			$exam = array('upload_data' => $this->upload->data());
			$data['exam'] = $exam['upload_data']['file_name'];
		}

		if (!$this->upload->do_upload('medical')) {
			$data['medical'] = "No-Image.jpg";
		} else {
			$medical = array('upload_data' => $this->upload->data());
			$data['medical'] = $medical['upload_data']['file_name'];
		}

		// dd($data);

		$app_new_id = $this->Student_model->add_applicationinfo($data);
		if ($app_new_id > 0) {
			$this->session->set_flashdata('success', 'Application has been submitted. Please visit school for further process.');
			redirect(base_url() . 'student/admission');
			//paypal integration
			//Set variables for paypal form
			// $returnURL = base_url() . 'student/application_paymentSuccess'; //payment success url
			// $failURL = base_url() . 'student/paymentFail'; //payment fail url
			// $notifyURL = base_url() . 'student/paypalipn'; //ipn url

			// //  $userID = $_SESSION['student_id'];
			// $amount = $_POST['amount'];
			// //$logo = base_url().'Your_logo_url';
			// $this->paypal_lib->add_field('return',  $returnURL);
			// $this->paypal_lib->add_field('fail_return', $failURL);
			// $this->paypal_lib->add_field('notify_url', $notifyURL);
			// $this->paypal_lib->add_field('item_name', "Application Fee");
			// $this->paypal_lib->add_field('custom', $_POST['scourse']);
			// $this->paypal_lib->add_field('item_number',  $app_new_id);
			// $this->paypal_lib->add_field('amount', $amount);
			// //   $this->paypal_lib->image($logo);
			// $this->paypal_lib->paypal_auto_form();
			// // echo $app_new_id;
			// return $app_new_id;




		} else {
			return 0;
		}
	}




	function fees_paymentSuccess()
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('student/header', $data);
		$this->load->view('student/payment-success-modal');
		$this->load->view('student/footer');
	}

	function application_paymentSuccess()
	{
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);
		$paypalInfo = array();
		foreach ($raw_post_array as $keyval) {
			$keyval = explode('=', $keyval);
			if (count($keyval) == 2)
				$paypalInfo[$keyval[0]] = urldecode($keyval[1]);
		}
		$this->db->where('id', $paypalInfo['item_number']);
		$query  = $this->db->get('applications');
		$res = $query->row_array();
		$application_no = (!empty($res['applicationid'])) ? $res['applicationid'] : $paypalInfo['item_number'];
		$data['studentId'] = $application_no;
		$data['payment_for'] = $paypalInfo['item_name'];
		$data['txn_id'] = $paypalInfo["txn_id"];
		$data['payment_amt'] = $paypalInfo["payment_gross"];
		$data['currency_code'] = $paypalInfo["mc_currency"];
		$data['status'] = $paypalInfo["payment_status"];
		// $data['payment_date'] = $paypalInfo["payment_date"];
		$data['payment_recived_id'] = $paypalInfo["receiver_id"];
		$data['payment_date'] = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $paypalInfo['payment_date']);
		$rst = $this->Student_model->storefeeTransaction($data);
		if ($rst) {
			$this->db->where('id', $paypalInfo['item_number']);
			$this->db->update('applications', array('payment_status' => 'yes'));
		}
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();

		if ($this->mail_Send_Application_Approved($data['studentId'], $data['payment_amt'], $data['payment_date'])) {
			$data['sent_mail'] = true;
		} else {
			$data['sent_mail'] = false;
		}
		$this->load->view('student/header', $data);
		$this->load->view('student/application-payment-success', $data);
		$this->load->view('student/footer');
	}


	function paymentFail()
	{
		$this->load->view('paypal/paymentFail');
	}




	function admission_payment()
	{
		//paypal return transaction details array
		$appid = $this->uri->segment(3);
		$data = array();
		if ($appid != '') {
			$sqlQuery = "SELECT a.*,c.course_name FROM applications a LEFT JOIN course c ON c.id=a.course WHERE a.id=$appid";
			$result = $this->Student_model->get_query_row($sqlQuery);
			$feestypeId = 2;
			if ($result != '') {
				$course_fees = $this->Student_model->applications_get($result, $feestypeId);

				$course_fee_id = ($course_fees != '') ? $course_fees['id'] : 0;
				$sqlQuery1 = "SELECT * FROM installment WHERE course_fee_id=$course_fee_id AND is_active='yes'";
				$data['installment'] = $this->Student_model->get_query_row($sqlQuery1);
				$data['course_fees'] = $course_fees;
			}
			$data['appinfo'] = $result;
		}


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

	function get_installdetails()
	{
		//paypal return transaction details array
		$install_type = $this->input->post('install_type');
		$installment_id = $this->input->post('installment_id');
		$install = $this->Student_model->install_get($installment_id);
		$array_install = json_decode($install['due_amount_date']);
		$html = '';
		foreach ($array_install as $key => $installvalue) {
			if ($key == $install_type) {
				foreach ($installvalue as $inskey => $val) {
					$due_date = ($inskey == 0) ? "<span> Instant Payment </span>" : "<span>" . $val->due_date . "</span>";
					$checkbox = ($inskey == 0) ? "style='color:green'" : "style='color:red'";
					$html .= '<div class="instalment-row"><i class="far fa-check-circle" ' . $checkbox . '></i>
					<input readonly type = "text" value = ' . $val->amount . ' id = "feeamount" />
					<label> - ' . $due_date . '</label>
					</div>';
				}
			}
		}

		// <input type = "text" value = ' . $n["payable_amount"] . ' id = "feeamount" />
		// <div> <p>Due dates : </p>' . str_replace(',', '<br>', $n["duedates"]) . '
		// 	</div>

		echo $html;
	}

	function process_coursefee()
	{
		$studfees = array();
		$amount = $_POST['totalamount'];
		$course_fee_id = $_POST['coursefeeid'];
		$app_new_id = $_POST['appid'];
		$installType = $_POST['install_typeid'];
		//$cutom_arr = array('course_fee' => $course_fee_id, 'install_type' => $installType);
		//  $install = $this->Student_model->move_applicationinfo($app_new_id);
		// $stid = $this->Student_model->move_applicationinfo($app_new_id);
		$stid = $this->Student_model->applicationinfo_movingto_students($app_new_id);
		if ($stid == -1) {
			$this->session->set_flashdata('danger', 'Payment Failed');
			redirect(base_url() . 'Student');
		} else {
			$studentappId = $this->db->get_where('students', array('id' => $stid))->row()->studentId;
			$coursefees = $this->Student_model->get_query_row("SELECT id,due_amount_date  FROM installment WHERE course_fee_id=$course_fee_id");
			$coursefeesarr = json_decode($coursefees['due_amount_date']);

			foreach ($coursefeesarr as $k => $cf_value) {
				if ($k == $installType) {
					$sno = 1;
					foreach ($cf_value as $val) {
						$studfees[] = array(
							'install_sno' => $sno,
							'due_date' => $val->due_date,
							'feeamount' => $val->amount,
							'paid_amount' => "0",
							'payment_status' => 'no',
							'paid_date' => date('Y-m-d H:i:s')
						);
						$sno++;
					}
				}
			}
			$stdentfee = array(
				'student_id' => $stid,
				'course_fee_id' => $course_fee_id,
				'installment_type_id' => $installType,
				'payment_details' => json_encode($studfees),
				'created' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date)),
				'modified' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date))
			);
			$this->db->insert('students_online_payments', $stdentfee);
			echo "Success!!Please use this studentId:" . $studentappId . " and the password you had given with application to login.";

			// //Set variables for paypal form
			$returnURL = base_url() . 'student/coursefees_paymentSuccess'; //payment success url
			$failURL = base_url() . 'student/paymentFail'; //payment fail url
			$notifyURL = base_url() . 'student/paypalipn'; //ipn url

			$this->paypal_lib->add_field('rm', 2);
			$this->paypal_lib->add_field('return',  $returnURL);
			$this->paypal_lib->add_field('fail_return', $failURL);
			$this->paypal_lib->add_field('notify_url', $notifyURL);
			$this->paypal_lib->add_field('item_name', "Course Fee");
			$this->paypal_lib->add_field('custom', $course_fee_id);
			$this->paypal_lib->add_field('item_number', $studentappId);
			$this->paypal_lib->add_field('amount', $amount);
			$this->paypal_lib->paypal_auto_form();
		}
	}

	public function pay_from_student($encryptedInfo)
	{

		$decrypted = urlsafe_b64decode($encryptedInfo);
		$param = $array = explode(',', $decrypted);

		list($studentappId, $course_fee_id, $item, $amount, $s_no) = $param;

		$this->session->set_userdata('s_no', $s_no);

		$returnURL = base_url() . 'student/unpaid_fee_success';
		$failURL = base_url() . 'student/paymentFail';
		$notifyURL = base_url() . 'student/paypalipn';

		$this->paypal_lib->add_field('rm', 2);
		$this->paypal_lib->add_field('return',  $returnURL);
		$this->paypal_lib->add_field('fail_return', $failURL);
		$this->paypal_lib->add_field('notify_url', $notifyURL);
		$this->paypal_lib->add_field('item_name', $item);
		$this->paypal_lib->add_field('custom', $course_fee_id);
		$this->paypal_lib->add_field('item_number', $studentappId);
		$this->paypal_lib->add_field('amount', $amount);
		$this->paypal_lib->paypal_auto_form();
	}

	public function coursefees_paymentSuccess()
	{
		$paidfee = array();
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);
		$paypalInfo = array();
		$flag = true;
		foreach ($raw_post_array as $keyval) {
			$keyval = explode('=', $keyval);
			if (count($keyval) == 2)
				$paypalInfo[$keyval[0]] = urldecode($keyval[1]);
		}

		if ($paypalInfo['payment_status'] == 'Completed') {
			$studentId = $paypalInfo['item_number'];
			$courseFeeId = $paypalInfo['custom'];
			$stud_id = $this->db->get_where('students', array('studentId' => $studentId))->row()->id;
			$studentfee = $this->db->get_where('students_online_payments', array('student_id' => $stud_id, 'course_fee_id' => $courseFeeId))->row();
			$studentfee_arr = json_decode($studentfee->payment_details);

			$data['studentId'] = (!empty($studentId)) ? $studentId : $stud_id;
			$data['payment_for'] = $paypalInfo['item_name'];
			$data['txn_id'] = $paypalInfo["txn_id"];
			$data['payment_amt'] = $paypalInfo["payment_gross"];
			$data['currency_code'] = $paypalInfo["mc_currency"];
			$data['status'] = $paypalInfo["payment_status"];
			$data['payment_date'] = $paypalInfo["payment_date"];
			$data['payment_recived_id'] = $paypalInfo["receiver_id"];
			$data['course_fee_id'] = $courseFeeId;
			$data['payment_date'] = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $data['payment_date']);

			foreach ($studentfee_arr as $k => $sf_val) {
				if ($sf_val->payment_status == 'no' && $flag == true) {
					$paidfee[] = array(
						'install_sno' => $sf_val->install_sno,
						'due_date' => $sf_val->due_date,
						'feeamount' => $sf_val->feeamount,
						'paid_amount' => $paypalInfo['payment_gross'],
						'payment_status' => 'yes',
						'paid_date' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date))
					);
					$flag = false;
				} else {
					$paidfee[] = array(
						'install_sno' => $sf_val->install_sno,
						'due_date' => $sf_val->due_date,
						'feeamount' => $sf_val->feeamount,
						'paid_amount' =>  $sf_val->paid_amount,
						'payment_status' => $sf_val->payment_status,
						'paid_date' => $sf_val->paid_date
					);
				}
			}


			$payment_details = array('payment_details' => json_encode($paidfee));
			if (!empty($payment_details)) {
				$payment_details['modified'] = $this->nepali_current_date;
				$this->db->where(array('student_id' => $stud_id, 'course_fee_id' => $courseFeeId));
				$this->db->update('students_online_payments', $payment_details);

				$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
			}
			$rst = $this->Student_model->storefeeTransaction($data);
			$this->session->set_flashdata('success', 'Payment Success');
		} else {
			$this->session->set_flashdata('danger', 'Payment Failed');
		}

		if (isset($_SESSION['s_no'])) {
			$_SESSION['s_no'] = null;
			redirect(base_url() . 'student/my-payments');
		}

		redirect(base_url() . 'Student');
	}
	/* 
	
	[payer_email] => sb-pndsf8465536@personal.example.com
    [payer_id] => SVJ97L4ZBX4BY
    [payer_status] => VERIFIED
    [first_name] => John
    [last_name] => Doe
    [address_name] => John Doe
    [address_street] => Flat no. 507 Wing A Raheja Residency
    [address_city] => Mumbai
    [address_state] => Maharashtra
    [address_country_code] => IN
    [address_zip] => 400097
    [residence_country] => IN
    [txn_id] => 7X442182MW3678513
    [mc_currency] => USD
    [mc_fee] => 107.78
    [mc_gross] => 2150.00
    [protection_eligibility] => ELIGIBLE
    [payment_fee] => 107.78
    [payment_gross] => 2150.00
    [payment_status] => Completed
    [payment_type] => instant
    [handling_amount] => 0.00
    [shipping] => 0.00
    [item_name] => Coursefee
    [item_number] => ECS2021000002
    [quantity] => 1
    [txn_type] => web_accept
    [payment_date] => 2021-11-20T10:36:10Z
    [business] => sb-jfjqt8277261@business.example.com
    [receiver_id] => 6JPEJAGNJCGW8
    [notify_version] => UNVERSIONED
    [custom] => 1
    [verify_sign] => AWOxO3gj01NbyLVXRfVGrDWGA9VwA9uMONy61vZgWHJ0Ke2.-LTv9pTU       
        
}*/

	public function convert()
	{
		$date = date('Y-m-d H:i:s');

		$r = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $date);
		test_view_array($r);
	}

	//shankar code of assignment start from here

	public function get_assignment()
	{
		if (isset($_SESSION['student_id'])) {

			$student_id = $_SESSION['student_id'];

			$asgn_id = $this->uri->segment(3);
			$m = $this->uri->segment(4);
			$year = $this->uri->segment(5);

			if ($m < 10) {
				$month = '0' . $m;
			} else {
				$month = $m;
			}

			$list_subjects = $this->Student_model->get_assignment_list($student_id, $asgn_id, $month, $year);

			// echo"<pre>";
			// print_r($list_subjects);
			// exit();

			if (empty($asgn_id)) {
				$asgn_id = $list_subjects[0]['assignment_id'];
			}
			$std_folder = $student_id . '_' . $asgn_id;

			$remark_by_teacher = $this->Student_model->uploaded_assignent($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 name
						// echo "File Name -> $files[$i]<br>";

						//get file extension
						$file = pathinfo($files[$i]);
						$extension = $file['extension'];
						// echo "file extension $extension<br>";

						if (in_array($extension, $file_extensions)) {
							$img[$i] = "student_assignment/$std_folder/$files[$i]";
						}
					}
				}
			}
			$result = array();
			$result['subject'] = $list_subjects;
			$result['remark_by_teacher'] = $remark_by_teacher;
			$result['images'] = $img ? $img : '';



			if (empty($result['subject']) and empty($result['remark_by_teacher']) and empty($result['images'])) {
				echo 0;
			} else {
				echo json_encode($result);
			}
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function get_assignment_list()
	{
		if (isset($_SESSION['student_id'])) {
			$student_id = $_SESSION['student_id'];
			$m = $this->uri->segment(3);
			$year = $this->uri->segment(4);

			if ($m < 10) {
				$month = '0' . $m;
			} else {
				$month = $m;
			}

			$data['list_subjects'] = $this->Student_model->get_assignment_list($student_id, '', $month, $year);

			$list_subjects = array();

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

				$assignmentData = $this->Student_model->uploaded_assignent($student_id, $value['assignment_id']);

				if ($assignmentData) {

					array_push($list_subjects, 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'],
						'teacher_name' => $value['teacher_name'],
						'subject_name' => $value['subject_name'],
						'subject_icon' => $value['subject_icon'],
						'flag' => $assignmentData[0]['Flag'],
						'status' => 1
					));
				} else {
					array_push($list_subjects, 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'],
						'teacher_name' => $value['teacher_name'],
						'subject_name' => $value['subject_name'],
						'subject_icon' => $value['subject_icon'],
						'status' => 0
					));
				}
			}

			echo json_encode($list_subjects);
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function assignment_image()
	{
		if (isset($_SESSION['student_id'])) {
			$student_id = $_SESSION['student_id'];
			$asgn_id = $this->input->post('asgn_id');

			$std_folder = $student_id . '_' . $asgn_id;
			if (!is_dir('student_assignment')) {
				mkdir('./student_assignment', 0777, true);
			}
			if (!is_dir('student_assignment/' . $std_folder)) {
				mkdir('./student_assignment/' . $std_folder, 0777, true);
			}

			$check_file = glob('./student_assignment/' . $std_folder . '/*');

			foreach ($check_file as $delete_file) { // iterate files
				if (is_file($delete_file)) {
					unlink($delete_file); // delete file
				}
			}

			$das = array();
			if (isset($_FILES["images"]["name"]) &&  !empty($_FILES["images"]["name"])) {
				$output = '';
				$config['upload_path'] = './student_assignment/' . $std_folder;
				$config['allowed_types'] = 'gif|jpg|png|jpeg|jfif|jiff';

				$this->load->library('upload', $config);
				$this->upload->initialize($config); //initialize upload library

				for ($count = 0; $count < count($_FILES["images"]["name"]); $count++) {
					$_FILES["file"]["name"] = $_FILES["images"]["name"][$count];
					$_FILES["file"]["type"] = $_FILES["images"]["type"][$count];
					$_FILES["file"]["tmp_name"] = $_FILES["images"]["tmp_name"][$count];
					$_FILES["file"]["error"] = $_FILES["images"]["error"][$count];
					$_FILES["file"]["size"] = $_FILES["images"]["size"][$count];

					if ($this->upload->do_upload('file')) {
						$data = $this->upload->data();
						$das[$count] = base_url() . 'student_assignment/' . $std_folder . '/' . $data["file_name"];
					}
				}
			}

			if ($das) {
				$data = array(
					'assignment_id' => $asgn_id,
					'student_id' => $student_id,
					'Path' => $std_folder,
					'remark' => '',
					'Flag' => 0
				);
				$stid = $this->Student_model->upload_assignment($data);
			}

			echo json_encode($das);
		}
	}

	function assignment_class_submit()
	{
		if (isset($_SESSION['student_id'])) {
			$student_id = $_SESSION['student_id'];
			$asgn_id = $this->uri->segment(3);

			$asgn_data = array(
				'assignment_id' => $asgn_id,
				'student_id' => $student_id,
				'uploaded_date' => date('Y-m-d', strtotime($this->nepali_current_date)),
				'Flag' => 2
			);

			$stid = $this->Student_model->upload_assignment_submit($asgn_data);
			echo $stid;
		} else {
			redirect(base_url() . 'Student');
		}
	}

	function assignment_class_cancel()
	{
		if (isset($_SESSION['student_id'])) {
			$student_id = $_SESSION['student_id'];
			$asgn_id = $this->uri->segment(3);


			$stid = $this->Student_model->upload_assignment_cancel($asgn_id, $student_id);


			$std_folder = $student_id . '_' . $asgn_id;
			if (!is_dir('student_assignment')) {
				mkdir('./student_assignment', 0777, true);
			}
			if (!is_dir('student_assignment/' . $std_folder)) {
				mkdir('./student_assignment/' . $std_folder, 0777, true);
			}

			$check_file = glob('./student_assignment/' . $std_folder . '/*');

			foreach ($check_file as $delete_file) { // iterate files
				if (is_file($delete_file)) {
					unlink($delete_file); // delete file
				}
			}

			echo true;
		} else {
			redirect(base_url() . 'Student');
		}
	}
	//shankar code end here

	// Notification Module - 13-10-2021

	public function my_notifications()
	{
		if (isset($_SESSION['student_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;

			$sql = $this->Student_model->getStudentNotification($_SESSION['student_id'], $dateArr);

			if (!$sql) {
				$this->load->helper('url');
				$data['currentURL'] = current_url();
				$data['menulist'] = $this->Student_model->get_studentMenus();
				$this->load->view('student/header', $data);
				$this->load->view('student/my-notifications', $data);
				$this->load->view('student/footer');
			} else {
				$data['result'] = $sql;

				$this->load->helper('url');
				$data['currentURL'] = current_url();
				$data['menulist'] = $this->Student_model->get_studentMenus();
				$this->load->view('student/header', $data);
				$this->load->view('student/my-notifications', $data);
				$this->load->view('student/footer');
			}
		} else {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();
			$this->load->view('student/header', $data);
			$this->load->view('student/my-notifications', $data);
			$this->load->view('student/footer');
		}
	}

	public function ajax_displayNotificationByDate()
	{

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

		if ($sql == false) {
			$json = json_encode('failed');
			echo $json;
		} else {
			$notifyArr = array();
			// $count = 1;
			foreach ($sql as $row) {
				$originalDate = $row['created_at'];
				$newDate = date("d-m-Y", strtotime($originalDate));
				$newTime = date("h:i", strtotime($originalDate));

				$holder = '';

				// 		if($count == 1) {
				// $holder = '<div class="content-exam-box-one notif-active">';
				// 		} else {
				// 			$holder = '<div class="content-exam-box-one">';
				// 		}
				$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>Date : <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>';
				// $count++;
				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 Module - 13-10-2021


	// Shankar Code Forgot_Password functionality Start from here 25-10-21


	public function student_fp_password()
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$this->load->view('student/header', $data);
		$this->load->view('student/student-password-reset');
		$this->load->view('student/footer');
	}

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

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

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

	public function send_email_reset_password()
	{

		if ($_POST) {
			$url =  str_replace("send_email_reset_password", "create-password", current_url());
			$emailId = $_POST['studentID'];
			$query = $this->db->get_where('students', array('email' => $emailId));
			$student_name = $query->row_array();

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

			$mail_url = urlsafe_b64encode($emailId);

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

			$approve_data = array(
				"studname" => $student_name['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', $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() . 'student/reset-password');
			} else {
				$this->session->set_flashdata('failed', "Mailer Error: " . $this->email->print_debugger());
				redirect(base_url() . 'student/reset-password');
			}
		} else {
			redirect(base_url() . 'Student', 'refresh');
		}
	}

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

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

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

	public function change_student_password()
	{
		if ($_POST) {
			$data = array(
				'password' => md5($_POST['password'])
			);
			$this->db->where('id', $_POST['student_id']);
			$this->db->where('email', $_POST['student_email']);

			$this->db->update('students', $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() . 'Student');
		} else {
			redirect(base_url() . 'Student', 'refresh');
		}
	}

	// Forgot_Password functionality ENd here 25-10-21

	// Student's Attendance - 03-11-2021 - Afras Khan

	public function attendance()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

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

		$sql = "Select sb.student_id, sb.classroom_id, c.course_id as course_id, cs.subject_id as subject_id, s.subject_name as subject_name, s.subject_icon as icon from students std inner join student_batch sb on std.id = sb.student_id AND std.batch_id = sb.batch_id  inner join classroom c on sb.classroom_id = c.id inner join course_subjects cs on c.course_id = cs.course_id inner join subject s on s.id = cs.subject_id WHERE std.id = '$_SESSION[student_id]'";

		$data['subject_names'] = $this->Student_model->get_table_info('student_batch', '', $sql);



		// $sub_ids = array_column($data['subject_names'], 'subject_id');

		$data['count'] = [];
		foreach ($data['subject_names'] as $key => $value) {


			$countSql = "SELECT student_id, count(*) as total_count, SUM(CASE when STATUS = 'present' then 1 else 0 end) AS present_count FROM `student_attendence` where student_id = '$_SESSION[student_id]' AND subject_id = '$value[subject_id]' AND classroom_id = '$value[classroom_id]'";
			$data['count'][] = $this->db->query($countSql)->row_array();
		}

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

		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$this->load->view('student/header', $data);
		$this->load->view('student/attendance');
		$this->load->view('student/footer');
	}

	public function view_attendance()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/view_attendance.php'))
			show_404();

		if (count($_POST) == 0) {
			$this->session->set_flashdata('failed', 'Please select one subject below to view its attendance');
			redirect(base_url() . 'student/attendance');
		}

		$data['classroom_id'] = $this->input->post('classroom_id');
		$data['subject_id'] = $this->input->post('subject_id');
		$student_id = $_SESSION['student_id'];
		$data['icon'] = $this->input->post('icon');
		$total_count = $this->input->post('total_count');
		$present_count = $this->input->post('present_count');
		$data['total_present_count'] = $present_count . '/' . $total_count;
		$data['total_present_percentage'] = ($present_count / $total_count) * 100;
		$data['subject_name'] = $this->input->post('subject_name');
		$month = date('m', strtotime($this->nepali_current_date));
		$year = date('Y', strtotime($this->nepali_current_date));

		$whereClause = array(
			'student_id' => $_SESSION['student_id'],
			'subject_id' => $data['subject_id'],
			'classroom_id' => $data['classroom_id'],
			'MONTH(attendence_date)' => $month,
			'YEAR(attendence_date)' => $year
		);

		$data['result'] = $this->Student_model->get_student_attendance($whereClause);

		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$this->load->view('student/header', $data);
		$this->load->view('student/view_attendance');
		$this->load->view('student/footer');
	}

	public function ajax_get_attendance_by_month()
	{

		$whereClause = array(
			'student_id' => $_SESSION['student_id'],
			'subject_id' => $this->input->post('subId'),
			'classroom_id' => $this->input->post('cId'),
			'MONTH(attendence_date)' => $this->input->post('monthNum'),
			'YEAR(attendence_date)' => $this->input->post('yearNum')
		);

		$result = $this->Student_model->get_student_attendance($whereClause);

		if (empty($result)) {
			echo 'failed';
			return;
		}

		$tableString = '<thead><tr><th>Date</th><th>Time</th><th>Present (P)/ Absent (A)</th></tr></thead><tbody>';
		$totalCount = count($result);
		$presentCount = 0;

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


			$presentCount += $value['status'] == 'present' ? 1 : 0;
			$class_name = $value['status'] == 'present' ? 'att-present' : 'att-absent';
			$attendance_key = $value['status'] == 'present' ? 'P' : 'A';
			$tableString .= '<tr> <td>' . $value["date"] . '</td> <td>' . date('g:i A', strtotime($value['time'])) . '</td> <td><span class="' . $class_name . '">' . $attendance_key . '</span></td></tr>';
		}

		$tableString .= '</tbody><tfoot><tr><td><strong>Total Days (Current Month)</strong></td>';
		$tableString .= '<td><strong>' . $presentCount . '/' . $totalCount . '</strong></td></tr></tfoot>';

		echo $tableString;
	}

	// Student's Attendance End - 03-11-2021 - Afras Khan

	// Student's Info - Afras Khan - 03-11-2021

	public function view_info()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/my-info.php'))
			show_404();

		$data['result'] = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row_array();

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

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

		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$this->load->view('student/header', $data);
		$this->load->view('student/my-info');
		$this->load->view('student/footer');
	}

	public function view_course()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/my-info.php'))
			show_404();

		$data['student'] = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row_array();

		$sql = $this->db->order_by('id', 'DESC')->get_where('student_batch', array('student_id' => $_SESSION['student_id']))->row_array();

		if (empty($sql)) {

			$data['student_exist'] = false;
		} else {
			$data['student_exist'] = true;
			$studentbatch = $this->db->get_where('batch', array('id' => $sql['batch_id']))->row_array();

			$query = 'SELECT crs.course_name,c.classroom_name, s.subject_name from classroom c inner join course crs on crs.id = c.course_id inner join course_subjects cs on c.course_id = cs.course_id inner join subject s on s.id = cs.subject_id WHERE c.id =' . $sql["classroom_id"] . '';

			$data['course_subject'] = $this->Student_model->get_table_info('classroom', '', $query);

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

			$fromMonth =  date("M", strtotime($studentbatch['b_from']));

			$toMonth =  date("M", strtotime($studentbatch['b_end']));

			$fromYear = date("y", strtotime($studentbatch['b_from']));

			$toYear = date("y", strtotime($studentbatch['b_end']));

			$data['startEndDate'] = $fromMonth . ' ' . $fromYear . ' to ' . $toMonth . ' ' . $toYear;
		}

		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();
		$this->load->view('student/header', $data);
		$this->load->view('student/my-course');
		$this->load->view('student/footer');
	}

	public function ajax_update_student_password()
	{

		$pwd = md5($this->input->post('pwd'));

		$data = array(
			'password' => $pwd
		);

		$this->db->trans_start();
		$this->db->where('id', $_SESSION['student_id']);
		$this->db->update('students', $data);
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			echo 'failed';
		} else {
			echo 'success';
		}
	}

	public function view_payments()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/my-payments.php'))
			show_404();

		//Student Info
		$data['student_info_array'] = $this->Admin_model->get_table_info_row('students', array('id' => $_SESSION['student_id']));

		// ALREADY PAID INSTALLMENTS
		$sql = "Select sop.*,ft.feetype_name, s.StudentId as student_code, pt.payment_type_name, cf.amount from students_online_payments sop
		inner join payment_types pt on pt.id = sop.installment_type_id
		inner join course_fees cf on cf.id = sop.course_fee_id
		inner join students s on sop.student_id = s.id
		inner join fee_types ft on ft.id = cf.fees_type
		WHERE sop.student_id = '$_SESSION[student_id]'
		AND ft.id != 3 
		AND ft.id != 4 
		AND cf.course_id = s.course
		AND cf.batch_id = s.batch_id";

		$data['payments'] = $this->Admin_model->get_table_info('students_online_payments', '', $sql);

		if (!empty($data['payments'])) {

			foreach ($data['payments'] as $index => $ele) {

				$student_installments = json_decode($ele['payment_details']);
				$encryptedString = $ele['student_code'] . ',' . $ele['course_fee_id'] . ',' . $ele['feetype_name'];
				foreach ($student_installments as $key => $value) {
					$due_date = date('Y-m-d', strtotime($value->due_date));
					$current_date = date('Y-m-d', strtotime($this->nepali_current_date));
					if ($value->payment_status == 'no') {
						$encryptedString .= ',' . $value->feeamount . ',' . $value->install_sno . ',' . 1;
						break;
					}
				}
				$data['payments'][$index]['encrypted'] = urlsafe_b64encode($encryptedString); // Studentid,CourseFee,Feetype,Amount,S_no
			}
		}

		// Not Paid Fees

		$not_paid_query = "Select s.studentId,cf.amount, ft.feetype_name, i.course_fee_id, i.due_amount_date from installment i inner JOIN course_fees cf on cf.id = i.course_fee_id inner join students s on s.id = $_SESSION[student_id] inner join fee_types ft on ft.id = cf.fees_type
		WHERE cf.batch_id = s.batch_id 
		AND cf.course_id = s.course
		AND ft.id != 3 
		AND ft.id != 4 
		AND cf.id NOT IN (SELECT course_fee_id from students_online_payments WHERE student_id = $_SESSION[student_id])";

		$not_paid_installments = $this->Student_model->get_table_info('installment', '', $not_paid_query);

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

			$decoded = json_decode($value['due_amount_date']);

			$count = count((array)$decoded);

			$not_paid_installments[$key]['single_payment'] = $count == 1 ? 'Yes' : 'No';

			$encrypted = $value['studentId'] . ',' . $value['course_fee_id'] . ',' . $value['feetype_name'];
			$flag = true;
			foreach ($decoded as $index => $ele) {
				foreach ($ele as $key2 => $val) {
					$due_date = date('Y-m-d', strtotime($val->due_date));
					$current_date = date('Y-m-d', strtotime($this->nepali_current_date));
					if ($flag) {
						$encrypted .= ',' . $val->amount . ',' . $key2 . ',' . 1;
						$flag = false;
						break;
					}
				}
				break;
			}


			$not_paid_installments[$key]['encrypted'] = urlsafe_b64encode($encrypted);

			if ($count > 1) {

				$decoded_installment = array_keys((array)json_decode($value['due_amount_date']));

				$feetype_clause = '';
				foreach ($decoded_installment as $index => $ele) {

					if ($index == 0) {
						$feetype_clause .= "id = '$ele'";
					} else {
						$feetype_clause .= " or id = '$ele'";
					}
				}

				$fee_types = $this->Student_model->get_table_info('payment_types', $feetype_clause, '', 'ASC');

				$html = '<select style="width:50%" name="installment_type" onchange="get_payment_details(this,' . $value['course_fee_id'] . ')" class="form-control mt-2" id="installment-dropdown">';
				foreach ($fee_types as $index => $ele) {
					if ($index == 0) {
						$html .= '<option selected value="">Select type of installment</option>';
					}
					$html .= '<option value="' . $ele['id'] . '">' . $ele['payment_type_name'] . '</option>';
				}

				$html .= '</select>';

				$not_paid_installments[$key]['dropdown'] = $html;
			} // If Count > 0
		}

		$data['not_paid_fees'] = $not_paid_installments;
		// dd($data['not_paid_fees']);


		// Student Code - Course_fee_id - Feetype-Name - Fee-Amount - S.NO

		$query = "Select sf.*,cf.fee_values from student_fee_online_transactions sf 
		inner join students s on sf.studentId = s.studentId
		inner join course_fees cf on cf.id = sf.course_fee_id WHERE s.id = '$_SESSION[student_id]'";

		$data['transactions'] = $this->Admin_model->get_table_info('student_fee_online_transactions', '', $query);

		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$this->load->view('student/header', $data);
		$this->load->view('student/my-payments');
		$this->load->view('student/footer');
	}

	public function ajax_get_fee_installments()
	{

		$course_fee_id = $this->input->post('course_fee_id');
		$installment_key = $this->input->post('installment_type');

		$sql_item_name = "Select f.feetype_name from fee_types f inner join course_fees cf on cf.fees_type = f.id WHERE cf.id = $course_fee_id";
		$fee_type_col = $this->Student_model->get_general_row_details('fee_types', '', $sql_item_name);

		$fee_type_name = $fee_type_col['feetype_name'];

		$whereClause = "Select cf.id,cf.amount, i.id as installment_id, i.due_amount_date from course_fees cf inner join installment i on cf.id = i.course_fee_id WHERE cf.id = '$course_fee_id'";

		$selected_installment = $query = $this->Student_model->get_general_row_details('course_fees', '', $whereClause);

		if (!empty($query)) {

			// decoding due_amount_date from installments
			$selected_installment['due_amount_date'] = (array)json_decode($query['due_amount_date']);
			$first_due_amount = '';
			$s_no_new = '';
			$signal = true;
			// filtering the array with user selected option with $installment_key
			foreach ($selected_installment['due_amount_date'] as $key => $value) {
				if ($key != $installment_key) {
					unset($selected_installment['due_amount_date'][$key]);
				} else {
					foreach ($value as $index => $ele) {
						$due_date = date('Y-m-d', strtotime($ele->due_date));
						$current_date = date('Y-m-d', strtotime($this->nepali_current_date));
						if ($signal) {
							$first_due_amount = $ele->amount;
							$s_no_new = $index + 1;
							$signal = false;
						}
						$selected_installment['due_amount_date'][$key][$index]->payment_status = 'no';
					}
				}
			}

			// test_view_array($decoded);
			// In the above forloop, Check the duedate is greater than current date. and concatinate that index value + 1 to encrypted variable instead of 1.

			$data['installment'] = $selected_installment;

			// Re arranging keys of $data['installment']['due_amount_date'] below
			$data['installment']['due_amount_date'] = array_values($data['installment']['due_amount_date']);
			$student_identification = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row()->studentId;

			$code_encryption = $student_identification . ',' . $course_fee_id . ',' . $fee_type_name . ',' . $first_due_amount . ',' . $installment_key . ',' . $s_no_new;

			// Studentid,CourseFee,Feetype,Amount,S_no

			$encrypted = urlsafe_b64encode($code_encryption);

			$html = '<div class="user-info-one-fees mb-5">
			<p>Payment Dates:</p>
			<ul class="mt-3 sele-sub-opt-two" style="list-style-type: none;">';
			// test_view_array($data['installment']['due_amount_date']);
			foreach ($data['installment']['due_amount_date'] as $index => $val) {
				$flag = true;
				foreach ($val as $key2 => $ele) {
					$due_date = date('Y-m-d', strtotime($ele->due_date));
					$current_date = date('Y-m-d', strtotime($this->nepali_current_date));
					$payClass = $due_date > $current_date ? '' : 'red-pay';
					$html .= '<li><div class="outter-pay-wrap" style="display: flex;">';
					if ($due_date > $current_date) {
						$html .= '<div class="outter-check"><i class="fa fa-check"></i></div>';
					} else {
						$html .= '<div class="outter-check red-pay"><i class="fas fa-times"></i></div>';
					}

					$html .= '<p class="paid-para">' . $ele->amount . '</p></div>';
					$html .= '<div class="paid-space"> Due on : ' . date('d-m-Y', strtotime($ele->due_date)) . '</div>';
					if ($flag) {
						$html .= '<a href="' . base_url() . '/student/pay_unpaid_fees/' . $encrypted . '" class="fees-pay-btn text-white">Pay Now</a>';
						$flag = false;
					}
					$html .= '</li>';
				}

				$html .= '</ul></div>';
			}
			echo $html;
		} else {
			echo 'failed';
		}
	}

	public function pay_unpaid_fees($encrypt)
	{
		$decrypted = urlsafe_b64decode($encrypt);
		$param = $array = explode(',', $decrypted);

		list($studentappId, $course_fee_id, $item, $amount, $installment_key, $s_no) = $param;
		$this->session->set_userdata('s_no', $s_no);

		$returnURL = base_url() . 'student/unpaid_fee_success';
		$failURL = base_url() . 'student/paymentFail';
		$notifyURL = base_url() . 'student/paypalipn';

		$this->paypal_lib->add_field('rm', 2);
		$this->paypal_lib->add_field('return',  $returnURL);
		$this->paypal_lib->add_field('fail_return', $failURL);
		$this->paypal_lib->add_field('notify_url', $notifyURL);
		$this->paypal_lib->add_field('item_name', $item);
		$this->paypal_lib->add_field('custom', $course_fee_id);
		$this->paypal_lib->add_field('item_number', $studentappId);
		$this->paypal_lib->add_field('amount', $amount);
		$this->paypal_lib->add_field('on1', $installment_key);
		$this->paypal_lib->add_field('on2', $s_no);
		$this->paypal_lib->paypal_auto_form();
	}

	public function unpaid_fee_success()
	{
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);

		$paypalInfo = array();
		$flag = true;
		foreach ($raw_post_array as $keyval) {
			$keyval = explode('=', $keyval);
			if (count($keyval) == 2)
				$paypalInfo[$keyval[0]] = urldecode($keyval[1]);
		}
		if ($paypalInfo['payment_status'] == 'Completed') {
			$studentId = $paypalInfo['item_number'];
			$item_type = $paypalInfo['item_name'];
			$courseFeeId = $paypalInfo['custom'];
			$stud_id = $this->db->get_where('students', array('studentId' => $studentId))->row()->id;

			$data['studentId'] = (!empty($studentId)) ? $studentId : $stud_id;
			$data['payment_for'] = $paypalInfo['item_name'];
			$data['txn_id'] = $paypalInfo["txn_id"];
			$data['payment_amt'] = $paypalInfo["payment_gross"];
			$data['currency_code'] = $paypalInfo["mc_currency"];
			$data['status'] = $paypalInfo["payment_status"];
			$data['payment_date'] = $paypalInfo["payment_date"];
			$data['payment_recived_id'] = $paypalInfo["receiver_id"];
			$data['course_fee_id'] = $courseFeeId;
			$installment_key = $paypalInfo['option_name1'];
			$s_no = $paypalInfo['option_name2'];

			$data['payment_date'] = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $data['payment_date']);

			$rst = $this->Student_model->storefeeTransaction($data);

			$check_id_record_exist = $this->db->get_where('students_online_payments', array('student_id' => $stud_id, 'course_fee_id' => $courseFeeId))->row();

			if ($check_id_record_exist) {

				$payment_installments = $check_id_record_exist->payment_details;
				$payment_row_id = $check_id_record_exist->id;
				$flag = true;
				$installment_data = (array)json_decode($payment_installments);
				foreach ($installment_data as $key => $value) {
					if ($value->payment_status == 'no' && $value->install_sno == $installment_key) {
						$installment_data[$key]->paid_amount = $paypalInfo['payment_gross'];
						$installment_data[$key]->payment_status = 'yes';
						$installment_data[$key]->paid_date = $this->nepali_current_date;
						$flag = false;
					}
				}

				$update_data['payment_details'] = json_encode($installment_data);
				$update_data['modified'] = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));

				$update_payment = $this->Student_model->add_edit_table('students_online_payments', $payment_row_id, $update_data);

				if (!$update_payment) {
					$this->session->set_flashdata('failed', "Fees could not be paid, Please try again later");
					redirect(base_url() . "student/my-payments");
				} else {
					$updated_installments = $this->db->get_where('students_online_payments', array('id' => $payment_row_id))->row_array();

					$response['status'] = true;
					$response['data'] = $updated_installments;
					$response['student_code'] = $studentId;
					$response['item']  = $item_type;
					$response['installment_key'] = $installment_key;
					//send mail start
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					//send mail end
					$this->session->set_flashdata('success', "You have paid the fees successfully");
					redirect(base_url() . "student/my-payments");
				}
			} else {

				$installment_data_query = $this->db->get_where('installment', array('course_fee_id' => $courseFeeId))->row()->due_amount_date;

				$installment_data = (array)json_decode($installment_data_query);

				$flag = true;
				$to_be_inserted = array();
				foreach ($installment_data as $key => $value) {
					if ($key != $installment_key) {
						unset($installment_data[$key]);
					} else {
						foreach ($value as $index => $ele) {
							if ($flag && ($s_no == $index + 1)) {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => $paypalInfo['payment_gross'],
									'payment_status' => 'yes',
									'paid_date' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date))
								);
								$flag = false;
							} else {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => "0",
									'payment_status' => 'no',
									'paid_date' => ''
								);
							}
						}
					}
				}

				$stdentfee = array(
					'student_id' => $stud_id,
					'course_fee_id' => $courseFeeId,
					'installment_type_id' => $installment_key,
					'payment_details' => json_encode($to_be_inserted),
					'created' => $this->nepali_current_date,
					'modified' => $this->nepali_current_date
				);

				$insert_payment = $this->db->insert('students_online_payments', $stdentfee);
				if (!$insert_payment) {
					$this->session->set_flashdata('failed', "Fees could not be paid, Please try again later");
					redirect(base_url() . 'student/my-payments');
				} else {
					//send mail start
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					//send mail end
					$this->session->set_flashdata('success', "You have paid the fees successfully");
					redirect(base_url() . 'student/my-payments');
				}
			}
		}
	}

	// Student's Info End - Afras Khan - 03-11-2021

	// Calendarn - 08-11-2021 - Afras Khan

	public function my_calendar()
	{
		if (isset($_SESSION['student_id'])) {
			$this->load->helper('url');
			$data['currentURL'] = current_url();
			$data['menulist'] = $this->Student_model->get_studentMenus();

			$data['curr_date'] = $current_date = date('Y-m-d', strtotime($this->nepali_current_date));

			$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)));

			$sql = "Select sd.*, sb.classroom_id, c.course_id as course_id, cs.subject_id as subject_id, s.subject_name as subject_name, s.subject_icon as icon from 
				students std 
				inner join student_batch sb on std.id = sb.student_id AND std.batch_id = sb.batch_id
				inner join classroom c on sb.classroom_id = c.id
				inner join course_subjects cs on c.course_id = cs.course_id
				inner join subject s on s.id = cs.subject_id
				inner join session_details sd on sd.subject_id = s.id
				inner join classroom_session cse on cse.id = sd.session_id
				AND cse.classroom_id = c.id
				WHERE std.id = '$_SESSION[student_id]' 
				AND (sb.student_id = std.id AND std.batch_id = sb.batch_id 
				AND sb.batch_id = cse.batch_id)  AND LOWER(sd.day) = '$presentDay' AND
				('$current_date' between cse.start_date and cse.end_date)  AND cse.is_active = 'yes' ORDER BY sd.start";

			$data['subject_names'] = $this->Student_model->get_table_info('student_batch', '', $sql);


			if (!empty($data['subject_names'])) {

				$teachersArray = array();
				$teacherInfo = '';

				foreach ($data['subject_names'] as $key => $value) {
					if ($key == 0) {
						$teacherInfo .= "(cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
					} else {
						$teacherInfo .= " OR (cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
					}
				}

				$teacherInfoQuery = "Select cts.subject_id as SubjectId, t.id as Id, t.teacherId as TeacherId, t.teacher_name as TeacherName from teacher t inner join classroom_teacher_subject cts on t.id = cts.teacher_id where $teacherInfo";

				$teachersArray = $this->Student_model->get_table_info('teacher', '', $teacherInfoQuery);


				foreach ($teachersArray as $key => $value) {
					foreach ($data['subject_names'] as $key2 => $value2) {
						if ($value['SubjectId'] == $value2['subject_id']) {
							$data['subject_names'][$key2]['teacher_name'] = $value['TeacherName'];
						}
					}
				}
			} else {
				$data['subject_names'] = null;
			}

			$this->load->view('student/header', $data);
			$this->load->view('student/my-calendar');
			$this->load->view('student/footer');
		} else {
			redirect(base_url() . 'Student');
		}
	}

	public function ajax_get_sessions_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)));

		$sql = "Select sd.*, sb.classroom_id, c.course_id as course_id, cs.subject_id as subject_id, s.subject_name as subject_name, s.subject_icon as icon 
			from students std 
			inner join student_batch sb on std.id = sb.student_id AND std.batch_id = sb.batch_id
			inner join classroom c on sb.classroom_id = c.id
			inner join course_subjects cs on c.course_id = cs.course_id
			inner join subject s on s.id = cs.subject_id
			inner join session_details sd on sd.subject_id = s.id
			inner join classroom_session cse on cse.id = sd.session_id
			AND cse.classroom_id = c.id
			WHERE (std.id = '$_SESSION[student_id]' 
		AND sb.batch_id = cse.batch_id) AND LOWER(sd.day) = '$day' AND
			(DATE('$date') between cse.start_date and cse.end_date)  AND cse.is_active = 'yes' ORDER BY sd.start";

		$data = $this->Student_model->get_table_info('student_batch', '', $sql);

		// echo $this->db->last_query();

		if (!empty($data)) {

			$teacherInfo = '';

			foreach ($data as $key => $value) {
				if ($key == 0) {
					$teacherInfo .= "(cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
				} else {
					$teacherInfo .= " OR (cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
				}
			}

			$teacherInfoQuery = "Select cts.subject_id as SubjectId, t.id as Id, t.teacherId as TeacherId, t.teacher_name as TeacherName from teacher t inner join classroom_teacher_subject cts on t.id = cts.teacher_id where $teacherInfo";

			$teachersArray = $this->Student_model->get_table_info('teacher', '', $teacherInfoQuery);


			foreach ($teachersArray as $key => $value) {
				foreach ($data as $key2 => $value2) {
					if ($value['SubjectId'] == $value2['subject_id']) {
						$data[$key2]['teacher_name'] = $value['TeacherName'];
					}
				}
			}

			$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);

				$teacher_info = array_key_exists('teacher_name', $value) ? 'By: <span>' . $value["teacher_name"] . '</span>' : 'Teacher not assigned';

				$sessions .= '<div class="upcoming-tab">';
				$sessions .= '<div class="upcoming-sub-img"><img src="' . base_url() . 'assets_admin/images/icons/' . $value["icon"] . '"></div>';
				$sessions .= '<div class="upcoming-subject">';
				$sessions .= '<h4>' . $value["subject_name"] . '</h4>';
				$sessions .= '<p class="mt-2">' . $teacher_info . '</p>';
				$sessions .= '</div>';
				$sessions .= '<div class="upcoming-date">';
				if (strtolower($pday) === strtolower($sessionDay) && ($now >= $begintime && $now <= $endtime) && $date == date('Y-m-d')) {
					$sessions .= '<div class="my-class-btn-wrap"> <a target="_blank" href = "' . $value['join_link'] . '"> <button class="join-class-btn">Join Class</button></a></div>';
				} else {
					$sessions .= '<span>' . date('h:i a', strtotime($value['start'])) . '</span>';
				}
				$sessions .= '</div></div>';
			}

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

	// Calendar End - 08-11-2021 - Afras Khan

	// My Classes - 09-11-2021 - Afras Khan

	public function my_classes()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/my-classes.php'))
			show_404();


		$this->load->helper('url');
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$data['subject_names'] = $this->my_classes_Function();

		$this->load->view('student/header', $data);
		$this->load->view('student/my-classes');
		$this->load->view('student/footer');
	}


	public function my_classes_Function()
	{
		$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'))));

		// $presentDay = strtolower(date('l', strtotime($this->nepali_current_date)));
		$current_date = date('Y-m-d', strtotime($this->nepali_current_date));

		$sql = "Select sd.*, sb.classroom_id, c.course_id as course_id, cs.subject_id as subject_id, s.subject_name as subject_name, s.subject_icon as icon 
			from students std 
			inner join student_batch sb on std.id = sb.student_id AND std.batch_id = sb.batch_id
			inner join classroom c on sb.classroom_id = c.id
			inner join course_subjects cs on c.course_id = cs.course_id
			inner join subject s on s.id = cs.subject_id
			inner join session_details sd on sd.subject_id = cs.subject_id
			inner join classroom_session cse on cse.id = sd.session_id
			AND cse.classroom_id = c.id
			WHERE (std.id = '$_SESSION[student_id]' 
			AND sb.batch_id = cse.batch_id)
			AND LOWER(sd.day) = '$presentDay' 
			AND	('$current_date' between cse.start_date and cse.end_date)
			AND cse.is_active = 'yes' ORDER BY sd.start ASC";

		$data['subject_names'] = $this->Student_model->get_table_info('student_batch', '', $sql);

		// dd($data['subject_names']);

		if (!empty($data['subject_names'])) {

			$teachersArray = array();
			$teacherInfo = '';

			foreach ($data['subject_names'] as $key => $value) {
				if ($key == 0) {
					$teacherInfo .= "(cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
				} else {
					$teacherInfo .= " OR (cts.classroom_id = '$value[classroom_id]' AND cts.subject_id = '$value[subject_id]')";
				}
			}

			$teacherInfoQuery = "Select cts.subject_id as SubjectId, t.id as Id,t.photo, t.teacherId as TeacherId, t.teacher_name as TeacherName from teacher t inner join classroom_teacher_subject cts on t.id = cts.teacher_id where $teacherInfo";

			$teachersArray = $this->Student_model->get_table_info('teacher', '', $teacherInfoQuery);

			// echo $this->db->last_query();
			// test_view_array($teachersArray);

			foreach ($teachersArray as $key => $value) {
				foreach ($data['subject_names'] as $key2 => $value2) {
					if ($value['SubjectId'] == $value2['subject_id']) {
						$data['subject_names'][$key2]['teacher_name'] = $value['TeacherName'];
						$data['subject_names'][$key2]['teacher_image'] = $value['photo'];
					}
				}
			}



			foreach ($data['subject_names'] as $key => $value) {
				$sessionDay = $value['day'];

				$s = $value['start'];
				$pday =  date("l");
				// $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);

				if (strtolower($pday) === strtolower($sessionDay) && ($now >= $begintime && $now <= $endtime)) {
					$class_session = 'Active';
				} else {
					$class_session = 'InActive';
				}

				$class_time = date('h:i A', strtotime($value['start'])) . ' - ' . date('h:i A', strtotime($end));

				$data['subject_names'][$key]['class_time'] = $class_time;
				$data['subject_names'][$key]['class_session'] = $class_session;
			}
		} else {
			$data['subject_names'] = null;
		}

		return $data['subject_names'];
	}

	// My Classes End - 09-11-2021 - Afras Khan

	// to get application fee by shivakumar start
	public function get_applicationfee()
	{
		$courseId = $_REQUEST['course_id'];
		$batchId = $_REQUEST['batch_id'];
		$feesType = 1; // In feesType table - 1st vlaue should be Application Fee 
		$sql = "SELECT * FROM `course_fees` WHERE batch_id=$batchId AND course_id=$courseId AND fees_type=$feesType AND due_date >= DATE(now())";
		$result = $this->Student_model->get_query_row($sql);
		echo $rst = ($result != '') ? json_encode($result) : 0;
	}

	public function library()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/library.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();
		$studentID = $this->db->get_where("students", array('id' => $_SESSION['student_id']))->row()->studentId;

		$CI = &get_instance();
		$ecDB = $CI->load->database('erisnClassroom_lms', TRUE);
		$gsData = $ecDB->query("SELECT * FROM lms_general_settings")->row_array();
		if (isset($gsData) && !empty($gsData)) {
			$data['general_setting'] = $gsData;
		}
		if (!empty($_POST['searchfilter']) == 'search_filter') {

			$from_date = (isset($_POST['start_date']) && !empty($_POST['start_date'])) ? date('Y-m-d', strtotime($_POST['start_date'])) : date('Y-m-1', strtotime($this->nepali_current_date));
			$enddate = (isset($_POST['end_date']) && !empty($_POST['end_date'])) ? date('Y-m-d', strtotime($_POST['end_date'])) : date('Y-m-d', strtotime($this->nepali_current_date));
			$status = (isset($_POST['status']) && !empty($_POST['status'])) ? $_POST['status'] : '';

			$q = '';
			if ($from_date != '' && $enddate != '')
				$q .= "AND lbt.issued_date BETWEEN '$from_date' AND '$enddate'";
			$data['start_date'] = $from_date;
			$data['end_date'] = $enddate;
			if ($status != '')
				$data['status'] = $status;
			$data['book_data'] = $ecDB->query("SELECT lbt.*,lb.title,lb.fine_per_day as fine FROM lms_book_transactions lbt JOIN lms_books lb ON lbt.book_id=lb.id WHERE lbt.eu_unique_id='$studentID' $q")->result_array();
		} else {
			$data['book_data'] = $ecDB->query("SELECT lbt.*,lb.title,lb.fine_per_day as fine FROM lms_book_transactions lbt JOIN lms_books lb ON lbt.book_id=lb.id WHERE lbt.eu_unique_id='$studentID'")->result_array();
		}
		$data['todayDate'] = date('Y-m-d', strtotime($this->nepali_current_date));
		$this->load->view('student/header', $data);
		$this->load->view('student/library');
		$this->load->view('student/footer');
	}
	// to get application fee by shivakumar end


	// Hostel - Afras Khan - 09/12/2021

	public function hostel()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/hostel.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();
		$data['student_id'] = $student_id = $_SESSION['student_id'];

		$course_query = "Select b.id as batch_id,b.b_name,c.id as course_id,c.course_name from batch b 
		INNER JOIN students s on s.batch_id = b.id
		INNER JOIN course c on c.id = s.course
		WHERE s.id = $student_id";

		$data['course_details'] = $course_details = $this->Admin_model->get_table_info_row('students', '', $course_query);

		$hostel_query = "Select IFNULL(c.amount,'-') as amount,hp.plan_name as fee_values from hostel_plans hp
		LEFT JOIN course_fees c on hp.id = c.hostel_plan_id
		INNER JOIN students s on s.batch_id = c.batch_id
		AND c.batch_id = $course_details[batch_id] 
		AND c.course_id = $course_details[course_id]
		AND c.fees_type = 3 AND c.course_id = s.course
		GROUP BY c.id";

		$data['hostel_details'] = $hostel_details = $this->Admin_model->get_table_info('course_fees', '', $hostel_query);
		// dd($hostel_details);
		$this->load->view('student/header', $data);
		$this->load->view('student/hostel');
		$this->load->view('student/footer');
	}

	public function hostel_fee()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/hostel-fee.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$batch_id = $this->db->order_by('id', 'DESC')->get_where('student_batch', array('student_id' => $_SESSION['student_id']))->row();

		if (!empty($batch_id)) {
			$batch_id = $batch_id->batch_id;
			$hostel_fee_sql = "Select ft.id, ft.feetype_name, cf.amount,cf.fee_values, cf.id as cf_id from fee_types ft inner join course_fees cf on ft.id = cf.fees_type inner join students s on s.id = $_SESSION[student_id] WHERE ft.id = 3 AND cf.batch_id = $batch_id AND cf.course_id = s.course AND cf.course_id = s.course";

			$data['hostel_fees'] = $get_hostel_types = $this->Student_model->get_table_info('fee_types', '', $hostel_fee_sql);
		} else {
			$data['hostel_fees'] = [];
		}

		$this->load->view('student/header', $data);
		$this->load->view('student/hostel-fee');
		$this->load->view('student/footer');
	}

	public function ajax_get_hostel_installments()
	{
		$course_fee_id = $this->input->post('id');

		$installments_column_query = $this->db->get_where('installment', array('course_fee_id' => $course_fee_id));

		$check_installment = $installments_column_query->row();
		$installments_column = '';
		if (!$check_installment) {
			echo false;
			exit();
		} else {
			$installments_column = $check_installment->due_amount_date;
		}

		// Decoded Installment and convert to array and fetched the keys (feetype_ids)
		$decoded_installment = array_keys((array)json_decode($installments_column));
		$feetype_clause = '';
		foreach ($decoded_installment as $key => $value) {
			if ($key == 0) {
				$feetype_clause .= "id = '$value'";
			} else {
				$feetype_clause .= " or id = '$value'";
			}
		}

		$fee_types = $this->Student_model->get_table_info('payment_types', $feetype_clause, '', 'ASC');

		$html = '<select name="installment_type" onchange="gettextname()" class="form-control mt-2" id="installment-dropdown">';
		foreach ($fee_types as $key => $value) {
			if ($key == 0)
				$html .= '<option value="">Select type of installment</option>';
			$html .= '<option value="' . $value['id'] . '">' . $value['payment_type_name'] . '</option>';
		}

		$html .= '</select>';

		echo $html;
	}

	public function get_hostel_details()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/hostel-info.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();


		if (count($_POST) < 1) {
			$this->session->set_flashdata('failed', "Please select a Hostel Plan");
			redirect(base_url() . 'student/hostel_fee');
		}

		$course_fee_id = $this->input->post('course_fee_id');
		$installment_key = $this->input->post('installment_type');

		$sql_item_name = "Select f.feetype_name from fee_types f inner join course_fees cf on cf.fees_type = f.id WHERE cf.id = $course_fee_id";
		$fee_type_col = $this->Student_model->get_general_row_details('fee_types', '', $sql_item_name);

		$fee_type_name = $fee_type_col['feetype_name'];

		$whereClause = "Select cf.id,cf.amount, i.id as installment_id, i.due_amount_date from course_fees cf inner join installment i on cf.id = i.course_fee_id WHERE cf.id = '$course_fee_id'";

		$selected_installment = $query = $this->Student_model->get_general_row_details('course_fees', '', $whereClause);

		if (!empty($query)) {

			// decoding due_amount_date from installments
			$selected_installment['due_amount_date'] = (array)json_decode($query['due_amount_date']);
			$first_due_amount = '';

			// filtering the array with user selected option with $installment_key
			foreach ($selected_installment['due_amount_date'] as $key => $value) {
				if ($key != $installment_key) {
					unset($selected_installment['due_amount_date'][$key]);
				} else {
					foreach ($value as $index => $ele) {
						if ($index == 0) {
							$first_due_amount = $ele->amount;
						}
						$selected_installment['due_amount_date'][$key][$index]->payment_status = 'no';
					}
				}
			}

			$data['installment'] = $selected_installment;

			// Re arranging keys of $data['installment']['due_amount_date'] below
			$data['installment']['due_amount_date'] = array_values($data['installment']['due_amount_date']);
			$student_identification = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row()->studentId;

			$encrypted = $student_identification . '*' . $course_fee_id . '*' . $first_due_amount . '*' . $fee_type_name . '*' . $installment_key . '*' . 1;
			$data['encrypted'] = urlsafe_b64encode($encrypted);
		} else {
			$this->session->set_flashdata('failed', "We are facing a technical issue, Please try again in sometime");
			redirect(base_url() . 'student/hostel_fee');
		}

		$this->load->view('student/header', $data);
		$this->load->view('student/hostel-info');
		$this->load->view('student/footer');
	}

	public function pay_hostel_fees($encrypt)
	{
		$decrypted = urlsafe_b64decode($encrypt);
		$param = $array = explode('*', $decrypted);

		list($studentappId, $course_fee_id, $amount, $item, $installment_key, $s_no) = $param;

		$returnURL = base_url() . 'student/hostel_success';
		$failURL = base_url() . 'student/paymentFail';
		$notifyURL = base_url() . 'student/paypalipn';

		$this->paypal_lib->add_field('rm', 2);
		$this->paypal_lib->add_field('return',  $returnURL);
		$this->paypal_lib->add_field('fail_return', $failURL);
		$this->paypal_lib->add_field('notify_url', $notifyURL);
		$this->paypal_lib->add_field('item_name', $item);
		$this->paypal_lib->add_field('custom', $course_fee_id);
		$this->paypal_lib->add_field('item_number', $studentappId);
		$this->paypal_lib->add_field('amount', $amount);
		$this->paypal_lib->add_field('on1', $installment_key);
		$this->paypal_lib->add_field('on2', $s_no);
		$this->paypal_lib->paypal_auto_form();
	}



	public function hostel_success()
	{
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);

		$paypalInfo = array();
		$flag = true;
		foreach ($raw_post_array as $keyval) {
			$keyval = explode('=', $keyval);
			if (count($keyval) == 2)
				$paypalInfo[$keyval[0]] = urldecode($keyval[1]);
		}

		// test_view_array($paypalInfo);

		if ($paypalInfo['payment_status'] == 'Completed') {
			$studentId = $paypalInfo['item_number'];
			$item_type = $paypalInfo['item_name'];
			$courseFeeId = $paypalInfo['custom'];
			$stud_id = $this->db->get_where('students', array('studentId' => $studentId))->row()->id;

			$data['studentId'] = (!empty($studentId)) ? $studentId : $stud_id;
			$data['payment_for'] = $paypalInfo['item_name'];
			$data['txn_id'] = $paypalInfo["txn_id"];
			$data['payment_amt'] = $paypalInfo["payment_gross"];
			$data['currency_code'] = $paypalInfo["mc_currency"];
			$data['status'] = $paypalInfo["payment_status"];
			$data['payment_date'] = $paypalInfo["payment_date"];
			$data['payment_recived_id'] = $paypalInfo["receiver_id"];
			$data['course_fee_id'] = $courseFeeId;
			$installment_key = $paypalInfo['option_name1'];
			$s_no = $paypalInfo['option_name2'];

			$data['payment_date'] = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $data['payment_date']);

			$rst = $this->Student_model->storefeeTransaction($data);

			$check_id_record_exist = $this->db->get_where('students_online_payments', array('student_id' => $stud_id, 'course_fee_id' => $courseFeeId))->row();

			if ($check_id_record_exist) {

				$payment_installments = $check_id_record_exist->payment_details;
				$payment_row_id = $check_id_record_exist->id;
				$flag = true;
				$installment_data = (array)json_decode($payment_installments);

				foreach ($installment_data as $key => $value) {
					if ($value->payment_status == 'no' && $flag && $value->install_sno == $s_no) {
						$installment_data[$key]->paid_amount = $paypalInfo['payment_gross'];
						$installment_data[$key]->payment_status = 'yes';
						$installment_data[$key]->paid_date = $this->nepali_current_date;
						$flag = false;
					}
				}

				$update_data['payment_details'] = json_encode($installment_data);
				$update_data['modified'] = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));

				$update_payment = $this->Student_model->add_edit_table('students_online_payments', $payment_row_id, $update_data);

				if (!$update_payment) {
					$response['status'] = false;
					$response['data'] = $data;

					$this->session->set_userdata('hostel_data', $response);
					redirect(base_url() . "student/navigate_to_hostel");
				} else {
					$updated_installments = $this->db->get_where('students_online_payments', array('id' => $payment_row_id))->row_array();

					$response['status'] = true;
					$response['data'] = $updated_installments;
					$response['student_code'] = $studentId;
					$response['item']  = $item_type;
					$response['installment_key'] = $installment_key;

					// Mail sent to student about fess - Shankar
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					// Mail sent to student about fess - Shankar

					$this->session->set_userdata('hostel_data', $response);
					redirect(base_url() . "student/navigate_to_hostel");
				}
			} else {

				$update_clause['hostel'] = 'yes';
				$update_student = $this->Student_model->add_edit_table('students', $stud_id, $update_clause);

				if (!$update_student) {
					$response['status'] = false;
					$response['data'] = $data;
					$this->session->set_userdata('hostel_data', $response);
					redirect(base_url() . "student/navigate_to_hostel");
				}

				$installment_data_query = $this->db->get_where('installment', array('course_fee_id' => $courseFeeId))->row()->due_amount_date;

				$installment_data = (array)json_decode($installment_data_query);

				$flag = true;
				$to_be_inserted = array();
				foreach ($installment_data as $key => $value) {
					if ($key != $installment_key) {
						unset($installment_data[$key]);
					} else {
						foreach ($value as $index => $ele) {
							if ($flag) {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => $paypalInfo['payment_gross'],
									'payment_status' => 'yes',
									'paid_date' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date))
								);
								$flag = false;
							} else {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => "0",
									'payment_status' => 'no',
									'paid_date' => ''
								);
							}
						}
					}
				}

				$stdentfee = array(
					'student_id' => $stud_id,
					'course_fee_id' => $courseFeeId,
					'installment_type_id' => $installment_key,
					'payment_details' => json_encode($to_be_inserted),
					'created' => $this->nepali_current_date,
					'modified' => $this->nepali_current_date
				);

				$insert_payment = $this->db->insert('students_online_payments', $stdentfee);
				if (!$insert_payment) {
					$response['status'] = false;
					$response['data'] = $data;
					$this->session->set_userdata('hostel_data', $response);
					redirect(base_url() . "student/navigate_to_hostel");
				} else {
					// Mail sent to student about fess - Shankar
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					// Mail sent to student about fess - Shankar
					$response['status'] = true;
					$response['data'] = $stdentfee;
					$response['student_code'] = $studentId;
					$response['item']  = $item_type;
					$response['installment_key'] = $installment_key;
					$this->session->set_userdata('hostel_data', $response);
					redirect(base_url() . "student/navigate_to_hostel");
				}
			}
		}
	}

	public function navigate_to_hostel()
	{

		$response = $this->session->userdata('hostel_data');

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		if ($response['status']) {

			$installment = $response['data']; // Payment Data
			$student_code = $response['student_code']; // Code for encryption
			$item = $response['item']; // item for encryption
			$installment_key = $response['installment_key']; // key for encryption

			$installment['payment_details'] = (array)json_decode($installment['payment_details']);
			// test_view_array($installment);
			$course_fee_id = $installment['course_fee_id'];

			$course_fees_info = $this->db->get_where('course_fees', array('id' => $installment['course_fee_id']))->row();

			$whereClause = "Select cf.id,cf.amount, i.id as installment_id, i.due_amount_date from course_fees cf inner join installment i on cf.id = i.course_fee_id WHERE cf.id = '$installment[course_fee_id]'";

			$data['installment']  = $this->Student_model->get_general_row_details('course_fees', '', $whereClause);

			$flag = true;
			$amount_encrypt = 0;
			foreach ($installment['payment_details'] as $key => $value) {

				if ($flag && $value->payment_status == 'no') {
					$amount_encrypt = $value->feeamount;
					$flag = false;
				}

				$installment['payment_details'][$key]->amount = $value->feeamount;
				unset($installment['payment_details'][$key]->feeamount);
			}

			$encrypted = $student_code . '*' . $course_fee_id . '*' . $amount_encrypt . '*' . $item . '*' . $installment_key;

			$data['encrypted'] = urlsafe_b64encode($encrypted);
			$data['installment']['due_amount_date'] = array();
			$data['installment']['due_amount_date'][] = $installment['payment_details'];

			$_SESSION['hostel_data'] = null;
			$this->session->set_flashdata('success', "You have successfully paid the fees");
			redirect(base_url() . 'student/hostel');
		}
	}
	// Hostel Ends - Afras Khan - 09/12/2021


	//-*-- Bus Facility Module start here - Shankar -*-//

	public function BusFacility()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$student_id = $_SESSION['student_id'];

		$query = $this->db->query('select cf.amount,cf.fees_type,	 installment_type_id, course_fee_id, payment_details from students_online_payments sop, fee_types ft, course_fees cf, students s where  sop.student_id= ' . $student_id . ' and sop.course_fee_id = cf.id and cf.fees_type = ft.id and ft.id = 4 AND s.id = sop.student_id AND s.course = cf.course_id AND s.batch_id = cf.batch_id')->row_array();

		if ($query) {

			$BTSdb = $this->load->database('erisnClassroom_bts', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.
			$data['route_name'] = $BTSdb->query('select sbrd.route_id, r.route_name,rd.place_name, pick_up_id, drop_id from bt_students_bus_route_details sbrd, bt_routes_details rd, bt_routes r where student_id=' . $student_id . ' and r.id = sbrd.route_id and sbrd.pick_up_id = rd.id and sbrd.drop_id = rd.id ORDER BY sbrd.id DESC')->row_array();
			$data['payment_details'] = $query;

			$this->load->view('student/header', $data);
			$this->load->view('student/bus_details_info');
			$this->load->view('student/footer');
		} else {
			$this->load->view('student/header', $data);
			$this->load->view('student/bus');
			$this->load->view('student/footer');
		}
	}

	public function BusFacilityDetails()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$sqlQuery = 'select cf.id as course_fee_id, cf.amount, cf.fees_type from course_fees cf, students s where s.id=' . $_SESSION['student_id'] . ' and  s.is_active = "yes" and cf.batch_id = s.batch_id and cf.course_id = s.course and cf.fees_type = 4 and s.course = cf.course_id AND s.batch_id = cf.batch_id';

		$data['bus_fee'] = $this->Student_model->get_query_row($sqlQuery);

		if (isset($data['bus_fee']) && !empty($data['bus_fee'])) {
			$course_id = $data['bus_fee']['course_fee_id'];

			$sqlQuery1 = ' select id as installment_id, course_fee_id, due_amount_date from installment where course_fee_id = ' . $course_id . ' and is_active = "yes"';

			$data['installment'] = $this->Student_model->get_query_row($sqlQuery1);
		}

		$BTSdb = $this->load->database('erisnClassroom_bts', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.
		$data['route_name'] = $BTSdb->query('select * from bt_routes')->result_array();

		// echo "<pre>";print_r($data);exit();

		$this->load->view('student/header', $data);
		$this->load->view('student/bus_details');
		$this->load->view('student/footer');
	}

	public function get_bus_stops_name($id)
	{
		$BTSdb = $this->load->database('erisnClassroom_bts', TRUE);
		$route_name = $BTSdb->query('select id, place_name from bt_routes_details where route_id=' . $id . ' order by route_order ASC')->result_array();
		echo json_encode($route_name);
	}

	public function get_bus_payment_json($method_id, $course_fee_id)
	{
		$route_name =  $this->db->query('select JSON_EXTRACT(due_amount_date,"$.' . $method_id . '") as pay from installment where course_fee_id =' . $course_fee_id)->row_array();

		//echo json_decode($route_name['pay']);
		echo json_encode(json_decode($route_name['pay']));
	}

	public function bus_fee_management()
	{
		// echo"<pre>";print_r($_POST);exit();
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		// $BTSdb = $this->load->database('erisnClassroom_bts', TRUE);
		// $query = $BTSdb->query('select * from bt_students_bus_route_details where student_id='. $_SESSION['student_id']);

		// $update_array = array(
		// 	'route_id' 		=> $_POST['route_name'],
		// 	'student_id' 	=> $_SESSION['student_id'],
		// 	'pick_up_id'	=> $_POST['stop_name'],
		// 	'drop_id' 		=> $_POST['stop_name'],
		// 	'is_active'		=> 'yes'

		// );

		// $arr = json_encode($update_array);

		// if ($query->num_rows() > 0) {			

		// 	$BTSdb->where('student_id', $_SESSION['student_id']);
		// 	$BTSdb->update('bt_students_bus_route_details', $update_array);
		// 	if ($this->db->trans_status() === FALSE)
		// 		redirect(base_url() . 'student');		 	

		// }else{
		// 	$BTSdb->insert('bt_students_bus_route_details', $update_array);
		// }	

		$student_identification = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row()->studentId;

		$returnURL = base_url() . 'student/bus_fee_success';
		$failURL = base_url() . 'student/paymentFail';
		$notifyURL = base_url() . 'student/paypalipn';

		$course_fee_id = $_POST['course_fee_id'];
		$amount = $_POST['paying_amount'];
		$installment_key = $_POST['mode_payment'];

		$item = $this->db->get_where('fee_types', array('id' => $_POST['fee_type_id']))->row()->feetype_name;


		$this->paypal_lib->add_field('rm', 2);
		$this->paypal_lib->add_field('return',  $returnURL);
		$this->paypal_lib->add_field('fail_return', $failURL);
		$this->paypal_lib->add_field('notify_url', $notifyURL);
		$this->paypal_lib->add_field('item_name', $item);
		$this->paypal_lib->add_field('custom', $course_fee_id);
		$this->paypal_lib->add_field('item_number', $student_identification);
		$this->paypal_lib->add_field('amount', $amount);
		$this->paypal_lib->add_field('on1', $installment_key);
		$this->paypal_lib->add_field('on2', $_POST['route_name']);
		$this->paypal_lib->add_field('on3', $_POST['stop_name']);
		$this->paypal_lib->add_field('on4', $_POST['stop_name']);
		$this->paypal_lib->paypal_auto_form();
	}

	public function bus_fee_success()
	{
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);


		$paypalInfo = array();
		$flag = true;
		foreach ($raw_post_array as $keyval) {
			$keyval = explode('=', $keyval);
			if (count($keyval) == 2)
				$paypalInfo[$keyval[0]] = urldecode($keyval[1]);
		}


		if ($paypalInfo['payment_status'] == 'Completed') {
			$studentId = $paypalInfo['item_number'];
			$item_type = $paypalInfo['item_name'];
			$courseFeeId = $paypalInfo['custom'];
			$stud_id = $this->db->get_where('students', array('studentId' => $studentId))->row()->id;

			$data['studentId'] = (!empty($studentId)) ? $studentId : $stud_id;
			$data['payment_for'] = $paypalInfo['item_name'];
			$data['txn_id'] = $paypalInfo["txn_id"];
			$data['payment_amt'] = $paypalInfo["payment_gross"];
			$data['currency_code'] = $paypalInfo["mc_currency"];
			$data['status'] = $paypalInfo["payment_status"];
			$data['payment_date'] = $paypalInfo["payment_date"];

			$data['payment_date'] = convert_ADdateTime_to_BSdateTime($this->nepaliDateObject, $data['payment_date']);

			$data['payment_recived_id'] = $paypalInfo["receiver_id"];
			$data['course_fee_id'] = $courseFeeId;
			$installment_key = $paypalInfo['option_name1'];
			$route_name = $paypalInfo['option_name2'];
			$pick_id = $paypalInfo['option_name3'];
			$drop_id = $paypalInfo['option_name4'];
			$rst = $this->Student_model->storefeeTransaction($data);

			$check_id_record_exist = $this->db->get_where('students_online_payments', array('student_id' => $stud_id, 'course_fee_id' => $courseFeeId))->row();

			if ($check_id_record_exist) {

				$payment_installments = $check_id_record_exist->payment_details;
				$payment_row_id = $check_id_record_exist->id;
				$flag = true;
				$installment_data = (array)json_decode($payment_installments);

				foreach ($installment_data as $key => $value) {
					if ($value->payment_status == 'no' && $flag) {
						$installment_data[$key]->paid_amount = $paypalInfo['payment_gross'];
						$installment_data[$key]->payment_status = 'yes';
						$installment_data[$key]->paid_date = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));
						$flag = false;
					}
				}

				$update_data['payment_details'] = json_encode($installment_data);
				$update_data['modified'] = date('Y-m-d H:i:s', strtotime($this->nepali_current_date));

				$update_payment = $this->Student_model->add_edit_table('students_online_payments', $payment_row_id, $update_data);

				if (!$update_payment) {
					$response['status'] = false;
					$response['data'] = $data;

					$this->session->set_userdata('bus_data', $response);
					redirect(base_url() . "student/navigate_to_Bus");
				} else {
					$updated_installments = $this->db->get_where('students_online_payments', array('id' => $payment_row_id))->row_array();

					$response['status'] = true;
					$response['data'] = $updated_installments;
					$response['student_code'] = $studentId;
					$response['item']  = $item_type;
					$response['installment_key'] = $installment_key;

					// Mail sent to student about fess - Shankar
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					// Mail sent to student about fess - Shankar

					$this->session->set_userdata('bus_data', $response);
					redirect(base_url() . "student/navigate_to_Bus");
				}
			} else {

				$BTSdb = $this->load->database('erisnClassroom_bts', TRUE);
				$query = $BTSdb->query('select * from bt_students_bus_route_details where student_id=' . $stud_id);
				$BusFacility_array = array(
					'route_id' 		=> $route_name,
					'student_id' 	=> $stud_id,
					'pick_up_id'	=> $pick_id,
					'drop_id' 		=> $drop_id,
					'is_active'		=> 'yes'
				);

				if ($query->num_rows() > 0) {
					$BusFacility_array['modified'] = $this->nepali_current_date;
					$BTSdb->where('student_id', $_SESSION['student_id']);
					$BTSdb->update('bt_students_bus_route_details', $BusFacility_array);
					if ($this->db->trans_status() === FALSE)
						redirect(base_url() . 'student');
				} else {
					$BusFacility_array['created'] = $this->nepali_current_date;
					$BTSdb->insert('bt_students_bus_route_details', $BusFacility_array);
				}

				$installment_data_query = $this->db->get_where('installment', array('course_fee_id' => $courseFeeId))->row()->due_amount_date;

				$installment_data = (array)json_decode($installment_data_query);

				$flag = true;
				$to_be_inserted = array();
				foreach ($installment_data as $key => $value) {
					if ($key != $installment_key) {
						unset($installment_data[$key]);
					} else {
						foreach ($value as $index => $ele) {
							if ($flag) {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => $paypalInfo['payment_gross'],
									'payment_status' => 'yes',
									'paid_date' => date('Y-m-d H:i:s', strtotime($this->nepali_current_date))
								);
								$flag = false;
							} else {
								$to_be_inserted[] = array(
									'install_sno' => $index + 1,
									'due_date' => $ele->due_date,
									'feeamount' => $ele->amount,
									'paid_amount' => "0",
									'payment_status' => 'no',
									'paid_date' => ''
								);
							}
						}
					}
				}

				$stdentfee = array(
					'student_id' => $stud_id,
					'course_fee_id' => $courseFeeId,
					'installment_type_id' => $installment_key,
					'payment_details' => json_encode($to_be_inserted),
					'created' => $this->nepali_current_date,
					'modified' => $this->nepali_current_date
				);

				$insert_payment = $this->db->insert('students_online_payments', $stdentfee);
				if (!$insert_payment) {
					$response['status'] = false;
					$response['data'] = $data;
					$this->session->set_userdata('bus_data', $response);
					redirect(base_url() . "student/navigate_to_Bus");
				} else {
					// Mail sent to student about fess - Shankar
					$this->mail_Send_Fees_Approved($stud_id, $courseFeeId);
					// Mail sent to student about fess - Shankar
					$response['status'] = true;
					$response['data'] = $stdentfee;
					$response['student_code'] = $studentId;
					$response['item']  = $item_type;
					$response['installment_key'] = $installment_key;
					$this->session->set_userdata('bus_data', $response);
					redirect(base_url() . "student/navigate_to_Bus");
				}
			}
		}
	}

	public function navigate_to_Bus()
	{

		$response = $this->session->userdata('bus_data');
		// echo"<pre>";print_r($response);exit();
		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		if ($response['status']) {

			$_SESSION['bus_data'] = null;
			$this->session->set_flashdata('success', "You have successfully paid the fees");
			redirect(base_url() . 'student/BusFacility');
		}
	}
	//-*--- Bus Facility Module End here - Shankar ---*-//

	// application email send

	public function mail_Send_Application_Approved($student_id, $amount, $payment_date)
	{
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$data['baseurl']	= base_url();

		$result = $this->db->query("select a.name as student_name, a.email,  c.course_name from applications a, course c where a.applicationid = '$student_id' and a.course = c.id")->row_array();

		$data['student_data'] = array(
			'student_name'	=> $result['student_name'],
			'course_name'	=> $result['course_name'],
			'student_id'	=> $student_id,
			'amount'		=> $amount,
			'date'			=> $payment_date
		);

		$msg = $this->load->view('email-applicationfee', $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($result['email']);
		//$this->email->to('shankar@erisn.com');

		$this->email->subject('Application Fee');
		$this->email->message($msg);

		if ($this->email->send()) {
			return true;
		} else {
			return false;
		}
	}

	// Application Email End 

	// Fee Installment Email send Start

	public function mail_Send_Fees_Approved($student_id, $course_fee_id)
	{

		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$data['baseurl']	= base_url();

		$result = $this->db->query("select studentId, a.name as student_name, a.email,  c.course_name from students a, course c where a.id = '$student_id' and a.course = c.id")->row_array();

		$get_json = $this->db->query(" select pt.payment_type_name, sop.payment_details, ft.feetype_name from students_online_payments sop, payment_types pt, course_fees cf, fee_types ft where sop.student_id = '$student_id' and sop.course_fee_id = '$course_fee_id' and sop.installment_type_id = pt.id and sop.course_fee_id = cf.id and cf.fees_type = ft.id")->row_array();


		$data['student_data'] = array(
			'student_name'	=> $result['student_name'],
			'course_name'	=> $result['course_name'],
			'student_id'	=> $result['studentId'],
			'fee_details'	=> $get_json['payment_type_name'],
			'payment_method' => $get_json['payment_details'],
			'fee_type_name'	=> $get_json['feetype_name']

		);

		$msg = $this->load->view('email-payment', $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($result['email']);
		//$this->email->to('shankar@erisn.com');

		$this->email->subject('Application Fee');
		$this->email->message($msg);

		if ($this->email->send()) {
			return true;
		} else {
			return false;
		}
	}

	// Fee Installment Email send End

	public function student_fees()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');


		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$data['result'] = $this->db->query('select o.* from student_fee_online_transactions o, students s where s.id =' . $_SESSION['student_id'] . ' and s.studentId = o.studentId order by o.id DESC')->result_array();

		$this->load->view('student/header', $data);
		$this->load->view('student/student-fee-details');
		$this->load->view('student/footer');
	}

	public function invoice($studID, $txn_ID)
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');


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


		$data['menulist'] = $this->Student_model->get_studentMenus();

		$studentID = urlsafe_b64decode($studID);
		$txnID = urlsafe_b64decode($txn_ID);

		if ($studentID != '' && $txnID != '') {
			$student_ID = $this->db->get_where('students', array('studentId' => $studentID))->row();

			if ($student_ID != '') {
				$sql1 = "SELECT sfot.*,course_fees.fee_values,s.course as courseID,s.name,s.studentId,b.b_from,b.b_name as batch_name,b.b_end,sb.batch_id,cl.course_id,cl.section_id, sfot.invoice_no FROM student_fee_online_transactions sfot LEFT JOIN students s ON sfot.studentId=s.studentId LEFT JOIN student_batch sb ON s.id=sb.student_id AND s.batch_id = sb.batch_id LEFT JOIN classroom cl ON cl.id=sb.classroom_id LEFT JOIN batch b ON sb.batch_id=b.id 
					INNER JOIN course_fees ON sfot.course_fee_id = course_fees.id
				WHERE sfot.studentId='$studentID' AND sfot.txn_id='$txnID' order by sb.id desc";
				$payment_data = $this->Admin_model->get_query_row($sql1);
				$student_data = array(
					'student_fee_online_transactions_id'	=> $payment_data['id'],
					'studentId' 							=> $payment_data['studentId'],
					'payment_for' 							=> $payment_data['fee_values'] . '(' . $payment_data['payment_for'] . ')',
					'txn_id' 								=> $payment_data['txn_id'],
					'payment_amt' 							=> $payment_data['payment_amt'],
					'paid_date' 							=> $payment_data['payment_date'],
					'studentname' 							=> $payment_data['name'],
					'batch_name' 							=> $payment_data['batch_name'],
					'batch_from' 							=> $payment_data['b_from'],
					'batch_end' 							=> $payment_data['b_end'],
					'course_id' 							=> (isset($payment_data['course_id']) && !empty($payment_data['course_id'])) ? $payment_data['course_id'] : $payment_data['courseID'],
					'received_by' 							=> $payment_data['payment_recived_id'],
					'payment_method' 						=> $payment_data['payment_method'],
					'fine_amount'							=> $payment_data['fine_amount'],
					'tdt'									=> date('Y-m-d H:i:s', strtotime($this->nepali_current_date)),
					'deduction_type'						=> $payment_data['deduction_type'],
					'deduction_amount'						=> $payment_data['deduction_amount'],
					'section_id' 							=> $payment_data['section_id'],
					'bill_print_count'						=> $payment_data['bill_print_count'],
					'course_fee_id'							=> $payment_data['course_fee_id'],
					'install_sno'							=> $payment_data['install_sno'],
					'invoice_no'							=> $payment_data['invoice_no'],
					'parent_pan'							=> $student_ID->parent_pan
				);
				$data['invoice_data'] = $student_data;
			} else {
				$sql2 = "SELECT soft.*,course_fees.fee_values,a.name,a.course,b.b_name as batch_name,b.b_from,b.b_end, soft.invoice_no FROM student_fee_online_transactions soft LEFT JOIN applications a ON a.applicationid=soft.studentId LEFT JOIN batch b ON b.id=a.batch_id INNER JOIN course_fees ON sfot.course_fee_id = course_fees.id WHERE soft.studentId='$studentID' AND soft.txn_id='$txnID' order by sb.id desc";
				$paymentdata = $this->Admin_model->get_query_row($sql2);
				if (count($paymentdata) > 0) {
					$application_data = array(
						'student_fee_online_transactions_id' 	=> $paymentdata['id'],
						'studentId' 							=> $paymentdata['studentId'],
						'payment_for' 							=> $paymentdata['fee_values'] . '(' . $paymentdata['payment_for'] . ')',
						'txn_id' 								=> $paymentdata['txn_id'],
						'payment_amt' 							=> $paymentdata['payment_amt'],
						'paid_date' 							=> $paymentdata['payment_date'],
						'studentname' 							=> $paymentdata['name'],
						'batch_name' 							=> $paymentdata['batch_name'],
						'batch_from' 							=> $paymentdata['b_from'],
						'batch_end' 							=> $paymentdata['b_end'],
						'course_id' 							=> $paymentdata['course'],
						'received_by' 							=> $paymentdata['payment_recived_id'],
						'payment_method' 						=> $paymentdata['payment_method'],
						'fine_amount'							=> $paymentdata['fine_amount'],
						'tdt'									=> date('Y-m-d H:i:s', strtotime($this->nepali_current_date)),
						'deduction_type'						=> $paymentdata['deduction_type'],
						'deduction_amount'						=> $paymentdata['deduction_amount'],
						'section_id' 							=> 0,
						'bill_print_count'						=> $paymentdata['bill_print_count'],
						'course_fee_id'							=> $paymentdata['course_fee_id'],
						'install_sno'							=> $paymentdata['install_sno'],
						'invoice_no'							=> $paymentdata['invoice_no'],
						'parent_pan'							=> $student_ID->parent_pan
					);
					$data['invoice_data'] = $application_data;
				}
			}
		}

		$this->load->view('student/header', $data);
		$this->load->view('student/student-fee-invoice');
		$this->load->view('student/footer');
	}

	public function invoicedownload($studID, $txn_ID)
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');



		$this->load->library('m_pdf');
		$data['school_info'] = $this->Admin_model->get_logo_from_setting();
		$studentID = urlsafe_b64decode($studID);
		$txnID = urlsafe_b64decode($txn_ID);

		if ($studentID != '' && $txnID != '') {
			$student_ID = $this->db->get_where('students', array('studentId' => $studentID))->row();
			if ($student_ID != '') {
				$this->db->where('studentId', $studentID);
				$this->db->where('txn_id', $txnID);
				$this->db->set('bill_print_count', 'bill_print_count+1', FALSE);
				$update = $this->db->update('student_fee_online_transactions');
				$sql1 = "SELECT sfot.*,course_fees.fee_values,s.course as courseID,s.name,s.studentId,b.b_name as batch_name,b.b_from,b.b_end,sb.batch_id,cl.course_id,cl.section_id, sfot.invoice_no FROM student_fee_online_transactions sfot LEFT JOIN students s ON sfot.studentId=s.studentId LEFT JOIN student_batch sb ON s.id=sb.student_id AND sb.batch_id = s.batch_id LEFT JOIN classroom cl ON cl.id=sb.classroom_id LEFT JOIN batch b ON sb.batch_id=b.id
					INNER JOIN course_fees ON sfot.course_fee_id = course_fees.id
				WHERE sfot.studentId='$studentID' AND sfot.txn_id='$txnID' order by sb.id desc";
				$payment_data = $this->Admin_model->get_query_row($sql1);
				$student_data = array(
					'student_fee_online_transactions_id' => $payment_data['id'],
					'studentId' => $payment_data['studentId'],
					'payment_for' => $payment_data['fee_values'] . '(' . $payment_data['payment_for'] . ')',
					'txn_id' => $payment_data['txn_id'],
					'payment_amt' => $payment_data['payment_amt'],
					'paid_date' => $payment_data['payment_date'],
					'studentname' => $payment_data['name'],
					'batch_name' => $payment_data['batch_name'],
					'batch_from' => $payment_data['b_from'],
					'batch_end' => $payment_data['b_end'],
					'received_by' => $payment_data['payment_recived_id'],
					'payment_method' => $payment_data['payment_method'],
					'course_id' => (isset($payment_data['course_id']) && !empty($payment_data['course_id'])) ? $payment_data['course_id'] : $payment_data['courseID'],

					'tdt'		=> date('Y-m-d H:i:s', strtotime($this->nepali_current_date)),
					'section_id' => $payment_data['section_id'],
					'payment_method' => $payment_data['payment_method'],
					'fine_amount'	=> $payment_data['fine_amount'],
					'deduction_type'	=> $payment_data['deduction_type'],
					'deduction_amount'	=> $payment_data['deduction_amount'],
					'bill_print_count'	=> $payment_data['bill_print_count'],
					'course_fee_id'		=> $payment_data['course_fee_id'],
					'install_sno'		=> $payment_data['install_sno'],
					'invoice_no'		=> $payment_data['invoice_no'],
					'parent_pan'		=> $student_ID->parent_pan
				);
				$data['invoice_data'] = $student_data;
			} else {
				$this->db->where('studentId', $studentID);
				$this->db->where('txn_id', $txnID);
				$this->db->set('bill_print_count', 'bill_print_count+1', FALSE);
				$update = $this->db->update('student_fee_online_transactions');
				$sql2 = "SELECT soft.*,course_fees.fee_values,a.name,a.course,b.b_name as batch_name,b.b_from,b.b_end, soft.invoice_no FROM student_fee_online_transactions soft LEFT JOIN applications a ON a.applicationid=soft.studentId LEFT JOIN batch b ON b.id=a.batch_id INNER JOIN course_fees ON sfot.course_fee_id = course_fees.id WHERE soft.studentId='$studentID' AND soft.txn_id='$txnID' order by sb.id desc";
				$paymentdata = $this->Admin_model->get_query_row($sql2);
				if (count($paymentdata) > 0) {
					$application_data = array(
						'student_fee_online_transactions_id' => $paymentdata['id'],
						'studentId' => $paymentdata['studentId'],
						'payment_for' => $paymentdata['fee_values'] . '(' . $paymentdata['payment_for'] . ')',
						'txn_id' => $paymentdata['txn_id'],
						'payment_amt' => $paymentdata['payment_amt'],
						'paid_date' => $paymentdata['payment_date'],
						'studentname' => $paymentdata['name'],
						'batch_name' => $paymentdata['batch_name'],
						'batch_from' => $paymentdata['b_from'],
						'batch_end' => $paymentdata['b_end'],
						'received_by' => $paymentdata['payment_recived_id'],
						'payment_method' => $paymentdata['payment_method'],
						'course_id' => $paymentdata['course'],
						'tdt'		=> date('Y-m-d H:i:s', strtotime($this->nepali_current_date)),
						'section_id' => 0,
						'payment_method' => $paymentdata['payment_method'],
						'fine_amount'	=> $paymentdata['fine_amount'],
						'deduction_type'	=> $paymentdata['deduction_type'],
						'deduction_amount'	=> $paymentdata['deduction_amount'],
						'bill_print_count'  => $paymentdata['bill_print_count'],
						'course_fee_id'		=> $paymentdata['course_fee_id'],
						'install_sno'		=> $paymentdata['install_sno'],
						'invoice_no'		=> $paymentdata['invoice_no'],
						'parent_pan'		=> $student_ID->parent_pan
					);
					$data['invoice_data'] = $application_data;
				}
			}
		}
		// $this->load->view('student/invoicepdf', $data);
		$html = $this->load->view('student/invoicepdf', $data, true);
		$pdfFilePath = $studentID . '-' . date('Y-m-dHis') . ".pdf";
		$pdf = $this->m_pdf->loadforinvoice();
		$pdf->WriteHTML($html, 2);
		$pdf->Output($pdfFilePath, "D");
	}

	//shankar code for batch wise route list

	public function routes_list_batch_wise()
	{
		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

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


		$data['menulist'] = $this->Student_model->get_studentMenus();

		$student_id = $_SESSION['student_id'];

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

		$busTrack = $this->load->database('erisnClassroom_bts', TRUE);

		$batch_wise_route = $busTrack->query('select route_ids from bt_batch_routes where batch_id=' . $get_student_batch['batch_id'])->row_array();

		$data_array = array();

		if (!empty($batch_wise_route)) {

			$bus_routes = $busTrack->query('select * from  bt_routes  where  id IN (' . $batch_wise_route['route_ids'] . ')')->result_array();

			if (!empty($bus_routes)) {
				foreach ($bus_routes as $key => $val) {
					$t_amount = $this->db->query('select amount from course_fees where route_id=' . $val['id'] . ' AND batch_id = ' . $get_student_batch['batch_id'] . ' AND course_id=' . $get_student_batch['course'])->row_array();

					array_push($data_array, array(
						'id' 			=> $val['id'],
						'route_name' 	=> $val['route_name'],
						'pickup_start'	=> $val['pickup_start'],
						'drop_start'	=> $val['drop_start'],
						'amount'		=> (!empty($t_amount) && isset($t_amount)) ? $t_amount['amount'] : '--',
						'color'			=> (!empty($t_amount) && isset($t_amount)) ? 'inherit' : 'red'
					));
				}
			}
		}
		$data['route_data'] = $data_array;
		$this->load->view('student/header', $data);
		$this->load->view('student/student-route-batch');
		$this->load->view('student/footer');
	}

	public function get_route_price_list()
	{
		$busTrack = $this->load->database('erisnClassroom_bts', TRUE);
		$batch_wise_route = $busTrack->query('select place_name from bt_routes_details where route_id=' . $_POST['route_id'] . ' ORDER BY route_order ASC')->result_array();
		if (!empty($batch_wise_route)) {
			echo json_encode($batch_wise_route);
		} else {
			echo json_encode('');
		}
	}

	public function hostel_old_function()
	{

		if (!isset($_SESSION['student_id']))
			redirect(base_url() . 'student');

		if (!file_exists(APPPATH . 'views/student/hostel.php'))
			show_404();

		$data['currentURL'] = current_url();
		$data['menulist'] = $this->Student_model->get_studentMenus();

		$hostel_status = $this->db->get_where('students', array('id' => $_SESSION['student_id']))->row()->hostel;

		if ($hostel_status == 'yes') {

			/*HOSTEL BED INFORMATION */

			$hmsDb = $this->load->database('hms', TRUE);

			$h_sql = "Select b.block_name,f.floor_name,r.room_name,r.room_ac,be.bed_name,s.food_type,
			s.joined_date from hms_students s 
			inner join hms_blocks b on s.block_id = b.id
			inner join hms_floors f on s.floor_id = f.id
			inner join hms_rooms r on s.room_id = r.id
			inner join hms_beds be on s.bed_id = be.id
			WHERE s.student_id = $_SESSION[student_id] 
			ORDER By s.id DESC ";

			$hostel_room_info =  $hmsDb->query($h_sql)->row_array();

			$data['hostel_room'] = $hostel_room_info;


			$this->load->view('student/header', $data);
			$this->load->view('student/hostel-info');
			$this->load->view('student/footer');
		} else {
			$this->load->view('student/header', $data);
			$this->load->view('student/hostel_old');
			$this->load->view('student/footer');
		}
	}

	public function printcount_increment()
	{
		$this->db->query('update student_fee_online_transactions set bill_print_count = bill_print_count + 1 where id =' . $_REQUEST['inoviceids']);
		return true;
	}
}