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

class Patient extends CI_Controller {

function __construct() 
{
    parent::__construct();
    $this->load->model('Patient_model');
    $this->load->model('Home_model');
    $this->load->model('Doctor_model');
    $this->load->model('Search_doctor_model');    
}

/*CONTROLLER PATIENT DASHBOARD */
public function index()
{
	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 {
 	$userdata = $this->session->userdata('UserData');
 	
 		$template['page'] = "patient_dash";
		$template['page_title'] = "Dashboard";
		$template['data'] = "Patient page";
		
		$patient_data = $this->Patient_model->get_single_patient($userdata['id']);
	
		//$patient_data['pt_complement'] = decrypt_data($patient_data['pt_complement']);
		  // print_r($patient_data['pt_complement']);die();
		$completed_consultation = $this->Patient_model->get_patient_completed_consultation($userdata['id']);


		$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']); //get all confirmed and waiting list bookings
		/*$canceled_consultation = $this->Patient_model->get_patient_canceled_consultation($userdata['id']); //get all canceled bookings*/

		$policy = $this->Patient_model->get_policy();
		$promocodes = $this->Patient_model->get_all_promocodes();
		//print_r($promocodes);die();

		//print_r($completed_consultation);
		//$clinic_list = $this->Doctor_model->get_doctor_clinic_list($userdata['id']);
		//$template['clinic_list'] = $clinic_list;
		//print_r($patient_data);

		$recent  = $this->Home_model->get_recent_chat($userdata['id'],$userdata['type']);

		//FETCHING NOTIFICATION FOR DASHBOARD VIEW
		$notifications = $this->Patient_model->get_notifications($userdata['id'],1,10);
		$this->session->set_userdata('notifications',$notifications);

		
		$template['recent'] = $recent;
		$template['patient_data'] = $patient_data;
		$template['policy'] = $policy;
		$template['completed_consultation'] = $completed_consultation;
		$template['confirmed_consultation'] = $confirmed_consultation;
		$template['promocodes'] = $promocodes;
		$template['notifications'] = $notifications;
		/*$template['canceled_consultation'] = $canceled_consultation;*/
		$this->load->view('template/template', $template);
 	
 }
 else
 {
 	$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => 'Error', 'class' => 'danger'));
 	header('Location: '.base_url());
 }
}

/*FUNCTION FOR LOADING CANCELED BOOKINGS IN PATIENT DASHBOARD*/
public  function load_canceled_booking()
{
	$userdata = $this->session->userdata('UserData');
  	$canceled_consultation = $this->Patient_model->get_patient_canceled_consultation($userdata['id']); //get all canceled bookings
	$template['canceled_consultation'] = $canceled_consultation;
	$this->load->view('patient_dash_canceled_booking',$template);
}

/*FUNCTION FOR RETURNING BOOKING DATA FOR GIVEN BOOKING ID*/
public  function getBooking()
{
  $result = $this->Patient_model->get_Booking($_POST['booking_id']);

  $result['book_date'] = date('d F Y',$result['book_date']);
  $result['doc_pic'] = ''. base_url().$result['doc_pic'].'';
  //print_r($result['doc_pic']);die();
  print json_encode($result);
}

