load->model('BustrackingAdmin_Model'); //Load the required helpers here $this->load->helper('common_helper'); $this->load->library('upload'); $this->nepaliDateObject = new NepaliDate(); $this->nepali_current_date = cuurentNepaliDate($this->nepaliDateObject); } public function is_valid_admin_emailid($eid) { $this->form_validation->set_message('is_valid_admin_emailid', 'This Email Id does not exist. Please check again.'); if($this->BustrackingAdmin_Model->check_is_emailid_valid($eid)) return true; else return false; } public function is_valid_admin_credentials() { $eid = $_POST['email']; $encrypt_password = md5($_POST['password']); $this->form_validation->set_message('is_valid_admin_credentials', 'Invalid password. Please check again.'); if($this->BustrackingAdmin_Model->check_login_credentials($eid, $encrypt_password)) return true; else return false; } public function login() { $data['title'] = 'Admin Login'; $this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_is_valid_admin_emailid'); $this->form_validation->set_rules('password', 'Password', 'required'); if(isset($_POST['password']) && $_POST['password']!='') $this->form_validation->set_rules('password', 'Password', 'callback_is_valid_admin_credentials'); if($this->form_validation->run() === FALSE){ $this->load->view('bustracking-admin/login', $data); } else { $encrypt_password = md5($this->input->post('password')); $where = 'email="'.$this->input->post('email').'" AND password="'.$encrypt_password.'"'; $loginData = $this->BustrackingAdmin_Model->get_admin_details($where); if(isset($loginData[0]) && !empty($loginData[0])) { if($loginData[0]['status']=='Active') { 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', ''); } } $lnData = array( 'bt_lin_id' => $loginData[0]['id'], 'bt_lin_name' => $loginData[0]['admin_name'], 'bt_lin_login' => true, ); $this->session->set_userdata('busAULoginData', $lnData); //Set Message $this->session->set_flashdata('success', 'Welcome To Admin Users Dashboard.'); $redirectToHere = 'dashboard'; $detailsHere = $this->BustrackingAdmin_Model->get_admin_details('', "SELECT admin_role_ids FROM bt_admin WHERE id = ".$loginData[0]['id']); if(isset($detailsHere[0]['admin_role_ids']) && $detailsHere[0]['admin_role_ids']!='') { $permissionDetailsHere = $this->BustrackingAdmin_Model->get_bt_admin_role_permissions('', "SELECT menu_ids FROM bt_admin_role_permissions WHERE admin_role_ids IN(".$detailsHere[0]['admin_role_ids'].")"); $menuIdsHere = explode(',', $permissionDetailsHere[0]['menu_ids']); if(!empty($menuIdsHere)) { $menuDetailsHere = $this->BustrackingAdmin_Model->get_admin_menu_details('', "SELECT page_link FROM bt_admin_menu WHERE id =".$menuIdsHere[0]); if(isset($menuDetailsHere[0]['page_link']) && $menuDetailsHere[0]['page_link']!='') $redirectToHere = $menuDetailsHere[0]['page_link']; } } redirect(base_url().$redirectToHere); } else{ $this->session->set_flashdata('danger', 'Your account is inactive. Please contact the administrator.'); $this->load->view('bustracking-admin/login', $data); } } else{ $this->session->set_flashdata('danger', 'Login Credential in invalid!'); $this->load->view('bustracking-admin/login', $data); } } } /*----------------------------------- SATRT Of Logout --------------------------------------------------------*/ public function logout() { $this->common_logout(); //Set Message $this->session->set_flashdata('success', 'You are logged out successfully.'); redirect(base_url().'admin'); } public function common_logout() { $lnEuIdId = 0; // unset the loggout admin user data $this->session->unset_userdata('busAULoginData'); } public function ajaxLogout() { $this->common_logout(); echo 'Success'; exit; } /*----------------------------------- ENDDD Of Logout --------------------------------------------------------*/ /*----------------------------- START of Admin User Password Functionality -----------------------------*/ public function fp_check_is_emailid_valid($eid) { $this->form_validation->set_message('fp_check_is_emailid_valid', 'This Email Id does not exist. Please check again.'); if($this->BustrackingAdmin_Model->check_is_emailid_valid($eid)) return true; else{ return false; } } public function forgot_password() { if (!file_exists(APPPATH.'views/bustracking-admin/forgot-password.php')) show_404(); $data['title'] = 'Forgot Password'; $this->form_validation->set_rules('email', 'email', 'required|valid_email|callback_fp_check_is_emailid_valid'); if($this->form_validation->run() === FALSE){ $this->load->view('bustracking-admin/forgot-password', $data); } else { $where = 'email="'.$this->input->post('email').'" '; $detailsHere = $this->BustrackingAdmin_Model->get_admin_details($where); $rpData['nameHere'] = ''; if(isset($detailsHere[0]['admin_name'])) $rpData['nameHere'] = $detailsHere[0]['admin_name']; $rpData['emailId'] = urlsafe_b64encode($this->input->post('email')); $emailContent = $this->load->view('bustracking-admin/emails/admin-user-forgot-password.php', $rpData, TRUE); $emailData['to'] = $this->input->post('email'); $emailData['subject'] = 'Erisn Classroom Bustracking - Admin User Password Recovery Mail'; $emailData['message'] = $emailContent; //echo $emailContent;exit; $result = ciSendEmail($emailData); $this->session->set_userdata('isForgotPasswordSuccess', 'Yes'); $this->load->view('bustracking-admin/forgot-password', $data); } } function reset_password($encodedEmailId) { if(isset($encodedEmailId) && $encodedEmailId!='') { $decodedEmailId = urlsafe_b64decode($encodedEmailId); $data['encodedEmailId'] = $encodedEmailId; $data['title'] = 'Reset Password'; $this->form_validation->set_rules('password', 'Enter New Password', 'trim|required'); $this->form_validation->set_rules('conf_password', 'Retype New Password', 'required|matches[password]'); if($this->form_validation->run() === FALSE) { $this->load->view('bustracking-admin/reset-password', $data); } else { $where = 'email ="'.$decodedEmailId.'"'; $isValidUser = $this->BustrackingAdmin_Model->get_admin_details($where); if(!empty($isValidUser) && count($isValidUser)==1) { $this->BustrackingAdmin_Model->reset_admin_password($isValidUser[0]['id'], $this->input->post('password')); //Set Message $this->session->set_userdata('isResetPasswordSuccess', 'Yes'); redirect('reset-password/'.$encodedEmailId); } else{ $this->session->set_flashdata('danger', 'OOps. Something went wrong.'); redirect('reset-password/'.$encodedEmailId); } } } else { redirect(base_url()."admin"); } } /*----------------------------- ENDDD of Admin User Password Functionality -----------------------------*/ public function dashboard() { $data['title'] = 'Dashboard'; $data['driver_count'] = $this->BustrackingAdmin_Model->count_query('bt_drivers'); $data['bus_count'] = $this->BustrackingAdmin_Model->count_query('bt_buses'); $data['student_count'] = $this->BustrackingAdmin_Model->count_query('bt_students_bus_route_details'); $query = $this->db->query('select * from bt_routes'); $data['route_name'] = $query->result_array(); $this->load->view('bustracking-admin/common/left-menu', $data); $this->load->view('bustracking-admin/common/header', $data); $this->load->view('bustracking-admin/dashboard', $data); //$ecDB = $this->load->database('erisnClassroom', TRUE); //$CI = &get_instance(); //$ecDB = $CI->load->database('erisnClassroom', TRUE); //$qry = $ecDB->query("SELECT id,name,email FROM students"); //echo '
'; print_r($qry->result());
		//exit;
	}
	
	/*----------------------------------- START Of Admin Roles --------------------------------------------------------*/
	public function roles()
	{
		$data['title'] = 'Roles';
		
		$sqlRole = 'SELECT r.*, rp.menu_ids FROM bt_admin_roles AS r, bt_admin_role_permissions AS rp WHERE r.id = rp.admin_role_ids';
		$rolesList = $this->BustrackingAdmin_Model->get_bt_admin_roles('', $sqlRole);		
		if(!empty($rolesList))
		{
			foreach($rolesList as $key=>$role)
			{
				$rPs = '';
				$sqlRolePermissions = 'SELECT menu_name FROM bt_admin_menu WHERE id IN('.$role['menu_ids'].')';
				$rolePermissions = $this->BustrackingAdmin_Model->get_bt_admin_roles('', $sqlRolePermissions);
				if(!empty($rolePermissions))
				{
					foreach($rolePermissions as $p)
					{
						if($rPs=='')
							$rPs = $p['menu_name'];
						else
							$rPs .= ','.$p['menu_name'];
					}
				}				
				$rolesList[$key]['permissions'] = $rPs;
			}
		}
		$data['roleList'] = $rolesList;
		//echo '
'; print_r($data['roleList']);exit;
		
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/roles', $data);
	}
	
	public function ajaxCheckIsRoleAlreadyExists()
	{
		$result = 'Insufficient Data';
		if(isset($_POST['role_name']) && $_POST['role_name']!='' && isset($_POST['id']) && $_POST['id']!='')
		{
			if($this->BustrackingAdmin_Model->check_role_exists($_POST['id'], $_POST['role_name']))
				$result = 'Unique Role';
			else
				$result = 'Duplicate Role';
		}
		echo $result;
		exit;
	}
	
	public function add_edit_role($idVal)
	{
		$sql = "SELECT * FROM bt_admin_roles WHERE id = $idVal";
		$details = $this->BustrackingAdmin_Model->get_bt_admin_roles("id = $idVal");
		if (empty($details) && $idVal != 0)
			redirect(base_url().'roles');
		
		$data['title'] = 'Add New Role';
		if($idVal > 0)
			$data['title'] = 'Update Role';
			
		$data['details'] = $details;
		$data['idVal'] = $idVal;
		$data['menus'] = $this->BustrackingAdmin_Model->get_admin_menu_details('', 'SELECT id,menu_name FROM bt_admin_menu WHERE status="Active" AND parent_id=0');
		$data['role_permissions'] = $this->BustrackingAdmin_Model->get_bt_admin_role_permissions('', "SELECT menu_ids FROM bt_admin_role_permissions WHERE admin_role_ids = $idVal");
		
		if(count($_POST) > 0)
		{
			$permissions = '';
			if(isset($_POST['role_permissions']) && !empty($_POST['role_permissions']))
			{
				$permissions = implode(',', $_POST['role_permissions']);
				unset($_POST['role_permissions']);
			}
			
			$res = $this->BustrackingAdmin_Model->add_edit_admin_role($idVal, $_POST);
			if($res)
			{
				if($permissions!='')
				{
					if($idVal == 0)
					{
						$rpData['admin_role_ids'] = $res;
						$rpData['menu_ids'] = $permissions;
						$this->BustrackingAdmin_Model->add_edit_admin_role_permissions(0, $rpData);
					}
					else
					{
						$getRPrid = $this->BustrackingAdmin_Model->get_bt_admin_role_permissions('', "SELECT id FROM bt_admin_role_permissions WHERE admin_role_ids = $idVal");
						if(isset($getRPrid[0]['id']))
						{
							$rpData['admin_role_ids'] = $idVal;
							$rpData['menu_ids'] = $permissions;
							$this->BustrackingAdmin_Model->add_edit_admin_role_permissions($getRPrid[0]['id'], $rpData);
						}
					}
				}
				$this->session->set_flashdata('success', str_replace('%s', 'new role', THE_ADD_SUCCESS_MSG));
				if ($idVal > 0)
					$this->session->set_flashdata('success', str_replace('%s', 'role', THE_UPDATE_SUCCESS_MSG));
			}
			redirect(base_url().'roles');
		}
		
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-role', $data);
	}
	
	public function delete_role()
	{
		$roleId = $_POST['id'];
		$sql = "SELECT id FROM bt_admin WHERE admin_role_ids=".$roleId;
		$result = $this->BustrackingAdmin_Model->get_admin_details('', $sql);
		//echo '
'; print_r($result);exit;
		if(!empty($result))
			echo 'Error';
		else
		{
			$this->BustrackingAdmin_Model->delete_admin_role($roleId);			
			echo 'Success';
		}	
	}
	/*----------------------------------- ENDDD Of Admin Roles --------------------------------------------------------*/
	
	/*----------------------------------- START Of Admin Users --------------------------------------------------------*/
	public function users()
	{
		$data['title'] = 'Users';
		
		$sql = 'SELECT a.*, ar.role_name FROM bt_admin AS a, bt_admin_roles AS ar WHERE a.admin_role_ids = ar.id';
		$data['userList'] = $this->BustrackingAdmin_Model->get_admin_details('', $sql);
		
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/users', $data);
	}
	
	public function ajaxCheckIsUserEmailAlreadyExists()
	{
		$result = 'Insufficient Data';
		if(isset($_POST['email']) && $_POST['email']!='' && isset($_POST['id']) && $_POST['id']!='')
		{
			if($this->BustrackingAdmin_Model->check_emailid_exists($_POST['id'], $_POST['email']))
				$result = 'Unique Email';
			else
				$result = 'Duplicate Email';
		}
		echo $result;
		exit;
	}
	
	public function add_edit_user($idVal)
	{
		$sql = "SELECT * FROM bt_admin WHERE id = $idVal";
		$details = $this->BustrackingAdmin_Model->get_admin_details("id = $idVal");
		if (empty($details) && $idVal != 0)
			redirect(base_url().'users');
		
		$data['title'] = 'Add New User';
		if($idVal > 0)
			$data['title'] = 'Update User';
			
		$data['details'] = $details;
		$data['idVal'] = $idVal;
		$data['roles'] = $this->BustrackingAdmin_Model->get_bt_admin_roles('', 'SELECT id,role_name FROM bt_admin_roles WHERE status="Active"');
		
		if(count($_POST) > 0)
		{
			if(isset($_POST['password']))
				$_POST['password'] = md5($_POST['password']);
			if(isset($_POST['confirm_password']))
				unset($_POST['confirm_password']);
			
			$res = $this->BustrackingAdmin_Model->add_edit_admin_user($idVal, $_POST);
			
			$this->session->set_flashdata('success', str_replace('%s', 'new user', THE_ADD_SUCCESS_MSG));
			if ($idVal > 0)
				$this->session->set_flashdata('success', str_replace('%s', 'user', THE_UPDATE_SUCCESS_MSG));
			
			redirect(base_url().'users');
		}
		
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-user', $data);
	}
	
	public function delete_user()
	{
		$userId = $_POST['id'];
		$result = $this->BustrackingAdmin_Model->delete_admin_user($userId);
		if($result)
			echo 'Success';
		else
			echo 'Error';
	}
	/*----------------------------------- ENDDD Of Admin Users --------------------------------------------------------*/

	/*----------Add Bus Code start here from Shankar--------------------------*/

	public function bus_list($id='')
	{
		$query_bus_list = $this->db->query('select * from bt_buses');
		$data['result'] = $query_bus_list->result_array();
		if ($id == '1') {
			$this->session->set_flashdata('success', "The bus has been deleted successfully");
		}else if($id == '0'){
			$this->session->set_flashdata('failed', "Bus has been assign to Student Bus Route you can't Delete "); 
		}
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/buses_list', $data);

	}

	public function viewBus($id)
	{
		if ($id > 0) {
			$query_bus_list = $this->db->query('select * from bt_buses where id='.$id);
			$data['result'] = $query_bus_list->row_array();
			
			$this->load->view('bustracking-admin/common/left-menu', $data);
			$this->load->view('bustracking-admin/common/header', $data);
			$this->load->view('bustracking-admin/view-bus', $data);
		}
	}

	public function bus_add_edit($id)
	{
		$data['title'] = 'Add Bus';
		if($id > 0)
			$data['title'] = 'Update Bus';

		$data['bus_id'] = $id;

		$data['detailsHere'] = $this->BustrackingAdmin_Model->get_admin_details('', "SELECT * FROM bt_buses WHERE id = ".$id);

		if (isset($_POST['submit'])) {				
			
			if ($_POST['bus_id'] == 0) {
				$das = array();
				if (!empty($_FILES['file']['name'])) {					
					$profile_image='';
					$temp = explode(".", $_FILES["file"]["name"]);
					$newfilename = date("mdYHis") . '.' . end($temp);
					
					$output = '';
					$config['upload_path'] = 'assets-bustracking/images/bus_image/';
					$config['allowed_types'] = 'gif|jpg|png|JPG';

					$this->load->library('upload', $config);
					$this->upload->initialize($config); //initialize upload library
					
					$_FILES["file"]["name"] = $newfilename;
					$_FILES["file"]["type"] = $_FILES["file"]["type"];
					$_FILES["file"]["tmp_name"] = $_FILES["file"]["tmp_name"];
					$_FILES["file"]["error"] = $_FILES["file"]["error"];
					$_FILES["file"]["size"] = $_FILES["file"]["size"];
					if ($this->upload->do_upload('file')) {
						$data = $this->upload->data();
						$profile_image = 'assets-bustracking/images/bus_image/' . $data["file_name"];
					}else{
						$this->upload->display_errors();
					}
					
					
				}					
					
				$data_array = array(
					'reg_no'	=> $_POST['reg_no'],
					'bus_brand'	=> $_POST['brand'], 
					'seats'		=> $_POST['seat'],	
					'year'		=> $_POST['year'],
					'image'		=> $profile_image
				);

				$this->db->insert('bt_buses', $data_array);
				$last_id = $this->db->insert_id();
				if ($last_id > 0) {
					$this->session->set_flashdata('success', str_replace('%s', 'Bus', THE_ADD_SUCCESS_MSG));
					redirect(base_url() . 'buses');

				}else{
					$this->session->set_flashdata('failed', str_replace('%s', 'Bus', THE_ADD_ERROR_MSG));
					redirect(base_url() . 'buses');
				}
			}else{
				
				if (!empty($_FILES['file']['name'])) {					

					$get_data = $this->db->query('select image from bt_buses where id='.$_POST['bus_id']);
					$delete_image = $get_data->row_array();

					if ($delete_image) {
						if (file_exists($delete_image['image'])) {
							unlink($delete_image['image']);							
						}
						
					}

					$temp = explode(".", $_FILES["file"]["name"]);
					$newfilename = date("mdYHis") . '.' . end($temp);
					// move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
					// $config['upload_path']   = 'assets_bustracking/images/bus_image/';
					$output = '';
					$config['upload_path'] = 'assets-bustracking/images/bus_image/';
					$config['allowed_types'] = 'gif|jpg|png|JPG';

					$this->load->library('upload', $config);
					$this->upload->initialize($config); //initialize upload library
					
					$_FILES["file"]["name"] = $newfilename;
					$_FILES["file"]["type"] = $_FILES["file"]["type"];
					$_FILES["file"]["tmp_name"] = $_FILES["file"]["tmp_name"];
					$_FILES["file"]["error"] = $_FILES["file"]["error"];
					$_FILES["file"]["size"] = $_FILES["file"]["size"];
					if ($this->upload->do_upload('file')) {
						$data = $this->upload->data();
						$profile_image = 'assets-bustracking/images/bus_image/' . $data["file_name"];
					}else{
						$this->upload->display_errors();
					}
					
					
				}

				$data_array = array(
					'reg_no'	=> $_POST['reg_no'],
					'bus_brand'	=> $_POST['brand'], 
					'seats'		=> $_POST['seat'],	
					'year'		=> $_POST['year']
				);
				
				if(isset($profile_image) && !empty($profile_image)){
					$data_array['image'] = $profile_image;
				}
				
				$this->db->where('id',$_POST['bus_id']);
				$this->db->update('bt_buses', $data_array);
				
				if ($this->db->affected_rows() > 0) {
					$this->session->set_flashdata('success', str_replace('%s', 'Bus', THE_UPDATE_SUCCESS_MSG));
					redirect(base_url() . 'buses');

				}else{
					$this->session->set_flashdata('failed', 'You have Not changed anything');
					redirect(base_url() . 'buses');
				}
				

			}
		}

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-bus', $data);


	}

	public function deleteBus()
	{	
		$id = $_POST['id'];
		$table = $_POST['table'];
		$data = $this->BustrackingAdmin_Model->delete_bus($id, $table);
		print_r($data);
	}

	// Driver Module Start Here

	public function viewDriver($id='')
	{
		if ($id > 0) {
			$query_bus_list = $this->db->query('select * from bt_drivers where id='.$id);
			$data['result'] = $query_bus_list->row_array();
			
			$this->load->view('bustracking-admin/common/left-menu', $data);
			$this->load->view('bustracking-admin/common/header', $data);
			$this->load->view('bustracking-admin/view-driver', $data);
		}
	}


	public function drivers_list($id='')
	{
		$query_bus_list = $this->db->query('select * from bt_drivers');
		$data['result'] = $query_bus_list->result_array();
		if ($id == '1') {
			$this->session->set_flashdata('success', "The Driver has been deleted successfully");
		}else if($id == '0'){
			$this->session->set_flashdata('failed', "Driver has been assign to Bus Route you can't Delete "); 
		}
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/drivers_list', $data);

	}

	public function driver_add_edit($id)
	{
		$data['title'] = 'Add Driver';
		if($id > 0)
			$data['title'] = 'Update Driver';

		$data['driver_id'] = $id;

		$data['detailsHere'] = $this->BustrackingAdmin_Model->get_admin_details('', "SELECT * FROM bt_drivers WHERE id = ".$id);

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

			if ($_POST['driver_id'] == 0) {
				$image1=$document1=$document2=$document3=$temp='';
				$temp = explode(".", $_FILES["image"]["name"]);
				$newfilename = date("mdYHis") . '.' . end($temp);

				$tempdoc1 = explode(".", $_FILES["doc1"]["name"]);
				$doc_one = date("mdYHisv") . '.' . end($tempdoc1);

				$tempdoc2 = explode(".", $_FILES["doc2"]["name"]);
				$doc_two = date("mdYHisv") . '.' . end($tempdoc2);

				$tempdoc3 = explode(".", $_FILES["doc3"]["name"]);
				$doc_three = date("mdYHisv") . '.' . end($tempdoc3);
				
				$output = '';
				$config['upload_path'] = 'assets-bustracking/images/driver_images/';
				$config['allowed_types'] = 'gif|jpg|png|JPG|pdf';

				$this->load->library('upload', $config);
				$this->upload->initialize($config); //initialize upload library
				
				$_FILES["image"]["name"] = $newfilename;

				$_FILES["doc1"]["name"] = $doc_one;
				$_FILES["doc2"]["name"] = $doc_two;
				$_FILES["doc3"]["name"] = $doc_three;
				
				if ($this->upload->do_upload('image')) {
					$data = $this->upload->data();
					$image1 = 'assets-bustracking/images/driver_images/' . $data["file_name"];
				}

				if ($this->upload->do_upload('doc1')) {
					$data = $this->upload->data();
					$document1 = 'assets-bustracking/images/driver_images/' . $data["file_name"];
				}

				if ($this->upload->do_upload('doc2')) {
					$data = $this->upload->data();
					$document2 = 'assets-bustracking/images/driver_images/' . $data["file_name"];
				}

				if ($this->upload->do_upload('doc3')) {
					$data = $this->upload->data();
					$document3 = 'assets-bustracking/images/driver_images/' . $data["file_name"];
				}
				
					
				$data_array = array(
					'name'				=> $_POST['first_name'] . ' ' . $_POST['last_name'],
					'licence'			=> $_POST['licence'], 
					'dob'				=> $_POST['dob'],	
					'contact_number'	=> $_POST['contact'],
					'address'			=> $_POST['address'],	
					'image'				=> $image1,
					'document1'			=> $document1,
					'document2'			=> $document2,
					'document3'			=> $document3,
					'driver_id'			=> generate_driver_id(),
					'password'			=> md5($_POST['password'])
				);

				$this->db->insert('bt_drivers', $data_array);
				$last_id = $this->db->insert_id();
				if ($last_id > 0) {
					$this->session->set_flashdata('success', str_replace('%s', 'Driver', THE_ADD_SUCCESS_MSG));
					redirect(base_url() . 'drivers');

				}else{
					$this->session->set_flashdata('failed', str_replace('%s', 'Driver', THE_ADD_ERROR_MSG));
					redirect(base_url() . 'drivers');
				}
			}else{

				$get_data = $this->db->query('select * from bt_drivers where id='.$_POST['driver_id']);
					$delete_image = $get_data->row_array();

				$data_array = array(
					'name'				=> $_POST['first_name'] . ' ' . $_POST['last_name'],
					'licence'			=> $_POST['licence'], 
					'dob'				=> $_POST['dob'],	
					'contact_number'	=> $_POST['contact'],
					'address'			=> $_POST['address'],
					'password'			=> md5($_POST['password']),
				);

				$output = '';
				$config['upload_path'] = 'assets-bustracking/images/driver_images/';
				$config['allowed_types'] = 'gif|jpg|png|JPG|pdf';

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

				if (!empty($_FILES['image']['name'])) {
					if (file_exists($delete_image['image'])) {
							unlink($delete_image['image']);
					
						$temp = explode(".", $_FILES["image"]["name"]);
						$newfilename = date("mdYHis") . '.' . end($temp);
						$_FILES["image"]["name"] = $newfilename;

						if ($this->upload->do_upload('image')) {
							$data = $this->upload->data();
							$data_array['image'] = 'assets-bustracking/images/driver_images/' . $data["file_name"];
						}
					}

				}

				if (!empty($_FILES['doc1']['name'])) {
					if (file_exists($delete_image['document1'])) {
							unlink($delete_image['document1']);
					
						$tempdoc1 = explode(".", $_FILES["doc1"]["name"]);
						$doc_one = date("mdYHisv") . '.' . end($tempdoc1);
						$_FILES["doc1"]["name"] = $doc_one;
						if ($this->upload->do_upload('doc1')) {
							$data = $this->upload->data();
							$data_array['document1'] = 'assets-bustracking/images/driver_images/' . $data["file_name"];
						}
					}	

				}

				if (!empty($_FILES['doc2']['name'])) {
					if (file_exists($delete_image['document2'])) {
							unlink($delete_image['document2']);
					
						$tempdoc2 = explode(".", $_FILES["doc2"]["name"]);
						$doc_two = date("mdYHisv") . '.' . end($tempdoc2);
						$_FILES["doc2"]["name"] = $doc_two;
						if ($this->upload->do_upload('doc2')) {
							$data = $this->upload->data();
							$data_array['document2'] = 'assets-bustracking/images/driver_images/' . $data["file_name"];
						}
					}
				}

				if (!empty($_FILES['doc3']['name'])) {
					if (file_exists($delete_image['document3'])) {
							unlink($delete_image['document3']);						
					
						$tempdoc3 = explode(".", $_FILES["doc3"]["name"]);
						$doc_three = date("mdYHisv") . '.' . end($tempdoc3);
						$_FILES["doc3"]["name"] = $doc_three;

						if ($this->upload->do_upload('doc3')) {
							$data = $this->upload->data();
							$data_array['document3'] = 'assets-bustracking/images/driver_images/' . $data["file_name"];
						}
					}
				}	
				
				
				$this->db->where('id',$_POST['driver_id']);
				$this->db->update('bt_drivers', $data_array);
				
				if ($this->db->affected_rows() > 0) {
					$this->session->set_flashdata('success', str_replace('%s', 'Driver', THE_UPDATE_SUCCESS_MSG));
					redirect(base_url() . 'drivers');

				}else{
					$this->session->set_flashdata('failed', "You Have Not Updated Anything");
					redirect(base_url() . 'drivers');
				}
				

			}
		}

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-driver', $data);


	}

	public function deleteDriver()
	{	
		$id = $_POST['id'];
		$table = $_POST['table'];
		$data = $this->BustrackingAdmin_Model->delete_driver($id, $table);
		print_r($data);
	}


	//  Routes Module Start Here

	public function viewRoute($id)
	{
		if ($id > 0) {
			$query_bus_list = $this->db->query('select r.id as id,rd.id as details_id, route_name, latitude,longitude,d.id as driver_id, d.name as driver_name,b.id as bus_id,place_name,stops,working_id,pickup_start,drop_start, bus_brand as bus_name,stops from bt_routes r, bt_routes_details rd, bt_drivers d, bt_buses b where r.id='. $id .' and r.id = rd.route_id and r.bus_id = b.id and r.driver_id = d.id order by rd.route_order');
			$data['result'] = $query_bus_list->result_array();
			
			$this->load->view('bustracking-admin/common/left-menu', $data);
			$this->load->view('bustracking-admin/common/header', $data);
			$this->load->view('bustracking-admin/view-route-details', $data);
		}
	}


	public function routes_list($id)
	{
		$query_bus_list = $this->db->query('select r.id as id, route_name, latitude,longitude,d.name as driver_name,bus_brand as bus_name,stops from bt_routes r, bt_routes_details rd, bt_drivers d, bt_buses b where r.id = rd.route_id and r.bus_id = b.id and r.driver_id = d.id GROUP BY r.id');
		$data['result'] = $query_bus_list->result_array();
		if ($id == '1') {
			$this->session->set_flashdata('success', "The Route has been deleted successfully");
		}else if($id == '0'){
			$this->session->set_flashdata('failed', "Route is assign to Student Route you can't Delete "); 
		}
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/routes-lists', $data);

	}

	public function route_add_edit($id)
	{
		$data['title'] = 'Add New Route';
		if($id > 0)
			$data['title'] = 'Update Route';

		$data['route_id'] = $id;

		$data['detailsHere'] = $this->BustrackingAdmin_Model->get_admin_details('', "select r.id as id,rd.id as details_id, route_name, latitude,longitude,d.id as driver_id, d.name as driver_name,b.id as bus_id,place_name,stops,working_id,pickup_start,drop_start, bus_brand as bus_name,stops from bt_routes r, bt_routes_details rd, bt_drivers d, bt_buses b where r.id=". $id .' and r.id = rd.route_id and r.bus_id = b.id and r.driver_id = d.id order by rd.route_order');

		$data['driver_data'] = $this->BustrackingAdmin_Model->get_admin_details('', "SELECT id,name FROM bt_drivers ");
		$data['bus_data']	= $this->BustrackingAdmin_Model->get_admin_details('', "SELECT id,bus_brand FROM bt_buses");

		$data['weekDays']	= getDayList_E();

		if (isset($_POST['submit'])) {				
			// echo"
";print_r($_POST);
			// print_r(implode(",", $_POST['working_day']));
			// exit();
			if ($id == 0) {	

				$data_array = array(
					'route_name'	=> $_POST['name'],
					'bus_id'		=> $_POST['bus'], 
					'driver_id'		=> $_POST['driver'],	
					'working_id'	=> implode(",", $_POST['working_day']),
					'stops'			=> $_POST['stops'],	
					'pickup_start'	=> $_POST['pictime'],
					'drop_start'	=> $_POST['droptime'],
					'created'		=> date('Y-m-d H:i:s')						
				);

				$this->db->insert('bt_routes', $data_array);
				$last_id = $this->db->insert_id();
				if ($last_id > 0) {
					for ($i=1; $i <= count($_POST['ro_det_id']) ; $i++) { 						
						
						$route_data = array(
							'route_id'		=> $last_id,
							'latitude'		=> $_POST['latitude'][$i],
							'longitude'		=> $_POST['longitude'][$i],
							'place_name'  	=> $_POST['placeName'][$i],
							'route_order' 	=> $_POST['conter'][$i],
							'created'		=> date('Y-m-d H:i:s') 
						);
						$this->db->insert('bt_routes_details', $route_data);
						$id_route_list = $this->db->insert_id();
					}

					if ($id_route_list) {
						$this->session->set_flashdata('success', str_replace('%s', 'Route', THE_ADD_SUCCESS_MSG));
						redirect(base_url() . 'routes');
					}else{
						$this->session->set_flashdata('failed', str_replace('%s', 'Route', THE_ADD_ERROR_MSG));
						redirect(base_url() . 'routes');
					}						

				}else{
					$this->session->set_flashdata('failed', str_replace('%s', 'Route', THE_ADD_ERROR_MSG));
						redirect(base_url() . 'routes');
				}
			}else{

				$flash_message = 0;
				$data_array = array(
					'route_name'		=> $_POST['name'],
					'bus_id'			=> $_POST['bus'], 
					'driver_id'			=> $_POST['driver'],	
					'working_id'		=> implode(",", $_POST['working_day']),
					'stops'				=> $_POST['stops'],
					'pickup_start'		=> $_POST['pictime'],
					'drop_start'		=> $_POST['droptime'],
				);
							
				
				$this->db->where('id',$_POST['route_id']);
				$this->db->update('bt_routes', $data_array);
				$this->db->trans_complete();

				if($this->db->trans_status() === FALSE)
				{
				    
				}
				else
				{
					if($this->db->affected_rows() > 0)
    				{
    					

    					for ($i=1; $i <= count($_POST['ro_det_id']); $i++) { 
    						
    						$data_update = array(
								'place_name'	=> $_POST['placeName'][$i],
								'latitude'		=> $_POST['latitude'][$i],
								'longitude'		=> $_POST['longitude'][$i],
								'route_order'	=> $_POST['conter'][$i],
								'route_id'		=> $_POST['route_id'],
								'modified'		=> date('Y-m-d H:i:s')
							);

							if (empty($_POST['ro_det_id'][$i])) {

								$this->db->insert('bt_routes_details', $data_update);
								$id_route_list = $this->db->insert_id();
								$flash_message = 1;

							}else{

								$this->db->where('id',$_POST['ro_det_id'][$i]);
								$this->db->update('bt_routes_details', $data_update);
								$this->db->trans_complete();
							}
								

							if($this->db->affected_rows() > 0){
								$flash_message = 1;
							}else{

							}

    					}
    					
    				}else{
    					
    					for ($i=1; $i <= count($_POST['ro_det_id']); $i++) { 
    						
    						$data_update = array(
								'place_name'	=> $_POST['placeName'][$i],
								'latitude'		=> $_POST['latitude'][$i],
								'longitude'		=> $_POST['longitude'][$i],
								'route_order'	=> $_POST['conter'][$i],
								'route_id'		=> $_POST['route_id'],
								'modified'		=> date('Y-m-d H:i:s')
							);

							if (empty($_POST['ro_det_id'][$i])) {

								$this->db->insert('bt_routes_details', $data_update);
								$id_route_list = $this->db->insert_id();
								$flash_message = 1;

							}else{

								$this->db->where('id',$_POST['ro_det_id'][$i]);
								$this->db->update('bt_routes_details', $data_update);
								$this->db->trans_complete();
							}
								

							if($this->db->affected_rows() > 0){
								$flash_message = 1;
							}else{

							}

    					}
    				}
				}
				
				
				if ($flash_message > 0) {
					$this->session->set_flashdata('success', str_replace('%s', 'Route', THE_UPDATE_SUCCESS_MSG));
					redirect(base_url() . 'routes');

				}else{
					$this->session->set_flashdata('success', str_replace('%s', "Route's", THE_UPDATE_SUCCESS_MSG));
					redirect(base_url() . 'routes');
				}				

			}
		}

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-routes_test', $data);


	}

	public function deleteRoute()
	{	
		$id = $_POST['id'];
		$table = $_POST['table'];
		$data = $this->BustrackingAdmin_Model->check_delete_route($id, $table);
		print_r($data);
	}

	public function delete_Route_Row()
	{	

		$check_delete = $this->BustrackingAdmin_Model->check_delete_route($_POST['route_id'],$_POST['detail_id']);
		// echo $route_id;
		// $data = array('route_id'=>$route_id, 'details_id'=> $route_detail_id);
		// echo json_encode($data);
	}	

	/*----------Add Bus Code  End  here from Shankar--------------------------*/

	// dashboard get route data

	public function route_details_data($id)
	{
		
		echo json_encode($this->BustrackingAdmin_Model->get_admin_details('', "select route_name,latitude,longitude,place_name,pickup_start,drop_start from bt_routes r, bt_routes_details rd, bt_drivers d, bt_buses b where r.id=". $id .' and r.id = rd.route_id and r.bus_id = b.id and r.driver_id = d.id order by rd.route_order'));

	}

	public function student_list($id='')
	{
		$query1 = $this->db->query('select brd.place_name, student_id, sbrd.id  from bt_students_bus_route_details sbrd, bt_routes br, bt_routes_details brd where sbrd.route_id = br.id and sbrd.pick_up_id = brd.id')->result_array();

		if ($id == '1') {
			$this->session->set_flashdata('success', "The Student has been deleted successfully");
		}else if($id == '0'){
			$this->session->set_flashdata('danger', "Student is assign to Bus Route you can't Delete "); 
		}

		$details = array();
		if (count($query1) > 0) {
			$erisndb = $this->load->database('classroom', TRUE);
			foreach($query1 as $key => $value)
			{
				$query = $erisndb->query('select name, classroom_name, studentId, mobile from students s, student_batch sb, classroom c where s.id ='. $value['student_id'] . ' and s.id = sb.student_id and sb.classroom_id = c.id')->row_array();
				if (!empty($query)) {
					array_push($details, array(
						'id'			=> $value['id'],
						'student_id'	=> $query['studentId'],
						'student_name'	=> $query['name'],
						'stop_name'		=> $value['place_name'],
						'class_name'	=> $query['classroom_name'],
						'contact_no'	=> $query['mobile']
					));
				}
			}

		}

		$data['student_list'] = $details;		
			
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/students', $data);
	}

	public function student_view_info($id)
	{
		
		$route_data = $this->db->query('
			select br.id as route_id, student_id, bb.reg_no as bus_no, route_name, place_name as drop_point 
			from bt_students_bus_route_details sbrd, bt_routes br,bt_buses bb, bt_routes_details brd 
			where sbrd.id ='.$id .' and sbrd.route_id = br.id and sbrd.drop_id = brd.id and br.bus_id = bb.id')->row_array();

		if (count($route_data) > 0) {
			$erisndb = $this->load->database('classroom', TRUE);			
			
			$data['student_details'] = $erisndb->query('
				select s.studentId,s.photo, s.name as student_name, s.email,s.mobile,s.dob, s.gender,s.address1, c.classroom_name, cf.amount as bus_fee_total , sop.payment_details
				from students s, student_batch sb, classroom c, students_online_payments sop, course_fees cf
				where s.id = '.$route_data['student_id'].' and s.batch_id = sb.batch_id and sb.student_id = s.id and sb.classroom_id = c.id and sop.student_id = s.id and sop.course_fee_id = cf.id 
				')->row_array();
		
		}
		$data['route_data'] = $route_data;
		$data['route_details'] = $this->db->query('select brd.place_name, brd.id , sbrd.id as student_list_id from bt_routes_details brd, bt_routes br , bt_students_bus_route_details sbrd where sbrd.id ='. $id . ' and sbrd.route_id = brd.route_id group by brd.id')->result_array();
		
		$data['route_name'] = $this->db->query('select id as route_id, route_name from bt_routes')->result_array();
		$data['update'] = '';
		// echo"
";print_r($data);exit();
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/student-info', $data);
	}

	public function student_edit_info($id)
	{
		$route_data = $this->db->query('
			select br.id as route_id, student_id, bb.reg_no as bus_no, route_name, place_name as drop_point 
			from bt_students_bus_route_details sbrd, bt_routes br,bt_buses bb, bt_routes_details brd 
			where sbrd.id ='.$id .' and sbrd.route_id = br.id and sbrd.drop_id = brd.id and br.bus_id = bb.id')->row_array();

		if (count($route_data) > 0) {
			$erisndb = $this->load->database('classroom', TRUE);			
			
			$data['student_details'] = $erisndb->query('
				select s.studentId,s.photo, s.name as student_name, s.email,s.mobile,s.dob, s.gender,s.address1, c.classroom_name, cf.amount as bus_fee_total , sop.payment_details
				from students s, student_batch sb, classroom c, students_online_payments sop, course_fees cf
				where s.id = '.$route_data['student_id'].' and s.batch_id = sb.batch_id and sb.student_id = s.id and sb.classroom_id = c.id and sop.student_id = s.id and sop.course_fee_id = cf.id 
				')->row_array();
		
		}
		$data['route_data'] = $route_data;

		$data['route_details'] = $this->db->query('select brd.place_name, brd.id , sbrd.id as student_list_id from bt_routes_details brd, bt_routes br , bt_students_bus_route_details sbrd where sbrd.id ='. $id . ' and sbrd.route_id = brd.route_id group by brd.id')->result_array();
		$data['update'] = 1;
		$data['route_name'] = $this->db->query('select id as route_id, route_name from bt_routes')->result_array();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/student-info', $data);
	}

	public function student_update_info()
	{		
			$data = array(
				'route_id'	=> $_POST['route_id'],
				'pick_up_id' => $_POST['stop_id'],
				'drop_id'	 => $_POST['stop_id']
			);
			$this->db->where('id', $_POST['id']);

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

		redirect(base_url() . 'students');

	}

	public function deleteStudent()
	{	
		// $id = $_POST['id'];
		// $table = $_POST['table'];
		// $data = $this->BustrackingAdmin_Model->delete_driver($id, $table);
		print_r(0);
	}

	public function trips()
	{
		$find_date = date('Y-m-d', strtotime($this->nepali_current_date));
		if ($_POST) {
			$find_date = $_POST['search_date'];
		}
		$search = $this->db->query('select br.id as route_id, bd.id as driver_id, stops, route_name, bd.name as driver_name,reg_no from bt_routes br, bt_drivers bd, bt_buses bb where br.driver_id = bd.id and br.bus_id = bb.id')->result_array();
		$data_array = array();
		foreach($search as $k => $v)
		{
			$route_stops_order = $this->db->query('SELECT * FROM bt_routes_details WHERE route_id ='. $v['route_id'] .'  ORDER BY route_order DESC LIMIT 1')->row_array();
			
			$trip_details = $this->db->query('select * from bt_trips where route_id='.$v['route_id'] .' and route_stop_id ='. $route_stops_order['id'] .' and DATE(created) ="'.$find_date .'"')->result_array();
			
			if (!empty($trip_details)) {
				foreach($trip_details as $key => $val)
				{
					array_push($data_array, array(
						'route_id'  	=> $v['route_id'],
						'driver_id' 	=> $v['driver_id'],
						'stops'			=> $v['stops'],
						'route_name'	=> $v['route_name'],
						'driver_name'	=> $v['driver_name'],
						'reg_no'		=> $v['reg_no'],
						'trip_type'		=> $val['trip_type'],
						'status'		=> $val['status'],
						'trip_id'		=> $val['id']
					));
				}
			}
			else{
				$trip_details_find = $this->db->query('select * from bt_trips where route_id='.$v['route_id'] .' and DATE(created) = "'.$find_date . '" group by route_id , trip_type ORDER BY id ')->result_array();
				
				if (!empty($trip_details_find)) {
					foreach($trip_details_find as $key => $val)
					{
						array_push($data_array, array(
							'route_id'  	=> $v['route_id'],
							'driver_id' 	=> $v['driver_id'],
							'stops'			=> $v['stops'],
							'route_name'	=> $v['route_name'],
							'driver_name'	=> $v['driver_name'],
							'reg_no'		=> $v['reg_no'],
							'trip_type'		=> $val['trip_type'],
							'status'		=> 'In-Complete',
							'trip_id'		=> $val['id']
						));
					}
				}
			}
		}
		$data['search'] = $data_array;
		$data['search_date'] = $find_date;
		// print_r('
');print_r($data);exit();
		$this->load->view('bustracking-admin/common/left-menu');
		$this->load->view('bustracking-admin/common/header');
		$this->load->view('bustracking-admin/trips', $data);	
	}

	public function trip_details()
	{
		$content = array_filter(explode(" ",str_replace('_hello_','', base64_decode($this->uri->segment(3)))));
		// print_r('
');print_r($content);exit();
		$trip_details = $this->db->query(
			'SELECT bt.id as trip_id,bt.route_stop_id, bt.time ,bt.status, br.id as route_id,contact_number, stops, route_name,place_name, bd.name as driver_name,reg_no FROM bt_trips bt , bt_routes_details brd , bt_routes br ,bt_buses bb , bt_drivers bd 
			WHERE bt.route_id = '. $content[1] .'
			AND bt.route_stop_id = brd.id
			AND bt.route_id = br.id
			AND br.bus_id = bb.id
			AND br.driver_id = bd.id
			AND bt.trip_type = "'. $content[3] .'"
			AND DATE(bt.created) = "'. $content[5] .'"
			GROUP BY bt.route_stop_id 
			ORDER by bt.id')->result_array();

		
		$trip_details_data = array();
		$trip_unreached_details_data = array();
		// $checker[] = '';	
		if (!empty($trip_details)) {
			$driver_details = array(
				'driver_name' 		=> $trip_details[0]['driver_name'],
				'contact_number' 	=> $trip_details[0]['contact_number'],
				'reg_no'			=> $trip_details[0]['reg_no']
			);
		
			foreach ($trip_details as $key => $value) {
				$checker[] = $value['route_stop_id'];
				$student_count = $this->BustrackingAdmin_Model->get_Count_Student_routes_details($value['route_stop_id']);
				$student_catch_bus = $this->BustrackingAdmin_Model->get_Count_Student_trip_details($value['trip_id']);

				array_push($trip_details_data, array(

					'trip_id'		=> $value['trip_id'],
					'route_id'		=> $value['route_id'],
					'stop_id'		=> $value['route_stop_id'],
					'place_name' 	=> $value['place_name'],
					'time'			=> date('H:i', strtotime($value['time'])),
					'students'		=> $student_catch_bus['student_count'] .'/'. $student_count['student_count']

				));

				
			}
		}

		$data['route_history'] = $trip_details_data;

		if (isset($checker) || !empty($checker)) {
			$this->db->select('route_id, id as stop_id, place_name');
			$this->db->from('bt_routes_details');
			$this->db->where('route_id', $content[1]);
			$this->db->where_not_in('id', $checker);
			$query = $this->db->get()->result_array();
	        
	        if (!empty($query)) {
	        	foreach($query as $k => $v)
	        	{
	        		$student_count = $this->BustrackingAdmin_Model->get_Count_Student_routes_details($v['stop_id']);
					

					array_push($trip_unreached_details_data, array(
						'route_id'		=> $v['route_id'],
						'stop_id'		=> $v['stop_id'],
						'place_name' 	=> $v['place_name'],
						'time'			=> '---',
						'students'		=> '0/'. $student_count['student_count']

					));
	        	}
	        }

	        $data['pending_trips'] = $trip_unreached_details_data;
		}	

		// 
		$data['driver_details'] = $driver_details;
		// print_r('
');print_r($data);exit();
		$this->load->view('bustracking-admin/common/left-menu');
		$this->load->view('bustracking-admin/common/header');
		$this->load->view('bustracking-admin/trip-details', $data);
	}

	public function get_droppoint_from_route()
	{
		$route_id = json_decode($this->input->post('route_id'));

		$list_drops = $this->db->query('select id as drop_id, place_name from bt_routes_details where route_id ='. $route_id . ' order by route_order')->result_array();
		
		echo json_encode($list_drops);
	}

	public function trip_details_view()
	{
		$content = array_filter(explode(" ",str_replace('_hello_','', base64_decode($this->uri->segment(3)))));
		
		$trip_id = $content[1];
		if ($trip_id != 00 ) {
		
			
			$query = "select student_id from bt_students_trip where trip_id = '$trip_id'";
			$student_list_trip = $this->BustrackingAdmin_Model->get_query_result_bus_tracking($query);

			//making array to quama seperated value to match with route_student_details
			$student_list_trip = implode(', ', array_map(function ($entry) {
				return $entry['student_id'];
			}, $student_list_trip));
			


			$studet_list_route = $this->BustrackingAdmin_Model->get_query_result_bus_tracking("select student_id from bt_students_bus_route_details bsbrd, bt_trips bt where bt.id = '$trip_id' and bt.route_id = bsbrd.route_id and bt.route_stop_id = bsbrd.pick_up_id" ); 

			$details_trip = array();
			foreach ($studet_list_route as $key => $value) {
				$classroom = $this->load->database('classroom', TRUE);
				$student_name = $classroom->query('select name from students where id = '.$value['student_id'].'')->row_array();
				
				if(in_array($value['student_id'], explode(',',$student_list_trip)))
				{
					array_push($details_trip, array(
						'student_name' 	=> $student_name['name'],
						'status'		=> 'Attended'
					));
				}else{
					array_push($details_trip, array(
						'student_name' 	=> $student_name['name'],
						'status'		=> 'Not Attended'
					));
				}
			}

			
		}else{

			$route_id = $content[3];
			$stop_id = $content[5];

			$trip_student = $this->db->query('select student_id from bt_students_bus_route_details where route_id='. $route_id .' AND pick_up_id ='.$stop_id .' order by student_id')->result_array();
			
			if (!empty($trip_student)) {
				
				$details_trip = array();
				foreach ($trip_student as $key => $value) {
					$classroom = $this->load->database('classroom', TRUE);
					$student_name = $classroom->query('select name from students where id = '.$value['student_id'].'')->row_array();					
					
						array_push($details_trip, array(
							'student_name' 	=> $student_name['name'],
							'status'		=> 'Not Attended'
						));					
				}

			}
		}
		$data['student_trip_details'] = $details_trip;
		$this->load->view('bustracking-admin/common/left-menu');
		$this->load->view('bustracking-admin/common/header');
		$this->load->view('bustracking-admin/trip-details-view',$data);
	}

	public function route_batch_list()
	{
		

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

		$query = $this->db->query('select id, batch_id, route_ids from bt_batch_routes ')->result_array();

		if (!empty($query)) {

			foreach ($query as $key => $value) {
				$batch = $classroom->query('select b_name from batch where id= '. $value['batch_id'])->row_array();	
				$query[$key]['batch_name'] = $batch['b_name'];

				$rPs = '';
			
				$rolePermissions = $this->db->query('SELECT route_name FROM bt_routes WHERE id IN('.$value['route_ids'].')')->result_array();
				if(!empty($rolePermissions))
				{
					foreach($rolePermissions as $p)
					{
						if($rPs=='')
							$rPs = $p['route_name'];
						else
							$rPs .= ','.$p['route_name'];
					}
				}				
				$query[$key]['permissions'] = $rPs;

			}
			
		}
		$data['roleList'] = $query;
		$this->load->view('bustracking-admin/common/left-menu');
		$this->load->view('bustracking-admin/common/header');
		$this->load->view('bustracking-admin/route-batch-list',$data);
	}

	public function route_batch_add_edit($id)
	{
		$classroom = $this->load->database('classroom', TRUE);
		$data['title'] = 'Save';
		$data['idVal'] = $id; 
		$data['batch_list'] = $classroom->query('select id,b_name, b_from, b_end, is_active from batch order by is_active desc')->result_array();

		$data['route_list'] = $this->db->query('select id,route_name from bt_routes')->result_array();

		if ($id > 0) {
			// $data['title'] = 'Update';
			$data['role_permissions'] = $this->db->query("SELECT batch_id,route_ids FROM bt_batch_routes WHERE id = $id")->row_array();
			$classroom = $this->load->database('classroom', TRUE);

			$data['check_active'] = $classroom->query('select is_active from batch where id='.$data['role_permissions']['batch_id'])->row_array();
		}
		
		if (count($_POST) > 0) {
			
			$permissions = '';
			if(isset($_POST['role_permissions']) && !empty($_POST['role_permissions']))
			{
				$permissions = implode(',', $_POST['role_permissions']);
				unset($_POST['role_permissions']);
			}
			
			if($permissions!='')
			{
				if($id == 0)
				{
					$rpData['batch_id'] = $_POST['batch_id'];
					$rpData['route_ids'] = $permissions;
					$this->BustrackingAdmin_Model->add_edit_batch_route_permissions(0, $rpData);
				}
				else
				{
					$getRPrid = $this->db->query("SELECT id FROM bt_batch_routes WHERE id = $id")->row_array();
					if(isset($getRPrid['id']) && !empty($getRPrid))
					{
						$rpData['route_ids'] = $permissions;
						$this->BustrackingAdmin_Model->add_edit_batch_route_permissions($getRPrid['id'], $rpData);
					}
				}
			}
			$this->session->set_flashdata('success', str_replace('%s', 'new role', THE_ADD_SUCCESS_MSG));
			if ($id > 0)
				$this->session->set_flashdata('success', str_replace('%s', 'role', THE_UPDATE_SUCCESS_MSG));
			
			redirect(base_url().'route-batch-list');
		}

		$this->load->view('bustracking-admin/common/left-menu');
		$this->load->view('bustracking-admin/common/header');
		$this->load->view('bustracking-admin/route-batch-add-edit',$data);
	}

	public function delete_batch_route()
	{
		$roleId = $_POST['id'];
		$result = $this->db->query("SELECT route_ids FROM bt_batch_routes WHERE id=".$roleId)->row_array();
		if (!empty($result)) {
			$res = $this->db->query('SELECT student_id FROM bt_students_bus_route_details WHERE route_id IN('.$result['route_ids'].')')->row_array();

			if(!empty($res))
				echo 'Error'; 
			else
			{
				$this->BustrackingAdmin_Model->delete_batch_route_role($roleId);			
				echo 'Success';
			}
		}
				
	}

	public function check_batch_exits()
	{
		$roleId = $_POST['batch_id'];
		$result = $this->db->query("SELECT id FROM bt_batch_routes WHERE batch_id=".$roleId)->row_array();
		
			if(!empty($result))
				echo 'Error'; 
			else						
				echo 'Success';						
	}


	public function check_batch_route_assign()
	{
		$route_ids = $_POST['route_ids'];
		$id =  (int)$_POST['id'];

		if ($id > 0) {

			$result = $this->db->query("SELECT batch_id,route_ids FROM bt_batch_routes WHERE id=".$id)->row_array();
			
			$checking_diffrence = array_diff(explode(',',$result['route_ids']), $route_ids);
			
			if (!empty($checking_diffrence)) {
				$cnt = 0;
				$route_id = implode(",", $checking_diffrence);
				$student_list = $this->db->query('SELECT student_id FROM bt_students_bus_route_details WHERE route_id IN('.$route_id.')')->result_array();
				if (!empty($student_list)) {
					$classroom = $this->load->database('classroom', TRUE);
					
					foreach ($student_list as $key => $value) {
						$student_present = $classroom->query('SELECT id FROM students WHERE batch_id ='.$result['batch_id'] .' AND id ='. $value['student_id'])->row_array();
						if (!empty($student_present))
							$cnt++;						
					}
				}
				if ($cnt > 0) 
					echo 'Error';
				else
					echo 'Success';
			}else{
				echo "Success";
			}
			
		}else{
			echo 'Success';
		}
								
	}
}