<?php 

class Webservice_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
//		date_default_timezone_set("Asia/Kolkata");
 	}
/*.........................Patient Model....................................*/

//..................auth token checking for patient

	function check_auth_token($authtoken){
		$query = $this->db->get_where('tbl_authtoken',array('authtoken'=>$authtoken));
	//	echo $this->db->last_query();exit();
		if($query->num_rows() > 0){
			return true;
		}
		else{
			return false;
		}
	}

//..................auth token checking for doctor

	function check_auth_token_doctor($authtoken){
		$query = $this->db->get_where('tbl_authtoken_doctors',array('authtoken'=>$authtoken));
		if($query->num_rows() > 0){
			return true;
		}
		else{
			return false;
		}
	}
 //........................ user(Patient) registration

	function registration($data,$type) {
		$data['is_registration_completed'] = 1;
		if($type == 'user'){
			$data['name'] = encrypt_data($data['name']);
			$data['rg'] = encrypt_data($data['rg']);
			$data['gender'] = encrypt_data($data['gender']);
			$data['weight'] = encrypt_data($data['weight']);
			$data['height'] = encrypt_data($data['height']);
			$data['blood_group'] = encrypt_data($data['blood_group']);
			$data['zip_code'] = encrypt_data($data['zip_code']);
			$data['street_address'] = encrypt_data($data['street_address']);
			$data['locality'] = encrypt_data($data['locality']);
			$data['number'] = encrypt_data($data['number']);
			$data['landmark'] = encrypt_data($data['landmark']);
			if($this->db->insert('tbl_registration', $data)){
				$insertid = $this->db->insert_id();
				$this->db->query("update tbl_registration set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where id = ".$insertid);

				$query = $this->db->get_where("tbl_registration",array("id"=>$insertid))->row_array(); 
				$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
				$this->db->where('id',$insertid);
				$query_date = $this->db->get('tbl_registration')->row();

				unset($query['dob']);
				$query['dob'] = $query_date->dob;
				$query['name'] = decrypt_data($query['name']);
				$query['rg'] = decrypt_data($query['rg']);
				$query['gender'] = decrypt_data($query['gender']);
				$query['weight'] = decrypt_data($query['weight']);
				$query['height'] = decrypt_data($query['height']);
				$query['blood_group'] = decrypt_data($query['blood_group']);
				$query['zip_code'] = decrypt_data($query['zip_code']);
				$query['street_address'] = decrypt_data($query['street_address']);
				$query['locality'] = decrypt_data($query['locality']);
				$query['number'] = decrypt_data($query['number']);
				$query['landmark'] = decrypt_data($query['landmark']);
				$return_array = array('status'=>'success','userdata'=>$query);
			}
			else{
				$return_array = array('status'=>'fail');
			}
		}else{
			//$data['name'] = encrypt_data($data['name']);
			$data['about'] = encrypt_data($data['about']);
			//$data['price'] = encrypt_data($data['price']);		
			$data['gender'] = encrypt_data($data['gender']);
			//$data['domiciliary_status'] = encrypt_data($data['domiciliary_status']);
			$data['rg'] = encrypt_data($data['rg']);
			$data['crm'] = encrypt_data($data['crm']);
			$data['cep'] = encrypt_data($data['cep']);
			$data['street_address'] = encrypt_data($data['street_address']);
			$data['locality'] = encrypt_data($data['locality']);
			$data['number'] = encrypt_data($data['number']);
			$data['complement'] = encrypt_data($data['complement']);
			if($this->db->insert('tbl_doctors', $data)){
				$insertid = $this->db->insert_id();
				$this->db->query("update tbl_doctors set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where id = ".$insertid);
				
				$this->db->insert('tbl_clinic_doctors',array('doctor_id'=>$insertid,'clinic_id'=> 0));	
				$this->db->insert('tbl_consultation',array('doctor_id'=>$insertid,'clinic_id'=> 0,'date'=>'""','date_secondary'=>'""','active_schedule'=> 0));
				
				$this->db->select('tbl_specialization.id as specialization_id,tbl_specialization.specialization_name,tbl_doctors.*');
				$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization');
				$query = $this->db->get_where("tbl_doctors",array("tbl_doctors.id"=>$insertid));

				$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
				$this->db->where('id',$insertid);
				$query_date = $this->db->get('tbl_doctors')->row(); 

				$query = $query->row_array();

				unset($query['dob']);
				$query['dob'] = $query_date->dob;
				//$query['name'] = decrypt_data($query['name']);
				$query['about'] = decrypt_data($query['about']);
				//$query['price'] = decrypt_data($query['price']);
				$query['gender'] = decrypt_data($query['gender']);
				//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
				$query['rg'] = decrypt_data($query['rg']);
				$query['crm'] = decrypt_data($query['crm']);
				$query['cep'] = decrypt_data($query['cep']);
				$query['street_address'] = decrypt_data($query['street_address']);
				$query['locality'] = decrypt_data($query['locality']);
				$query['number'] = decrypt_data($query['number']);
				$query['complement'] = decrypt_data($query['complement']);


				$return_array = array('status'=>'success','userdata'=>$query);
			}
			else{
				$return_array = array('status'=>'fail');
			}
		}
			return $return_array;
	}

//..........................insert users bystanders details

	function insert_bystander_registration($new,$result){
		$new['patient_id'] = $result['userdata']['id'];
		if($this->db->insert('tbl_patient_dependent',$new)){
			return true;
		}
	}