/*FUNCTION FOR CANCELING BOOKING - PATIENT DASHBOARD*/
public  function cancelBooking()
{
	//print_r($_POST);die();
	$userdata = $this->session->userdata('UserData');
  	$result = $this->Patient_model->cancel_Booking($_POST['booking_id']);
  	$nowin_server = date("Y-m-d TH:i:s");
  	/*CODE FOR WALLET INSERTION*/
  	/*---------------------------------------------------*/
  	$booking_details = $this->Doctor_model->get_booking_details($_POST['booking_id']);
  	if($booking_details['visit_type']==0 && ($booking_details['payment_type'] == '2'))
  	{
  		$wallet = $this->Doctor_model->get_wallet_for_doctor($booking_details['doc_id']);
  		//print_r($wallet);exit();
  		$earn = $booking_details['book_price'] - (($booking_details['book_price'] * $booking_details['ipok_fee'])/100);
  		$wallet['future_earn'] = $wallet['future_earn'] - $earn;
  		$wallet['total_earn'] = $wallet['total_earn'] - $earn;
  		$this->Doctor_model->update_wallet($booking_details['doc_id'],$wallet);
  	}
  	/*---------------------------------------------------*/

  	/*CODE FOR SENTING NOTIFICATION  - PATIENT NOTIFICATION*/
	/*------------------------------------------------*/
	$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doc_id']);
	$text_pat = 'Your appointment scheduled in the system, on '.date('d.m.Y',$booking_details['time_start']).' at '.date('H:i a',$booking_details['time_start']).', doctor '.$doctor_data['dr_name'] .' is Canceled!';

	$notification_pat = array('patient_id' => $booking_details['pat_id'],'type'=>3,'message'=>$text_pat,'read_status'=>0,'time'=>strtotime($nowin_server),'booking_id' => $_POST['booking_id']);
	$patient_insert_id = $this->Home_model->insert_notification_patient($notification_pat);

	$fcm_user = $this->Home_model->get_patient_fcm($booking_details['pat_id']);
	//print_r($fcm_user);
	if(!empty($fcm_user['fcm_token']))
	{
		//print_r($fcm_user['fcm_token']);die();
		$pat_push_obj['id'] = $patient_insert_id;
		$pat_push_obj['type'] = "Consultation Canceled";
		$pat_push_obj['booking_id'] = $booking_details['book_id'];
		$pat_push_obj['booking_date'] = $booking_details['book_date'];
		$pat_push_obj['doctor_id'] = $booking_details['doc_id'];
		$pat_push_obj['doctor_name'] = $doctor_data['dr_name'];
		$pat_push_obj['doctor_specialization'] = $doctor_data['dr_specialization'];
		$pat_push_obj['message'] = $text_pat;
		$pat_push_obj['time'] = strtotime($nowin_server);
		$pat_push_obj['to'] = $fcm_user['fcm_token'];
		$user_type = '1'; //patient push
		$push_status = push_sent($pat_push_obj,$user_type);
	}
	/*------------------------------------------------*/

  	$check_waiting_list = $this->Patient_model->check_waiting_list($result);
  	//print_r($check_waiting_list);die();
  	if($check_waiting_list['count']>0)
  	{
  		$this->Patient_model->change_waitinglist_to_confirmed($check_waiting_list['booking_id']);
  		$booking_details_waiting = $this->Doctor_model->get_booking_details($check_waiting_list['booking_id']);

  		/*CODE FOR SENTING WAITING LIST NOTIFICATION  - PATIENT NOTIFICATION*/
		/*------------------------------------------------*/
		$doctor_data_waiting = $this->Doctor_model->get_single_doctor($booking_details_waiting['doc_id']);
		$patient_data_waiting = $this->Patient_model->get_single_patient($booking_details_waiting['pat_id']);
		$text_pat_waiting = 'Your appointment scheduled in the system, on '.date('d.m.Y',$booking_details_waiting['time_start']).' at '.date('H:i a',$booking_details_waiting['time_start']).', doctor '.$doctor_data_waiting['dr_name'] .' is Confirmed!';

		$notification_pat_waiting = array('patient_id' => $booking_details_waiting['pat_id'],'type'=>0,'message'=>$text_pat_waiting,'read_status'=>0,'time'=>strtotime($nowin_server),'booking_id' => $check_waiting_list['booking_id']);

		$patient_insert_id = $this->Home_model->insert_notification_patient($notification_pat_waiting);

		$fcm_user = $this->Home_model->get_patient_fcm($booking_details_waiting['pat_id']);
		//print_r($fcm_user);
		if(!empty($fcm_user['fcm_token']))
		{
			//print_r($fcm_user['fcm_token']);die();
			$pat_push_obj['id'] = $patient_insert_id;
			$pat_push_obj['type'] = "Consultation Confirmation";
			$pat_push_obj['booking_id'] = $check_waiting_list['booking_id'];
			$pat_push_obj['booking_date'] = $booking_details_waiting['book_date'];
			$pat_push_obj['doctor_id'] = $booking_details_waiting['doc_id'];
			$pat_push_obj['doctor_name'] = $doctor_data_waiting['dr_name'];
			$pat_push_obj['doctor_specialization'] = $doctor_data_waiting['dr_specialization'];
			$pat_push_obj['message'] = $text_pat_waiting;
			$pat_push_obj['time'] = strtotime($nowin_server);
			$pat_push_obj['to'] = $fcm_user['fcm_token'];
			$user_type = '1'; //patient push
			$push_status = push_sent($pat_push_obj,$user_type);
		}
		/*------------------------------------------------*/

		/*CODE FOR  SENTING WAITING LIST NOTIFICATION - DOCTOR NOTIFICATION*/
		  	/*------------------------------------------------*/
			$text = 'A new appointment was scheduled in the system, on '.date('d.m.Y',$booking_details_waiting['time_start']).' at '.date('H:i a',$booking_details_waiting['time_start']).', patient '.decrypt_data($patient_data_waiting['pt_name']);

			$notification = array('doctor_id' => $booking_details_waiting['doc_id'],'type'=>2,'message'=>$text,'read_status'=>0,'time'=>strtotime($nowin_server) );

			$doctor_insert_id = $this->Home_model->insert_notification_doctor($notification);

			$fcm_doctor = $this->Home_model->get_doctor_fcm($booking_details_waiting['doc_id']);
			if(!empty($fcm_doctor['fcm_token']))
			{
				$doc_push_obj['id'] = $doctor_insert_id;
				$doc_push_obj['type'] = "New Consultation";
				$doc_push_obj['message'] =$text;
				$doc_push_obj['read_status'] = false;
				$doc_push_obj['to'] = $fcm_doctor['fcm_token'];
				$user_type = '2';
				$push_status = push_sent($doc_push_obj,$user_type);
			}
			/*------------------------------------------------*/

  	}
  	$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
	$template['confirmed_consultation'] = $confirmed_consultation;
	$this->load->view('patient_dash_scheduled_booking',$template);
}

/*FUNCTION FOR CHECKING CANCELLATION POLICY - PATIENT DASHBOARD*/
public  function check_cancelBooking()
{
	//print_r($_POST);die();
	$userdata = $this->session->userdata('UserData');
	$result = $this->Patient_model->get_Booking($_POST['booking_id']);
	$policy = $this->Patient_model->get_all_policy();
	
	$nowin_server = date("Y-m-d TH:i:s");
	if($_POST['UTCoffset']['sign']=='+')
		{
			$nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('+'.$_POST['UTCoffset']['hour'].' hour +'.$_POST['UTCoffset']['minute'].' minutes',strtotime($nowin_server)));
		}
		elseif ($_POST['UTCoffset']['sign']=='-') 
		{
			$nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('-'.$_POST['UTCoffset']['hour'].' hour -'.$_POST['UTCoffset']['minute'].' minutes',strtotime($nowin_server)));
		}

	$day = date('Y-m-d H:i:s',$result['time_start']);
	$newdate = date("Y-m-d H:i:s",strtotime($day." -".$policy['duration']." hours"));

	if(strtotime($nowin_server_addoffset)<strtotime($newdate))
	{
		$res = array('status' => 'success', 'msg'=>'booking can canceled');
	}
	else
	{
		$res = array('status' => 'error', 'msg'=>'booking cannot be canceled');
	}

	print json_encode($res);
  	/*$result = $this->Patient_model->cancel_Booking($_POST['booking_id']);
  	$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
	$template['confirmed_consultation'] = $confirmed_consultation;
	$this->load->view('patient_dash_scheduled_booking',$template);*/
}