//.......................insert bystanders pics of patient

	function updatePicbystander($data,$id){
		$this->db->update('tbl_patient_dependent', $data, array('patient_id' => $id));
		return $this->db->get_where('tbl_patient_dependent',array('patient_id'=>$id))->row();
	}

 //.................check whether username or email exist or not for both


	function dataExist($data,$type){
//print_r($data);print_r($type);
		if(isset($data['username']) && strlen($data['username'])){
 			if($type == 'user'){
				$query_uname = $this->db->get_where("tbl_registration",array("username"=>$data['username'])); 
 			}else{
 				$query_uname = $this->db->get_where("tbl_doctors",array("username"=>$data['username'])); 
 			}
			
		}
		if(isset($data['email']) && strlen($data['email'])){
			if($type == 'user'){
				$query_email = $this->db->get_where("tbl_registration",array("email"=>$data['email']));
			}else{
				$query_email = $this->db->get_where("tbl_doctors",array("email"=>$data['email']));
			}
			
		}
		if(isset($query_uname) && ($query_uname->num_rows() > 0))
		{
			if($query_uname->num_rows() > 0){

				if(isset($query_email)){

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

						$return_array = array('message'=>'username and email are already exist','status'=>'fail');
					}
					else{

						$return_array = array('message'=>'username already exist','status'=>'fail');
					}
				}

				else{

					$return_array = array('message'=>'username already exist','status'=>'fail');
				}
			}
			else{
				$return_array = array('message'=>'success','status'=>'success');
			}
		}
		else if(isset($query_email)){

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

				$return_array = array('message'=>'email already exist','status'=>'fail');
			}
			else{

				$return_array = array('message'=>'success','status'=>'success');
			}
		}else if(isset($query_uname)){
			if($query_uname->num_rows() > 0){

				$return_array = array('message'=>'username already exist','status'=>'fail');
			}
			else{

				$return_array = array('message'=>'success','status'=>'success');
			}
		}
		else{
			$return_array = array('message'=>'fail','status'=>'fail');
		}
		return $return_array;
	}

 //....................set Patient authtoken in database


	function authtoken_registration($authtoken,$userid){
		$data = array('authtoken'=>$authtoken,'userid'=>$userid);
		if($this->db->insert('tbl_authtoken', $data)){
			return true;
		}
		else{
			return false;
		}
	}

 //....................check fb uid exist for doctor

	function is_this_uid_exit_doctor($data){
		$query = $this->db->get_where('tbl_doctors',array('uid'=>$data['uid']))->row();
		//echo $this->db->last_query();
		//echo"<pre>";print_r($query);echo"</pre>";exit();
		if($query){
			if($query->email == $data['email']){	
				$return_array = $this->update_doctor_registration_data($data,$query);
       		}else{
       			$type = 'doctor';
       			$email_verify = $this->dataExist($data,$type);
       			if($email_verify['status'] == 'success'){
       				$return_array = $this->update_doctor_registration_data($data,$query);
       			}else{
       				$return_array = $email_verify;
       			}
       		}
		}else{
			$return_array = array('status'=>'failed');
		}
		return $return_array;
	}

 //....................check fb uid exist for patient

	function is_this_uid_exit_patient($data){
		$query = $this->db->get_where('tbl_registration',array('uid'=>$data['uid'],'access_token'=>$data['access_token']))->row();
		//echo"<pre>";print_r($query);echo"</pre>";exit();
		if($query){
			if($query->email == $data['email']){	
				$return_array = $this->update_patient_registration_data($data,$query);
       		}else{
       			$type = 'user';
       			$email_verify = $this->dataExist($data,$type);
       			if($email_verify['status'] == 'success'){
       				$return_array = $this->update_patient_registration_data($data,$query);
       			}else{
       				$return_array = $email_verify;
       			}
       		}
		}else{
			$return_array = array('status'=>'failed');
		}
		return $return_array;
	}

 //....................if uid exist for doctor thn update doctor registration data

	function update_doctor_registration_data($data,$query){
		//$data['password'] = md5($data['password']);
				//$data['dob'] = $data['dob'];
				
				$data['cep'] = encrypt_data($data['zip_code']);
				$data['complement'] = encrypt_data($data['landmark']);
				$data['about'] = encrypt_data($data['biodata']);
				$data['specialization'] = $data['specialization_id'];
				$data['gender'] = encrypt_data(strtoupper($data['gender']));
				$data['username'] = $data['uid'];
				$data['is_registration_completed'] = 1;
				//$data['name'] = encrypt_data($data['name']);
				//$data['price'] = encrypt_data($data['price']);
				//$data['domiciliary_status'] = encrypt_data($data['domiciliary_status']);
				$data['rg'] = encrypt_data($data['rg']);
				$data['crm'] = encrypt_data($data['crm']);
				$data['street_address'] = encrypt_data($data['street_address']);
				$data['locality'] = encrypt_data($data['locality']);
				$data['number'] = encrypt_data($data['number']);

				unset($data['zip_code']);
				unset($data['landmark']);
				unset($data['biodata']);
				unset($data['specialization_id']);

	            if($this->db->update('tbl_doctors',$data,array('uid'=>$data['uid']))){
				$this->db->query("update tbl_doctors set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where uid = ".$data['uid']);

				

	            	$this->db->select('tbl_doctors.*,tbl_specialization.id as specialization_id,tbl_specialization.specialization_name,tbl_authtoken_doctors.doctor_id ,tbl_authtoken_doctors.authtoken');
					$this->db->join('tbl_authtoken_doctors', 'tbl_authtoken_doctors.doctor_id = tbl_doctors.id');
					$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization');
					$query = $this->db->get_where("tbl_doctors",array('tbl_doctors.id'=>$query->id))->row_array();

					unset($query['dob']);

					$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
					$this->db->where('uid',$data['uid']);
					$query_date = $this->db->get('tbl_doctors')->row(); 
					$query['dob'] = $query_date->dob;
					$query['cep'] = decrypt_data($query['zip_code']);
					$query['complement'] = decrypt_data($query['landmark']);
					$query['about'] = decrypt_data($query['biodata']);
					$query['gender'] = decrypt_data($query['gender']);
					//$query['name'] = decrypt_data($query['name']);
					//$query['price'] = decrypt_data($query['price']);
					//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
					$query['rg'] = decrypt_data($query['rg']);
					$query['crm'] = decrypt_data($query['crm']);
					$query['street_address'] = decrypt_data($query['street_address']);
					$query['locality'] = decrypt_data($query['locality']);
					$query['number'] = decrypt_data($query['number']);

					$return_array = array('status'=>'success','userdata'=>$query);
		            }else{
		            	$return_array = array('status'=>'failed');
		            }
					return $return_array;
	}

 //....................if uid exist for patient thn update patient registration data

	function update_patient_registration_data($data,$query){
		//$data['password'] = md5($data['password']);
		//$data['dob'] = encrypt_data($data['dob']);
		$data['username'] = $data['uid'];
		$new = array();
		$type = 'user';
		$data['is_registration_completed'] = 1;
		if(isset($data['bystander_name']) || isset($data['bystander_relation'])  || isset($data['bystander_cpf']) || isset($data['bystander_dob']) ){
			if(isset($data['bystander_name'])){	
				$new['dependent_name'] = $data['bystander_name'];
				unset($data['bystander_name']);
			}
			if(isset($data['bystander_relation'])){	
				$new['relation'] = $data['bystander_relation'];
				unset($data['bystander_relation']);
			}
			if(isset($data['bystander_cpf'])){	
				$new['cpf'] = $data['bystander_cpf'];
				unset($data['bystander_cpf']);
			}
			if(isset($data['bystander_dob'])){	
				$new['dob'] = strtotime($data['bystander_dob']);
				unset($data['bystander_dob']);
			}
			$data['gender'] = strtoupper($data['gender']);
			if($this->db->update('tbl_registration',$data,array('uid'=>$data['uid']))){
				$this->db->query("update tbl_registration set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where uid = ".$data['uid']);

				$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
				$this->db->where('id',$insertid);
				$query_date = $this->db->get('tbl_registration')->row();

				$rslt = $this->db->get_where('tbl_registration',array('uid'=>$data['uid']))->row_array();
				unset($rslt['dob']);
				$rslt['dob'] = $query_date->dob;
				$result = array('status'=>'success','userdata'=>$rslt);
				$ress = 'true';
			}
			$this->insert_bystander_registration($new,$result);
		}else{
			if($this->db->update('tbl_registration',$data,array('uid'=>$data['uid']))){
				$ress = 'true';
			}
		}

        if($ress == 'true'){
        	$this->db->select("tbl_registration.*,CAST(AES_DECRYPT(`tbl_registration.dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new,tbl_authtoken.userid ,tbl_authtoken.authtoken");
			$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id');
			$query = $this->db->get_where("tbl_registration",array('tbl_registration.id'=>$query->id))->row_array();
			$query['name'] = decrypt_data($query['name']);
			$query['rg'] = decrypt_data($query['rg']);
			$query['dob'] = $query['dob_new'];
			unset($query['dob_new']);
			$query['gender'] = decrypt_data($query['gender']);
			$query['weight'] = decrypt_data($query['weight']);
			$query['height'] = decrypt_data($query['height']);
			$query['blood_group'] = decrypt_data($query['blood_group']);
			$query['zip_code'] = decrypt_data($query['zip_code']);
			$query['street_address'] = decrypt_data($query['street_address']);
			$query['locality'] = decrypt_data($query['locality']);
			$query['number'] = decrypt_data($query['number']);
			$query['landmark'] = decrypt_data($query['landmark']);
			$return_array = array('status'=>'success','userdata'=>$query);
            }else{
            	$return_array = array('status'=>'failed');
            }
			return $return_array;
	}

 
 //.................... update doctor fbuid

	function update_doctor_fbuid($id,$data){
		$this->db->update('tbl_doctors',array('uid'=>$data['uid'],'access_token'=>$data['access_token']),array('id'=>$id));
	}

 //.................... update patient fbuid

	function update_patient_fbuid($id,$data){
		$this->db->update('tbl_registration',array('uid'=>$data['uid'],'access_token'=>$data['access_token']),array('id'=>$id));
	}

 //....................user login

	function login($data){
		$this->db->select("tbl_registration.*,tbl_authtoken.userid ,tbl_authtoken.authtoken");
		$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id', 'inner');
		$querys = $this->db->get_where("tbl_registration",array("username"=>$data['username'],"password"=>md5($data['password'])));
		$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id', 'inner');
		$query_emails = $this->db->get_where("tbl_registration",array("email"=>$data['username'],"password"=>md5($data['password'])));
		if($querys->num_rows() > 0 || $query_emails->num_rows() > 0){
			if($querys->num_rows() > 0){
				$query = $querys->row_array();
				$this->db->select("CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
				$this->db->where('id',$query['id']);
				$querydate = $this->db->get('tbl_registration')->row();
				$query['name'] = decrypt_data($query['name']);
				$query['rg'] = decrypt_data($query['rg']);
				$query['dob'] = $querydate->dob_new;
				$query['gender'] = decrypt_data($query['gender']);
				$query['weight'] = decrypt_data($query['weight']);
				$query['height'] = decrypt_data($query['height']);
				$query['blood_group'] = decrypt_data($query['blood_group']);
				$query['zip_code'] = decrypt_data($query['zip_code']);
				$query['street_address'] = decrypt_data($query['street_address']);
				$query['locality'] = decrypt_data($query['locality']);
				$query['number'] = decrypt_data($query['number']);
				$query['landmark'] = decrypt_data($query['landmark']);

				$return_array = array('status'=>'success','userdata'=>$query);
			}
			if($query_emails->num_rows() > 0){
				$query_email = $query_emails->row_array();
				$this->db->select("CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
				$this->db->where('id',$query_email['id']);
				$querydate = $this->db->get('tbl_registration')->row();
				$query_email['name'] = decrypt_data($query_email['name']);
				$query_email['rg'] = decrypt_data($query_email['rg']);
				$query_email['dob'] = $querydate->dob_new;
				$query_email['gender'] = decrypt_data($query_email['gender']);
				$query_email['weight'] = decrypt_data($query_email['weight']);
				$query_email['height'] = decrypt_data($query_email['height']);
				$query_email['blood_group'] = decrypt_data($query_email['blood_group']);
				$query_email['zip_code'] = decrypt_data($query_email['zip_code']);
				$query_email['street_address'] = decrypt_data($query_email['street_address']);
				$query_email['locality'] = decrypt_data($query_email['locality']);
				$query_email['number'] = decrypt_data($query_email['number']);
				$query_email['landmark'] = decrypt_data($query_email['landmark']);
				$return_array = array('status'=>'success','userdata'=>$query_email);
			}

		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//get users bystanders details

	function get_patient_depend($id){
		$this->db->select('dependent_name as bystander_name,relation as bystander_relation,dob as bystander_dob,cpf as bystander_cpf,image as bystander_profile_photo');
		return $query = $this->db->get_where('tbl_patient_dependent',array('patient_id'=>$id))->result();
	}

 //....................doctor login

	function doctor_login($data){
		$this->db->select('tbl_doctors.*,tbl_specialization.id as specialization_id,tbl_specialization.specialization_name,tbl_authtoken_doctors.doctor_id ,tbl_authtoken_doctors.authtoken');
		$this->db->join('tbl_authtoken_doctors', 'tbl_authtoken_doctors.doctor_id = tbl_doctors.id');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization');
		$query = $this->db->get_where("tbl_doctors",array("username"=>$data['username'],"password"=>md5($data['password'])))->row_array();
		//print_r($query);exit();
         if(count($query) < 0 || $query == ''){
         	$this->db->select('tbl_doctors.*,tbl_specialization.id as specialization_id,tbl_specialization.specialization_name,tbl_authtoken_doctors.doctor_id ,tbl_authtoken_doctors.authtoken');
         	$this->db->join('tbl_authtoken_doctors', 'tbl_authtoken_doctors.doctor_id = tbl_doctors.id');
			$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization');
			$query_email = $this->db->get_where("tbl_doctors",array("email"=>$data['username'],"password"=>md5($data['password'])))->row_array();
			if(count($query_email) < 0 || $query_email == ''){
				$return_array = array('status'=>'fail');
			}else{
				$this->db->select("CAST(AES_DECRYPT(`tbl_doctors`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
				$this->db->where('id',$query_email['id']);

				$querydate = $this->db->get('tbl_doctors')->row();
				$query_email['dob'] = $querydate->dob_new;
				$query_email['cep'] = decrypt_data($query_email['cep']);
				$query_email['complement'] = decrypt_data($query_email['complement']);
				$query_email['about'] = decrypt_data($query_email['about']);
				$query_email['gender'] = decrypt_data($query_email['gender']);
				//$query_email['name'] = decrypt_data($query_email['name']);
				//$query_email['price'] = decrypt_data($query_email['price']);
				//$query_email['domiciliary_status'] = decrypt_data($query_email['domiciliary_status']);
				$query_email['rg'] = decrypt_data($query_email['rg']);
				$query_email['crm'] = decrypt_data($query_email['crm']);
				$query_email['street_address'] = decrypt_data($query_email['street_address']);
				$query_email['locality'] = decrypt_data($query_email['locality']);
				$query_email['number'] = decrypt_data($query_email['number']);
				$return_array = array('status'=>'success','userdata'=>$query_email);
			}
         }else{
			$this->db->select("CAST(AES_DECRYPT(`tbl_doctors`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
			$this->db->where('id',$query['id']);
			$querydate = $this->db->get('tbl_doctors')->row();
			$query_email = $query;
			$query_email['dob'] = $querydate->dob_new;
			$query_email['cep'] = decrypt_data($query_email['cep']);
			$query_email['complement'] = decrypt_data($query_email['complement']);
			$query_email['about'] = decrypt_data($query_email['about']);
			$query_email['gender'] = decrypt_data($query_email['gender']);
			//$query_email['name'] = decrypt_data($query_email['name']);
			//$query_email['price'] = decrypt_data($query_email['price']);
			//$query_email['domiciliary_status'] = decrypt_data($query_email['domiciliary_status']);
			$query_email['rg'] = decrypt_data($query_email['rg']);
			$query_email['crm'] = decrypt_data($query_email['crm']);
			$query_email['street_address'] = decrypt_data($query_email['street_address']);
			$query_email['locality'] = decrypt_data($query_email['locality']);
			$query_email['number'] = decrypt_data($query_email['number']);

         	$return_array = array('status'=>'success','userdata'=>$query_email);
         }

		return $return_array;
	}

 // set patient's profile pic path into database for both

	function updatePic($data,$id,$type){
		if($type=='user'){
			$this->db->update('tbl_registration', $data, array('id' => $id));
		}else{
			$this->db->update('tbl_doctors', $data, array('id' => $id));
		}
	}
	
	public function get_updatePic_doctor($id){
		$this->db->select('profile_pic');
		$this->db->where('id',$id);
		return $this->db->get('tbl_doctors')->row();
	}


// insert fb user data to tbl_facebook_user
/*
	function fb_login($data){
		if($this->db->insert('tbl_facebook_user', array('uid'=>$data['uid'],'access_token'=>$data['access_token'])))
		{
			$return_array = array('status'=>'success');
		}
		else{
			$return_array = array('status'=>'fail');
		}

		return $return_array;
	}*/

//..................... check email exist or not for patient

	function email_exist($data){
		$query_email = $this->db->get_where("tbl_registration",array("email"=>$data));
		if($query_email->num_rows() > 0){
			$return_array = array('status'=>'exist');
		}
		else{
			$return_array = array('status'=>'not exist');
		}
		return $return_array;
	}

//..................... check email exist or not for doctor

	function email_exist_doctor($data){
		$query_email = $this->db->get_where("tbl_doctors",array("email"=>$data));
		if($query_email->num_rows() > 0){
			$return_array = array('status'=>'exist');
		}
		else{
			$return_array = array('status'=>'not exist');
		}
		return $return_array;
	}

//..................... check uid exist for doctor

	function is_uid_exist($data){
		$query_uid = $this->db->get_where("tbl_doctors",array("uid"=>$data));
		if($query_uid->num_rows() > 0){
			$return_array = array('status'=>'exist');
		}
		else{
			$return_array = array('status'=>'not exist');
		}
		return $return_array;
	}

//..................... check uid exist for patient

	function is_uid_exist_patient($data){
		$query_uid = $this->db->get_where("tbl_registration",array("uid"=>$data));
		if($query_uid->num_rows() > 0){
			$return_array = array('status'=>'exist');
		}
		else{
			$return_array = array('status'=>'not exist');
		}
		return $return_array;
	}

//.............. Get User(Patient) data based on email

	function get_userdata($data){
		$this->db->select("tbl_registration.*,CAST(AES_DECRYPT(`tbl_registration.dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new,tbl_authtoken.userid ,tbl_authtoken.authtoken");
		$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id', 'inner');
		$query_userdatas = $this->db->get_where("tbl_registration",array("email"=>$data));
		if($query_userdatas->num_rows() > 0){
			$query_userdata = $query_userdatas->row_array();
			$query_userdata['name'] = decrypt_data($query_userdata['name']);
			$query_userdata['rg'] = decrypt_data($query_userdata['rg']);
			$query_userdata['dob'] = $query_userdata['dob_new'];
			unset($query_userdata['dob_new']);
			$query_userdata['gender'] = decrypt_data($query_userdata['gender']);
			$query_userdata['weight'] = decrypt_data($query_userdata['weight']);
			$query_userdata['height'] = decrypt_data($query_userdata['height']);
			$query_userdata['blood_group'] = decrypt_data($query_userdata['blood_group']);
			$query_userdata['zip_code'] = decrypt_data($query_userdata['zip_code']);
			$query_userdata['street_address'] = decrypt_data($query_userdata['street_address']);
			$query_userdata['locality'] = decrypt_data($query_userdata['locality']);
			$query_userdata['number'] = decrypt_data($query_userdata['number']);
			$query_userdata['landmark'] = decrypt_data($query_userdata['landmark']);
			$return_array = array('status'=>'success','userdata'=>$query_userdata);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//.............. Get doctor data based on email

	function get_userdata_doctor($data){
		$this->db->select('tbl_doctors.*,tbl_authtoken_doctors.doctor_id ,tbl_authtoken_doctors.authtoken,tbl_specialization.id as specialization_id,tbl_specialization.specialization_name');
		$this->db->join('tbl_authtoken_doctors', 'tbl_authtoken_doctors.doctor_id = tbl_doctors.id', 'inner');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization');
		$query_userdata = $this->db->get_where("tbl_doctors",array("email"=>$data));
		if($query_userdata->num_rows() > 0){



			$doc_result = $query_userdata->row_array();
			$this->db->select("CAST(AES_DECRYPT(`tbl_doctors`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
			$this->db->where('id',$doc_result ['id']);
			$querydate = $this->db->get('tbl_doctors')->row();
			$query = $doc_result;
			$query['dob'] = $query_date->dob_new;
			$query['cep'] = decrypt_data($query['zip_code']);
			$query['complement'] = decrypt_data($query['landmark']);
			$query['about'] = decrypt_data($query['biodata']);
			$query['gender'] = decrypt_data($query['gender']);
			//$query['name'] = decrypt_data($query['name']);
			//$query['price'] = decrypt_data($query['price']);
			//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
			$query['rg'] = decrypt_data($query['rg']);
			$query['crm'] = decrypt_data($query['crm']);
			$query['street_address'] = decrypt_data($query['street_address']);
			$query['locality'] = decrypt_data($query['locality']);
			$query['number'] = decrypt_data($query['number']);

			$return_array = array('status'=>'success','userdata'=>$query);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//.............. Get doctor data based on uid

	function get_userdata_doctor_by_uid($data){
		$this->db->select('tbl_doctors.*,tbl_authtoken_doctors.doctor_id ,tbl_authtoken_doctors.authtoken,tbl_specialization.id as specialization_id,tbl_specialization.specialization_name');
		$this->db->join('tbl_authtoken_doctors', 'tbl_authtoken_doctors.doctor_id = tbl_doctors.id', 'left');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.	specialization','left');
		$query_userdata = $this->db->get_where("tbl_doctors",array("uid"=>$data));
		if($query_userdata->num_rows() > 0){
			$query = $query_userdata->row_array();
			$this->db->select("CAST(AES_DECRYPT(`tbl_doctors`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
			$this->db->where('id',$query['id']);
			$querydate = $this->db->get('tbl_doctors')->row();

			$query['dob'] = $query_date->dob_new;
			$query['cep'] = decrypt_data($query['zip_code']);
			$query['complement'] = decrypt_data($query['landmark']);
			$query['about'] = decrypt_data($query['biodata']);
			$query['gender'] = decrypt_data($query['gender']);
			//$query['name'] = decrypt_data($query['name']);
			//$query['price'] = decrypt_data($query['price']);
			//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
			$query['rg'] = decrypt_data($query['rg']);
			$query['crm'] = decrypt_data($query['crm']);
			$query['street_address'] = decrypt_data($query['street_address']);
			$query['locality'] = decrypt_data($query['locality']);
			$query['number'] = decrypt_data($query['number']);

			$return_array = array('status'=>'success','userdata'=>$query);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//.............. Get User(Patient) data based on uid

	function get_userdata_patient_by_uid($data){
		$this->db->select("tbl_registration.*,CAST(AES_DECRYPT(`tbl_registration.dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new,tbl_authtoken.userid ,tbl_authtoken.authtoken");
		$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id', 'left');
		$query_userdatas = $this->db->get_where("tbl_registration",array("uid"=>$data));
		if($query_userdatas->num_rows() > 0){
			$query_userdata = $query_userdatas->row_array();
			$query_userdata['name'] = decrypt_data($query_userdata['name']);
			$query_userdata['rg'] = decrypt_data($query_userdata['rg']);
			$query_userdata['dob'] = $query_userdata['dob_new'];
			unset($query_userdata['dob_new']);
			$query_userdata['gender'] = decrypt_data($query_userdata['gender']);
			$query_userdata['weight'] = decrypt_data($query_userdata['weight']);
			$query_userdata['height'] = decrypt_data($query_userdata['height']);
			$query_userdata['blood_group'] = decrypt_data($query_userdata['blood_group']);
			$query_userdata['zip_code'] = decrypt_data($query_userdata['zip_code']);
			$query_userdata['street_address'] = decrypt_data($query_userdata['street_address']);
			$query_userdata['locality'] = decrypt_data($query_userdata['locality']);
			$query_userdata['number'] = decrypt_data($query_userdata['number']);
			$query_userdata['landmark'] = decrypt_data($query_userdata['landmark']);
			$return_array = array('status'=>'success','userdata'=>$query_userdata);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		//echo $this->db->last_query();exit();
		return $return_array;
	}

//.............. Insert uid for doctor

	public function insert_uid_doctor($data){

		$data['is_registration_completed'] = 0;
        $data['name'] = encrypt_data($data['name']);
		$data['about'] = encrypt_data($data['about']);
		//$data['price'] = encrypt_data($data['price']);		
		$data['gender'] = encrypt_data($data['gender']);
		//$data['domiciliary_status'] = encrypt_data($data['domiciliary_status']);
		$data['rg'] = encrypt_data($data['rg']);
		$data['crm'] = encrypt_data($data['crm']);
		$data['cep'] = encrypt_data($data['cep']);
		$data['street_address'] = encrypt_data($data['street_address']);
		$data['locality'] = encrypt_data($data['locality']);
		$data['number'] = encrypt_data($data['number']);
		$data['complement'] = encrypt_data($data['complement']);

		$this->db->insert('tbl_doctors',$data);

		$insertid = $this->db->insert_id();
		$this->db->query("update tbl_doctors set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where id = ".$insertid);

		$this->db->select('tbl_doctors.*');

		$query_userdata = $this->db->get_where("tbl_doctors",array("id"=>$insertid));
		if($query_userdata->num_rows() > 0){
		    $query = $query_userdata->row_array();
			$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
				$this->db->where('id',$insertid);
				$query_date = $this->db->get('tbl_doctors')->row(); 

				unset($query['dob']);
				$query['dob'] = $query_date->dob;
				//$query['name'] = decrypt_data($query['name']);
				$query['about'] = decrypt_data($query['about']);
				$query['price'] = decrypt_data($query['price']);
				$query['gender'] = decrypt_data($query['gender']);
				$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
				$query['rg'] = decrypt_data($query['rg']);
				$query['crm'] = decrypt_data($query['crm']);
				$query['cep'] = decrypt_data($query['cep']);
				$query['street_address'] = decrypt_data($query['street_address']);
				$query['locality'] = decrypt_data($query['locality']);
				$query['number'] = decrypt_data($query['number']);
				$query['complement'] = decrypt_data($query['complement']);
			

			    $return_array = array('status'=>'success','userdata'=>$query);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
		
	}

//.............. Insert uid for patient

	public function insert_uid_patient($data){
		$data['is_registration_completed'] = 0;
		$this->db->insert('tbl_registration',$data);
		$insertid = $this->db->insert_id();
		$this->db->select("tbl_registration.*,CAST(AES_DECRYPT(`tbl_registration.dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
		$query_userdatas = $this->db->get_where("tbl_registration",array("id"=>$insertid));
		if($query_userdatas->num_rows() > 0){
			$query_userdata = $query_userdatas->row_array();
			$query_userdata['name'] = decrypt_data($query_userdata['name']);
			$query_userdata['rg'] = decrypt_data($query_userdata['rg']);
			$query_userdata['dob'] = $query_userdata['dob_new'];
			unset($query_userdata['dob_new']);
			$query_userdata['gender'] = decrypt_data($query_userdata['gender']);
			$query_userdata['weight'] = decrypt_data($query_userdata['weight']);
			$query_userdata['height'] = decrypt_data($query_userdata['height']);
			$query_userdata['blood_group'] = decrypt_data($query_userdata['blood_group']);
			$query_userdata['zip_code'] = decrypt_data($query_userdata['zip_code']);
			$query_userdata['street_address'] = decrypt_data($query_userdata['street_address']);
			$query_userdata['locality'] = decrypt_data($query_userdata['locality']);
			$query_userdata['number'] = decrypt_data($query_userdata['number']);
			$query_userdata['landmark'] = decrypt_data($query_userdata['landmark']);
			$return_array = array('status'=>'success','userdata'=>$query_userdata);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
		
	}



//set fb login data

	/*function set_fbdata($data,$authToken){

		if($this->db->insert('tbl_registration',array('name'=>$data['name'],'email'=>$data['email'],'gender'=>$data['gender'],'profile_photo'=>$data['profile_photo']))){
				$insertid = $this->db->insert_id();
				$set_authtoken = $this->authtoken_registration($authToken,$insertid);
				if($set_authtoken){

					if($this->db->insert('tbl_facebook_user',array('uid'=>$insertid,'fb_uid'=>$data['uid'],'access_token'=>$data['access_token'],'social_provider'=>'FACEBOOK'))){
						$this->db->join('tbl_authtoken', 'tbl_authtoken.userid = tbl_registration.id', 'inner');
						$query = $this->db->get_where("tbl_registration",array('tbl_registration.id'=>$insertid));
						$return_array = array('status'=>'success','userdata'=>$query->row_array());
					}
					else{
						$return_array = array('status'=>'fail');
					}
				}
		}
		return $return_array;
	}*/

//..................... delete patient and doctor based on id

	function delete_registration($uid,$type){
		if($type == 'user'){
		  if($this->db->where_in('id', $uid)->delete('tbl_registration')){
		  }
		}else{
			 if($this->db->where_in('id', $uid)->delete('tbl_doctors')){
		  }
		}
	}

//..................... delete patient bystander registration based on id

	function delete_patient_registration($uid){
		$this->db->where('patient_id',$uid);
		$this->db->delete('tbl_patient_dependent');
		return true;
	}

//................... get userdata using authtoken


	function get_auth_token($authtoken){
		
		$this->db->join('tbl_registration', 'tbl_authtoken.userid = tbl_registration.id', 'inner');
		$query = $this->db->get_where("tbl_authtoken",array("authtoken"=>$authtoken));
		if ($query->num_rows() > 0) {

			$return_array = array('status'=>'success','userdata'=>$query->row_array());
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//.....................get home details

	function get_home_details($id){
		$res = array();
		$res['doctor_count'] = $this->db->count_all('tbl_doctors');
		$res['clinic_count'] = $this->db->count_all('tbl_clinic');
		$res['booking_count'] = $this->db->count_all('tbl_booking');
		$res['charity_count'] = $this->db->count_all('tbl_charity');
		$this->db->select('count(id) as count');
		//$query = $this->db->get_where('tbl_patient_notification',array('patient_id'=>$id))->result();
		$query = $this->notification_list_unread_count($id);
		$res['notification_count'] = $query->count;
		return $res;
	}
//................... patient location update

	function location_update($data,$headers){
		$query = $this->db->get_where("tbl_authtoken",array("authtoken"=>$headers['Auth']));

		if ($query->num_rows() > 0) {
			$userid = $query->row_array();
			$sql = $this->db->insert_string('tbl_user_location', array("userid"=>$userid['userid'],"location_name"=>$data['location_name'],"location_latitude"=>$data['location_latitude'],"location_longitude"=>$data['location_longitude'])) . ' ON DUPLICATE KEY UPDATE userid = ' .$userid['userid'].',location_name ='.'"' .$data['location_name'].'"'.',location_latitude='.$data['location_latitude'].',location_longitude='.$data['location_longitude'];
			if($this->db->query($sql)){
			
				$return_array = array('status'=>'success');
			}
			else{

				$return_array = array('status'=>'fail');
			}
		}
		return $return_array;
	}

//...................... update fcm token using authtoken for user

	function update_fcm_token($data,$authtoken){
		if($this->db->update('tbl_authtoken', $data, array('authtoken' => $authtoken))){

			$return_array = array('status'=>'success');

		}
		else{
			$return_array = array('status'=>'fail');
		}

		return $return_array;

	}

//...................... update fcm token using authtoken for doctor

	function update_fcm_token_doctor($data,$authtoken){
		if($this->db->update('tbl_authtoken_doctors', $data, array('authtoken' => $authtoken))){

			$return_array = array('status'=>'success');

		}
		else{
			$return_array = array('status'=>'fail');
		}

		return $return_array;

	}

//................ get closest location details of doctors from user location


	function get_closest_location($lat,$lng){	

		$this->db->select("tbl_clinic.street_address as location_name,tbl_clinic.location_lattitude as location_lattitude,tbl_clinic.location_longitude as location_longitude,ROUND(( 6371 * acos( cos( radians({$lat}) ) * cos( radians( `tbl_clinic`.`location_lattitude` ) ) * cos( radians( `tbl_clinic`.`location_longitude` ) - radians({$lng}) ) + sin( radians({$lat}) ) * sin( radians( `tbl_clinic`.`location_lattitude` ) ) ) )) AS distance");
		$this->db->from("tbl_clinic");
		$this->db->join("tbl_clinic_doctors","tbl_clinic.id = tbl_clinic_doctors.clinic_id","INNER");
		$this->db->join("tbl_doctors","tbl_clinic_doctors.doctor_id = tbl_doctors.id","INNER",false);
		$this->db->having('distance <= 10');
		$this->db->order_by("distance", "asc");
		$results = $this->db->get();
        return $results->result_array();
	}

// ...............get location details of  user or patient

	function get_location($authtoken){

		$query = $this->db->get_where("tbl_authtoken",array("authtoken"=>$authtoken));
		if ($query->num_rows() > 0) {
			$uid = $query->row_array();
			$query_location = $this->db->get_where("tbl_user_location",array("userid"=>$uid['userid']));
			if($query_location->num_rows() > 0){
				$return_array = array('status'=>'success','data'=>$query_location->row_array());
			}
			else{
				$return_array = array('status'=>'fail');
			}
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}


//........................ get doctor specialisations


	function get_doctor_specialisation(){
		$this->db->select("DISTINCT(tbl_specialization.specialization_name),tbl_specialization.id as specialization_id");
		$this->db->group_by('tbl_specialization.specialization_name');
		$query = $this->db->get_where("tbl_specialization");
		if ($query->num_rows() > 0) {
			$return_array = array('status'=>'success','data'=>$query->result_array());
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//........................ get doctor specialisations

	function get_specialisation(){
		$this->db->select("DISTINCT(tbl_specialization.specialization_name) as name,tbl_specialization.id");
		//$this->db->group_by('tbl_specialization.specialization_name');
		$query = $this->db->get_where("tbl_specialization");
		if ($query->num_rows() > 0) {
			$return_array = array('status'=>'success','data'=>array('specializations'=>$query->result_array()));
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//................. get doctor profile


	function get_doctor_profile($doctorid){
		$this->db->select('tbl_doctors.*,
							tbl_specialization.specialization_name,
							tbl_specialization.sub_name,
							tbl_clinic.street_address as location_name,
							tbl_clinic.location_lattitude,tbl_clinic.location_longitude,
							COUNT(DISTINCT(tbl_review.review_id)) as reviewcount,
							GROUP_CONCAT(DISTINCT(tbl_doctors_photos.photo_url) SEPARATOR ",") as photos
						');
		$this->db->join('tbl_clinic_doctors', 'tbl_clinic_doctors.doctor_id = tbl_doctors.id','INNER');
		$this->db->join('tbl_clinic', 'tbl_clinic.id = tbl_clinic_doctors.clinic_id','INNER');
		$this->db->join('tbl_doctors_photos', 'tbl_doctors_photos.doctor_id = tbl_doctors.id','LEFT');
		$this->db->join('tbl_specialization', 'tbl_specialization.id = tbl_doctors.specialization','LEFT');
		$this->db->join('tbl_review', 'tbl_review.doctor_id = tbl_doctors.id','LEFT');		
		$query = $this->db->get_where("tbl_doctors",array("tbl_doctors.id"=>$doctorid));
		
		if($query->num_rows() > 0 && !is_null($query->row_array()['id'])){
			
			$query = $query->row_array();
			$this->db->select("CAST(AES_DECRYPT(`tbl_doctors`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob_new");
			$this->db->where('id',$query['id']);
			$querydate = $this->db->get('tbl_doctors')->row();
			$query['dob'] = $query_date->dob_new;
			$query['cep'] = decrypt_data($query['zip_code']);
			$query['complement'] = decrypt_data($query['landmark']);
			$query['about'] = decrypt_data($query['biodata']);
			$query['gender'] = decrypt_data($query['gender']);
			//$query['name'] = decrypt_data($query['name']);
			//$query['price'] = decrypt_data($query['price']);
			//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
			$query['rg'] = decrypt_data($query['rg']);
			$query['crm'] = decrypt_data($query['crm']);
			$query['street_address'] = decrypt_data($query['street_address']);
			$query['locality'] = decrypt_data($query['locality']);
			$query['number'] = decrypt_data($query['number']);

			$return_array = array('status'=>'success','data'=>$query);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

// .................fetch all reviews of a particular doctor

	function review_list($id,$start,$per_page){
		$this->db->join('tbl_registration','tbl_registration.id = tbl_review.reviewer_id');
		$this->db->limit($per_page,$start);
		$query = $this->db->get_where("tbl_review",array("tbl_review.doctor_id"=>$id))->result_array();
		//echo $this->db->last_query();exit();
		if(count($query)> 0){
			return $query;
		}
		else{
			return false;
		}
	}

//................ fetch all reviews of particular clinic

	function review_list_clinic($id,$start,$per_page){
		$this->db->join('tbl_registration','tbl_registration.id = tbl_review_clinic.reviewer_id');
		$this->db->limit($per_page,$start);
		$query = $this->db->get_where("tbl_review_clinic",array("tbl_review_clinic.clinic_id"=>$id))->result_array();
		if(count($query)> 0){

			return $query;
		}
		else{
			return false;
		}
	}

//..................... insert doctor booking details

	function doctor_booking($data,$patient_id){
		$query = $this->db->get_where('tbl_authtoken',array('authtoken'=>$patient_id));		
		if($query->num_rows() > 0){
			$date = strtotime(date('Y-m-d'));
			if($data['date'] < $date){
				$return_array = array('status'=>'fail','msg' =>'Please select date from future');
			}else{

				if(isset($data['promocode_id']) && strlen(trim($data['promocode_id']," ")) > 0){
					$res = $this->get_promocode_result($data);
					//echo"<pre>";print_r(count($res['data']['promo_data']));echo"</pre>";exit();
					if($res['status'] == 'success'){
						$patientid = $query->row_array();
						$return_array = $this->doctor_booking_wth_promocode($data,$res['data'],$patientid);
					}else{
						$return_array = $res;
					}
				}else{
					$patientid = $query->row_array();

					$return_array = $this->doctor_booking_wth_promocode($data,'',$patientid);
				} // promocode else closing bracket
			}
		}
		else{
			$return_array = array('status'=>'fail','msg' =>'Invalid Auth token');
		}
		return $return_array;
	}

//........................ insert doctor booking with promocode

	public function doctor_booking_wth_promocode($data,$promocode,$patientid){
		$this->db->select('accept_return,return_timeperiod');
		$this->db->where('id',$data['doctor_id']);
		$check_doctor_status = $this->db->get('tbl_doctors')->row();
		if($check_doctor_status->accept_return == '1'){
			$old_date = date('Y-m-d',$data['date']);
			$newdate = date("Y-m-d",strtotime($old_date." -".$check_doctor_status->return_timeperiod." day"));
			$new_date = strtotime($newdate);

			$this->db->where('doctor_id',$data['doctor_id']);
			$this->db->where('clinic_id',$data['clinic_id']);
			$this->db->where('patient_id',$patientid['userid']);
			$this->db->where('free_visit_status',0);
			$this->db->where('visit_type',0);
			$this->db->where('date >=',$new_date);
			$this->db->where('date <=',$data['date']);
			$this->db->order_by('id','DESC');
			$this->db->limit(1,0);
			$res = $this->db->get('tbl_booking')->row();
			//echo $this->db->last_query();exit();
			//print_r($res);exit();
			if($res){
				$visit = $res;
			}else{
				$visit = '';
			}
			$return_array = $this->get_doctor_booking_result($data,$patientid,$visit,$promocode);
		}else{
			$return_array = $this->get_doctor_booking_result($data,$patientid,'',$promocode);
		}
		return $return_array;
	}

//........................ get doctor booking result
	public function get_doctor_booking_result($data,$patientid,$res,$promocode){

		if(isset($res) && $res != ''){
			if($res->visit_type == '0'){
				$this->db->update('tbl_booking',array('free_visit_status'=>'1'),array('id'=>$res->id));
				$visit = '1';
				$is_payment_required = false;
				$payment_status = '1';
				$free_visit_status = '2';
			}else{
				$visit = '0';
				$free_visit_status = '0';
				if($data['payment_mode'] == '1'){
					$payment_status = '1';
				}else{
					$payment_status = '0';
				}
				$is_payment_required = true;
			}
		}else{
			$visit = '0';
			$is_payment_required = true;
			$free_visit_status = '0';
			if($data['payment_mode'] == '1'){
				$payment_status = '1';
			}else{
				$payment_status = '0';
			}
		}

		if(isset($promocode) && ($promocode != '')){
			$new_amnt = ($data['amount'] * $promocode['promo_data']['amount'])/100;
			$diff = $data['amount'] - $new_amnt;
			$promo_name = $promocode['promo_data']['name'];
		}else{
			$new_amnt = '';
			$diff = $data['amount'];
			$promo_name = '';
		}

		$check = $this->db->get_where('tbl_booking',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id'],'date'=>$data['date'],'time'=>$data['time'],'payment_status'=>'1'));
		$this->db->select('name,profile_pic,specialization');
		$doctr_data = $this->db->get_where('tbl_doctors',array('id'=>$data['doctor_id']))->row_array();
		//print_r($doctr_data);exit();
		$special = $this->db->get_where('tbl_specialization',array('id'=>$doctr_data['specialization']))->row();
		$fcm_user = $this->db->get_where('tbl_authtoken',array('userid'=>$patientid['userid']))->row();
		$conslt_time =  date('Y-m-d h:i:s');
		$conslt_time = strtotime($conslt_time);
		$settngs = $this->db->get('settings')->row();
		$ipokefees = $settngs->ipok_fee;
		if($check->num_rows() <= 0){
				//$patientid = $query->row_array();
			//$offset=5.5*60*60;
			$date_def = date('Y-m-d',$data['date']);
			$times = explode('-', $data['time']);
			$start_time = strtotime($date_def.$times[0]);
			$end_time = strtotime($date_def.$times[1]);
			$msg = "Your booking for doctor ".$doctr_data['name']." at time ".$data['time']." is confirmed";
			$msg2 = "You have a new booking on  ".date('jS F Y',$data['date'])." at ".date('h:i A',$start_time);
			if($this->db->insert('tbl_booking',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id'],'patient_id'=>$patientid['userid'],'ipok_fee'=>$ipokefees,'date'=>$data['date'],'time'=>$data['time'],'booking_status'=>'1','payment_status'=>$payment_status,'free_visit_status'=>$free_visit_status,'visit_type'=>$visit,'amount'=>$data['amount'],'promo_name'=>$promo_name,'promo_amount'=>$new_amnt,'payment_type'=>$data['payment_mode'],'total_sum'=>$diff,'time_start'=>$start_time,'time_end'=>$end_time,'requested_date'=>time()))){
				$insert_id = $this->db->insert_id();

				if($visit == '0'){
					$doctor_wallet = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$data['doctor_id']))->row();
					$ipkfee = $this->db->get('settings')->row();
					$futures = $diff - (($diff * $ipkfee->ipok_fee)/100);

					if($doctor_wallet){
						$future = $futures + (decrypt_data($doctor_wallet->future_earn));
						$total = $future + (decrypt_data($doctor_wallet->reedem_earn));
						$this->db->update('tbl_wallet_details',array('future_earn'=>encrypt_data($future),'total_earn'=>encrypt_data($total)),array('doctor_id'=>$data['doctor_id']));
					}else{
						$this->db->insert('tbl_wallet_details',array('future_earn'=>encrypt_data($futures),'total_earn'=>encrypt_data($futures),'doctor_id'=>$data['doctor_id'],'reedem_earn'=>encrypt_data('0')));
					}
				}
				
				if($payment_status == '1'){
					$this->db->insert('tbl_patient_notification',array('patient_id'=>$patientid['userid'],'type'=>'0','message'=>$msg,'time'=>$conslt_time,'booking_id'=>$insert_id,'read_status'=>'0'));
					$patient_insert_id = $this->db->insert_id();

					$new['id'] = $patient_insert_id;
					$new['type'] = "Consultation Confirmation";
					$new['booking_id'] = $insert_id;
					$new['booking_date'] = $data['date'];
					$new['doctor_id'] = $data['doctor_id'];
					$new['doctor_name'] = $doctr_data['name'];
					$new['doctor_specialization'] = $special->specialization_name;
					$new['doctor_photo'] = $doctr_data['profile_pic'];
					$new['message'] = $msg;
					$new['time'] = $conslt_time;
					$new['to'] =$fcm_user->fcm_token;
					$user_type = '1';
	                $user_push = $this->push_sent($new,$user_type);
					
					$this->db->insert('tbl_doctor_notifications',array('doctor_id'=>$data['doctor_id'],'type'=>'2','message'=>$msg2,'time'=>$conslt_time,'read_status'=>'0'));
					$doctor_insert_id = $this->db->insert_id();
					$fcm_doctor = $this->db->get_where('tbl_authtoken_doctors',array('doctor_id'=>$data['doctor_id']))->row();
					$news['id'] = $doctor_insert_id;
					$news['type'] = "New Consultation";
					$news['message'] =$msg2;
					$news['read_status'] = false;
					$news['to'] = $fcm_doctor->fcm_token;
					$doctor_type = '2';
					$doctor_push = $this->push_sent($news,$doctor_type);
				}
				$return_array = array('status'=>'success','data'=>array('booking_id'=>$insert_id,'is_waiting'=>false,'is_payment_required'=>$is_payment_required));
			}
			else{
				$return_array = array('status'=>'fail','msg' =>'insertion failed');
			}
		}
		elseif($check->num_rows() == 1){
			$date_def = date('Y-m-d',$data['date']);
			$times = explode('-', $data['time']);
			$start_time = strtotime($date_def.$times[0]);
			$end_time = strtotime($date_def.$times[1]);
			$msg = "Your booking for doctor ".$doctr_data['name']." at time ".$data['time']." is in Waiting list";
			if($this->db->insert('tbl_booking',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id'],'patient_id'=>$patientid['userid'],'ipok_fee'=>$ipokefees,'date'=>$data['date'],'time'=>$data['time'],'booking_status'=>'0','payment_status'=>$payment_status,'free_visit_status'=>$free_visit_status,'visit_type'=>$visit,'amount'=>$data['amount'],'promo_name'=>$promo_name,'promo_amount'=>$new_amnt,'payment_type'=>$data['payment_mode'],'total_sum'=>$diff,'time_start'=>$start_time,'time_end'=>$end_time,'requested_date'=>time()))){
				$insert_id = $this->db->insert_id();
				if($payment_status == '1'){
					$this->db->insert('tbl_patient_notification',array('patient_id'=>$patientid['userid'],'type'=>'1','message'=>$msg,'time'=>$conslt_time,'booking_id'=>$insert_id,'read_status'=>'0'));
					$patient_insert_id = $this->db->insert_id();

					$new['id'] = $patient_insert_id;
					$new['type'] = "Waiting List";
					$new['booking_id'] = $insert_id;
					$new['booking_date'] = $data['date'];
					$new['doctor_id'] = $data['doctor_id'];
					$new['doctor_name'] = $doctr_data['name'];
					$new['doctor_specialization'] = $special->specialization_name;
					$new['doctor_photo'] = $doctr_data['profile_pic'];
					$new['message'] = $msg;
					$new['time'] = $conslt_time;
					$new['to'] =$fcm_user->fcm_token;
					$user_type = '3';
	                $user_push = $this->push_sent($new,$user_type);
				}
			$return_array = array('status'=>'failed','data' =>array('booking_id'=>$insert_id,'is_waiting'=>true,'is_payment_required'=>$is_payment_required));
		}

		}
		elseif($check->num_rows() > 1){
			$return_array = array('status'=>'fail','msg' =>'Selected Doctor not available');
		}
		return $return_array;
	}

//........................ get promocodes based on id

	public function get_promocode_result($data){
		$query = $this->db->get_where('tbl_promocode',array('id'=>$data['promocode_id']))->row();
		if($query){
			$doctors_id = explode(',',$query->doctor_id);
			if(in_array($data['doctor_id'], $doctors_id)){
				if($data['date'] >= $query->valid_from && $data['date'] <= $query->valid_to){
					$new =array();
					$new['name'] = $query->promo_name;
					$new['amount'] = $query->amount;
					$res = array('status'=>'success','data'=>array('promo_data'=>$new));
				}else{
					$res = array('status'=>'fail','msg'=>'Promocode get Expired');
				}
			}else{
				$res =array('status'=>'fail','msg'=>'Promocode is not used by this doctor');
			}
		}else{
			$res = array('status'=>'fail','msg'=>'Invalid Promocode Id');
		}
		return $res;
	}

//............................ get clinic specialisation

	function is_cpf_exist($cpf){
		$res = $this->db->get_where('tbl_cpf_number',array('cpf'=>$cpf))->row();
		if($res){
			$query = array('status'=>'error');
		}else{
			$query = array('status'=>'success');
		}
		return $query;
	}

	function get_clinic_specialisation(){
		$this->db->select("DISTINCT(tbl_specialization.specialization_name),tbl_clinic_specialization.clinic_id,tbl_specialization.id");
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_clinic_specialization.specialization_id');
		$this->db->group_by('tbl_specialization.id');
		$query = $this->db->get_where("tbl_clinic_specialization");
		if ($query->num_rows() > 0) {
			$return_array = array('status'=>'success','data'=>$query->result_array());
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//........................ search a doctor by differnt fields

	function search_doctor_query($data,$lat,$lng){
 		$this->db->select("DISTINCT(tbl_clinic.id) as clinic_id,tbl_doctors.id as doctor_id,
 							tbl_doctors.name,
 							tbl_doctors.profile_pic AS doctor_photo,
							tbl_doctors.price,
							tbl_doctors.domiciliary_status,
							tbl_doctors.online_status as online,
							tbl_specialization.specialization_name AS specialisation,
							tbl_clinic.name as clinic_name,
							ROUND(( 6371 * acos( cos( radians({$lat}) ) * cos( radians( `tbl_clinic`.`location_lattitude` ) ) * cos( radians( `tbl_clinic`.`location_longitude` ) - radians({$lng}) ) + sin( radians({$lat}) ) * sin( radians( `tbl_clinic`.`location_lattitude` ) ) ) )) AS distance
						");
		$this->db->from("tbl_doctors");

		$this->db->join('tbl_clinic_doctors', 'tbl_doctors.id = tbl_clinic_doctors.doctor_id','INNER');
		$this->db->join('tbl_clinic', 'tbl_clinic_doctors.clinic_id = tbl_clinic.id','INNER');
		$this->db->join("tbl_specialization","tbl_doctors.specialization = tbl_specialization.id","LEFT");
		
		
 		if(isset($data['query']) && strlen($data['query'])){
 			$query = $data['query'];
 			$where = 'tbl_doctors.name LIKE '."'$query%'";
 			$this->db->where($where);
			$this->db->having('distance <= 20');
 		}
 		if(isset($data['speciality']) && strlen($data['speciality'])){

 			$speciality = $data["speciality"];
 			$where = 'tbl_doctors.specialization ='. "'$speciality'";
			$this->db->where($where);
 		}
 		// if(isset($data['date']) && strlen($data['date'])){
 		// 	$this->db->join("tbl_doctor_leave","tbl_doctors.id = tbl_doctor_leave.doctor_id and tbl_clinic_doctors.clinic_id = tbl_doctor_leave.clinic_id","LEFT");
 		// 	$date = $data["date"];
 		// 	$this->db->where("(tbl_doctor_leave.start_date IS NULL or ($date<tbl_doctor_leave.start_date OR $date>tbl_doctor_leave.end_date))");
 		// 	//$new_where = "(select count(*) from tbl_doctor_leave where ($date > tbl_doctor_leave.start_date OR  $date < tbl_doctor_leave.end_date)) =". 0;
 		// 	//$this->db->where($new_where);
			// //$this->db->or_where($or_where);
 		// }
 		if(isset($data['others']) && strlen($data['others'])){
 			if($data['others'] == 'MEN' || $data['others'] == 'WOMEN'){
 				if($data['others'] == 'MEN'){
		 			$data['others'] = 'MALE';
		 		}
		 		if($data['others'] == 'WOMEN'){
		 			$data['others'] = 'FEMALE';
		 		}
		 		$others = $data['others'];
		 		$where = 'tbl_doctors.gender ='. "'$others'";
		 		$this->db->where($where);
 			}
 			if($data['others'] == 'LOWER VALUE'){
 				
		 		$where = 'tbl_doctors.price';
		 		$this->db->order_by($where,'asc');
 			}
 			if($data['others'] == 'MOST WELL ASSESSED'){
 				$inner_query = $this->db->query("SELECT doctor_id,COUNT(doctor_id) AS count FROM tbl_review GROUP BY doctor_id HAVING COUNT(doctor_id) = (SELECT MAX(mycount) AS count FROM (SELECT COUNT(doctor_id) AS mycount,doctor_id FROM tbl_review GROUP BY doctor_id) AS c)");
		
				if($inner_query->num_rows() > 0){
					$resultArray = $inner_query->result_array();
					$doctorID = $resultArray[0]['doctor_id'];
					$where = 'tbl_doctors.id ='."'$doctorID'";
					$this->db->where($where);
				}
		 	}
		 	if($data['others'] == 'DOMICILIARY ATTENDANCE'){
		 		
		 		$where = "CAST(AES_DECRYPT(tbl_doctors.domiciliary_status,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) =". 1;
		 		$this->db->where($where);
		 	}
 		}
 		if(isset($data['location_name']) && strlen($data['location_name']) && isset($data['location_latitude']) && strlen($data['location_latitude']) && isset($data['location_longitude']) && strlen($data['location_longitude'])){

 			$datalat = $data['location_latitude'];
 			$datalong = $data['location_longitude'];
 			$where = "ROUND(( 6371 * acos( cos( radians({$datalat}) ) * cos( radians( `location_lattitude` ) ) * cos( radians( `location_longitude` ) - radians({$datalong}) ) + sin( radians({$datalat}) ) * sin( radians( `location_lattitude` ) ) ) )) <=". 50;
			$this->db->where($where);
 		}
 		if(isset($data['clinic_id']) && strlen($data['clinic_id'])){
 			
 			$where = 'tbl_clinic_doctors.clinic_id';
 			$this->db->where($where,$data['clinic_id']);
 		}
 		
 		$query = $this->db->get();
		//echo $this->db->last_query();exit();
		//print_r($this->db->last_query());die();
		if ($query->num_rows() > 0) {
			$querys = $query->result_array();
			//echo "<pre>";print_r($querys);exit();
			if(isset($data['date']) && strlen($data['date'])){
				$day = date('D',$data['date']);
				$day = strtolower($day);
				$date = $data['date'];
				$leave_query = $this->db->query("SELECT * FROM `tbl_doctor_leave` WHERE ($date >= `tbl_doctor_leave`.`start_date` AND $date <= `tbl_doctor_leave`.`end_date`)")->result();
				//echo $this->db->last_query();
				if($leave_query){
					//echo"s";
					foreach ($leave_query as $key => $value) {
						foreach ($querys as $keys => $values) {
							if(($values['doctor_id'] == $value->doctor_id ) && ($values['clinic_id'] == $value->clinic_id)){
								//echo"n".$values['clinic_id'].'-'.$values['doctor_id']."<br>";
								unset($querys[$keys]);
							}else{
								//echo"s".$values['clinic_id'].'-'.$values['doctor_id'];
								$consult = $this->db->get_where('tbl_consultation',array('clinic_id'=>$values['clinic_id'],'doctor_id'=>$values['doctor_id']))->row();
								if($consult){
									if($consult->date != '""'){
										$consult_date = json_decode($consult->date);
										foreach ($consult_date as $consult_key => $consult_value) {
											$new_array_day = array();
											$new_array_day[] = $consult_value->day;
										}
									//	print_r($new_array_day);
										if(!in_array($day, $new_array_day)){
											unset($querys[$keys]);
										}
									}else{
										unset($querys[$keys]);
									}
								}
							}
						}
					}
				}else{
					foreach ($querys as $keys => $values) {
						//echo"s".$values['clinic_id'].'-'.$values['doctor_id'];
						$consult = $this->db->get_where('tbl_consultation',array('clinic_id'=>$values['clinic_id'],'doctor_id'=>$values['doctor_id']))->row();
						if($consult){
							if($consult->date != '""'){
								$consult_date = json_decode($consult->date);
								foreach ($consult_date as $consult_key => $consult_value) {
									$new_array_day = array();
									$new_array_day[] = $consult_value->day;
								}
								//print_r($new_array_day);
								if(!in_array($day, $new_array_day)){
									unset($querys[$keys]);
								}
							}else{
								unset($querys[$keys]);
							}
						}
					}
				}
			}
			//echo"<pre>";print_r($querys);exit();
			$return_array = array('status'=>'success','data'=>$querys);
		}
		else{
			$return_array = array('status'=>'fail');
		}		
		return $return_array;		
	}

//...................search clinic based on different fields

	function search_clinic_query($data,$lat,$lng){
 		
 		
 		
		$this->db->select("tbl_clinic.id as clinic_id,
							tbl_clinic.name,
							tbl_clinic.profile_photo AS clinic_photo,
							ROUND(( 6371 * acos( cos( radians({$lat}) ) * cos( radians( `location_lattitude` ) ) * cos( radians( `location_longitude` ) - radians({$lng}) ) + sin( radians({$lat}) ) * sin( radians( `location_lattitude` ) ) ) )) AS distance,
							tbl_specialization.specialization_name as speciality_of_the_clinic
						");
		$this->db->from("tbl_clinic");

		$this->db->join("tbl_clinic_specialization","tbl_clinic.id = tbl_clinic_specialization.clinic_id","LEFT");
		$this->db->join("tbl_specialization","tbl_specialization.id = tbl_clinic_specialization.specialization_id","LEFT" );
		if(isset($data['query']) && strlen($data['query'])){
			$query = $data["query"];
 			$where = 'tbl_clinic.name LIKE '."'$query%'";
			$this->db->where($where);

 		}
 		if(isset($data['speciality']) && strlen($data['speciality'])){
 			$speciality = $data["speciality"];
 			$where = 'tbl_clinic_specialization.specialization_id ='. "'$speciality'";
			$this->db->where($where);
 		}
 		if(isset($data['location_name']) && strlen($data['location_name']) && isset($data['location_latitude']) && strlen($data['location_latitude']) && isset($data['location_longitude']) && strlen($data['location_longitude'])){

 			
 			$datalat = $data['location_latitude'];
 			$datalong = $data['location_longitude'];
 			$where = "ROUND(( 6371 * acos( cos( radians({$datalat}) ) * cos( radians( `location_lattitude` ) ) * cos( radians( `location_longitude` ) - radians({$datalong}) ) + sin( radians({$datalat}) ) * sin( radians( `location_lattitude` ) ) ) )) <=". 50;
			$this->db->where($where);
 		}
		$query = $this->db->get();
		//echo $this->db->last_query();exit();
		if ($query->num_rows() > 0) {
			$return_array = array('status'=>'success','data'=>$query->result_array());
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;		
	}

	

//................................ Doctors Availability

	function doctor_availability($ID){
		$this->db->select("tbl_consultation.*");
		$query = $this->db->get_where('tbl_consultation',array('doctor_id' => $ID['doctor_id'],'clinic_id' => $ID['clinic_id']))->row_array();		
		if (count($query) > 0) {
			$this->db->select('consultation_duration');
			$res=$this->db->get_where('tbl_doctors',array('id'=>$ID['doctor_id']))->row();
			$query['duration'] = $res->consultation_duration;
			$return_array = array('status'=>'success','data'=>$query);
		}
		else{
			$return_array = array('status'=>'fail');
		}
		return $return_array;
	}

//..................................... clinic profile

	function clinic_profile($clinicId){

							
		$this->db->select('tbl_clinic.id as clinic_id,
							tbl_clinic.name as clinic_name,
							GROUP_CONCAT(DISTINCT(tbl_specialization.specialization_name) SEPARATOR ",") as clinic_specialization,
							tbl_clinic.profile_photo as clinic_photo,
							tbl_clinic.location_lattitude as latitude,
							tbl_clinic.location_longitude as longitude,
							tbl_clinic.about as about,
							tbl_clinic.cep,
							tbl_clinic.street_address,
							tbl_clinic.locality,
							tbl_clinic.number,
							COUNT(DISTINCT(tbl_review_clinic.clinic_id)) as no_of_reviews');
		$this->db->from('tbl_clinic');
		$this->db->join('tbl_clinic_specialization','tbl_clinic_specialization.clinic_id = tbl_clinic.id');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_clinic_specialization.specialization_id','LEFT');
		$this->db->join('tbl_review_clinic','tbl_review_clinic.clinic_id = tbl_clinic.id','LEFT');
		$this->db->where('tbl_clinic.id',$clinicId);
		$query = $this->db->get();

		if($query->num_rows() > 0){
			$result = array('status'=>'success','data'=>$query->row_array());
		}
		else{
			$result = array('status' => 'fail');
		}
		return $result;

	}

//................................ get doctor available dates

	/*function get_doctor_dates($data){
		$this->load->helper('file');
		$string = read_file('commonData.php');
		$this->string = json_decode($string);
//		date_default_timezone_set("Asia/Kolkata");
		//$times = explode('-', $data['time_interval']);			
		//$where = strtotime($this->string->default_date. $times[0]).'<= unix_timestamp(concat("2001-01-01"," ",time)) and unix_timestamp(concat("2001-01-01"," ",time)) <= '.strtotime($this->string->default_date . $times[1]);			
		$this->db->select("tbl_booking.*,l.start_date,l.end_date");
		$this->db->from('tbl_booking');
		$this->db->join("tbl_doctor_leave l","l.doctor_id = {$data['doctor_id']} AND monthname(CONVERT_TZ(FROM_UNIXTIME(`l`.`start_date`),@@session.time_zone,'+00:00')) = '{$data['month']}' AND year(CONVERT_TZ(FROM_UNIXTIME(`l`.`start_date`),@@session.time_zone,'+00:00')) = '".$data['year']."' OR monthname(CONVERT_TZ(FROM_UNIXTIME(`l`.`end_date`),@@session.time_zone,'+00:00')) = '{$data['month']}' AND year(CONVERT_TZ(FROM_UNIXTIME(`l`.`end_date`),@@session.time_zone,'+00:00')) = '".$data['year']."'","LEFT", false);
		$this->db->where('monthname(CONVERT_TZ(FROM_UNIXTIME(`tbl_booking`.`date`),@@session.time_zone,"+00:00"))', $data['month']);
		$this->db->where('year(CONVERT_TZ(FROM_UNIXTIME(`tbl_booking`.`date`),@@session.time_zone,"+00:00"))', $data['year']);
		//$this->db->where('tbl_booking.time',$data['time_interval']);
		$this->db->where('tbl_booking.doctor_id',$data['doctor_id']);
		$this->db->group_by('tbl_booking.id');
		$query = $this->db->get();	

		if($query->num_rows() > 0){
			$result = array('status'=>'success','data'=>$query->result_array());
		}
		else{
			$result = array('status' => 'fail');
		}
		return $result;
	}*/
	
	public function get_doctor_dates($data){
		$query = $this->db->get_where('tbl_consultation',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id']))->row();
		$leave = $this->db->get_where('tbl_doctor_leave',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id']))->result();
		if($query){
			if($query->active_schedule == '0'){
				$result = array('status'=>'success','data'=>$query->date,'leave'=>$leave);	
			}else{
				$result = array('status'=>'success','data'=>$query->date_secondary,'leave'=>$leave);	
			}
		}else{
			$result = array('status'=>'success');
		}
		//print_r($result);exit();
		return $result;
	}

//............................ booking list of a patient

	function get_booking_list($authtoken){
			$this->db->select("tbl_booking.id as booking_id,
								tbl_booking.date as date,
								tbl_booking.time as time_interval,
								tbl_doctors.id as id,
								tbl_doctors.name as doctor_name,
								tbl_doctors.profile_pic as doctor_photo,
								tbl_booking.booking_status");
			$this->db->from('tbl_booking');
			$this->db->join('tbl_authtoken','tbl_authtoken.userid = tbl_booking.patient_id','INNER');
			$this->db->join('tbl_doctors','tbl_doctors.id = tbl_booking.doctor_id','INNER');
			$this->db->where('tbl_authtoken.authtoken',$authtoken);
			$this->db->where('tbl_booking.payment_status','1');
			$query = $this->db->get();
			if($query->num_rows() > 0){
					$result = array('status'=>'success','data'=>$query->result_array());
				}
				else{
					$result = array('status' => 'fail');
				}
				return $result;
	}



/*...........................................................................................*/
/*..................................... Doctor Model .......................................*/

//........................ Register Doctor
	function register_doctor($data){
	    //$data['name'] = encrypt_data($data['name']);
		$data['about'] = encrypt_data($data['about']);
		//$data['price'] = encrypt_data($data['price']);		
		$data['gender'] = encrypt_data($data['gender']);
		//$data['domiciliary_status'] = encrypt_data($data['domiciliary_status']);
		$data['rg'] = encrypt_data($data['rg']);
		$data['crm'] = encrypt_data($data['crm']);
		$data['cep'] = encrypt_data($data['cep']);
		$data['street_address'] = encrypt_data($data['street_address']);
		$data['locality'] = encrypt_data($data['locality']);
		$data['number'] = encrypt_data($data['number']);
		$data['complement'] = encrypt_data($data['complement']);
		if($this->db->insert('tbl_doctors', $data)){
				$insertid = $this->db->insert_id();
				$this->db->query("update tbl_doctors set dob = AES_ENCRYPT(".$data['dob'].",'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA')where id = ".$insertid);

				$this->db->select("CAST(AES_DECRYPT(`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
				$this->db->where('id',$insertid);
				$query_date = $this->db->get('tbl_doctors')->row(); 
				$query = $query->row_array();
				unset($query['dob']);
				$query['dob'] = $query_date->dob;
				//$query['name'] = decrypt_data($query['name']);
				$query['about'] = decrypt_data($query['about']);
				//$query['price'] = decrypt_data($query['price']);
				$query['gender'] = decrypt_data($query['gender']);
				//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);
				$query['rg'] = decrypt_data($query['rg']);
				$query['crm'] = decrypt_data($query['crm']);
				$query['cep'] = decrypt_data($query['cep']);
				$query['street_address'] = decrypt_data($query['street_address']);
				$query['locality'] = decrypt_data($query['locality']);
				$query['number'] = decrypt_data($query['number']);
				$query['complement'] = decrypt_data($query['complement']);
				$query = $this->db->get_where("tbl_doctors",array("id"=>$insertid)); 

				$return_array = array('status'=>'success','userdata'=>$query);
			}
			else{
				$return_array = array('status'=>'fail');
			}
			return $return_array;
	}

// check username or email exist or not 


	function dataExist_doctor($data){

		if(isset($data['username']) && strlen($data['username'])){

			$query_uname = $this->db->get_where("tbl_doctors",array("username"=>$data['username'])); 
		}
		if(isset($data['email']) && strlen($data['email'])){

			$query_email = $this->db->get_where("tbl_doctors",array("email"=>$data['email']));
		}
		if(isset($query_uname))
		{
			if($query_uname->num_rows() > 0){

				if(isset($query_email)){

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

						$return_array = array('message'=>'username and email are already exist');
					}
					else{

						$return_array = array('message'=>'username already exist');
					}
				}

				else{

					$return_array = array('message'=>'username already exist');
				}
			}
			else{
				$return_array = array('message'=>'success');
			}
		}
		else if(isset($query_email)){

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

				$return_array = array('message'=>'email already exist');
			}
			else{

				$return_array = array('message'=>'success');
			}
		}
		else{
			$return_array = array('message'=>'fail');
		}
		return $return_array;
	}

//..................... delete doctor based on id

	function delete_registration_doctor($uid){
		 if($this->db->where_in('id', $uid)->delete('tbl_doctors')){


		 }
	}
	
	
	function is_waiting_list_used($data,$time){
		$query = $this->db->get_where('tbl_booking',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id'],'date'=>$data['date'],'time'=>$time))->result();
		if(count($query) > 0){
			return $query;
		}else{
			return false;
		}
	}

//........................ set authtoken in database for doctor


	function authtoken_registration_doctor($authtoken,$userid){
		$data = array('authtoken'=>$authtoken,'doctor_id'=>$userid);
		if($this->db->insert('tbl_authtoken_doctors', $data)){
			return true;
		}
		else{
			return false;
		}
	}

//................. set profile pic path into database

	function updatePic_doctor($data,$id){
		$this->db->update('tbl_doctors', $data, array('id' => $id));
	}

//.......................add patient review for doctors

	function doctor_review($data,$authtoken){

		$this->db->select('userid');
		$rslt = $this->db->get_where('tbl_authtoken',array('authtoken'=>$authtoken))->row();
		if($rslt){
			$this->db->select('name');
			$doctr_data = $this->db->get_where('tbl_registration',array('id'=>$rslt->userid))->row();
			$msg = "Your have a new review from  ".decrypt_data($doctr_data->name);
			$data['reviewer_id'] = $rslt->userid;
			$datetime = Date('Y-m-d h:i:s');
			$data['date'] = strtotime($datetime);
			$query = $this->db->get_where('tbl_booking',array('medical_record_id'=>$data['medical_record_id']))->row();
			if($query){
				if($query->medical_record_id != '' || $query->medical_record_id != '0'){
					$this->db->update('tbl_medical_records',array('patient_review'=>encrypt_data($data['review'])),array('id'=>$data['medical_record_id']));
				}
			}
			unset($data['medical_record_id']);
			if($this->db->insert('tbl_review',$data)){
				$this->db->insert('tbl_doctor_notifications',array('doctor_id'=>$data['doctor_id'],'type'=>'1','message'=>$msg,'time'=>$data['date'],'read_status'=>'0'));
				$doctor_insert_id = $this->db->insert_id();
				$fcm_doctor = $this->db->get_where('tbl_authtoken_doctors',array('doctor_id'=>$data['doctor_id']))->row();
				$news['id'] = $doctor_insert_id;
				$news['type'] = "New Review";
				$news['message'] =$msg;
				$news['read_status'] = false;
				$news['to'] = $fcm_doctor->fcm_token;
				$doctor_type = '2';
				$doctor_push = $this->push_sent($news,$doctor_type);
				
				$res = array("status"=>"success","msg" =>"Insertion Success");
			}else{
				$res = array("status"=>"failed","msg" =>"Insertion failed");
			}
		}else{
			$res = array("status"=>"failed","msg" =>"Invalid Auth token");
		}
		return $res;
	}
	
	function notification($id,$start,$per_page){
		$this->db->select('tbl_patient_notification.id,tbl_patient_notification.booking_id,tbl_patient_notification.type,tbl_patient_notification.message,tbl_patient_notification.time,tbl_doctors.id as doctor_id,tbl_patient_notification.booking_id,tbl_booking.date,tbl_doctors.profile_pic as doctor_photo,tbl_doctors.name as doctor_name,tbl_specialization.specialization_name as doctor_specialization,tbl_patient_notification.read_status');
		$this->db->join('tbl_booking','tbl_booking.id = tbl_patient_notification.booking_id');
		$this->db->join('tbl_doctors','tbl_doctors.id = tbl_booking.doctor_id');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.specialization');
		$this->db->limit($per_page,$start);
		$this->db->order_by('tbl_patient_notification.id','DESC');
		$query = $this->db->get_where('tbl_patient_notification',array('tbl_patient_notification.patient_id'=>$id))->result();
		if(count($query) > 0){
			return $query;
		}else{
			return false;
		}
	}
	
	public function get_recent_chat_list($id,$start,$per_page,$type){
		$this->db->select('tbl_recent_chats.chat_id as id,tbl_recent_chats.patient_id,tbl_registration.name as patient_name,tbl_registration.profile_photo as patient_photo,tbl_recent_chats.doctor_id,tbl_doctors.name as doctor_name,tbl_doctors.profile_pic as doctor_photo,tbl_recent_chats.msg as message,tbl_recent_chats.sender_type,tbl_recent_chats.photo_url,tbl_recent_chats.video_url,tbl_recent_chats.type,tbl_recent_chats.time');
		$this->db->join('tbl_doctors','tbl_doctors.id = tbl_recent_chats.doctor_id');
		$this->db->join('tbl_registration','tbl_registration.id = tbl_recent_chats.patient_id');
		if($type == 'user'){
			$this->db->where('tbl_recent_chats.patient_id',$id);
		}else{
			$this->db->where('tbl_recent_chats.doctor_id',$id);
		}
		$query = $this->db->get('tbl_recent_chats')->result();
		//echo $this->db->last_query();exit();
		if(count($query) > 0){
			foreach ($query as $key => $value) {
				$query[$key]->patient_name = decrypt_data($value->patient_name);
				//$query[$key]->doctor_name = decrypt_data($value->doctor_name);
			}
			return $query;
		}else{
			return false;
		}
	}



//update booking time
/*
	function update_bookingdate($data){
		$result = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		$date = date('Y-m-d',$data['date']);
        $times = explode('-',$result->time);
        $start = strtotime($date.$times[0]);
        $end = strtotime($date.$times[1]);
		if($this->db->update('tbl_booking',array('date'=>$data['date'],'time_start'=>$start,'time_end'=>$end),array('id'=>$data['booking_id']))){
			$res = array("message" =>"Updated Successfully");
		}else{
			$res = false;
		}
		return $res;
	}
*/

//.................... get user id from auth token table

	function get_userid_frm_authtoken($auth){
		$this->db->select('userid');
		$rslt = $this->db->get_where('tbl_authtoken',array('authtoken'=>$auth))->row();
		return $rslt;
	}

//.................... get doctor id from auth token table

	function get_doctorid_frm_authtoken($auth){
		$this->db->select('doctor_id');
		$rslt = $this->db->get_where('tbl_authtoken_doctors',array('authtoken'=>$auth))->row();
		return $rslt;
	}

//........................... add dependent for patient

	function add_dependent($id,$data){
		if($this->db->insert('tbl_patient_dependent',array('patient_id'=>$id,'dependent_name'=>$data['dependent_name'],'relation'=>$data['dependent_relation'],'dob'=>$data['dependent_dob'],'image'=>$data['image'],'cpf'=>$data['dependent_cpf']))) {
			
			$result = $this->db->get_where('tbl_patient_dependent',array('patient_id'=>$id))->result();
			if(count($result) >0 ){
				return $result;
			}else{
				return false;
			}
		}
	}

//.......................get dependent list by userid
	
	function get_dependent_list_users($auth){
		$this->db->select('userid');
		$rslt = $this->db->get_where('tbl_authtoken',array('authtoken'=>$auth))->row();
		//echo $this->db->last_query();
		//print_r($rslt);
		if($rslt){
			$this->db->select('dependent_name,id as dependent_id,image as dependent_image,dob as age,relation as dependent_relation');
			$res = $this->db->get_where('tbl_patient_dependent',array('patient_id'=>$rslt->userid))->result();
			$res = array("status"=>"success","data"=>$res);
//echo $this->db->last_query();exit();
		}else{
			$res = array("status"=>"failed","msg" =>"Invalid Auth token");
		}
		return $res;
	}

//................................get upcomming consultation

	function get_upcoming_consultation($id){
		$date = strtotime(date('y-m-d h:i:s'));

		$this->db->select("tbl_doctors.id,tbl_doctors.name as doctor_name,tbl_doctors.online_status as doctor_online,tbl_doctors.consultation_duration,tbl_doctors.profile_pic as doctor_profile_photo,tbl_specialization.specialization_name as doctor_speciality,tbl_doctors.street_address,tbl_doctors.locality,tbl_doctors.number,tbl_doctors.complement,tbl_doctors.price as consultation_fee,tbl_clinic.location_lattitude as clinic_latitude,tbl_clinic.location_longitude as clinic_longitude,tbl_booking.date,tbl_booking.total_sum as total,tbl_booking.doctor_id,tbl_booking.clinic_id,tbl_booking.id as booking_id");
		$this->db->from("tbl_booking");
		$this->db->join("tbl_doctors","tbl_doctors.id = tbl_booking.doctor_id");
		$this->db->join("tbl_clinic","tbl_clinic.id = tbl_booking.clinic_id");
		$this->db->join("tbl_specialization","tbl_specialization.id = tbl_doctors.	specialization");
		$this->db->where("tbl_booking.id",$id);
		//$this->db->where("tbl_booking.date >= '".$date."'");
		$result = $this->db->get()->row();

		foreach ($result as $key => $value) {
			$result[$key]->street_address = decrypt_data($value->street_address);
			$result[$key]->locality = decrypt_data($value->locality);
			$result[$key]->number = decrypt_data($value->number);
			$result[$key]->complement = decrypt_data($value->complement);
			$result[$key]->consultation_fee = decrypt_data($value->consultation_fee);
		}

		$this->db->where('doctor_id',$result->doctor_id);
		$this->db->where('clinic_id',$result->clinic_id);
		$clinic_details = $this->db->get('tbl_consultation')->row();

		$this->db->select('cancelation_policy');
		$cancel_rslt = $this->db->get('tbl_policy')->row();
		$new = array();
		if($result){
			$new['address']['street'] = $result->street_address;
			$new['address']['locality'] = $result->locality;
			$new['address']['number'] = $result->number;
			$new['address']['complement'] = $result->complement;

			unset($result->street_address);
			unset($result->locality);
			unset($result->number);
			unset($result->complement);

			$new['address'] = implode(',',$new['address']);
			$result->address = $new['address'];
			$this->db->select('ipok_fee');
			$fee = $this->db->get('settings')->row();
			$actual = ($result->consultation_fee * $fee->ipok_fee)/100 ;
			$result->tax = $actual;
			$result->cancellation_policy = strip_tags($cancel_rslt->cancelation_policy);
		//	$result->cancellation_policy = preg_replace("/&nbsp;|\r\n/",'',$result->cancellation_policy);
			//$result->cancellation_policy = preg_replace('/&#39;/',"'",$result->cancellation_policy);
			//print_r($clinic_details);exit();
			$days = json_decode($clinic_details->date);
			//echo"<pre>"; print_r($days); echo"</pre>"; 
			if($days != ''){
				$doctr_days = array();
				foreach ($days as $key => $value) {
					//print_r($value->time->start);exit();
					$doctr_days[$key] = $value->day.' :'. $value->time->start .'-'. $value->time->end ;
				}
				$doctorday = implode(', ',$doctr_days);
				
			}else{
				$doctorday = '';
			}
			$result->doctor_available=$doctorday;
			$res = array("status"=>"success","data"=>$result);
		}else{
			$res = array("status"=>"failed");
		}
		return $res;
 		
	}

//........................ change patient password

	function change_patient_password($id,$data){
		$query = $this->db->get_where('tbl_registration',array('id'=>$id))->row_array();
		if($query){
            if(md5($data['current_password']) == $query['password']){
            	if($this->db->update('tbl_registration',array('password'=>md5($data['new_password'])),array('id'=>$id))){
            		$res = array("status"=>"success","msg"=>" Password Updated Successfully");
            	}else{
            		$res = array("status"=>"failed","msg"=>"Sorry Not updated. Something went wrong");
            	}
            }else{
            	$res = array("status"=>"failed","msg"=>"Current Password and Existing Password Doesn't match");
            }
		}else{
			$res = array("status"=>"failed","msg"=>"Password not Updated. User Cannot Exist");
		}
		return $res;
	}


	function doctor_change_password($id,$data){
		$query = $this->db->get_where('tbl_doctors',array('id'=>$id))->row_array();
		if($query){
            if(md5($data['old_password']) == $query['password']){
            	if($this->db->update('tbl_doctors',array('password'=>md5($data['new_password'])),array('id'=>$id))){
            		$res = array("status"=>"success","msg"=>" Password Updated Successfully");
            	}else{
            		$res = array("status"=>"failed","msg"=>"Sorry Not updated. Something went wrong");
            	}
            }else{
            	$res = array("status"=>"failed","msg"=>"Current Password and Existing Password Doesn't match");
            }
		}else{
			$res = array("status"=>"failed","msg"=>"Password not Updated. User Cannot Exist");
		}
		return $res;
	}

//.........................get promocode list 

	public function get_promocode_list(){
        $now = strtotime(date('Y-m-d 0:0:0'));
		//print_r($now); exit(); 
		$this->db->select('id,promo_name as title,valid_to as date,description,image');
		$this->db->where('valid_from <=',$now);
		$this->db->where('valid_to >=',$now);
		$this->db->where('status','1');
		$query = $this->db->get('tbl_promocode')->result();
		//echo $this->db->last_query();exit();
		if(count($query) > 0){
			$res = array("status"=>"success","data"=>$query);
		}else{
			$res = array("status"=>"failed");
		}
		return $res;
	}

//..........................cancel booking by patient

	public function cancel_booking($data){
		$query = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row_array();
		if($query){
			$this->db->select('duration');
			$dur = $this->db->get('tbl_policy')->row();

		    $old_date = date('Y-m-d h:i:sA',$query['time_start']);
			$newdate = date("Y-m-d h:i:sA",strtotime($old_date." -".$dur->duration." hour"));
			$new_date = strtotime($newdate);

			/*$offset=5.5*60*60; //converting 5 hours to seconds.
  			$dateFormat="Y-m-d h:i:sA";
  			$now_date=gmdate($dateFormat, time()+$offset);
  			$now = strtotime($now_date);*/
  			//$canceltime = $data['offset']/(1000);
            $new_time = date('H:i',$data['offset']);
            $new_time = explode(':',$new_time);
	        $nowin_server = date("Y-m-d TH:i:s");
	        if($data['offset'] > 0){
                $nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('+'.$new_time[0].' hour +'.$new_time[1].' minutes',strtotime($nowin_server)));
	        }else{
	            $nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('-'.$new_time[0].' hour -'.$new_time[1].' minutes',strtotime($nowin_server)));
	        }

	        $nowin_server_addoffset = strtotime($nowin_server_addoffset);
			$this->db->select('name,specialization');
	        $doctr_data = $this->db->get_where('tbl_doctors',array('id'=>$query['doctor_id']))->row_array();
			$special = $this->db->get_where('tbl_specialization',array('id'=>$doctr_data['specialization']))->row();
			$msg = "Your booking for doctor ".$doctr_data['name']." at time ".$query['time']."is Cancelled";
			$msg2 = "Your booking for doctor ".$doctr_data['name']." at time ".$query['time']." is confirmed";
			$conslt_time =  date('Y-m-d h:i:s');
			$conslt_time = strtotime($conslt_time);
			if($nowin_server_addoffset < $new_date){
				$this->db->update('tbl_booking',array('booking_status'=>'4'),array('id'=>$data['booking_id']));
				$this->db->insert('tbl_patient_notification',array('patient_id'=>$query['patient_id'],'type'=>'3','message'=>$msg,'time'=>$conslt_time,'booking_id'=>$query['id'],'read_status'=>'0'));
				$patient_insert_id = $this->db->insert_id();
				$fcm_user = $this->db->get_where('tbl_authtoken',array('userid'=>$query['patient_id']))->row();
				$new['id'] = $patient_insert_id;
				$new['type'] = "Cancel Consultation";
				$new['booking_id'] = $query['id'];
				$new['booking_date'] = $query['date'];
				$new['doctor_id'] = $query['doctor_id'];
				$new['doctor_name'] = $doctr_data['name'];
				$new['doctor_specialization'] = $special->specialization_name;
				$new['message'] = $msg;
				$new['time'] = $conslt_time;
				$new['to'] =$fcm_user->fcm_token;
				$user_type = '1';
				$push = $this->push_sent($new,$user_type);
				
				$ress = $this->db->get_where('tbl_booking',array('doctor_id'=>$query['doctor_id'],'clinic_id'=>$query['clinic_id'],'date'=>$query['date'],'time'=>$query['time'],'booking_status'=>'0'))->row_array();
				if($ress){
					$this->db->update('tbl_booking',array('booking_status'=>'1'),array('id'=>$ress['id']));
					$this->db->insert('tbl_patient_notification',array('patient_id'=>$ress['patient_id'],'type'=>'0','message'=>$msg2,'time'=>$conslt_time,'booking_id'=>$query['id'],'read_status'=>'0'));
					$patient_insert_id = $this->db->insert_id();
					$fcm_user = $this->db->get_where('tbl_authtoken',array('userid'=>$ress['patient_id']))->row();
					$new['id'] = $patient_insert_id;
					$new['type'] = "Waiting List";
					$new['booking_id'] = $query['id'];
					$new['booking_date'] = $query['date'];
					$new['doctor_id'] = $query['doctor_id'];
					$new['doctor_name'] = $doctr_data['name'];
					$new['doctor_specialization'] = $special->specialization_name;
					$new['message'] = $msg2;
					$new['time'] = $conslt_time;
					$new['to'] =$fcm_user->fcm_token;
					$user_type = '1';
					$push = $this->push_sent($new,$user_type);
					
					$msg3 = "You have a new booking on  ".date('jS F Y',$query['date'])." at ".date('h:i A',$query['time_start']);
					$this->db->insert('tbl_doctor_notifications',array('doctor_id'=>$query['doctor_id'],'type'=>'2','message'=>$msg3,'time'=>$conslt_time,'read_status'=>'0'));
					$doctor_insert_id = $this->db->insert_id();
					$fcm_doctor = $this->db->get_where('tbl_authtoken_doctors',array('doctor_id'=>$query['doctor_id']))->row();
					$news['id'] = $doctor_insert_id;
					$news['type'] = "New Consultation";
					$news['message'] =$msg3;
					$news['read_status'] = false;
					$news['to'] = $fcm_doctor->fcm_token;
					$doctor_type = '2';
					$doctor_push = $this->push_sent($news,$doctor_type);
				}
				if($query['visit_type'] == '0'){
					$doctor_wallet = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$query['doctor_id']))->row();
					$earn = $query['total_sum'] - (($query['total_sum'] * $query['ipok_fee'])/100);

					if($doctor_wallet){
						$future_earn = decrypt_data($doctor_wallet->future_earn) - $earn;
						$total = decrypt_data($doctor_wallet->total_earn) - $earn;
						$this->db->update('tbl_wallet_details',array('future_earn'=>encrypt_data($future_earn),'total_earn'=>encrypt_data($total)),array('doctor_id'=>$query['doctor_id']));
					}
				}
	            $res = array("status"=>"success");
	        }else{
	        	$res = array("status"=>"failed","message"=>"Sorry Your booking is not cancelled as per the cancelation policy");
	        }

		}else{
			$res = array("status"=>"failed",'message'=>'Booking Id doesnot exist');
		}
		return $res;
	}

//.................get promocode hospital list

	public function get_promocode_hospital_list($id,$lat,$lng){
		$query = $this->db->get_where('tbl_promocode',array('id'=>$id))->row();
		if($query){
			$doctors = explode(',',$query->doctor_id);
			$new_array = array();
			foreach ($doctors as $key => $value) {
				$this->db->select("tbl_doctors.name as doctor_name,
					tbl_doctors.price as fee,
					tbl_doctors.id as doctor_id,
					tbl_doctors.online_status as status,tbl_clinic_doctors.clinic_id,
					tbl_doctors.profile_pic as doctor_image,
					tbl_specialization.specialization_name as doctor_speciality,
					ROUND(( 6371 * acos( cos( radians({$lat}) ) * cos( radians( `tbl_clinic`.`location_lattitude` ) ) * cos( radians( `tbl_clinic`.`location_longitude` ) - radians({$lng}) ) + sin( radians({$lat}) ) * sin( radians( `tbl_clinic`.`location_lattitude` ) ) ) )) AS distance");
				$this->db->from("tbl_doctors");

				$this->db->join('tbl_clinic_doctors', 'tbl_doctors.id = tbl_clinic_doctors.doctor_id','INNER');
				$this->db->join('tbl_clinic', 'tbl_clinic_doctors.clinic_id = tbl_clinic.id','INNER');
				$this->db->join("tbl_specialization","tbl_doctors.specialization = tbl_specialization.id","LEFT");
				$this->db->where('tbl_doctors.id',$value);
				$res = $this->db->get()->result();
		        foreach ($res as $key => $values) {
		        	//$res[$key]->fee = decrypt_data($values->fee);
		        	$new_array[] = $values;
		        }
			$result = array("status"=>"success","data"=>$new_array);
			}
		}else{
			$result = array("status"=>"failed","msg"=>"No Promocode");
		}
		return $result;
	}

//..................set push status

	public function set_push_status($userid,$status){
		if($this->db->update('tbl_registration',array('push_notification'=>$status),array('id'=>$userid))){
			$res = array('status'=>'success');
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//.....................get push status

	public function get_push_status($userid){
		$this->db->select('push_notification');
		$res = $this->db->get_where('tbl_registration',array('id'=>$userid))->row();
		if($res){
			$res = array('status'=>'success','data'=>array('status'=>$res->push_notification));
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

		public function set_push_status_doctor($doctorid,$status){
		if($this->db->update('tbl_doctors',array('push_notification'=>$status),array('id'=>$doctorid))){
			$res = array('status'=>'success');
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//.....................get push status

	public function get_push_status_doctor($doctorid){
		$this->db->select('push_notification');
		$res = $this->db->get_where('tbl_doctors',array('id'=>$doctorid))->row();
		if($res){
			if($res->push_notification == '0'){
				$status = true;
			}else{
				$status = false;
			}
			$res = array('status'=>'success','data'=>array('notification_status'=>$status));
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//......................insert app feedback

	public function insert_app_feedback($data){
		//print_r($data);exit();
		if($this->db->insert('tbl_app_feedback',$data)){
			$res = array('status'=>'success');
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//....................... get faqs

	public function get_faqs($start,$per_page){
		$this->db->select('id,faq_title,faq_description');
		$this->db->where('faq_for','0');
		$this->db->limit($per_page,$start);
		$result = $this->db->get('tbl_faq')->result();
		if($result){
			return $result;
		}else{
			return false;
		}
		
	}

	public function get_doctor_faq_list($start,$per_page){
		$this->db->select('id,faq_title,faq_description');
		$this->db->where('faq_for','1');
		$this->db->limit($per_page,$start);
		$result = $this->db->get('tbl_faq')->result();
		if($result){
			return $result;
		}else{
			return false;
		}
		
	}

//...........................more services

	public function more_service(){
		$query = $this->db->get('tbl_charity')->result();
		if(count($query) > 0){
			$res = $res = array('status'=>'success','data'=>array('more_service'=>$query));
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//..................... donation hospital list

	public function donation_hospital_list($id){
		$this->db->select('tbl_clinic.name as clinic_name,tbl_clinic.id as clinic_id,tbl_charity_service.amount,tbl_clinic.profile_photo as clinic_photo');
		$this->db->join('tbl_clinic','tbl_clinic.id = tbl_charity_service.clinic_id');
		$query = $this->db->get_where('tbl_charity_service',array('tbl_charity_service.charity_id'=>$id))->result();
		//print_r($query);exit();
		if(count($query) > 0){
			foreach ($query as $key => $value) {
				$amount = explode(',',$value->amount);
				for($a = 0; $a < count($amount); $a++) {
				    for($b = 0; $b < count($amount)-1; $b++){
				        if($amount[$b] > $amount[$b+1]) {
				            $temp = $amount[$b+1];
				            $amount[$b+1]=$amount[$b];
				            $amount[$b]=$temp;
				        }       
				    }
				}
				unset($query[$key]->amount);
				$value->donation_amounts = $amount;
				
				$this->db->where('clinic_id',$value->clinic_id);
				$clinic_result = $this->db->get('tbl_clinic_specialization')->result();
				if(count($clinic_result) > 0){
					$new_aray = array(); 
					foreach ($clinic_result as $key => $value_clinic) {
						$this->db->where('id',$value_clinic->specialization_id);
						$row = $this->db->get('tbl_specialization')->row();
						$new_aray[] = $row->specialization_name;
					}
					$specality = implode(',',$new_aray);
				}else{
					$specality = "";
				}

				$value->clinic_specilaity = $specality;

			}
			
			$res = $res = array('status'=>'success','data'=>array('hospital_list'=>$query));
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//.........................edit dependent data

	public function edit_dependent($data,$id){
		if($this->db->update('tbl_patient_dependent',array('dependent_name'=>$data['dependent_name'],'relation'=>$data['dependent_relation'],'dob'=>$data['dependent_age'],'image'=>$data['image'],'cpf'=>$data['dependent_cpf']),array('id'=>$data['dependent_id']))){

			$result = $this->db->get_where('tbl_patient_dependent',array('patient_id'=>$id))->result();
			if(count($result) >0 ){
				return $result;
			}else{
				return false;
			}
		}
	}

// ........................add save card

	public function save_card($data){
		//print_r($data);exit();
		if($this->db->insert('tbl_card_details',$data)){
			$res = $res = array('status'=>'success');
		}else{
			$res = array('status'=>'failed');
		}
		return $res;
	}

//...........................get save card list

	public function get_saved_card_list($id){
		$query = $this->db->get_where('tbl_card_details',array('user_id'=>$id))->result_array();
		if(count($query) > 0){
			$new = array();
			foreach ($query as $key => $value) {
				$value['validity'] = decrypt_data($value['card_expiry_month']).'/'.decrypt_data($value['card_expiry_year']);
				$new[$key]['card_id'] = $value['id'];
				$new[$key]['card_holder_name'] = decrypt_data($value['card_holder_name']);
				$new[$key]['card_validity'] = $value['validity'];
				$new[$key]['card_number'] = decrypt_data($value['card_number']);

			}
			$res = array('status'=>'success','data'=>array('card_list'=>$new));
		}else{
			$res = array('status'=>'failed','data'=>array('card_list'=>[]));
		}
		return $res;
	}
	
	//..........................edit Save card

	public function edit_save_card($data){
		$id = $data['card_id'];
		unset($data['card_id']);
		if($this->db->update('tbl_card_details',$data,array('id'=>$id))){
			return true;	
		}else{
			return false;
		}
	}

//......................... get medical records

	public function get_medical_record($id){
		$query = $this->db->get_where('tbl_booking',array('id'=>$id))->row_array();
		if($query){
			if($query['medical_record_id'] != '0'){
				$this->db->select('tbl_doctors.id as doctor_id,tbl_doctors.name as doctor_name,tbl_doctors.profile_pic as doctor_profile_photo,tbl_doctors.price as consultation_fee,tbl_doctors.consultation_duration,tbl_specialization.specialization_name as doctor_speciality,tbl_booking.date,tbl_booking.total_sum as total,tbl_medical_records.*,tbl_registration.profile_photo');
				$this->db->join('tbl_doctors','tbl_doctors.id = tbl_booking.doctor_id');
				$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.specialization');
				$this->db->join('tbl_medical_records','tbl_medical_records.id = tbl_booking.medical_record_id');
				$this->db->join('tbl_registration','tbl_registration.id = tbl_booking.patient_id');
				$this->db->where('tbl_booking.id',$id);
				$result = $this->db->get('tbl_booking')->row_array();
				//echo"<pre>";print_r($result);echo"</pre>";
				if($result){
					//$result['consultation_fee'] = decrypt_data($result['consultation_fee']);
					$fee = $this->db->get('settings')->row();
 					$result['review'] = decrypt_data($result['patient_review']);
 					unset($result['patient_review']);

                    $actual = ($result['consultation_fee'] * $fee->ipok_fee)/100 ;
					//$result['tax'] = $actual; //Get in integer type since actual is in integer format
					$result['tax'] = (string)$actual;// Get in string type

					$result['anamnese'] = decrypt_data($result['main_complaint']);
					unset($result['main_complaint']);

					$result['anamnese_content'] = decrypt_data($result['description']);
					unset($result['description']);
					
					$let  = json_decode(decrypt_data($result['letters']));
					if($let == ''){
						$result['Letter_and_certificates'] = '';
					}else{
						$result['Letter_and_certificates'] = $let->certificate;
						unset($result['letters']);
					}
					if($result['other_observations']){
						$result['other_observation'] = decrypt_data($result['other_observations']);
						unset($result['other_observations']);
					}else{
						$result['other_observation'] = '';
					}

                    $ill = json_decode(decrypt_data($result['diseases']));
                    if($ill == ''){
                    	$new = [];
                    }else{
						$new = array();
						$news = array();
						$i=0;
						foreach ($ill->anamnese as $key => $value) {
							if($key != 'others'){
								$new[$i]['name'] = $key;
								$new[$i]['cause'] = $value;
							}else{
								$news['name'] = $key;
								$news['cause'] = $value;
							}
							$i++;
						}

						 $result['illness'] = $new;
					   
						if($news['cause'] != ''){
							$others = $news;
						}else{
							$others = [];
						}
						$result['is_curable'] = $others;
					}
                    unset($result['diseases']);
 					$med = array();
                    $prescrb = json_decode(decrypt_data($result['prescribtions']));
                    if($prescrb == ''){
                    	$med = [];
                    }else{
						foreach ($prescrb as $key => $value) {
							$med[$key]['medicine_name'] = $value->name;
							$med[$key]['about_medicine'] = $value->procedure;
							$med[$key]['medicine_quantity'] = $value->quantity;
						}
						$result['prescription'] = $med;
					}
                    unset($result['prescribtions']);

                    $examss = array();
                    $exam = json_decode(decrypt_data($result['exams']));

                    if($exam == ''){
                    	$examss = [];
                    }else{
						foreach ($exam as $key => $value) {
							$examss[$key]['test_name'] = $value->procedure;
							$examss[$key]['test_description'] = $value->observation;
						}
						$result['medical_test'] = $examss;
					}
                    unset($result['exams']);
                    $bud = array();
                    $budget = json_decode(decrypt_data($result['budget']));
                    if($budget == ''){
                    	$budget = [];
                    }else{
						foreach ($budget as $key => $value) {
							$bud[$key]['service_name'] = $value->procedure;
							$bud[$key]['service_charge'] = $value->amount;
						}
						$result['services'] = $bud;
					}
                    unset($result['budget']);
                    //echo"<pre>";print_r(json_decode($result['images']));echo "</pre>";exit();

                    $images = json_decode($result['images']);
                    if($images == ''){
                    	$images = [];
                    }else{
						$result['photos'] = $images;
					}
                    unset($result['images']);
                    unset($result['booking_id']);
                   // unset($result['id']);
					//echo "<pre>";print_r($result);echo"</pre>";exit();
                    $res = array('status'=>'success','data'=>$result);
				}
			}else{
				$res = array('status'=>'failed','msg'=>'No Medical Record Exist for this Id');
			}
		}else{
			$res = array('status'=>'failed','msg'=>'Booking Id Doesnot Exist');
		}
		return $res;
	}
	
	
	public function set_recent_chat($data){
		$query = $this->db->get_where('tbl_recent_chats',array('chat_id'=>$data['chat_list_id']))->row();
		$data['chat_id'] = $data['chat_list_id'];
		if(isset($data['message']) &&  strlen(trim($data['message']," ")) > 0){
			$data['msg'] = $data['message'];
		}else{
			$data['msg'] = '';
		}
		unset($data['chat_list_id']);
		unset($data['message']);
		if($query){
			if($this->db->update('tbl_recent_chats',$data,array('chat_id'=>$data['chat_id']))){
				return true;
			}else{
				return false;
			}
		}else{
			if($this->db->insert('tbl_recent_chats',$data)){
				return true;
			}else{
				return false;
			}
		}
	}
	
	public function chat_file_upload($data,$url){
		$query = $this->db->get_where('tbl_recent_chats',array('chat_id'=>$data['chat_list_id']))->row();
		if($query){
			if($data['type'] == 0){
				if($this->db->update('tbl_recent_chats',array('photo_url'=>$url),array('chat_id'=>$data['chat_list_id']))){
					$result = array('status'=>'success');
				}else{
					$result = array('status'=>'failed','message'=>'Sorry Something went wrong.. Try again later');
				}
			}else{
				if($this->db->update('tbl_recent_chats',array('video_url'=>$url),array('chat_id'=>$data['chat_list_id']))){
					$result = array('status'=>'success');
				}else{
					$result = array('status'=>'failed','message'=>'Sorry Something went wrong.. Try again later');
				}
			}
		}else{
			$result = array('status'=>'failed','message'=>'Invalid Chat List Id');
		}
		return $result;
	}


/********************************************************************************************/
/********************************************************************************************/
/********************************************************************************************/

/****************************************MEDICOS APP*****************************************/


//....................configure consultation by doctor

	public function configure_consultation($data,$doctor_id){
		//print_r($data);exit();
		$doc_query = $this->db->get_where('tbl_doctors',array('id'=>$doctor_id));

		if($data['is_home_consultation_available']){
			$data['home_consultation_available'] = 1;
		}else{
			$data['home_consultation_available'] = 0;
		}

		if($data['is_return_consultation_available']){
			$data['return_consultation_available'] = 1;
		}else{
			$data['return_consultation_available'] = 0;
		}

		if(isset($data['return_consultation_time_period'])){
			$data['timeperiod'] = $data['return_consultation_time_period'];
		}else{
			$data['timeperiod'] = 0;
		}
		//echo "<pre>";print_r($data);exit();
		if($doc_query->num_rows() > 0){
			$this->db->update('tbl_doctors',array('consultation_duration'=>$data['consultation_duration'],'price'=>$data['consultation_fee'],'	domiciliary_status'=>$data['home_consultation_available'],'accept_return'=>$data['return_consultation_available'],'return_timeperiod'=>$data['timeperiod']),array('id'=>$doctor_id));
			$res = $this->db->get_where("tbl_doctors",array("id"=>$doctor_id))->row_array();
			if($res['accept_return'] == '1'){
				$res['accept_return'] = true;
			}else{
				$res['accept_return'] = false;				
			}

			if($res['domiciliary_status'] == '1'){
				$res['domiciliary_status'] = true;
			}else{
				$res['domiciliary_status'] = false;				
			}
			//echo $this->db->last_query();exit();
			$return_array = array('status'=>'success','data'=>array('doctor_id'=>$doctor_id,'is_return_consultation_available'=>$res['accept_return'],'is_home_consultation_available'=>$res['domiciliary_status'],'consultation_price'=>$res['price'],'consultation_duration'=>$res['consultation_duration'],'return_consultation_time_period'=>$res['return_timeperiod']));
			//print_r($return_array);exit();

		}else{
			$return_array = array('status'=>'failed','message'=>'Doctor Id Doesnot Exist');
		}
		return $return_array;
	}

//....................set doctor vaction

	public function set_doctor_vacation($data,$doctor_id){
		$data['doctor_id'] = $doctor_id;
		if($this->db->insert('tbl_doctor_leave',$data)){
			return true;
		}
	}

//....................get doctor agenda

	public function get_doctor_agenda($clinic_id,$doctor_id){
		$query = $this->db->get_where('tbl_consultation',array('clinic_id'=>$clinic_id,'doctor_id'=>$doctor_id))->row();
		//echo $this->db->last_query();
		if($query){
			$doc_res = $this->db->get_where('tbl_doctors',array('id'=>$doctor_id))->row();
			
			if($query->date != '""'){
				$date = json_decode($query->date);
				$primary = array();
				foreach ($date as $key => $value) {
					$dayid = $this->get_dayid($value->day);
					$primary[$key]['id'] = $dayid; 
					$primary[$key]['start_time'] = strtotime($this->string->default_date.$value->time->start); 
					$primary[$key]['end_time'] = strtotime($this->string->default_date.$value->time->end); 
					$primary[$key]['break_start_time'] = strtotime($this->string->default_date.$value->time->break_from); 
					$primary[$key]['break_end_time'] = strtotime($this->string->default_date.$value->time->break_to); 
				}
				//echo"<pre>";print_r($primary);echo"</pre>";exit();
			}else{
				$primary = [];
			}
			if($query->date_secondary != '""'){
				$date_secondary = json_decode($query->date_secondary);
				$secondary = array();
				foreach ($date_secondary as $key => $value) {
					$dayid = $this->get_dayid($value->day);
					$secondary[$key]['id'] = $dayid; 
					$secondary[$key]['start_time'] = strtotime($this->string->default_date.$value->time->start); 
					$secondary[$key]['end_time'] = strtotime($this->string->default_date.$value->time->end); 
					$secondary[$key]['break_start_time'] = strtotime($this->string->default_date.$value->time->break_from); 
					$secondary[$key]['break_end_time'] = strtotime($this->string->default_date.$value->time->break_to); 
				}
				//echo"<pre>";print_r($secondary);echo"</pre>";exit();
			}else{
				$secondary = [];
			}

			$vac = $this->db->get_where('tbl_doctor_leave',array('doctor_id'=>$doctor_id,'clinic_id'=>$clinic_id))->result();
			$vacation =array();
			foreach ($vac as $key => $value) {
				$vac_date = $value->id;
				$vacation[$key]['id'] = $dayid; 
				$vacation[$key]['start_time'] = $value->start_date; 
				$vacation[$key]['end_time'] = $value->end_date; 
			}
			//echo"<pre>";print_r($vacation);echo"</pre>";exit();
			if(decrypt_data($doc_res->domiciliary_status) == '1'){
				$home_status = true;
			}else{
				$home_status = false;
			}

			if($doc_res->accept_return == '1'){
				$accept_status = true;
			}else{
				$accept_status = false;
			}

			$data = array('clinic_id'=>$clinic_id,'consultation_duration'=>$doc_res->consultation_duration,'consultation_price'=>$doc_res->price,'is_home_consultation_available'=>$home_status,'is_return_consultation_available'=>$accept_status,'return_consultation_time_period'=>$doc_res->return_timeperiod,'activated_schedule'=>$query->active_schedule,'primary_schedule'=>$primary,'secondary_schedule'=>$secondary,'vacations'=>$vacation);
			$return_array = array('status'=>'success','data'=>$data);
		}else{
			$return_array = array('status'=>'failed','message'=>'No consultation for this doctor in this clinic');
		}
		return $return_array;
	}

	function get_dayid($day){
		if($day == 'sun'){$dayid = '0';}elseif ($day == 'mon') {$dayid = '1';}elseif ($day == 'tue') {$dayid = '2';}elseif ($day == 'wed') {$dayid = '3';}elseif ($day == 'thu') {$dayid = '4';}elseif ($day == 'fri') {$dayid = '5';}elseif ($day == 'sat') {$dayid = '6';}
		return $dayid;
	}

//....................set doctor primary agenda

	public function set_doctor_primary_agenda($data,$doctor_id,$type){
 		$this->db->select("*");
 		$this->db->from("tbl_consultation");
 		$this->db->where_in("tbl_consultation.doctor_id",$doctor_id);
 		$query = $this->db->get();
 		$result = $query->result_array();

        $this->db->select('id,consultation_duration');
 		$duration = $this->db->get_where('tbl_doctors',array('id'=>$doctor_id))->row_array();
 		if($duration != ''){
	 		$insert_array = array();
			$not_available_day = array();
			$insert_array_exist = array();
			$flag = 0;
			$nameday = array();
	 		if(!empty($result)){
	 			foreach ($data['schedules'] as $key_day => $value_day) {
	 				foreach ($result as $key => $value) {
	 					if($type == '0'){
	 						$decode_time = json_decode($value['date'],true);
	 					}else{
	 						$decode_time = json_decode($value['date_secondary'],true);
	 					}
						
						//echo"<pre>";print_r($decode_time);echo"</pre>";exit();
	 					if(!empty($decode_time)){
	 						$valueday = $this->get_dayname($value_day->id);
	 						foreach($decode_time as $db_k => $db_v) {
	 							if(($valueday == $db_v['day']) && (($data['clinic_id'] != $value['clinic_id']))){
									$starttime  = date('h:i',$value_day->start_time);
	 								$endtime  = date('h:i',$value_day->end_time);
	 								if((strtotime($this->string->default_date.$db_v['time']['start']) <=  strtotime($this->string->default_date.$starttime) &&  strtotime($this->string->default_date.$starttime) <= strtotime($this->string->default_date.$db_v['time']['end'])) || (strtotime($this->string->default_date.$db_v['time']['start']) <=  strtotime($this->string->default_date.$endtime) && strtotime($this->string->default_date.$endtime) <= strtotime($this->string->default_date.$db_v['time']['end'])) || ( strtotime($this->string->default_date.$starttime) <= strtotime($this->string->default_date.$db_v['time']['start']) && strtotime($this->string->default_date.$db_v['time']['start']) <= strtotime($this->string->default_date.$endtime) ) || (strtotime($this->string->default_date.$starttime) <= strtotime($this->string->default_date.$db_v['time']['end']) && strtotime($this->string->default_date.$db_v['time']['end']) <= strtotime($this->string->default_date.$endtime))){
	 									$flag = 1;
										$get_fullname_day =  $this->get_fulldayname($valueday);
										$nameday[] = $get_fullname_day;
										//print_r($nameday);exit();
	 								}
	 							}
	 						}
	 					}
	 				}
	 			}
				$namesss = implode(',',$nameday);
	 			if($flag == 0){
	 				foreach ($data['schedules'] as $key_day => $value_day) {
	 					if($value_day->break_start_time != ''){
							$break_from = date('H:i',$value_day->break_start_time);
						}
						else{
							$break_from = 'null';
						}
						
						if($value_day->break_end_time != ''){
							$break_to = date('H:i',$value_day->break_end_time);
						}
						else{
							$break_to = 'null';
						}

						$valueday = $this->get_dayname($value_day->id);
						$res = array('day'=>$valueday,
									'time'=>array(
										'start'=>date('H:i',$value_day->start_time),
										'end'=>date('H:i',$value_day->end_time),
										'interval'=>$duration['consultation_duration'],
										'break_from'=>$break_from,
										'break_to'=>$break_to
										));
						array_push($insert_array_exist,$res);
	 				}
					//print_r($insert_array_exist);exit();
	 				$newData = json_encode($insert_array_exist);
	 				if($type == '0'){
	 					$this->db->update('tbl_consultation',array('date'=>$newData,'active_schedule'=>$data['activated_schedule']),array('doctor_id'=>$doctor_id,'clinic_id'=>$data['clinic_id']));
	 				}else{
	 					$this->db->update('tbl_consultation',array('date_secondary'=>$newData,'active_schedule'=>$data['activated_schedule']),array('doctor_id'=>$doctor_id,'clinic_id'=>$data['clinic_id']));
	 				}
	 		    		
					$return_array = array('status'=>'success','message'=>'Doctor assigned Successfully');
	 			}else{
	 				$return_array = array('status'=>'failed','message'=>"Schedule time for "."$namesss"." is not available");
	 			}	
	 		}else{
	 			$return_array = array('status'=>'failed','message'=>'Schedules are Corrupted');
	 		}
 		}else{
 			$return_array = array('status'=>'failed','message'=>'Doctor Id doesnot exist');
 		}
 		//print_r($return_array);exit();
 		return $return_array;
	}

	function get_dayname($id){
		if($id == '0'){$dayid = 'sun';}elseif ($id == '1') {$dayid = 'mon';}elseif ($id == '2') {$dayid = 'tue';}elseif ($id == '3') {$dayid = 'wed';}elseif ($id == '4') {$dayid = 'thu';}elseif ($id == '5') {$dayid = 'fri';}elseif ($id == '6') {$dayid = 'sat';}
		return $dayid;
	}
	
	
	function get_fulldayname($day){
		if($day == 'sun'){$dayname = 'Sunday';}elseif ($day == 'mon') {$dayname = 'Monday';}elseif ($day == 'tue') {$dayname = 'Tuesday';}elseif ($day == 'wed') {$dayname = 'Wednesday';}elseif ($day == 'thu') {$dayname = 'Thursday';}elseif ($day == 'fri') {$dayname = 'Friday';}elseif ($day == 'sat') {$dayname = 'Saturday';}
		return $dayname;
	}

	public function get_clinic_list($id){
		$this->db->select('tbl_clinic.id,tbl_clinic.name,tbl_clinic.email,tbl_clinic.profile_photo,tbl_clinic.location_lattitude,tbl_clinic.location_longitude,tbl_clinic.street_address,tbl_clinic.locality,tbl_clinic.number,tbl_clinic.complement');
		$this->db->join('tbl_clinic','tbl_clinic_doctors.clinic_id = tbl_clinic.id');
		$this->db->where('tbl_clinic_doctors.doctor_id',$id);
		$this->db->order_by('tbl_clinic.id','ASC');
		$query = $this->db->get('tbl_clinic_doctors')->result();
		array_splice($query, 0, 1);
		

		$this->db->select('tbl_clinic.id,tbl_clinic.name,tbl_clinic.email,tbl_clinic.profile_photo,tbl_doctors.default_latitude as location_lattitude,tbl_doctors.default_longitude as location_longitude,tbl_doctors.street_address,tbl_doctors.locality,tbl_doctors.number,tbl_doctors.complement');
		$this->db->from('tbl_clinic_doctors');
		$this->db->join('tbl_clinic','tbl_clinic_doctors.clinic_id = tbl_clinic.id');
		$this->db->join('tbl_doctors','tbl_clinic_doctors.doctor_id = tbl_doctors.id');
		$this->db->where('tbl_clinic_doctors.clinic_id','0');
		$this->db->where('tbl_clinic_doctors.doctor_id',$id);
		$query_default = $this->db->get()->result();
		$new_query = array_merge($query_default,$query);

		//echo"<pre>";print_r($new_query);exit();
		if(count($new_query) > 0){
			foreach ($new_query as $key => $value) {
				$location = decrypt_data($value->street_address).','.decrypt_data($value->locality).','.decrypt_data($value->number).','.decrypt_data($value->complement);
				$new[$key]['id'] = $value->id;
				$new[$key]['name'] = $value->name;
				$new[$key]['email'] = $value->email;
				$new[$key]['photo'] = $value->profile_photo;
				$new[$key]['location'] = $location;
				$new[$key]['latitude'] = $value->location_lattitude;
				$new[$key]['longitude'] = $value->location_longitude;
			}
			$return_array = array('status'=>'success','data'=>array('clinics'=>$new));
		}else{
			$return_array = array('status'=>'failed','data'=>array('clinics'=>[]));
		}
		return $return_array;
	}

	public function get_doctor_review_list($id,$start,$per_page){
		$this->db->select('tbl_review.review_id as id,tbl_registration.name as patient_name,tbl_registration.profile_photo as patient_profile_photo,tbl_registration.id as patient_id,tbl_review.date,tbl_review.review');
		$this->db->from('tbl_review');
		$this->db->join('tbl_registration','tbl_registration.id = tbl_review.reviewer_id');
		$this->db->where('tbl_review.doctor_id',$id);
		$this->db->limit($per_page,$start);
		$result = $this->db->get()->result();
		if(count($result) > 0){
			foreach ($result as $key => $value) {
				$result[$key]->patient_name = decrypt_data($value->patient_name);
			}
			return $result;
		}else{
			return false;
		}
	}

	public function get_patient_list($id,$start,$per_page){
		$this->db->select("DISTINCT(tbl_registration.id),tbl_registration.name,tbl_registration.occupation,tbl_registration.profile_photo,tbl_registration.dob,TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR),'%Y-%m-%d '), CURDATE()) as age");
		// $this->db->select("DISTINCT(tbl_registration.id),tbl_registration.name,tbl_registration.occupation,tbl_registration.profile_photo,tbl_registration.dob");
		$this->db->from('tbl_booking');
		$this->db->join('tbl_registration','tbl_registration.id = tbl_booking.patient_id');
		$this->db->where('tbl_booking.doctor_id',$id);
		$this->db->where("(tbl_booking.booking_status != '0' or tbl_booking.booking_status != '4')");
		$this->db->limit($per_page,$start);
		$this->db->order_by('tbl_registration.name','ASC');
		$result = $this->db->get()->result();
		/*if(count($result) > 0){
			foreach ($result as $key => $value) {
				//$dob=date('Y-m-d',$value->dob);
		    	$diff = (date('Y') - date('Y',$value->dob));
		    	$value->age = $diff;
			}
		}*/
		if(count($result) > 0){
			// foreach ($result as $key => $value) {
			// 	//$dob=date('Y-m-d',$value->dob);
		 //    	$diff = (date('Y') - date('Y',decrypt_data($value->dob)));
		 //    	//$value->age = $diff;
		 //    	$result[$key]->age = $diff;
		 //    	$result[$key]->name = decrypt_data($value->name);
		 //    	$result[$key]->dob = decrypt_data($value->dob);
			// }
			return $result;
		}else{
			return false;
		}
	}

	public function get_patient_anniversary_list($id,$start,$per_page){
		$O_month = date('m');
	 	$T_month = date('m', strtotime("last day of next month"));
	    if($T_month == "12") {
		  $TH_month = "01";
	    }else if($T_month <= "11") {
		  $TH_month = $T_month + "01";
	    }
	    if(strlen($TH_month) == 1) {
		  $TH_month="0".$TH_month;
	    }

		// $this->db->select("DISTINCT(tbl_registration.id),tbl_registration.name,tbl_registration.profile_photo,tbl_registration.dob,TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR),'%Y-%m-%d '), CURDATE()) as age");
		// $this->db->from('tbl_booking');
		// $this->db->join('tbl_registration','tbl_registration.id = tbl_booking.patient_id');
		// $this->db->where("tbl_booking.booking_status",'3');
		// $this->db->where('tbl_booking.doctor_id',$id);
		// $this->db->where("(DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$O_month-%' or DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$T_month-%' or DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$TH_month-%') ORDER BY DAYOFYEAR(DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e')) < DAYOFYEAR(CURDATE()) , DAYOFYEAR(DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(`tbl_registration`.`dob`,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e'))");
		
		// $this->db->limit($per_page,$start);
		// $result = $this->db->get()->result();
		//echo $this->db->last_query();exit();

		$result = $this->db->query("SELECT DISTINCT(reg_id) as id, reg_name as name, CAST(AES_DECRYPT(`reg_dob`, 'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob,reg_photo as profile_photo, TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(CAST(AES_DECRYPT(`reg_dob`, 'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR), '%Y-%m-%d '), CURDATE()) as age FROM (select tbl_registration.id as reg_id, tbl_registration.name as reg_name, tbl_registration.dob as reg_dob, tbl_registration.profile_photo as reg_photo from `tbl_registration` JOIN `tbl_booking` ON `tbl_registration`.`id` = `tbl_booking`.`patient_id` WHERE `tbl_booking`.`booking_status` = '3' AND `tbl_booking`.`doctor_id` = '$id') temp WHERE (DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(reg_dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$O_month-%' or DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(reg_dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$T_month-%' or DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(reg_dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e') like '%-$TH_month-%') ORDER BY DAYOFYEAR(DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(reg_dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e')) < DAYOFYEAR(CURDATE()) , DAYOFYEAR(DATE_FORMAT(FROM_UNIXTIME(CAST(AES_DECRYPT(reg_dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR)), '%Y-%m-%e')) LIMIT 20")->result();

		if(count($result) > 0){
			return $result;
		}else{
			return false;
		}
		
	}

	public function get_patient_medical_record_list($doctorid,$start,$per_page,$patientid){
		$this->db->select("name,profile_photo,id,CAST(AES_DECRYPT(`tbl_registration`.`dob`, 'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob");
		$this->db->where('id',$patientid);
		$pat_details = $this->db->get('tbl_registration')->row();
		$diff = (date('Y') - date('Y',$pat_details->dob));

		$this->db->where('doctor_id',$doctorid);
		$this->db->where('patient_id',$patientid);
		$this->db->where('booking_status','3');
		$this->db->limit($per_page,$start);
		$query = $this->db->get('tbl_booking')->result();

		$new = array();
		foreach ($query as $key => $value) {
			$new[$key]['id'] = $value->medical_record_id; 
			$new[$key]['date'] = $value->date; 
		}
		//echo"<pre>";print_r($query);echo"</pre>";exit();
		if(count($query) > 0){

			$return_array = array('status'=>'success','data'=>array('patient_id'=>$pat_details->id,'patient_name'=>$pat_details->name,'patient_profile_photo'=>$pat_details->profile_photo,'patient_age'=>$diff),'medical'=>$new);
		}else{
			$return_array = array('status'=>'error','data'=>array('patient_id'=>$pat_details->id,'patient_name'=>$pat_details->name,'patient_profile_photo'=>$pat_details->profile_photo,'patient_age'=>$diff,'medical'=>[]),'medical'=>[]);
		}
		return $return_array;
	}

	public function get_doctor_upcoming_consultation_list($doctorid,$start,$per_page,$type){
		$this->db->select('tbl_booking.id,tbl_registration.id as patient_id,tbl_registration.name as patient_name,tbl_registration.profile_photo as patient_profile_photo,tbl_booking.date');
		$this->db->from('tbl_booking');
		$this->db->join('tbl_registration','tbl_registration.id = tbl_booking.patient_id');
		$this->db->where('tbl_booking.doctor_id',$doctorid);
		$this->db->where('tbl_booking.booking_status','1');
		$this->db->where('tbl_booking.payment_status','1');
		if($type == '0'){
			$date = strtotime(date('Y-m-d h:i:s'));
			$this->db->where("tbl_booking.time_start > '".$date."'");
		}
		if($type == '1'){
			$date = strtotime(date('Y-m-d'));
			$this->db->where("tbl_booking.date = '".$date."'");
		}
		if($type == '2'){
			$date = strtotime(date('Y-m-d h:i:s'));
			$newdate = strtotime(date("Y-m-d",strtotime(date('Y-m-d')." +8day")));
			$this->db->where("tbl_booking.date >= '".$date."'");
			$this->db->where("tbl_booking.date < '".$newdate."'");
		}
		$this->db->order_by('tbl_booking.date','ASC');
		$reslt = $this->db->get()->result();
		//echo $this->db->last_query();exit();
		if(count($reslt) > 0){
			foreach ($reslt as $key => $value) {
				$reslt[$key]->patient_name = decrypt_data($value->patient_name);
			}
			return $reslt;
		}else{
			return false;
		}
		
	}

	public function get_patient_medical_record_details($data){
		$this->db->select("tbl_registration.id as patient_id,tbl_registration.name as patient_name,tbl_registration.occupation as patient_occupation,tbl_registration.profile_photo as patient_profile_photo,CAST(AES_DECRYPT(`tbl_registration`.`dob`, 'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dob,tbl_booking.total_sum,tbl_booking.date,tbl_doctors.consultation_duration,tbl_doctors.price");
		$this->db->from('tbl_booking');
		$this->db->join('tbl_registration','tbl_booking.patient_id = tbl_registration.id');
		$this->db->join('tbl_doctors','tbl_booking.doctor_id = tbl_doctors.id');
		$this->db->where('tbl_registration.id',$data['patient_id']);
		$result = $this->db->get()->row();
		//$result->price = decrypt_data($result->price);

		$settings = $this->db->get('settings')->row();

		$this->db->where('id',$data['medical_record_id']);
		$res = $this->db->get('tbl_medical_records')->row();
		//echo "<pre>";print_r($res);echo"</pre>";exit();
		if($res){
			$diff = (date('Y') - date('Y',$result->dob));
			$result->patient_age = $diff;
			unset($result->dob);
		

			$result->patient_review_id = $res->id;
			if(isset($res->patient_review)){
				$result->patient_review = decrypt_data($res->patient_review);
			}else{
				$result->patient_review = '';
			}
			$result->medical_record_id = $res->id;
			$result->medical_record_date = $result->date;
			$payment = array();
			$ipok_fee = ($result->price * $settings->ipok_fee)/100 ;
			$consult = $result->total_sum - $ipok_fee;
			$payment['consultation_duration'] = $result->consultation_duration;
			$payment['consultation_fee'] = (string)$consult;
			$payment['ipok_commission'] = (string)$ipok_fee;
			$payment['total'] = $result->total_sum;
			unset($result->total_sum);
			$result->payment_details = $payment;
			unset($result->consultation_duration);
			unset($result->price);
			unset($result->amount);

			$anamnese = array();
			$anamse_details = json_decode(decrypt_data($res->diseases));
			 //echo"<pre>";print_r($anamse_details);echo"</pre><br>";exit();
			if(isset($anamse_details)){
				foreach ($anamse_details->anamnese as $key => $value) {
				 	$ke = strtolower($key);
				 	$new[$ke] = $value;
				}
				unset($anamse_details->anamnese);
				$anamse_details->anamnese = (object)$new;
				$anamse_details->anamnese->principal_problem = decrypt_data($res->main_complaint);
				$anamse_details->anamnese->description = decrypt_data(strip_tags($res->description));
				if(isset($anamse_details->anamnese->others)){
		         	if(in_array('hepatitis',$anamse_details->anamnese->others)){
		         		 $anamse_details->anamnese->has_hepatitis= true;
		         	}else{
		         		$anamse_details->anamnese->has_hepatitis= false;
		         	}

		         	if(in_array('pregnancy',$anamse_details->anamnese->others)){
		         		 $anamse_details->anamnese->is_pregnant= true;
		         	}else{
		         		$anamse_details->anamnese->is_pregnant= false;
		         	}

		         	if(in_array('diabetis',$anamse_details->anamnese->others)){
		         		 $anamse_details->anamnese->has_diabetes= true;
		         	}else{
		         		$anamse_details->anamnese->has_diabetes= false;
		         	}

		         	if(in_array('healing_problems',$anamse_details->anamnese->others)){
		         		 $anamse_details->anamnese->has_healing_problems= true;
		         	}else{
		         		$anamse_details->anamnese->has_healing_problems= false;
		         	}
		         	unset($anamse_details->anamnese->others);
	         	}
	          	$result->anamnese = $anamse_details->anamnese;
          	}else{
          		$result->anamnese = [];
          	}
          	
          	$prescrib = json_decode(decrypt_data($res->prescribtions));
          	$med = array();
          	if(isset($prescrib)){
          		foreach ($prescrib as $key => $value) {
	          		$med_data = $this->db->get_where('tbl_medicine',array('medicine_name'=>$value->name,'medicine_dosage'=>$value->quantity))->row();
	            	$med[$key]['id'] = $med_data->id;
	            	$med[$key]['medicine_name'] = $value->name;
	            	$med[$key]['dosage'] = $value->procedure;
	        		$med[$key]['quantity'] = $value->quantity;
	            }
	          	$result->prescriptions = $med;
	          }else{
	          	$result->prescriptions = [];
	          }

          	$exams = json_decode(decrypt_data($res->exams));
          	$exam = array();
          	if(isset($exams)){
          		foreach ($exams as $key => $value) {
	            	$exam[$key]['exam'] = $value->procedure;
	            	$exam[$key]['observation'] = $value->observation;
	            }
	          	$result->exams = $exam;
	          }else{
	          	$result->exams = [];
	          }

          	$budgett = json_decode(decrypt_data($res->budget));
          	$budgt = array();
          	$budget=array();
          	if(isset($budgett)){
          		$sum = 0;
          		foreach ($budgett as $key => $value) {
	            	$budgt[$key]['item'] = $value->procedure;
	            	$budgt[$key]['quantity'] = $value->quantity;
	            	$budgt[$key]['amount'] = $value->amount;
	            	$sum = $sum + $value->amount;
	            }
	            $budget['total'] = $sum;
	            $budget['bill_items'] = $budgt;
	            $result->budget = $budget;
          	}else{
          		$result->budget = [];
          	}

            $medical = array();
			$medi = json_decode(decrypt_data($res->letters));
			if(isset($medi)){
				$medical[0]['title'] = '';
	            $medical[0]['certificate'] = strip_tags($medi->certificate);
	            $result->medical_certificates = $medical;
			}else{
				 $result->medical_certificates = [];
			}

            $photos = json_decode($res->images);
            if(isset($photos)){
            	$result->attached_images = $photos;
            }else{
            	$result->attached_images = [];
            }
            $result->other_observations = strip_tags(decrypt_data($res->other_observations));
			//echo "<pre>";print_r($result);echo"</pre>";exit();
			$return_array = array('status'=>'success','data'=>$result);

		}else{
			$return_array = array('status'=>'error','message'=>'Medical Record for this Id doesnot exist');
		}
		return $return_array;
	}

	public function get_doctor_notification_list($doctorid,$start,$per_page){

		//$this->db->select('id,type,message,read_status');
		//SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
		$this->db->select("read_status,id,type,message");
		$this->db->limit($per_page,$start);
		$result = $this->db->get_where('tbl_doctor_notifications',array('doctor_id'=>$doctorid))->result();
		//echo $this->db->last_query();exit();
		if(count($result) > 0){
			return $result;
		}else{
			return false;
		}

	}

	public function set_doctor_notification_status($data){
		if($data['status'] == true){
			$status = '1';
		}else{
			$status = '0';
		}
		if($this->db->update('tbl_doctor_notifications',array('read_status'=>$status),array('id'=>$data['notification_id']))){
			return true;
		}else{
			return false;
		}
	}
	
	public function cancel_booking_doctor($id,$data){
		$query = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		$doctr_data = $this->db->get_where('tbl_doctors',array('id'=>$id))->row_array();
		$special = $this->db->get_where('tbl_specialization',array('id'=>$doctr_data['specialization']))->row();
		$conslt_time =  strtotime(date('Y-m-d h:i:s'));
		$msg = "Sorry, Your booking at time ".$query->time." is cancelled by ".$doctr_data['name'];
		if($query){
			if($query->doctor_id == $id){
				$this->db->update('tbl_booking',array('booking_status'=>'4'),array('id'=>$data['booking_id']));
				$this->db->insert('tbl_patient_notification',array('patient_id'=>$query->patient_id,'type'=>'3','message'=>$msg,'time'=>$conslt_time,'booking_id'=>$data['booking_id'],'read_status'=>'0'));
				$patient_insert_id = $this->db->insert_id();
				
				$fcm_user = $this->db->get_where('tbl_authtoken',array('userid'=>$query->patient_id))->row();
				$new['id'] = $patient_insert_id;
				$new['type'] = "Cancel Consultation";
				$new['booking_id'] = $query->id;
				$new['booking_date'] = $query->date;
				$new['doctor_id'] = $query->doctor_id;
				$new['doctor_name'] = $doctr_data['name'];
				$new['doctor_specialization'] = $special->specialization_name;
				$new['message'] = $msg;
				$new['time'] = $conslt_time;
				$new['to'] =$fcm_user->fcm_token;
				$user_type = '1';
				$push = $this->push_sent($new,$user_type);
				
				if($query->visit_type == '0'){
					$doctor_wallet = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$id))->row();
					$earn = $query->total_sum - (($query->total_sum * $query->ipok_fee)/100);

					if($doctor_wallet){
						$future_earn = decrypt_data($doctor_wallet->future_earn) - $earn;
						$total = decrypt_data($doctor_wallet->total_earn) - $earn;
						$this->db->update('tbl_wallet_details',array('future_earn'=>encrypt_data($future_earn),'total_earn'=>encrypt_data($total)),array('doctor_id'=>$id));
					}
				}
				$result = array('status'=>'success');
			}else{
				$result = array('status'=>'failed','message'=>'Invalid Doctor ');
			}
		}else{
			$result = array('status'=>'failed','message'=>'Invalid Booking Id ');
		}
		return $result;
	}

	
	public function get_doctor_consultation_configuration($doctor_id){
		$this->db->select('consultation_duration,price as consultation_price,domiciliary_status,accept_return,return_timeperiod as return_consultation_time_period');
		$query = $this->db->get_where('tbl_doctors',array('id'=>$doctor_id))->row();
		if($query){
			//$query->consultation_price = decrypt_data($query->consultation_price);
			//$query->domiciliary_status = decrypt_data($query->domiciliary_status);
			if($query->accept_return == '0'){
				$query->is_return_consultation_available = false;
			}else{
				$query->is_return_consultation_available = true;
			}

			if($query->domiciliary_status == '0'){
				$query->is_home_consultation_available = false;
			}else{
				$query->is_home_consultation_available = true;
			}

			unset($query->accept_return);
			unset($query->domiciliary_status);

			$result = array('status'=>'success','data'=>$query);
		}else{
			$result = array('status'=>'error','message'=>'Doctor Id doesnot Exist');
		}
		return $result;
	}
	
	public function get_doctor_notification_list_unread_count($doctor_id){
		$this->db->select("count(id) as count");
		$result = $this->db->get_where('tbl_doctor_notifications',array('doctor_id'=>$doctor_id,'read_status'=>'0'))->row();
		return $result;
	}
	
	public function notification_list_unread_count($user_id){
		$this->db->select("count(id) as count");
		$result = $this->db->get_where('tbl_patient_notification',array('patient_id'=>$user_id,'read_status'=>'0'))->row();
		return $result;
	}

	
	public function start_consultation_doctor($data){
		$query = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($query){
			$this->db->update('tbl_booking',array('booking_status'=>'2'),array('id'=>$data['booking_id']));
			$result = array('status'=>'success');
		}else{
			$result = array('status'=>'failed','message'=>'Invalid Booking Id');
		}
		return $result;
	}
	
	public function get_consultation_basic_data(){
		$this->db->select('id,complaint_name as problem');
		$main = $this->db->get('tbl_main_complaints')->result();
		$query = $this->db->get('tbl_major_problems')->result();
		$new =array();
		$new['main_problems'] = $main;
		foreach ($query as $key => $value) {
			if($value->id != '7'){
				$this->db->select('id,subproblem_name as problem');
				$res = $this->db->get_where('tbl_major_subproblems',array('problem_category_id'=>$value->id))->result();
			}else{
				$this->db->select('DISTINCT(medicine_name)');
				$med = $this->db->get('tbl_medicine')->result();
				$med_array = array();
				foreach ($med as $key => $values) {
					$med_array[] = $values->medicine_name;
				}

				//print_r($med_array);exit();
			}
			if($value->id == '1'){
				if(count($res)>0){
					$new['heart_problems'] =$res;
				}else{
					$new['heart_problems'] =[];
				} 
			}
			if($value->id == '2'){
				if(count($res)>0){
					$new['kidney_problems'] =$res;
				}else{
					$new['kidney_problems'] =[];
				}  
			}
			if($value->id == '3'){
				if(count($res)>0){
					$new['joint_problems'] =$res; 
				}else{
					$new['joint_problems'] =[];
				}  
			}
			if($value->id == '4'){
				if(count($res)>0){
					$new['respiratory_problems'] =$res; 
				}else{
					$new['respiratory_problems'] =[];
				}  
			}
			if($value->id == '5'){
				if(count($res)>0){
					$new['gastric_problems'] =$res; 
				}else{
					$new['gastric_problems'] =[];
				}  
			}
			if($value->id == '6'){
				if(count($res)>0){
					$new['allergies'] =$res; 
				}else{
					$new['allergies'] =[];
				}  
			}
			if($value->id == '7'){
				if(count($med)>0){
					$new['medicine_names'] =$med_array;
				}else{
					$new['medicine_names'] =[];
				}  
			}
		}
		$this->db->select("DISTINCT(exam_procedure)");
		$xam = $this->db->get('tbl_exams')->result();

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

			$this->db->select('observation');
			$this->db->where('exam_procedure',$value->exam_procedure);
			$proc = $this->db->get('tbl_exams')->result();

			$new['exams'][$key]['name'] = decrypt_data($value->exam_procedure);
			foreach ($proc as $key1 => $value1) {
				$new['exams'][$key]['observations'][] =decrypt_data($value1->observation);
			}
		}

		$letter = $this->db->get_where('tbl_policy',array('id'=>'1'))->row();
		$new['letter_without_cid'] = $letter->letter;
		$new['letter_with_cid'] = $letter->cid_letter;

		$this->db->select('code');
		$code = $this->db->get('tbl_disease_code')->result();
		foreach ($code as $key => $value) {
			$new['CID'][] = $value->code;
		}

		$this->db->select('DISTINCT(budget_procedure)');
		$budget = $this->db->get('tbl_budget')->result();
		foreach ($budget as $key => $value) {
			$new['budget'][] = $value->budget_procedure;
		}
		
		$result = array('status'=>'success','data'=>$new);
		return $result;
	}
	
	public function set_anamnese($data,$doctor_id){
		$result = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($result){
			if($result->doctor_id == $doctor_id){
				$anamnese = array();
				$new = array();
				$new['main_complaint'] = encrypt_data($data['main_problem']);
				$new['booking_id'] = $data['booking_id'];
				if(isset($data['description'])){
					$new['description'] = encrypt_data($data['description']); 

				}
				if(isset($data['kidney_problems'])){
					foreach ($data['kidney_problems'] as $key => $value) {
						$anamnese['anamnese']['Kidney_Problem']= $value;
					}
				}
				if(isset($data['heart_problems'])){
					foreach ($data['heart_problems'] as $key => $value) {
						$anamnese['anamnese']['Heart_Problem'] =$value;
					}
					
				}
				if(isset($data['respiratory_problems'])){
					foreach ($data['respiratory_problems'] as $key => $value) {
						$anamnese['anamnese']['Breathing_Problem'] =$value;
					}
				}
				if(isset($data['gastric_problems'])){
					foreach ($data['gastric_problems'] as $key => $value) {
						$anamnese['anamnese']['Gastric_Problem'] =$value;
					}
				}
				if(isset($data['allergies'])){
					foreach ($data['allergies'] as $key => $value) {
						$anamnese['anamnese']['Allergies'] =$value;
					}
				}
				if(isset($data['medicines'])){
					foreach ($data['medicines'] as $key => $value) {
						$anamnese['anamnese']['Medications'][] = $value;
					}
				}
				if($data['has_hepatitis']){
					$anamnese['anamnese']['others'][] ='hepatitis';
				}
				if($data['is_pregnant']){
					$anamnese['anamnese']['others'][] ='pregnancy';
				}
				if($data['has_diabetes']){
					$anamnese['anamnese']['others'][] ='diabetis';
				}
				if($data['has_healing_problems']){
					$anamnese['anamnese']['others'][] ='healing_problems';
				}
				$new['diseases'] = encrypt_data(json_encode($anamnese));
				$rows = $this->db->get_where('tbl_medical_records',array('booking_id'=>$data['booking_id']))->row();
				if($rows){
					unset($new['booking_id']);
					if($this->db->update('tbl_medical_records',$new,array('booking_id'=>$data['booking_id']))){
						$return = array('status'=>'success');
					}else{
						$return = array('status'=>'failed','message'=>'Something Went Wrong..Try Again Later!');
					}
				}else{
					$this->db->insert('tbl_medical_records',$new);
					$last_id = $this->db->insert_id();
					if($this->db->update('tbl_booking',array('medical_record_id'=>$last_id),array('id'=>$data['booking_id']))){
						$return = array('status'=>'success');
					}else{
						$return = array('status'=>'failed','message'=>'Something Went Wrong..Try Again Later!');
					}
				}
			}else{	
				$return = array('status'=>'failed','message'=>'Invalid Doctor');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot exist');
		}
		return $return;
	}
	
	public function set_prescriptions($data,$doctor_id){
		$res = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($res){
			if($res->medical_record_id != '0' && $res->medical_record_id != ''){
				$new =array();
				foreach ($data['prescriptions'] as $key => $value) {
					$new[$key]['name'] = $value->name;
					$new[$key]['quantity'] = $value->quantity;
					$new[$key]['procedure'] = $value->dosage_and_administration;
				}
				if($this->db->update('tbl_medical_records',array('prescribtions'=>encrypt_data(json_encode($new))),array('booking_id'=>$data['booking_id']))) {
					$return = array('status'=>'success');
				}else{
					$return = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later!');
				}
			}else{
				$return = array('status'=>'failed','message'=>'Medical Record Doesnot Exist');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot Exist');
		}
		return $return;
	}

	public function get_medicine_basic_data($data){
		$med = $this->db->get_where('tbl_medicine',array('medicine_name'=>$data['medicine']))->result();
		if(count($med) > 0 ){
			foreach ($med as $key => $value) {
				$new['name'] = $value->medicine_name;
				$new['quantities'][]= $value->medicine_dosage;
				$new['dosage'][]= $value->medicine_procedure;
			}
			$return = array('status'=>'success','data'=>$new);
		}else{
			$return = array('status'=>'failed','message'=>'Medicine doesnot Exist');
		}
		return $return;
	}

	public function get_budget_basic_data($data){
		$budget = $this->db->get_where('tbl_budget',array('budget_procedure'=>$data['item']))->result();
		if(count($budget) > 0 ){
			foreach ($budget as $key => $value) {
				$new['name'] = $value->budget_procedure;
				$new['quantities'][]= $value->quantity;
				$new['values'][]= $value->amount;
			}
			$return = array('status'=>'success','data'=>$new);
		}else{
			$return = array('status'=>'failed','message'=>'Budget doesnot Exist');
		}
		return $return;
	}

	public function set_exams_procedures($data,$doctor_id){
		$res = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($res){
			if($res->medical_record_id != '0' && $res->medical_record_id != ''){
				$new =array();
				foreach ($data['exams'] as $key => $value) {
					$new[$key]['procedure'] = $value->name;
					$new[$key]['observation'] = $value->observation;
				}
				if($this->db->update('tbl_medical_records',array('exams'=>encrypt_data(json_encode($new))),array('booking_id'=>$data['booking_id']))){
					$return = array('status'=>'success');
				}else{
					$return = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later!');
				}
			}else{
				$return = array('status'=>'failed','message'=>'Medical Record Doesnot Exist');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot Exist');
		}
		return $return;
	}

	public function set_budgets($data,$doctor_id){
		$res = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($res){
			if($res->medical_record_id != '0' && $res->medical_record_id != ''){
				$new =array();
				foreach ($data['items'] as $key => $value) {
					$new[$key]['procedure'] = $value->name;
					$new[$key]['quantity'] = $value->quantity;
					$new[$key]['amount'] = $value->value;
				}
				if($this->db->update('tbl_medical_records',array('budget'=>encrypt_data(json_encode($new))),array('booking_id'=>$data['booking_id']))){
					$return = array('status'=>'success');
				}else{
					$return = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later!');
				}
			}else{
				$return = array('status'=>'failed','message'=>'Medical Record Doesnot Exist');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot Exist');
		}
		return $return;
	}

	
	public function forgot_password($data,$type){
		if($type == 'user'){
			$query = $this->db->get_where('tbl_registration',array('email'=>$data['email']))->row();
		}else{
			$query = $this->db->get_where('tbl_doctors',array('email'=>$data['email']))->row();
		}
		if($query){
			$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
				$result = '';
		    for ($i = 0; $i < 24; $i++)
		        $result .= $characters[mt_rand(0, 61)];
		    $link = base_pic_url().'Home/resetpassword/?i='.$query->id.'&c='.$result.'&t=';
			
		    if($type =='doctor')
		    {
		    	$link = $link.'2';
				$this->db->update('tbl_doctors',array('confirmation_code'=>$result),array('id'=>$query->id,'email'=>$data['email']));
		    }
		    else
		    {
		    	$link = $link.'1';
		    	$this->db->update('tbl_registration',array('confirmation_code'=>$result),array('id'=>$query->id,'email'=>$data['email']));
		    }
	     	$msg = "Hi ".$query->name.",<br><br>Your request for resetting password has been accepted. Use the following link to reset password. ".$link.". Please Do not share with anyone<br><br>Ipok Team";
	     	$sub = 'Reset Password';
	     	$reslt = $this->send_mail($msg,$data['email'],$sub);
	     	if($reslt){
	     		$return = array('status'=>'success','message'=>'Please check Your mail');
	     	}else{
	     		$return = array('status'=>'error','message'=>'Something Went Wrong.. Try Again Later!');
	     	}

		}else{
			$return = array('status'=>'error','message'=>'Email id Doesnot Exist');
		}
		return $return;
	}

	public function send_mail($msg,$email,$sub){
      $settings = $this->db->get('settings')->row();
      $configs = array(
                        'protocol'=>'smtp',
                        'smtp_host'=>$settings->smtp_host,
                        'smtp_user'=>$settings->smtp_username,
                        'smtp_pass'=>$settings->smtp_password,
                        'smtp_port'=>'587',
                        'smtp_timeout'=>20,
                        'mailtype' => 'html',
                        'charset' => 'iso-8859-1',
                        'wordwrap' => TRUE
                      ); 
      $this->load->library('email', $configs);
      $this->email->initialize($configs);
      $this->email->set_newline("\r\n");
      $this->email
        ->from($settings->admin_email, 'IPOK')
        ->to($email)
        ->subject($sub)
        ->message($msg);
      if($this->email->send()){
		return true;
		}
    }
	
	public function finalize_medical_record($data,$doctor_id){
    	$res = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($res){
			if($res->medical_record_id != '0' && $res->medical_record_id != ''){
				if(!isset($data['observations'])){
					$data['observations'] = '';
				}
				if(!isset($_FILES['photo'])){
					$data['images'] = '';
				}
				$this->db->update('tbl_medical_records',array('other_observations'=>encrypt_data($data['observations']),'images'=>$data['images']),array('booking_id'=>$data['booking_id']));
				$doctor_wallet = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$doctor_id))->row();
				$earn = $res->total_sum - (($res->total_sum * $res->ipok_fee)/100);
				if($res->visit_type == '0'){
					if($doctor_wallet){
						$redem_earn = decrypt_data($doctor_wallet->reedem_earn) + $earn;
						$future_earn = decrypt_data($doctor_wallet->future_earn) - $earn;
						$total = $redem_earn + $future_earn;
						$this->db->update('tbl_wallet_details',array('future_earn'=>encrypt_data($future_earn),'reedem_earn'=>encrypt_data($redem_earn),'total_earn'=>encrypt_data($total)),array('doctor_id'=>$doctor_id));
					}
				}
				if($this->db->update('tbl_booking',array('booking_status'=>'3'),array('id'=>$data['booking_id']))){
					$return = array('status'=>'success');
				}else{
					$return = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later!');
				}
			}else{
				$return = array('status'=>'failed','message'=>'Medical Record Doesnot Exist');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot Exist');
		}
		return $return;
    }
	
	public function set_medical_certificate($data){
    	$res = $this->db->get_where('tbl_booking',array('id'=>$data['booking_id']))->row();
		if($res){
			if($res->medical_record_id != '0' && $res->medical_record_id != ''){
				$new['days']= $data['days'];
				if($data['is_letter_with_cid']){
					$new['cid']= $data['CID'];
					$new['is_letter_with_cid'] = $data['is_letter_with_cid'];
				}else{
					$new['cid']= 'null';
					$new['is_letter_with_cid'] = $data['is_letter_with_cid'];
				}
				$new['certificate'] = $data['medical_certificate'];
				if($this->db->update('tbl_medical_records',array('letters'=>encrypt_data(json_encode($new))),array('booking_id'=>$data['booking_id']))){
					$return = array('status'=>'success');
				}else{
					$return = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later!');
				}

			}else{
				$return = array('status'=>'failed','message'=>'Medical Record Doesnot Exist');
			}
		}else{
			$return = array('status'=>'failed','message'=>'Booking Id doesnot Exist');
		}
		return $return;
    }
	
	public function get_wallet_details($doctor_id){
    	$result = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$doctor_id))->row();
    	if($result){
	    	$res = array('status'=>'success','data'=>array('doctor_id'=>$doctor_id,'redeemable_earnings'=>decrypt_data($result->reedem_earn),'future_earnings'=>decrypt_data($result->future_earn),'total_earnings'=>decrypt_data($result->total_earn)));
    	}else{
    		$res = array('status'=>'failed','data'=>array('doctor_id'=>$doctor_id,'redeemable_earnings'=>'0','future_earnings'=>'0','total_earnings'=>'0'));
    	}
    	return $res;
    }
	
	public function get_consultation_transaction_list($doctorid,$start,$per_page,$type){
    	$this->db->select("tbl_booking.id,tbl_booking.patient_id,tbl_registration.name as patient_name,tbl_doctors.consultation_duration as duration,(tbl_booking.total_sum - ((tbl_booking.total_sum * tbl_booking.ipok_fee) / 100)) as earnings,tbl_doctors.domiciliary_status as type,tbl_booking.date");
    	$this->db->from('tbl_booking');
    	$this->db->join('tbl_registration','tbl_registration.id = tbl_booking.patient_id');
    	$this->db->join('tbl_doctors','tbl_doctors.id = tbl_booking.doctor_id');
    	$this->db->where('tbl_doctors.id',$doctorid);
    	if($type == '1'){
    		$this->db->where('tbl_booking.booking_status','3');
    	}else{
    		$this->db->where("(tbl_booking.booking_status = '1' or tbl_booking.booking_status = '2')");
    	}
    	$this->db->limit($per_page,$start);
    	$query = $this->db->get()->result();
    	if(count($query) > 0 ){
    		foreach ($query as $key => $value) {
    			$query[$key]->patient_name = decrypt_data($value->patient_name);
    			if($value->type == '0'){
    				$query[$key]->type = '0';
    			}else{
    				$query[$key]->type = '0';
    			}
    		}
    		$result = array('status'=>'success','data'=>$query);
    	}else{
    		$result = array('status'=>'failed');
    	}
    	return $result;
    }
	
	public function add_bank($data){
    	if($this->db->insert('tbl_bank_accounts',$data)){
    		$last_id = $this->db->insert_id();
    		$query = $this->db->get_where('tbl_bank_accounts',array('id'=>$last_id))->row();
    		$query->account_no = decrypt_data($query->account_no);
    		$query->account_holder = decrypt_data($query->account_holder);
    		$result = array('status'=>'success','data'=>$query);
    	}else{
    		$result = array('status'=>'failed');
    	}
    	return $result;
    }
	
	public function edit_bank($data){
    	$query = $this->db->get_where('tbl_bank_accounts',array('id'=>$data['id']))->row();
    	if($query){
    		if($this->db->update('tbl_bank_accounts',$data,array('id'=>$data['id']))){
    			$bank_query = $this->db->get_where('tbl_bank_accounts',array('id'=>$data['id']))->row();
	    		$bank_query->account_no = decrypt_data($bank_query->account_no);
	    		$bank_query->account_holder = decrypt_data($bank_query->account_holder);
	    		$result = array('status'=>'success','data'=>$bank_query);
    		}else{
    			$result = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later');
    		}
    	}else{
    		$result = array('status'=>'failed','message'=>'Bank Id Doesnot Exist');
    	}
    	return $result;
    }
	
	public function delete_bank($data){
    	$query = $this->db->get_where('tbl_bank_accounts',array('id'=>$data['id']))->row();
    	if($query){
    		if($this->db->delete('tbl_bank_accounts',array('id'=>$data['id']))){
    			$result = array('status'=>'success');
    		}else{
    			$result = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later');
    		}
    	}else{
    		$result = array('status'=>'failed','message'=>'Bank Id Doesnot Exist');
    	}
    	return $result;
    }
	
	public function get_bank_list($id,$start,$per_page){
    	$this->db->select('id,bank_name,agency as agency_name,account_no as bank_account,account_holder as name');
    	$this->db->limit($per_page,$start);
    	$query = $this->db->get_where('tbl_bank_accounts',array('type_id'=>$id))->result();
    	if(count($query) > 0){
    		foreach ($query as $key => $value) {
    			$query[$key]->bank_account = decrypt_data($value->bank_account);
    			$query[$key]->name = decrypt_data($value->name);
    		}
    		$result =array('status'=>'success','data'=>$query);
    	}else{
    		$result = array('status'=>'failed');
    	}
    	return $result;
    }
	
	public function withdrawal_request($data){
		$bank = $this->db->get_where('tbl_bank_accounts',array('id'=>$data['bank_id']))->row();
		if($bank){
			$query = $this->db->get_where('tbl_wallet_details',array('doctor_id'=>$data['doctor_id']))->row();
			$data['date'] = strtotime(date('Y-m-d h:i:s'));
			$data['previous_reedem_earn'] = decrypt_data($query->reedem_earn);
			if(decrypt_data($query->reedem_earn) >= $data['amount']){
				$data['status'] = '0';
				if($this->db->insert('tbl_withdrawal_history',$data)){
					$last = $this->db->insert_id();
					$res = $this->db->get_where('tbl_withdrawal_history',array('id'=>$last))->row();
					$result = array('status'=>'success','data'=>$res);
				}else{
					$result = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later !');
				}
			}else{
				$data['status'] = '3';
				if($this->db->insert('tbl_withdrawal_history',$data)){
					$result = array('status'=>'failed','message'=>'Your account have no enough balance to withdraw as per your request');
				}else{
					$result = array('status'=>'failed','message'=>'Something Went Wrong.. Try Again Later !');
				}
			}
		}else{
			$result = array('status'=>'failed','message'=>'Bank Id Doesnot Exist');
		}
    	return $result;
    }
	
	public function get_withdrawal_history($doctorid,$start,$per_page){
    	$this->db->select('tbl_withdrawal_history.id,tbl_withdrawal_history.bank_id,tbl_withdrawal_history.amount,tbl_withdrawal_history.date,tbl_withdrawal_history.status,tbl_bank_accounts.bank_name,tbl_bank_accounts.account_no as bank_account');
    	$this->db->join('tbl_bank_accounts','tbl_bank_accounts.id = tbl_withdrawal_history.bank_id');
    	$this->db->limit($per_page,$start);
    	$query = $this->db->get_where('tbl_withdrawal_history',array('tbl_withdrawal_history.doctor_id'=>$doctorid))->result();
    	if(count($query) > 0){
    		foreach ($query as $key => $value) {
    			$query[$key]->bank_account = decrypt_data($value->bank_account);
    		}
    		return $query;
    	}else{
    		return false;
    	}
    }
	
	public function doctor_profile($id){
    	//$this->db->select('tbl_doctors.id,tbl_doctors.name,tbl_specialization.specialization_name as specialization,tbl_doctors.profile_pic as profile_photo,CONCAT_WS(" ", tbl_doctors.street_address, tbl_doctors.locality,tbl_doctors.number,tbl_doctors.complement) as address,tbl_doctors.telephone');
    	$this->db->select('tbl_doctors.id,tbl_doctors.name,tbl_specialization.specialization_name as specialization,tbl_doctors.profile_pic as profile_photo, tbl_doctors.street_address, tbl_doctors.locality,tbl_doctors.number,tbl_doctors.complement,tbl_doctors.telephone');
		$this->db->join('tbl_specialization','tbl_specialization.id = tbl_doctors.specialization');
    	$res = $this->db->get_where('tbl_doctors',array('tbl_doctors.id'=>$id))->row();
    	if($res){
    		$res->address = decrypt_data($res->street_address).' '.decrypt_data($res->locality).' '.decrypt_data($res->number).' '.decrypt_data($res->complement);
    		unset($res->street_address);
    		unset($res->locality);
    		unset($res->number);
    		unset($res->complement);

	    	$new[0] = $res->telephone;
	    	$res->phone =$new;
	    	unset($res->telephone);
	    	$result = array('status'=>'success','data'=>$res);
    	}else{
    		$result = array('status'=>'failed');
    	}
    	return $result;
    }
	
	public function check_wait_listed($data){
		$check = $this->db->get_where('tbl_booking',array('doctor_id'=>$data['doctor_id'],'clinic_id'=>$data['clinic_id'],'date'=>$data['date'],'time'=>$data['time']));
		if($check->num_rows() > 0){
			$is_booking = true;
		}else{
			$is_booking = false;
		}

		$this->db->select('accept_return,return_timeperiod');
		$this->db->where('id',$data['doctor_id']);
		$check_doctor_status = $this->db->get('tbl_doctors')->row();
		if($check_doctor_status->accept_return == '1'){
			$old_date = date('Y-m-d',$data['date']);
			$newdate = date("Y-m-d",strtotime($old_date." -".$check_doctor_status->return_timeperiod." day"));
			$new_date = strtotime($newdate);

			$this->db->where('doctor_id',$data['doctor_id']);
			$this->db->where('clinic_id',$data['clinic_id']);
			$this->db->where('patient_id',$data['user_id']);
			$this->db->where('free_visit_status',0);
			$this->db->where('visit_type',0);
			$this->db->where('date >=',$new_date);
			$this->db->where('date <=',$data['date']);
			$this->db->order_by('id','DESC');
			$this->db->limit(1,0);
			$old_book_res = $this->db->get('tbl_booking')->row();

			if(isset($old_book_res) && $old_book_res != ''){
				if($old_book_res->visit_type == '0'){
					$is_return_avail = true;
				}else{
					$is_return_avail = false;
				}
			}else{
				$is_return_avail = false;
			}
			
		}else{
			$is_return_avail = false;
		}
		$res = array('status'=>'success','booked'=>$is_booking,'is_return_avail'=>$is_return_avail);
		return $res;
	}
	
	Public function update_profile($id,$data){
		$this->db->where('tbl_registration.id',$id);
		if($this->db->update('tbl_registration',$data))
		{
			$result = array('status' => 'success');
		}
		else
		{
			$result = array('status' => 'error');
		}
		return $result;
	}

	public function set_patient_notification_status($data){
		if($data['status'] == true){
			$status = 1;
		}else{
			$status = 0;
		}
		if($this->db->update('tbl_patient_notification',array('read_status'=>$status),array('id'=>$data['notification_id']))){
			return true;
		}else{
			return false;
		}
	}
	
	
    public function checkBooking($id)
	{
		$this->db->select('count(*) as count,tbl_booking.date as booking_date,tbl_booking.id as booking_id,tbl_booking.time as booking_slot');
		$this->db->from('tbl_booking');
		$this->db->where('tbl_booking.id',$id);
		$this->db->where('tbl_booking.payment_status','0');
		$this->db->where('tbl_booking.booking_status!=4');
		$data =$this->db->get()->row_array();	
		//print_r($data);die();	
		return $data;
	}

	function get_booking_details($booking_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_booking');
		$this->db->where('id',$booking_id);
		$data =$this->db->get()->row_array();		
		return $data;
	}

	public function get_single_patient($id)
	{
		$this->db->select("tbl_registration.id as patientid,tbl_registration.name as pt_name,tbl_registration.username as pt_username,tbl_registration.profile_photo as pt_pic,tbl_registration.gender as pt_gender,tbl_registration.email as pt_email,CAST(AES_DECRYPT(`tbl_registration`.`dob`, 'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as pt_dob,tbl_registration.number as pt_number,tbl_registration.blood_group as pt_blood_group,tbl_registration.weight as pt_weight,tbl_registration.height as pt_height,tbl_registration.street_address as pt_street_add,tbl_registration.locality as pt_locality,tbl_registration.zip_code as pt_zip_code,tbl_registration.landmark as pt_complement,tbl_registration.rg as pt_rg,tbl_registration.cpf as pt_cpf,tbl_registration.customer_id as pt_customer_id
								 ");

		$this->db->from('tbl_registration');
		$this->db->where('tbl_registration.id',$id);
		$data =$this->db->get()->row_array();
		$data['pt_name'] = decrypt_data($data['pt_name']);		
		$data['pt_gender'] = decrypt_data($data['pt_gender']);		
		$data['pt_number'] = decrypt_data($data['pt_number']);		
		$data['pt_blood_group'] = decrypt_data($data['pt_blood_group']);		
		$data['pt_weight'] = decrypt_data($data['pt_weight']);		
		$data['pt_height'] = decrypt_data($data['pt_height']);		
		$data['pt_street_add'] = decrypt_data($data['pt_street_add']);		
		$data['pt_locality'] = decrypt_data($data['pt_locality']);		
		$data['pt_zip_code'] = decrypt_data($data['pt_zip_code']);		
		$data['pt_complement'] = decrypt_data($data['pt_complement']);		
		$data['pt_rg'] = decrypt_data($data['pt_rg']);		

		return $data;

	}
	
	
	public function get_single_doctor($id)
	{
		$this->db->select("tbl_doctors.id as doctorid,tbl_doctors.name as dr_name,tbl_doctors.profile_pic as dr_pic,tbl_doctors.email as dr_email,tbl_doctors.username as dr_username,CAST(AES_DECRYPT(tbl_doctors.dob,'Ptf/PWNWrULQT72syxfaaBRTS9JbiKrj9dfuVEvT3rA') as CHAR) as dr_dob,tbl_doctors.about as dr_bio,tbl_doctors.specialization as dr_specialization_id,tbl_doctors.price as dr_price,tbl_doctors.consultation_duration as dr_consult_duration,tbl_doctors.accept_return as dr_accept_return,tbl_doctors.return_timeperiod as dr_return_timeperiod,tbl_doctors.gender as dr_gender,tbl_doctors.locality as dr_neighbourhood,tbl_doctors.street_address as dr_rua,tbl_doctors.number as dr_number,tbl_doctors.telephone as dr_telephone,tbl_doctors.complement as dr_complement,tbl_doctors.rg as dr_rg,tbl_doctors.cpf as dr_cpf,tbl_doctors.crm as dr_crm,tbl_doctors.cep as dr_cep,tbl_specialization.specialization_name AS dr_specialization");
		$this->db->from('tbl_doctors');
		$this->db->join('tbl_specialization', 'tbl_specialization.id = tbl_doctors.specialization','left');

		$this->db->where('tbl_doctors.id',$id);

		$data =$this->db->get()->row_array();
		$data['dr_bio'] = decrypt_data($data['dr_bio']);
		//$data['dr_price'] = decrypt_data($data['dr_price']);
		$data['dr_gender'] = decrypt_data($data['dr_gender']);
		$data['dr_neighbourhood'] = decrypt_data($data['dr_neighbourhood']);
		$data['dr_rua'] = decrypt_data($data['dr_rua']);
		$data['dr_number'] = decrypt_data($data['dr_number']);
		$data['dr_complement'] = decrypt_data($data['dr_complement']);
		$data['dr_rg'] = decrypt_data($data['dr_rg']);
		$data['dr_crm'] = decrypt_data($data['dr_crm']);
		$data['dr_cep'] = decrypt_data($data['dr_cep']);
		return $data;
	}

	function get_single_doctor_row($id)
	{
		$this->db->select("*");
		$this->db->from("tbl_doctors");
		$this->db->where("tbl_doctors.id",$id);
		$query = $this->db->get()->row_array();

		$query['about'] = decrypt_data($query['about']);
		//$query['price'] = decrypt_data($query['price']);
		$query['gender'] = decrypt_data($query['gender']);
		$query['street_address'] = decrypt_data($query['street_address']);
		$query['locality'] = decrypt_data($query['locality']);
		$query['number'] = decrypt_data($query['number']);
		$query['complement'] = decrypt_data($query['complement']);
		$query['rg'] = decrypt_data($query['rg']);
		$query['crm'] = decrypt_data($query['crm']);
		$query['cep'] = decrypt_data($query['cep']);
		//$query['domiciliary_status'] = decrypt_data($query['domiciliary_status']);

		return $query;
	}

	public function get_wallet_for_doctor($doc_id)
	{
		$this->db->select('reedem_earn as reedem_earn,
							future_earn as future_earn,
							total_earn as total_earn');
		$this->db->from('tbl_wallet_details');
		$this->db->where('doctor_id',$doc_id);
		$query = $this->db->get()->row_array();

		$query['reedem_earn'] = decrypt_data($query['reedem_earn']);
		$query['future_earn'] = decrypt_data($query['future_earn']);
		$query['total_earn'] = decrypt_data($query['total_earn']);
		return $query;
	}

	public function update_wallet($id,$data)
	{
		$sql = $this->db->insert_string("tbl_wallet_details", array("doctor_id"=>$id,"reedem_earn"=>encrypt_data($data['reedem_earn']),"future_earn"=>encrypt_data($data['future_earn']),"total_earn"=>encrypt_data($data['total_earn']))) . " ON DUPLICATE KEY UPDATE doctor_id = " .$id.',reedem_earn ='.'"' .encrypt_data($data['reedem_earn']).'"'.',future_earn='.'"' .encrypt_data($data['future_earn']).'"' .',total_earn='. '"' .encrypt_data($data['total_earn']).'"';
			if($this->db->query($sql)){
				$return_array = array('status'=>'success');
			}
			else{
				$return_array = array('status'=>'fail');
			}
			
			return $return_array;
	}

	public function insert_notification_patient($data){
		if($this->db->insert('tbl_patient_notification',$data)){
			$insert_id = $this->db->insert_id();
			return $insert_id;
		}
	}

	 public function get_patient_fcm($pat_id)
		{
			$this->db->select('fcm_token');
			$this->db->from('tbl_authtoken');
			$this->db->where('userid',$pat_id);
			$query = $this->db->get();
			return $query->row_array();
		}

	public function insert_notification_doctor($data){
		if($this->db->insert('tbl_doctor_notifications',$data))
		{
			$insert_id = $this->db->insert_id();
			return $insert_id;
		}
	}

	public function get_doctor_fcm($doc_id){
		$this->db->select('fcm_token');
		$this->db->from('tbl_authtoken_doctors');
		$this->db->where('doctor_id',$doc_id);
		$query = $this->db->get();
		return $query->row_array();
	}

	public function set_payment_status($id)
	{
		$update = array('payment_status' => '1');
		$this->db->where('tbl_booking.id',$id);
		$this->db->update('tbl_booking', $update);	
	}

	public function get_booked_payed_data($id){
		$booked_data = $this->db->get_where('tbl_booking',array('id'=>$id))->row_array();
		if($booked_data){	
			$check = $this->db->get_where('tbl_booking',array('doctor_id'=>$booked_data['doctor_id'],'clinic_id'=>$booked_data['clinic_id'],'date'=>$booked_data['date'],'time'=>$booked_data['time'],'payment_status'=>'1'));
			if($check->num_rows() <= '0'){
				$is_result = 0;
				$res = array('status'=>'success','is_result'=>$is_result);
			}else if($check->num_rows() == '1'){
				$is_result = 1;
				$this->db->update('tbl_booking',array('booking_status'=>'0'),array('id'=>$id));
				$res = array('status'=>'success','is_result'=>$is_result);
			}else if($check->num_rows() >= '1'){
				$is_result = 2;
				$this->db->update('tbl_booking',array('booking_status'=>'4'),array('id'=>$id));
				$res = array('status'=>'error','is_result'=>$is_result,'message'=>'
					Selected Doctor Not Available');
			}
		}else{
			$res = array('status'=>'error','message'=>'No Booking Found');
		}
		return $res;
	}
	
	
	/*function push_sent($fcm_data,$type) {
	
		$data1 = "SELECT * FROM settings WHERE id = '0' ";

		$query1 = $this->db->query($data1);

		$rs = $query1->row();
		$key = $rs->api_key;
		if($type == '1'){
		 $data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"booking_id\" : \"".$fcm_data['booking_id']."\",\"booking_date\" : \"".$fcm_data['booking_date']."\",\"doctor_id\" : \"".$fcm_data['doctor_id']."\",\"doctor_name\" : \"".$fcm_data['doctor_name']."\",\"doctor_specialization\" : \"".$fcm_data['doctor_specialization']."\",\"message\" : \"".$fcm_data['message']."\",\"time\" : \"".$fcm_data['time']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		}else if($type == '2'){
		 $data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"message\" : \"".$fcm_data['message']."\",\"read_status\" : \"".$fcm_data['read_status']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		}else if($type == '3'){
			$data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"booking_id\" : \"".$fcm_data['booking_id']."\",\"booking_date\" : \"".$fcm_data['booking_date']."\",\"doctor_id\" : \"".$fcm_data['doctor_id']."\",\"doctor_name\" : \"".$fcm_data['doctor_name']."\",\"doctor_specialization\" : \"".$fcm_data['doctor_specialization']."\",\"message\" : \"".$fcm_data['message']."\",\"time\" : \"".$fcm_data['time']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		}
		// $data = "{ \"notification\": { \"title\": \"hi\", \"text\": \"hellonewmessage\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"12\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"eaME7PRPLF8:APA91bHhjEW8Li4zE_yWmYdIUU5Z-bwwpMv_4o35z9QrsxG5EpbVkt_vfI7LIm5BZnxdXY9QX2ilL8FKKaIU1bGTIp_4jjk246YPfR_OI5i87BEuZkQr0JZIp6VEbpQEu2LeSLcktIdk\"}";
		// $data = "{ \"notification\": { \"title\": \"".$fcm_data['title']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_token."\"}";

		$ch = curl_init("https://fcm.googleapis.com/fcm/send"); 
		$header = array('Content-Type: application/json', 'Authorization: key='.$key);

		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_setopt($ch, CURLOPT_POST, 1);

		//curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"notification\": { \"title\": \"olakka title\", \"text\": \"Olakka message\" }, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"$request[id]\"}}} \"to\" : \"cAAoKqSKvgk:APA91bH-mvqwAp1JYW1oBZl_aheVDb7HOWx0YjXU6Wmmm-G_CB-60T2M6WKwsjPDMUfu47nCf1qi4a9SREiwRifAFBWszVTL8XA1y4_nb7ZiI9EmX7rpKsWogsrzqXSwKt56cd8sH5ox\"}");

		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// curl_close($ch);

		$out = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($ch);
		//print_r($response); 

		curl_close($ch);

    }*/
	
	function push_sent($fcm_data,$type) {
	
		$data1 = "SELECT * FROM settings WHERE id = '0' ";

		$query1 = $this->db->query($data1);

		$rs = $query1->row();
		$key = $rs->api_key;
		//free booking,confirmed,for user
		if($type == '1'){
		 $data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"booking_id\" : \"".$fcm_data['booking_id']."\",\"booking_date\" : \"".$fcm_data['booking_date']."\",\"doctor_id\" : \"".$fcm_data['doctor_id']."\",\"doctor_name\" : \"".$fcm_data['doctor_name']."\",\"doctor_specialization\" : \"".$fcm_data['doctor_specialization']."\",\"message\" : \"".$fcm_data['message']."\",\"time\" : \"".$fcm_data['time']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		 //free booking, confirmed, for doctor
		}else if($type == '2'){
		 $data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"message\" : \"".$fcm_data['message']."\",\"read_status\" : \"".$fcm_data['read_status']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		}/*else if($type == '3'){
			$data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"booking_id\" : \"".$fcm_data['booking_id']."\",\"booking_date\" : \"".$fcm_data['booking_date']."\",\"doctor_id\" : \"".$fcm_data['doctor_id']."\",\"doctor_name\" : \"".$fcm_data['doctor_name']."\",\"doctor_specialization\" : \"".$fcm_data['doctor_specialization']."\",\"message\" : \"".$fcm_data['message']."\",\"time\" : \"".$fcm_data['time']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";
		}*/
		
		$ch = curl_init("https://fcm.googleapis.com/fcm/send"); 
		$header = array('Content-Type: application/json', 'Authorization: key='.$key);

		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_setopt($ch, CURLOPT_POST, 1);

		//curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"notification\": { \"title\": \"olakka title\", \"text\": \"Olakka message\" }, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"$request[id]\"}}} \"to\" : \"cAAoKqSKvgk:APA91bH-mvqwAp1JYW1oBZl_aheVDb7HOWx0YjXU6Wmmm-G_CB-60T2M6WKwsjPDMUfu47nCf1qi4a9SREiwRifAFBWszVTL8XA1y4_nb7ZiI9EmX7rpKsWogsrzqXSwKt56cd8sH5ox\"}");

		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// curl_close($ch);

		$out = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($ch);
		//print_r($response); 

		curl_close($ch);

    }










	
/*............................................................................................*/	
}