/*FUNCTION FOR RESCHEDULING BOOKING DATE - PATIENT DASHBOARD*/
public function reScheduleConsultation()
{
	$result = $this->Patient_model->get_Booking($_POST['booking_id']);
	$result['book_date'] = date('d F Y',$result['book_date']);
	$result['doc_pic'] = ''. base_url().$result['doc_pic'].'';
	print json_encode($result);
		
}

/*FUNCTION FOR UPDATING BOOKING DATA ON RESCHEDULING BOOKING DATE - PATIENT DASHBOARD*/
public function updateBooking()
{
	$userdata = $this->session->userdata('UserData');
	//print_r($_POST);
	$this->Patient_model->update_Booking($_POST);
	$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
	$template['confirmed_consultation'] = $confirmed_consultation;
	$this->load->view('patient_dash_scheduled_booking',$template);
}

/*CONTROLLER EDIT PROFILE*/
public function editProfile()
{
	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 	{
 		$userdata = $this->session->userdata('UserData');
 		$template['page'] = "patient_editprofile";
		$template['page_title'] = "Edit Profile";
		$template['data'] = "Patient page";
		$patient_data = $this->Patient_model->get_single_patient($userdata['id']);		//unset($patient_data['pt_gender']);
		$template['patient_data'] = $patient_data;
		$this->load->view('template/template', $template);
	}
	else
	{
		$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => 'Error', 'class' => 'danger'));
		header('Location: '.base_url());
	}
}

/*FUNCTION FOR UPDATING PATIENT PROFILE IN DB - EDIT PROFILE*/
public function saveProfile()
{

	$userdata = $this->session->userdata('UserData');
	$_POST['dob'] = strtotime($_POST['dob']);
	if(isset($_POST) and !empty($_POST))
	{
		$update_data = $_POST;
		if(isset($_FILES['profile_photo']['name']) and !empty($_FILES['profile_photo']['name']))
		{
			
			$fileName = $userdata['id'].'_'.$_FILES['profile_photo']['name'];
			$config = set_upload_options('./assets/uploads/profilepic/patient/'); 
			$config['file_name'] = $fileName;
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload('profile_photo')) 
			{
				//print_r("expression");die();
				$error = array('error' => $this->upload->display_errors('', '')); 
				$this->session->set_flashdata('message', array('message' => load_language('image_upload_error',true), 'title' => 'Error', 'class' => 'danger'));
				//header('Location: '.base_url().'Doctor/editProfile');
				redirect(base_url().'Patient/editProfile');
			}	
			else 
			{ 
				$imagedata = $this->upload->data(); 
				$fullfilepath='assets/uploads/profilepic/patient/'.$imagedata['file_name'];
				//$picdata = array('profile_pic'=>$fullfilepath);
				$update_data['profile_photo'] = $fullfilepath;
			}
		}
		else
		{
			unset($update_data['profile_photo']);
		}
		
		

		 $update_data = array(
							
							"name"=> encrypt_data($update_data['name']),
							"username"=> $update_data['username'],
							"rg" => encrypt_data($update_data['rg']),
							"dob" => $update_data['dob'],
							"gender" => encrypt_data($update_data['gender']),
							"weight" => encrypt_data($update_data['weight']),
							"height" => encrypt_data($update_data['height']), 
							"blood_group" => encrypt_data($update_data['blood_group']),
							"zip_code" => encrypt_data($update_data['zip_code']),
							"street_address" => encrypt_data($update_data['street_address']),
							"locality" => encrypt_data($update_data['locality']),
							"number" => encrypt_data($update_data['number']),
							"landmark" =>encrypt_data($update_data['landmark']),

							);
		

		$update = $this->Patient_model->update_profile($userdata['id'],$update_data);
		if($update['status']=='success')
		{
			$patient_data = $this->Patient_model->get_single_patient_row($userdata['id']);
			//print_r($patient_data);

			$new_userdata = array(
							"type"=>"PATIENT",
							"id"=> $patient_data['id'],
							"name"=> decrypt_data($patient_data['name']),
							"username"=> $patient_data['username'],
							"email"=> $patient_data['email'],
							"password" => $patient_data['password'],
							"cpf" => $patient_data['cpf'],
							"rg" => decrypt_data($patient_data['rg']),
							"dob" => $patient_data['dob'],
							"gender" => decrypt_data($patient_data['gender']),
							"weight" => decrypt_data($patient_data['weight']),
							"height" => decrypt_data($patient_data['height']), 
							"blood_group" => decrypt_data($patient_data['blood_group']),
							"zip_code" => decrypt_data($patient_data['zip_code']),
							"street_address" => decrypt_data($patient_data['street_address']),
							"locality" => decrypt_data($patient_data['locality']),
							"number" => decrypt_data($patient_data['number']),
							"landmark" =>decrypt_data($patient_data['landmark']),
							"profile_photo" => $patient_data['profile_photo'],
							"bystander_name" => $patient_data['bystander_name'],
	                        "bystander_relation" => $patient_data['bystander_relation'],
	                        "bystander_cpf" => $patient_data['bystander_cpf'],
	                        "bystander_dob" => $patient_data['bystander_dob'],
	                        "bystander_profile_photo" => $patient_data['bystander_profile_photo'],

							);

				$this->session->set_userdata('UserData',$new_userdata);
				header('Location: '.base_url().'Patient');

		}	
		else
		{
			$this->session->set_flashdata('message', array('message' => load_language('updation_failed',true), 'title' => 'Error', 'class' => 'danger'));
			redirect(base_url().'Patient/editProfile');		

		}

	}

}

/*FUNCTION FOR CHECKING EXISTING USERNAME - EDIT PROFILE*/
public function check_username_edit()
{
	$userdata = $this->session->userdata('UserData');
	$data = $_POST;
	if($userdata['username']==$data['username'])
	{
		print json_encode(array('message'=>'success'));
	}
	else
	{
		$check_result = $this->Home_model->usernameExist($data);
		//print_r($check_result);die();
		print json_encode($check_result);
	}
	
}

/*CONTROLLER ADD DEPENDENT*/
public function addDependent()
{
	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 	{
 		$userdata = $this->session->userdata('UserData');
 		$template['page'] = "patient_add_dependent";
		$template['page_title'] = "Add Dependent";
		$patient_data = $this->Patient_model->get_single_patient($userdata['id']);
		$dependent_data = $this->Patient_model->get_all_dependent_for_patient($userdata['id']);

		/*foreach ($dependent_data as $key => $value) {
			$dateOfBirth = date("Y-m-d",$value['dob']);
			$today = date("Y-m-d");
			$diff = date_diff(date_create($dateOfBirth), date_create($today));
			echo 'Age is '.$diff->format('%y');
		}*/
		$template['patient_data'] = $patient_data;
		$template['dependent_data'] = $dependent_data;
		$this->load->view('template/template', $template);
	}
	else
	{
		$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => load_language('error',true), 'class' => 'danger'));
 		header('Location: '.base_url());
	}
}

/*FUNCTION FOR INSERTING DEPENDENT DATA INTO DB - ADD DEPENDENT*/
public function saveDependent()
{
	$userdata = $this->session->userdata('UserData');
	if(isset($_POST) and !empty($_POST))
		{
			$data = $_POST;
			$data['dob'] = strtotime($_POST['dob']);
			$data['patient_id'] = $userdata['id'];
			//print_r($data);die();
			$result = $this->Patient_model->register_dependent($data);
			if($result['status'] == 'success')
			{	
				$fileName = $result['data']['id'].'_'.$_FILES['image']['name'];
				$config = set_upload_options('./assets/uploads/profilepic/patient_dependent/'); 
				$config['file_name'] = $fileName;
				$this->load->library('upload', $config);
				if ( ! $this->upload->do_upload('image')) 
				{
					$error = array('error' => $this->upload->display_errors('', '')); 
					$res = array(
					"status"=> "error",
					"error"=> "Upload Error",
					"message"=> load_language('image_upload_error',true) /*.$error['error']*/
					);	
					$this->Patient_model->delete_registration_dependent($result['data']['id']);
					$this->session->set_flashdata('message', array('message' => load_language('image_upload_error',true), 'title' => 'Error', 'class' => 'danger'));
					redirect(base_url().'Patient/addDependent');
				}	
				else 
				{ 

					$imagedata = $this->upload->data(); 
					$fullfilepath='assets/uploads/profilepic/patient_dependent/'.$imagedata['file_name'];
					$picdata = array('image'=>$fullfilepath);
					$this->Patient_model->updatePic_dependent($picdata,$result['data']['id']);

					$this->session->set_flashdata('message', array('message' =>load_language('dependent_add_success',true), 'title' => 'Success', 'class' => 'success'));
					header('Location: '.base_url().'Patient/addDependent');

				}
			}
			else
			{
				$this->session->set_flashdata('message', array('message' =>load_language('dependent_add_error',true), 'title' => 'Error', 'class' => 'danger'));
				redirect(base_url().'Patient/addDependent');	
			}

	 	
			
		}
}

/*CONTROLLER EDIT DEPENDENT DATA - DEPENDENT*/
public function editDependent()
{
	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 	{
 		$userdata = $this->session->userdata('UserData');
		$template['page_title'] = "Edit Dependent";
		$patient_data = $this->Patient_model->get_single_patient($userdata['id']);
		$dependent_data = $this->Patient_model->get_all_dependent_for_patient($userdata['id']);
		$template['patient_data'] = $patient_data;
		$template['dependent_data'] = $dependent_data;
		if(!empty($dependent_data))
		{
			if($this->uri->segment(3))
			{
				$dependent_id = $this->uri->segment(3);
				$dependent_detail = $this->Patient_model->get_single_dependent($dependent_id);
				$template['page'] = "patient_edit_dependent";
				$template['dependent_detail'] = $dependent_detail;
				$this->load->view('template/template', $template);
			}
			else
			{
				$template['page'] = "patient_view_dependent";
				$this->load->view('template/template', $template);
			}
		}
		else
		{
			$this->session->set_flashdata('message', array('message' => load_language('no_dependent_found',true), 'title' => 'Warning', 'class' => 'info'));
			header('Location: '.base_url().'Patient/addDependent');
		}
	}
	else
	{
		$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => 'Error', 'class' => 'danger'));
		header('Location: '.base_url());
	}
}

/*FUNCTION FOR UPDATING DEPENDENT DATA TO DB - DEPENDENT*/
public function updateDependent()
{	
	$userdata = $this->session->userdata('UserData');
	if(isset($_POST) and !empty($_POST))
	{
		$data = $_POST;
		$data['dob'] = strtotime($_POST['dob']);
		//print_r($_FILES['image']);die();
		if(isset($_FILES['image']['name']) and !empty($_FILES['image']['name']))
		{
			$fileName = $data['dependent_id'].'_'.$_FILES['image']['name'];
			$config = set_upload_options('./assets/uploads/profilepic/patient_dependent/'); 
			$config['file_name'] = $fileName;
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload('image')) 
			{
				//print_r("expression");die();
				$error = array('error' => $this->upload->display_errors('', '')); 
				$this->session->set_flashdata('message', array('message' => 'Profile Photo Cant be Uploaded, Try Again', 'title' => 'Error', 'class' => 'danger'));
				//header('Location: '.base_url().'Doctor/editProfile');
				unset($data['image']);
				redirect(base_url().'Patient/editDependent/'.$data['dependent_id']);
			}	
			else 
			{ 
				$imagedata = $this->upload->data(); 
				$fullfilepath='assets/uploads/profilepic/patient_dependent/'.$imagedata['file_name'];
				//$picdata = array('profile_pic'=>$fullfilepath);
				$data['image'] = $fullfilepath;
			}
		}
		else
		{
			unset($data['image']);
		}

		$update = $this->Patient_model->update_dependent_profile($data['dependent_id'],$data);
		if($update['status']=='success')
		{
			$dependent_data = $this->Patient_model->get_all_dependent_for_patient($userdata['id']);
			if(!empty($dependent_data)){$this->session->set_userdata('DependentData',$dependent_data);}
			redirect(base_url().'Patient/editDependent');
		}
		else
		{
			$error = array('error' => $this->upload->display_errors('', '')); 
			$this->session->set_flashdata('message', array('message' => load_language('dependent_update_failed',true), 'title' => 'Error', 'class' => 'danger'));
			//header('Location: '.base_url().'Doctor/editProfile');
			redirect(base_url().'Patient/editDependent'.$data['dependent_id']);
		}


	}
}

/*FUNCTION FOR CHECKING CREDENTIALS OF CURRENTLY LOGEDIN PATIENT - DELETE ACCOUNT*/
public function check_current_user_credential()
{

	$userdata = $this->session->userdata('UserData');
	if($_POST['username']==$userdata['username'])
	{
		$db_pass = $this->Patient_model->get_patient_password($userdata['id']);
		$enterd_pass = md5($_POST['password']);
		if($db_pass['password']==$enterd_pass)
		{
			$this->sentConfirmationcode($userdata);
			$res = array('status' =>'success' , 'msg'=>load_language('valid_credentials',true));
		}
		else
		{
			$res = array('status' =>'error' , 'msg'=>load_language('invalid_credentials',true));
		}
		
	}
	else
	{
		$res = array('status' =>'error' , 'msg'=>load_language('invalid_credentials',true));
	}
	print json_encode($res);	
}

/*FUNCTION FOR CHECKING CONFIRMATION CODE OF CURRENTLY LOGEDIN PATIENT - DELETE ACCOUNT*/
public function check_current_user_confirmationcode()
{
	$userdata = $this->session->userdata('UserData');
	$db_confirmation_code = $this->Patient_model->get_patient_confirmation_code($userdata['id']);
	if($db_confirmation_code['confirmation_code']==strtoupper($_POST['confirmation_code']))
	{
		$res = array('status' => 'success','msg'=>load_language('valid_code',true) );
		$this->Patient_model->disable_patient_account($userdata['id']);
	}
	else
	{
		$res = array('status' => 'error','msg'=>'Invalid Code' );
	}
	print json_encode($res);
}

/*FUNCTION FOR VIEWING ALL DOCTORS APPLICABLE FOR GIVEN PROMOCODE - PATIENT DASH*/
public function promocode()
{
	if($this->uri->segment(3))
	{
		$promo_id = $this->uri->segment(3);
		//print_r($promo_id);
		$promo_data = $this->Patient_model->get_promocode_details($promo_id);
		//print_r($promo_data);
		$doctor_applicable = explode(",",$promo_data['doctor_id']);
	/*	$ids = join("','",$doctor_applicable);   
		print_r($ids);die();*/
		$all_doctors = $this->Search_doctor_model->get_doctors_for_promocode($promo_id,$doctor_applicable);
		//print_r($all_doctors);die();
		$template['doctors_list'] = $all_doctors;
		$template['page'] = "patient_doctors_for_promocodes";
		$template['page_title'] = "Promocode";

		$this->load->view('template/template', $template);
	}
	else
	{
		redirect(base_url().'Patient');
	}


}

/*FUNCTION FOR SENTING CONFRIMATION CODE FOR ACCOUNT DELETION - PATIENT AND DOCTOR*/
	public function sentConfirmationcode($user)
	{
		$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    $result = '';
	    for ($i = 0; $i < 8; $i++)
	        $result .= $characters[mt_rand(0, 35)];
		$msg = "Hi ".$user['name'].",<br><br>Your Confirmation Code for Ipok Account Deactivation is ".$result.".

				<br><br>Ipok Team";
	
		send_mail($msg,$user['email'],'Account Deactivation');
		$this->Patient_model->set_confirmation_code($user,$result);
	}

/*FUNCTION FOR SENTING MAIL */
/*	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);
		$this->email->send();
  	}
*/
/* FUNCTION FOR VIEWING MEDICAL RECORD FOR GIVEN BOOKING ID - COMPLETED CONSULTATION,PATIENT DASHBOARD*/

public function record()
{
	
	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="PATIENT")&&(!empty($this->uri->segment(3))))
 	{
 		$booking_id = $this->uri->segment(3);
 		$booking_details = $this->Doctor_model->get_booking_details($booking_id);
 		$record_data = $this->Doctor_model->get_medical_record_for_booking($booking_id);
 		if(!empty($record_data))
 		{
 			$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doc_id']);
	 		$patient_data = $this->Patient_model->get_single_patient($booking_details['pat_id']);

	 		//echo "<pre>";print_r($record_data);echo "<br>";
	 		$record_data['diseases'] = json_decode(decrypt_data($record_data['diseases']));
	 		$record_data['prescribtions'] = json_decode(decrypt_data($record_data['prescribtions']));
	 		$record_data['exams'] = json_decode(decrypt_data($record_data['exams']));
	 		$record_data['budget'] = json_decode(decrypt_data($record_data['budget']));
	 		$record_data['letters'] = json_decode(decrypt_data($record_data['letters']));


	 		//echo "<pre>";print_r($record_data);die();
			$template['page'] = "patient_dash_service_summary";
			$template['page_title'] = "Record";
			$template['record_data'] = $record_data;
			$template['booking_details'] = $booking_details;
			$template['doctor_data'] = $doctor_data;
			$template['patient_data'] = $patient_data;
			$this->load->view('template/template', $template);
		}
		else
		{
			header('Location: '.base_url().'Home/error/url');
		}
 	}
 		
	else
	{
		$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => load_language('error',true), 'class' => 'danger'));
 		header('Location: '.base_url());
	}
}

 /*FUNCTION FOR PATIENT CHAT*/
 public function chat()
 {
 	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 	{
 		$userdata = $this->session->userdata('UserData');
 		$template['page'] = 'chat';
 		$template['page_title'] = "Chat";
		$this->load->view('template/template', $template);
 	}
 	else
 	{
 		redirect(base_url());
 	}
 }

 public function notification()
 {
 		if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="PATIENT")
 	{
 		$userdata = $this->session->userdata('UserData');

 		$page = 1;
 		$notifications = $this->Patient_model->get_notifications($userdata['id'],$page);
 		//echo "<pre>";
 		//print_r($notifications);die();
 		$notifications_total_count = $this->Patient_model->get_notifications_total_count($userdata['id']);
 		//print_r($notifications_total_count);die();
 		$template['page'] = 'patient_notifications_page';
 		$template['page_title'] = "Notification";
 		$template['notifications'] = $notifications;
 		$template['notifications_total_count'] = $notifications_total_count[0];
 		$template['notifications_page_no'] = $page;

		$this->load->view('template/template', $template);

 	}
 }

 public function notification_ajax()
{
	$userdata = $this->session->userdata('UserData');
	$page = 1;
	if(!empty($_POST))
	{$page = $_POST['page']+1;}
	$notifications = $this->Patient_model->get_notifications($userdata['id'],$page);
	$notifications_total_count = $this->Patient_model->get_notifications_total_count($userdata['id']);
	//print_r($notifications);die();
	$template['notifications'] = $notifications;
	$template['notifications_total_count'] = $notifications_total_count[0];
	$template['notifications_page_no'] = $page;

	$this->load->view('patient_notifications_list', $template);
}


	
	
}
