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

class Doctor extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */

function __construct() 
{
    parent::__construct();
    $this->load->model('Doctor_model');
    $this->load->model('Home_model');
    $this->load->model('Patient_model');
    $this->load->model('Search_doctor_model');
    global $default_date ;
    $this->default_date = '01/01/1970';

    
 
    //print_r(date_default_timezone_get());die();
}

/*CONTROLLER - DOCTOR DASHBOARD*/
public function index()
{

	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR"))
 {
 		
 		$userdata = $this->session->userdata('UserData');
 		$template['page'] = "doctor_dash";
		$template['page_title'] = "Dashboard";
		$template['data'] = "Doctor page";
		
		$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
		$clinic_list = $this->Doctor_model->get_doctor_clinic_list($userdata['id']);
		$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],'null');
		foreach ($day_appointment as $key => $value) 
		{
			$times = explode('-', $value['booking_time']);
			$day_appointment[$key]['time_start'] = $times[0];
			$day_appointment[$key]['time_end'] = $times[1];
		}

		/*CODE FOR FETCHING APPOINTMENTS COUNT(DAY/WEEK/MONTH/YEAR)*/
		$attendence = array();

		//DAY ATTENDENCE
		$attendence = $this->Doctor_model->get_doctor_num_attendence_fordate($userdata['id'],date('y-m-d'));

		//WEEK ATTENDENCE
		$attendence_week = 0;
		for ($i=0; $i < 7; $i++) 
		{ 
	      $day = date('D',strtotime('+'.$i.'day'));
		  $week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($userdata['id'],date('y-m-d',strtotime('+'.$i.'day'))); 
		  foreach ($week_appointments[$i] as $key => $value) 
		  {
		  	if(!empty($value['count']))
		  	{
		  		$attendence_week = $attendence_week + $value['count'];
		  	}
		  }
  		}
  		$attendence['attendence_week'] = $attendence_week;

  		//MONTH ATTENDENCE
  		$attendence_month = 0;
		$month_appointment = $this->Doctor_model->get_doctor_appointments_month($userdata['id']);
	  	foreach ($month_appointment as $key => $value) {
	  		if(!empty($value['count']))
		  	{
	  			$attendence_month = $attendence_month + $value['count'];
	  		}
	  	}
  		$attendence['attendence_month'] = $attendence_month;

		//YEAR ATTENDENCE
		$attendence_year = $this->Doctor_model->get_doctor_appointments_year($userdata['id']);
		$attendence['attendence_year'] = $attendence_year['count'];

		
		//CODE FOR SUMMARY IN NUMBERS
		$no_of_attendance = $this->Doctor_model->get_doctor_num_attendance($userdata['id']);
		$no_of_billed = $this->Doctor_model->get_doctor_num_billed($userdata['id']);
		$no_of_patients = $this->Doctor_model->get_doctor_num_patients($userdata['id']);
		$no_of_profileview = $this->Doctor_model->get_doctor_num_profileview($userdata['id']);

		if(empty($no_of_billed['amount']))
		{
			$no_of_billed['amount'] = 0;
		}

		$dash_view = array('no_of_attendance' => $no_of_attendance['count'],'no_of_billed'=>$no_of_billed['amount'],'no_of_patients' => $no_of_patients['count'],'no_of_profileview'=>$no_of_profileview['count']);

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

		$recent  = $this->Home_model->get_recent_chat($userdata['id'],$userdata['type']);
		//$recent = json_decode($recent);
	
		//PASSING VALUES TO VIEW
		$template['recent'] = $recent;
		$template['doctor_data'] = $doctor_data;
		$template['clinic_list'] = $clinic_list;
		$template['day_appointment'] = $day_appointment;
		$template['dash_view'] = $dash_view;
		$template['attendence'] = $attendence;
		$template['attendence'] = $attendence;
		$template['notifications'] = $notifications;
		$this->load->view('template/template', $template);

 }
 elseif($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="COLLABORATOR"))
 {
 	header('Location: '.base_url().'Doctor/collaborator');
 }
 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());
 }
}

/*GET DOCTOR APPOINMENTS FOR CURRENT MONTH - DOCTOR DASH*/
public function doctor_appointments_month()
{
	$userdata = $this->session->userdata('UserData');
	$month_appointment = $this->Doctor_model->get_doctor_appointments_month($userdata['id']);
  	$template['month_appointment'] = $month_appointment;
	$this->load->view('doctor_dash_appointments_month',$template); 
}


/*GET DOCTOR APPOINMENTS FOR CURRENT WEEK - DOCTOR DASH*/
public function doctor_appointments_week()
{
	//$day_appointments = array();
	$userdata = $this->session->userdata('UserData');
	for ($i=0; $i < 7; $i++) 
	{ 
      $day = date('D',strtotime('+'.$i.'day'));
      $dayno = date('d',strtotime('+'.$i.'day'));
	  $week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($userdata['id'],date('y-m-d',strtotime('+'.$i.'day')));      
  	}
  	$template['week_appointments'] = $week_appointments;
  	//print_r($week_appointments);die();
	$this->load->view('doctor_dash_appointments_week',$template); 
}

/*FUNCTION FOR CANCELING BOOKING - DOCTOR DASHBOARD*/
/*DESC : CHANGE BOOKING STATUS TO CANCEL FROM CONFIRMED AND NOTIFIY THE USER WITH CANCELATION.ALSO NOTIFY ANY USER IN WAITING LIST */
public  function cancelBooking()
{
	$nowin_server = date("Y-m-d TH:i:s");
	$userdata = $this->session->userdata('UserData');
  	$result = $this->Patient_model->cancel_Booking($_POST['booking_id']);
  	$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
  	/*CODE FOR WALLET INSERTION*/
  	/*---------------------------------------------------*/
  	$booking_details = $this->Doctor_model->get_booking_details($_POST['booking_id']);
  	if($booking_details['visit_type']==0)
  	{
  		//print_r($booking_details);die();
  		//$ipok_settings = $this->Home_model->get_ipok_settings();
  		$wallet = $this->Doctor_model->get_wallet_for_doctor($userdata['id']);
  		$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($userdata['id'],$wallet);
  	}
  	
  	/*---------------------------------------------------*/

  	/*CODE FOR SENTING NOTIFICATION  - PATIENT NOTIFICATION*/
	/*------------------------------------------------*/
	
	$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 '.$userdata['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'] = $_POST['booking_id'];
		$pat_push_obj['booking_date'] = $booking_details['book_date'];
		$pat_push_obj['doctor_id'] = $booking_details['doc_id'];
		$pat_push_obj['doctor_name'] = $userdata['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);
	}

	/*------------------------------------------------*/

  	//die();
  /*	$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']);
  	}
*/
 	$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],$_POST['selectedDate']);
		foreach ($day_appointment as $key => $value) 
		{
			$times = explode('-', $value['booking_time']);
			$day_appointment[$key]['time_start'] = $times[0];
			$day_appointment[$key]['time_end'] = $times[1];
		}

	$template['day_appointment'] = $day_appointment;
	$this->load->view('doctor_dash_appointments_day',$template); 
}


/*FUNCTION FOR RETURNING DOCTOR SCHEDULES FOR PARTICULAR CLINIC - DOCTOR DASH*/
public function getScheduleforClinic()
{
	if($this->session->userdata('UserData'))
 	{	
 		$userdata = $this->session->userdata('UserData');
     	if($userdata['type']=="DOCTOR")
     	{
     		$result = $this->Doctor_model->Schedulelist($_POST['clinic_id'],$userdata['id']);
     		//print_r($result);die();
     		if(!empty($result))
     		{
     			$res = array('status' => 'success', 'pri_schedule'=>$result['pri_schedule'],'sec_schedule'=>$result['sec_schedule'],'active_schedule'=>$result['active_schedule']);
     		}
     		else
     		{
     			$res = array('status' => 'fail', 'pri_schedule'=>$result['pri_schedule'],'sec_schedule'=>$result['sec_schedule'],'active_schedule'=>$result['active_schedule']);
     		}
     		
     		print json_encode($res);
     	}

    }
}

/*FUNCTION FOR ADDING DOCTOR SCHEDULE TO CONSULTATION TABLE - DOCTOR DASH*/
public function addSchedule()
{
	if($this->session->userdata('UserData'))
 	{
 		$userdata = $this->session->userdata('UserData');
     	if($userdata['type']=="DOCTOR")
     	{
     		// print_r($this->default_date);
     		//print_r($_POST);//die();
     		$insert_array = array();
     		$insert_array_sec = array();
			$not_available_day = array();
			$flag = 0;
			$request = $_POST;
			$flag_day_equal = 0;
			//print_r($request);echo"<br><br>";
			$consult_duration = $this->Doctor_model->check_consult_duration($userdata['id']); 
			//print_r($consult_duration['consultation_duration']);exit();
			$result = $this->Doctor_model->checkDoctorExist($this->session->userdata('UserData')['id']);
			//print_r($result);die();
			if(!empty($request))
			{
				if($request['active_schedule_type']=='0')
				{
					$schedule_day = $request['dct_sch_day'];
				}
				else
				{
					$schedule_day = $request['sec_dct_sch_day'];
				}

				if(!empty($result)){
				
					foreach ($schedule_day as $req_day_key => $req_day_value) 
					{
						foreach ($result as $db_key => $db_value) 
						{
							if($db_value['active_schedule']=='0')
							{
								$decode_date = json_decode($db_value['date'],true);
							}
							else
							{
								$decode_date = json_decode($db_value['date_secondary'],true);	
							}

							if(!empty($decode_date))
							{
								foreach ($decode_date as $time_key => $time_value) 
								{
									if($req_day_value == $time_value['day'] && $db_value['clinic_id'] != $request['dct_sch_clinic'])
									{

										if($request['active_schedule_type']=='0')
										{
											$startTime = 'dct_sch_'.$req_day_value.'_start';
											$endTime = 'dct_sch_'.$req_day_value.'_end';
										}
										else
										{
											$startTime = 'sec_dct_sch_'.$req_day_value.'_start';
											$endTime = 'sec_dct_sch_'.$req_day_value.'_end';
										}
										
										if((strtotime($this->default_date.$time_value['time']['start']) <= strtotime($this->default_date.$request[$startTime ]) && strtotime($this->default_date.$request[$startTime ]) <= strtotime($this->default_date.$time_value['time']['end'])) || (strtotime($this->default_date.$time_value['time']['start']) <= strtotime($this->default_date.$request[$endTime]) && strtotime($this->default_date.$request[$endTime ]) <= strtotime($this->default_date.$time_value['time']['end'])) || (strtotime($this->default_date.$request[$startTime ]) <= strtotime($this->default_date.$time_value['time']['start']) && strtotime($this->default_date.$time_value['time']['start']) <= strtotime($this->default_date.$request[$endTime])) || (strtotime($this->default_date.$request[$startTime ]) <= strtotime($this->default_date.$time_value['time']['end']) && strtotime($this->default_date.$time_value['time']['end']) <= strtotime($this->default_date.$request[$endTime])))
										{
											$flag_day_equal = 1;
										}

									}
								}
							}
						}

					}

					if($flag_day_equal == 0)
					{
						$res = $this->set_doctor_schedule_data($request,$consult_duration);

					}
					else
					{
						$res  = array('status' => 'fail','msg' => load_language('schedule_add_failed',true) );
					}
				}else{
					$this->Doctor_model->assignDoctors_default($this->session->userdata('UserData')['id'],$request['dct_sch_clinic']);
					$res = $this->set_doctor_schedule_data($request,$consult_duration);

				}

			}
			else
			{
				$res  = array('status' => 'fail','msg' => load_language('schedule_add_mismatch',true));
			}
			print json_encode($res);
			
     	}
 	}

}

function set_doctor_schedule_data($request,$consult_duration){
	$insert_array = array();
    $insert_array_sec = array();
	//FOREACH FOR ADD PRIMARY SCHEDULE TO INSERT ARRAY
	foreach ($request['dct_sch_day'] as $key_elseDay => $value_elseDay) 
		{							
			$start = 'dct_sch_'.$value_elseDay.'_start';
			$end = 'dct_sch_'.$value_elseDay.'_end';
			$intr_start = 'dct_intr_'.$value_elseDay.'_start';
			$intr_end = 'dct_intr_'.$value_elseDay.'_end';


			if((isset($request[$intr_start]) and !empty($request[$intr_start])) || (isset($request[$intr_end]) and !empty($request[$intr_end])))
			{
				$res = array('day'=>$value_elseDay,
							'time'=>array('start'=>$request[$start],
								'end'=>$request[$end],
								'interval'=>$consult_duration['consultation_duration'],
								'break_from'=>$request[$intr_start],
								'break_to'=>$request[$intr_end]));
				array_push($insert_array, $res);
			}
			else
			{
				$res = array('day'=>$value_elseDay,
							'time'=>array('start'=>$request[$start],
								'end'=>$request[$end],
								'interval'=>$consult_duration['consultation_duration'],
								'break_from'=>'null',
								'break_to'=>'null'));
				array_push($insert_array, $res);
			}
			
		}

	//FOREACH FOR ADD SECONDARY SCHEDULE TO INSERT ARRAY
	foreach ($request['sec_dct_sch_day'] as $key_elseDay => $value_elseDay) 
		{	
			$start_sec = 'sec_dct_sch_'.$value_elseDay.'_start';
			$end_sec = 'sec_dct_sch_'.$value_elseDay.'_end';
			$intr_start_sec = 'sec_dct_intr_'.$value_elseDay.'_start';
			$intr_end_sec = 'sec_dct_intr_'.$value_elseDay.'_end';

			if((isset($request[$intr_start_sec]) and !empty($request[$intr_start_sec])) || (isset($request[$intr_end_sec]) and !empty($request[$intr_end_sec])))
			{
				$res_sec = array('day'=>$value_elseDay,
							'time'=>array('start'=>$request[$start_sec],
								'end'=>$request[$end_sec],
								'interval'=>$consult_duration['consultation_duration'],
								'break_from'=>$request[$intr_start_sec],
								'break_to'=>$request[$intr_end_sec]));
				array_push($insert_array_sec, $res_sec);
			}
			else
			{
				$res_sec = array('day'=>$value_elseDay,
							'time'=>array('start'=>$request[$start_sec],
								'end'=>$request[$end_sec],
								'interval'=>$consult_duration['consultation_duration'],
								'break_from'=>'null',
								'break_to'=>'null'));
				array_push($insert_array_sec, $res_sec);
			}
		}
			
		//print_r($insert_array);
		//print_r($insert_array_sec);die();

		//ADDING SCHEDULE TO DB
		$this->Doctor_model->set_new_consultation($insert_array,$insert_array_sec,$request['active_schedule_type'],$request['dct_sch_clinic'],$this->session->userdata('UserData')['id']);
		$res  = array('status' => 'success','msg' =>  load_language('schedule_add_success',true) );
		return $res;
}

/*FUNCTION FOR CHECKING IF CONSULTATION DURATION IS SET WHILE ENTERING DOCTOR SCHEDULE - DOCTOR DASH*/
public function check_consultduration()
{
	$userdata = $this->session->userdata('UserData');
	$check_duration = $this->Doctor_model->check_consult_duration($userdata['id']);
	$arrayName = array('message' => 'success','data' =>$check_duration['consultation_duration'] );
	print json_encode($arrayName);
}

/*FUNCTION FOR ADDING LEAVE FOR DOCTOR - DOCTOR DASH*/
public function addVacation()
{
	if($this->session->userdata('UserData'))
 	{	
 		$userdata = $this->session->userdata('UserData');
     	if($userdata['type']=="DOCTOR")
     	{
     		$request = array('doctor_id' => $userdata['id'],'clinic_id' => $_POST['doc-leave-clinic'],'start_date' => strtotime($_POST['dctr-leave-start']),'end_date' => strtotime($_POST['dctr-leave-end']));
     		//print_r($request);
     		$result = $this->Doctor_model->insertVacation($request);
     		if($result)
     		{
     			$res = array('status' => 'success');
     		}
     		else
     		{
     			$res = array('status' => 'fail' );
     		}
     		print json_encode($res);
     	}
    }
}

/*FUNCTION FOR FETCHING APPOINMENTS FOR GIVEN DAY - DOCTOR DASH*/
public function get_myappointments_day()
{
	//print_r($_POST['appointment_day']);
	$userdata = $this->session->userdata('UserData');
	$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],$_POST['appointment_day']);
		foreach ($day_appointment as $key => $value) 
		{
			$times = explode('-', $value['booking_time']);
			$day_appointment[$key]['time_start'] = $times[0];
			$day_appointment[$key]['time_end'] = $times[1];
		}
	//print_r($day_appointment);
	$template['day_appointment'] = $day_appointment;
	$this->load->view('doctor_dash_appointments_day',$template); 
}

/*MEDICAL RECORDS PAGE*/
public function records()
{
	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR"))
 	{
	 	$userdata = $this->session->userdata('UserData');
		$template['page'] = "doctor_medical_records";
		$template['page_title'] = "Records";
		$userdata = $this->session->userdata('UserData');
		$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
		$patient_attended = $this->Doctor_model->get_single_doc_pat_attended($userdata['id'],'');
		$patient_attended_total = $this->Doctor_model->get_single_doc_pat_attended_count($userdata['id']);

		$patient_scheduled = $this->Doctor_model->get_single_doc_pat_scheduled($userdata['id'],'');

		$patient_scheduled_total = $this->Doctor_model->get_single_doc_pat_scheduled_count($userdata['id']);


		//print_r($patient_scheduled);die();


		/*CODE FOR SHOWING SUMMARY NUMBERS*/
		//CODE FOR SUMMARY IN NUMBERS
		$no_of_attendance = $this->Doctor_model->get_doctor_num_attendance($userdata['id']);
		$no_of_billed = $this->Doctor_model->get_doctor_num_billed($userdata['id']);
		$no_of_patients = $this->Doctor_model->get_doctor_num_patients($userdata['id']);
		$no_of_profileview = $this->Doctor_model->get_doctor_num_profileview($userdata['id']);

		if(empty($no_of_billed['amount']))
		{
			$no_of_billed['amount'] = 0;
		}

		$dash_view = array('no_of_attendance' => $no_of_attendance['count'],'no_of_billed'=>$no_of_billed['amount'],'no_of_patients' => $no_of_patients['count'],'no_of_profileview'=>$no_of_profileview['count']);
		
		$template['patient_attended'] = $patient_attended;
		$template['patient_attended_total'] = $patient_attended_total;
		$template['patient_attended_page'] = '1';

		$template['patient_scheduled'] = $patient_scheduled;
		$template['patient_scheduled_total'] = $patient_scheduled_total;
		$template['patient_scheduled_page'] = '1';
		$template['dash_view'] = $dash_view;

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

/*GET SCHEDULED MEDICAL RECORDS FOR NEXT PAGE - MEDICAL RECORDS*/
public function med_rec_scheduled_next()
{
	$userdata = $this->session->userdata('UserData');
	$patient_scheduled_total = $this->Doctor_model->get_single_doc_pat_scheduled_count($userdata['id']);
	$next_page = $_POST['currentpage']+1;
	$patient_scheduled = $this->Doctor_model->get_single_doc_pat_scheduled($userdata['id'],$next_page);
	$template['patient_scheduled'] = $patient_scheduled;
	$template['patient_scheduled_total'] = $patient_scheduled_total;
	$template['patient_scheduled_page'] = $next_page;
	$this->load->view('doctor_medical_records_scheduled', $template);
}

/*GET SCHEDULED MEDICAL RECORDS FOR PREV PAGE - MEDICAL RECORDS*/
public function med_rec_scheduled_prev()
{
	$userdata = $this->session->userdata('UserData');
	$prev_page = $_POST['currentpage']-1;
	$patient_scheduled = $this->Doctor_model->get_single_doc_pat_scheduled($userdata['id'],$prev_page);
	$patient_scheduled_total = $this->Doctor_model->get_single_doc_pat_scheduled_count($userdata['id']);
	$template['patient_scheduled'] = $patient_scheduled;
	$template['patient_scheduled_total'] = $patient_scheduled_total;
	$template['patient_scheduled_page'] = $prev_page;
	$this->load->view('doctor_medical_records_scheduled', $template); 
}

/*GET ATTENDED MEDICAL RECORDS FOR NEXT PAGE - MEDICAL RECORDS*/
public function med_rec_attended_next()
{
	$userdata = $this->session->userdata('UserData');
	$patient_attended_total = $this->Doctor_model->get_single_doc_pat_attended_count($userdata['id']);
	$next_page = $_POST['currentpage']+1;
	$patient_attended = $this->Doctor_model->get_single_doc_pat_attended($userdata['id'],$next_page);
	$template['patient_attended'] = $patient_attended;
	$template['patient_attended_total'] = $patient_attended_total;
	$template['patient_attended_page'] = $next_page;
	$this->load->view('doctor_medical_records_attended', $template);
}

/*GET ATTENDED MEDICAL RECORDS FOR PREV PAGE - MEDICAL RECORDS*/
public function med_rec_attended_prev()
{
	$userdata = $this->session->userdata('UserData');
	$prev_page = $_POST['currentpage']-1;
	$patient_attended = $this->Doctor_model->get_single_doc_pat_attended($userdata['id'],$prev_page);
	$patient_attended_total = $this->Doctor_model->get_single_doc_pat_attended_count($userdata['id']);
	$template['patient_attended'] = $patient_attended;
	$template['patient_attended_total'] = $patient_attended_total;
	$template['patient_attended_page'] = $prev_page;
	$this->load->view('doctor_medical_records_attended', $template); 
}

/*SEARCH FUNCTION IN SCHEDULED MEDICAL RECORDS - MEDICAL RECORDS*/
public function med_rec_scheduled_search()
{
	//print_r($_POST);	
	$userdata = $this->session->userdata('UserData');
	$patient_scheduled = $this->Doctor_model->get_single_doc_pat_scheduled_search($userdata['id'],$_POST['text']);
	//print_r(sizeof($patient_scheduled));
	$template['patient_scheduled'] = $patient_scheduled;
	$template['patient_scheduled_total'] = array('count'=>sizeof($patient_scheduled));
	$template['patient_scheduled_page'] = '1';
	$template['search_data'] = $_POST['text'];
	$this->load->view('doctor_medical_records_scheduled', $template); 
}

/*SEARCH FUNCTION IN ATTENDED MEDICAL RECORDS - MEDICAL RECORDS*/
public function med_rec_attended_search()
{
	//print_r($_POST);	
	$userdata = $this->session->userdata('UserData');
	$patient_attended = $this->Doctor_model->get_single_doc_pat_attended_search($userdata['id'],$_POST['text']);
	//print_r(sizeof($patient_scheduled));
	$template['patient_attended'] = $patient_attended;
	$template['patient_attended_total'] = array('count'=>sizeof($patient_attended));
	$template['patient_attended_page'] = '1';
	$template['search_data_att'] = $_POST['text'];
	$this->load->view('doctor_medical_records_attended', $template); 
}

/*FUNCTION FOR MEDICAL RECORDS VIEW - MEDICAL RECORDS*/
public function recordsview()
{
	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR"))
 	{
 		$patient_id = $this->uri->segment(3);
		//print_r($patient_id);die();
	 	$userdata = $this->session->userdata('UserData');
	 	$patient_data =  $this->Patient_model->get_single_patient($patient_id);

	 	//CODE FOR SUMMARY IN NUMBERS
		$no_of_attendance = $this->Doctor_model->get_doctor_num_attendance($userdata['id']);
		$no_of_billed = $this->Doctor_model->get_doctor_num_billed($userdata['id']);
		$no_of_patients = $this->Doctor_model->get_doctor_num_patients($userdata['id']);
		$no_of_profileview = $this->Doctor_model->get_doctor_num_profileview($userdata['id']);

		if(empty($no_of_billed['amount']))
		{
			$no_of_billed['amount'] = 0;
		}

		$dash_view = array('no_of_attendance' => $no_of_attendance['count'],'no_of_billed'=>$no_of_billed['amount'],'no_of_patients' => $no_of_patients['count'],'no_of_profileview'=>$no_of_profileview['count']);


	 	$consultation_list = $this->Doctor_model->get_single_doc_pat_consultation_list($userdata['id'],$patient_id);

	 	if(!empty($consultation_list))
	 	{
		 	$booking_details = $this->Doctor_model->get_booking_details($consultation_list['0']['book_id']);
		 	$record_data = $this->Doctor_model->get_medical_record_for_booking($consultation_list['0']['book_id']);
	 		/*if(empty($record_data))
	 			redirect(base_url());*/
	 		$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
	 		$patient_data = $this->Patient_model->get_single_patient($patient_id);

	 		if(!empty($record_data))
	 		{
	 			$record_data['diseases'] = json_decode($record_data['diseases']);
		 		$record_data['prescribtions'] = json_decode($record_data['prescribtions']);
		 		$record_data['exams'] = json_decode($record_data['exams']);
		 		$record_data['budget'] = json_decode($record_data['budget']);
		 		$record_data['letters'] = json_decode($record_data['letters']);
	 		}
 		}	

 		//print_r($record_data);die();
		$template['dash_view'] = $dash_view;
		$template['patient_data'] = $patient_data;
		$template['doctor_data'] = $doctor_data;
		$template['booking_details'] = $booking_details;
		$template['record_data'] = $record_data;
		$template['consultation_list'] = $consultation_list;
		$template['page'] = "doctor_medical_records_detail";
		$template['page_title'] = "Records";

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

}

/*AJAX FUNCTION FOR LOADING MEDICAL RECORD FOR GIVEN BOOKING ID*/
public function loadrecord()
{
	$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);
 	//print_r($record_data);die();
	$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doc_id']);
	$patient_data = $this->Patient_model->get_single_patient($booking_details['pat_id']);

	if(!empty($record_data))	
	{
		$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']));
	}
	
	$template['booking_details'] = $booking_details; 
	$template['record_data'] = $record_data; 
	$template['doctor_data'] = $doctor_data; 
	$template['patient_data'] = $patient_data; 
	$this->load->view('doctor_medical_records_recordview', $template);
}


/*FUNCTION FOR EDIT MEDICAL RECORDS - MEDICAL RECORDS*/
public function recordsedit()
{
	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR"))
 	{	
	 	$userdata = $this->session->userdata('UserData');
		$template['page'] = "doctor_medical_records_edit";
		$template['page_title'] = "Records";
		$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());
	}

}

/*CONTROLLER - SERVICE/CONSULTATION */
public function service()
{

	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR")&&(!empty($this->uri->segment(3))))
 	{
 		$booking_id = $this->uri->segment(3);
 		$current_booking_status = $this->Doctor_model->get_current_booking_status($booking_id);
 		
 		if($current_booking_status['booking_status']==1)
 		{

	 		$this->Doctor_model->change_booking_status($booking_id,2);
	 		$check_record = $this->Doctor_model->check_medical_record($booking_id);
	 		
	 		if($check_record['count']>0)
	 		{
	 			$template['record_id'] = $check_record['record_id'];
	 		}
	 		else
	 		{
	 			$record_id = $this->Doctor_model->insert_medical_record($booking_id);
	 			$array = array('medical_record_id' =>$record_id);
	 			$this->Doctor_model->update_booking($booking_id,$array);
	 			$template['record_id'] = $record_id;
	 		}
	 		
	 		$booking_details = $this->Doctor_model->get_booking_details($booking_id);

	 		$main_complaints = $this->Doctor_model->get_main_complaints();
	 		$major_problems = $this->Doctor_model->get_major_problems();
	 		foreach ($major_problems as $key => $value) 
	 		{
	 			$val = $this->Doctor_model->get_major_subproblems($value['id']);
	 		
	 			$major_problems[$key]['sub_problem'] = $val;
	 			
	 		}
	 		//echo "<pre>";
	 		//print_r($major_problems);die();

	 		$medicines = $this->Doctor_model->get_distinct_medicines(); //for use of medicines
			$exams = $this->Doctor_model->get_distinct_exams(); //for use of medicines			
	 		$procedure = $this->Doctor_model->get_distinct_procedure(); //for use of medicines
	 		$cidnumbers = $this->Doctor_model->get_distinct_cid(); //for use of medicines
	 		$certificate_letter = $this->Doctor_model->get_certificate_letters(); //for use of medicines

	 		//$medicine_list = $this->Doctor_model->get_all_medicines();

			$userdata = $this->session->userdata('UserData');
			$template['booking_details'] = $booking_details;
			$template['page'] = "doctor_dash_start_service";
			$template['page_title'] = "Service";
			$template['main_complaints'] = $main_complaints;
			$template['major_problems'] = $major_problems;
			$template['medicines'] = $medicines;
			$template['exams'] = $exams;
			$template['procedure'] = $procedure;
			$template['cidnumbers'] = $cidnumbers;
			$template['certificate_letter'] = $certificate_letter;
			//print_r($medicines);die();
			$this->load->view('template/template', $template);
		}
		else
		{
			header('Location: '.base_url().'Doctor');
		}	
	}
	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().'Home/error/url');
	}
}

/*Desc : FUNCTION FOR ADDING MEDICAL RECORD DATA INTO DATABASE - START SERVICE*/
public function endservice()
{
	$booking_id = $this->uri->segment(3);
	$this->Doctor_model->change_booking_status($booking_id,3);

	/*CODE FOR WALLET INSERTION*/
	/*------------------------------------------------*/
	$ipok_settings = $this->Home_model->get_ipok_settings();
	$booking_details = $this->Doctor_model->get_booking_details($booking_id);
	$wallet = $this->Doctor_model->get_wallet_for_doctor($booking_details['doc_id']);
	if(empty($wallet))
	{
		$wallet = array('reedem_earn' => 0,'future_earn' => 0 ,'total_earn' => 0 );
	}
	$earn = $booking_details['book_price'] - (($booking_details['book_price'] * $ipok_settings['ipok_fee'])/100);
	$wallet['reedem_earn'] = $wallet['reedem_earn'] + $earn;
  	$wallet['future_earn'] = $wallet['future_earn'] - $earn;
  	$this->Doctor_model->update_wallet($booking_details['doc_id'],$wallet);
  	/*------------------------------------------------*/
	redirect(base_url().'Doctor/recordsummary/'.$booking_id);	
}


/*Desc : FUNCTION FOR ADDING MEDICAL RECORD DATA INTO DATABASE - START SERVICE*/
public function recordsummary()
{
	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR")&&(!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))
 			redirect(base_url());
 		$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doc_id']);
 		$patient_data = $this->Patient_model->get_single_patient($booking_details['pat_id']);

 		$record_data['diseases'] = json_decode($this->encrypt->decode($record_data['diseases'])); 
 		$record_data['prescribtions'] = json_decode($this->encrypt->decode($record_data['prescribtions']));
 		$record_data['exams'] = json_decode($this->encrypt->decode($record_data['exams']));
 		$record_data['budget'] = json_decode($this->encrypt->decode($record_data['budget']));
 		$record_data['letters'] = json_decode($this->encrypt->decode($record_data['letters']));


 		//print_r($record_data);die();
		$template['page'] = "doctor_dash_start_service_summary";
		$template['page_title'] = "Service";
		$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
	{
		$this->session->set_flashdata('message', array('message' => load_language('session_invalid_error',true), 'title' => load_language('error',true), 'class' => 'danger'));
 		header('Location: '.base_url());
	}

}

/*Desc : FUNCTION FOR ADDING MEDICAL RECORD DATA INTO DATABASE - START SERVICE*/
public function save_medicalrecord_data()
{
	
	//print_r($_POST);
	//print_r($_FILES);
	
	$insert_array = array();
	$res = array();

	if(!empty($_POST) and $_POST['section']=='anamnesis')
	{

		if(isset($_POST['Kidney_Problem'])&&!empty($_POST['Kidney_Problem']))
		{
			$anamnese['Kidney_Problem'] = $_POST['Kidney_Problem'];
		}
		if(isset($_POST['Heart_Problem'])&&!empty($_POST['Heart_Problem']))
		{
			$anamnese['Heart_Problem'] = $_POST['Heart_Problem'];
		}
		if(isset($_POST['Joint_Problem'])&&!empty($_POST['Joint_Problem']))
		{
			$anamnese['Joint_Problem'] = $_POST['Joint_Problem'];
		}
		if(isset($_POST['Breathing_Problem'])&&!empty($_POST['Breathing_Problem']))
		{
			$anamnese['Breathing_Problem'] = $_POST['Breathing_Problem'];
		}
		if(isset($_POST['Gastric_Problem'])&&!empty($_POST['Gastric_Problem']))
		{
			$anamnese['Gastric_Problem'] = $_POST['Gastric_Problem'];
		}
		if(isset($_POST['Allergies'])&&!empty($_POST['Allergies']))
		{
			$anamnese['Allergies'] = $_POST['Allergies'];
		}
		if(isset($_POST['Medications'])&&!empty($_POST['Medications']))
		{
			$anamnese['Medications'] = $_POST['Medications'];
		}
		if(isset($_POST['others'])&&!empty($_POST['others']))
		{
			$anamnese['others'] = $_POST['others'];
		}
		
		if(!empty($anamnese)&&isset($anamnese))
		{
			$disease['anamnese'] = $anamnese;
			$myJSON = json_encode($disease);	
			$insert_array['diseases'] = $this->encrypt->encode($myJSON);
		}

		if(!empty($_POST['description']) and (isset($_POST['description'])))
		{
			$insert_array['description'] = $this->encrypt->encode($_POST['description']);
		}

		$insert_array['main_complaint'] = $this->encrypt->encode($_POST['main_complaint']);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('anamnese_updated_message',true) );
		}
		else
		{
			$res= array('status' => 'error','msg'=> load_language('updation_failed',true) );
		}
		

	}
	elseif(!empty($_POST) and $_POST['section']=='medicine' and !empty($_POST['medicine_list']))
	{
		//print_r($_POST['medicine_list']);die();

		foreach ($_POST['medicine_list'] as $key => $elem) 
		{
			$medicine[$key] = json_decode($elem); //decoding json medicine
		}

		$myJSON = json_encode($medicine); //json encoding for db entry
		$insert_array['prescribtions'] = $this->encrypt->encode($myJSON);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('medicine_updated_message',true));
		}
		else
		{
			$res= array('status' => 'error','msg'=> load_language('updation_failed',true) );
		}
		
	}
	elseif(!empty($_POST) and $_POST['section']=='exams')
	{
		//print_r($_POST);die();
		$exam = array();
		$exam['procedure'] = $_POST['exam_procedure'];
		$exam['observation'] = $_POST['observation'];
		
		$new =array();
		$new[] = $exam;
		//print_r(json_encode($new));exit();
		$myJSON = json_encode($new); //json encoding for db entry
		$insert_array['exams'] = $this->encrypt->encode($myJSON);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('exams_updated_message',true) );
		}
		else
		{
			$res= array('status' => 'error','msg'=> load_language('updation_failed',true) );
		}
		
	}
	elseif(!empty($_POST) and $_POST['section']=='budget' and !empty($_POST['budget']))
	{
		//print_r($_POST);die();

		foreach ($_POST['budget'] as $key => $elem) 
		{
			$budget[$key] = json_decode($elem); //decoding json medicine
		}

		$myJSON = json_encode($budget); //json encoding for db entry

		$insert_array['budget'] = $this->encrypt->encode($myJSON);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('procedure_updated_message',true));
		}
		else
		{
			$res= array('status' => 'error','msg'=>  load_language('updation_failed',true) );
		}
		
	}
	elseif(!empty($_POST) and $_POST['section']=='certificate' and !empty($_POST['certificate']))
	{
		$postdata = $_POST;
		unset($postdata['booking_id']);
		unset($postdata['section']);
		if($_POST['is_letter_with_cid']=='true')
		{
			$postdata['is_letter_with_cid'] = true;
		}
		else
		{
			$postdata['is_letter_with_cid'] = false;
		}
		//$postdata['is_letter_with_cid'] = (boolean)$postdata['is_letter_with_cid'];
		$letter_json = json_encode($postdata);
		//print_r($letter_json);die();

		$insert_array['letters'] = $this->encrypt->encode($letter_json);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('certificate_updated_message',true));
		}
		else
		{
			$res= array('status' => 'error','msg'=> load_language('updation_failed',true) );
		}
		
	}
	elseif(!empty($_POST) and $_POST['section']=='review' and !empty($_POST['review']))
	{
		//print_r($_POST);die();
		$offset = json_decode($_POST['offset']);
		$nowin_server = date("Y-m-d TH:i:s");
		if($offset->sign=='+')
		{
			$nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('+'.$offset->hour.' hour +'.$offset->minute.' minutes',strtotime($nowin_server)));
		}
		elseif ($offset->sign=='-') 
		{
			$nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('-'.$offset->hour.' hour -'.$offset->minute.' minutes',strtotime($nowin_server)));
		}

		$insert_array['patient_review'] = encrypt_data($_POST['review']);

		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
		if($update)
		{
			$res= array('status' => 'success','msg'=> load_language('review_updated',true));

			/*CODE FOR DOCTOR NOTIFICATION ON ADDING MEDICAL RECORD REVIEW*/
			/*------------------------------------------------*/
			$booking_details = $this->Search_doctor_model->get_booking_details($_POST['booking_id']);
			$patient_data = $this->Patient_model->get_single_patient($booking_details['patient_id']);

			$text = 'The patient '.decrypt_data($patient_data['pt_name']).' evaluated his consultation on '.date('d.m.Y',$booking_details['time_start']);

			$notification = array('doctor_id' => $booking_details['doctor_id'],'type'=>1,'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['doctor_id']);
			if(!empty($fcm_doctor['fcm_token']))
			{
				$doc_push_obj['id'] = $doctor_insert_id;
				$doc_push_obj['type'] = "New Review";
				$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);
			}
			/*------------------------------------------------*/

		}
		else
		{
			$res= array('status' => 'error','msg'=> load_language('insertion_failed',true) );
		}
		
	}
	
	print json_encode($res);

}

/*Desc:FUNCTION FOR SAVE MEDICAL RECORD FINAL DATA - SERVICE*/
public function save_medicalrecord_finaldata()
{
	//print_r($_FILES);
	//print_r($_POST);
	//die();
	$insert_array = array();
	if(!empty($_POST) )
	{
		
		$booking_id = $_POST['booking_id'];
 		if(!empty($_FILES))
 		{
 			if (!file_exists('./assets/uploads/medicalrecord/booking'.$booking_id)) 
	 		{
	    		mkdir('./assets/uploads/medicalrecord/booking'.$booking_id, 0777, true);
			}
			$files = $_FILES;
 			$config = set_upload_options('./assets/uploads/medicalrecord/booking'.$booking_id); 
 			$this->load->library('upload', $config);

	 		for ($i=0; $i < count($files['images']['name']) ; $i++) 
	 		{ 
 		
	 			$_FILES['images']['name'] = $files['images']['name'][$i];
		        $_FILES['images']['type'] = $files['images']['type'][$i];
		        $_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
		        $_FILES['images']['error'] = $files['images']['error'][$i];
		        $_FILES['images']['size'] = $files['images']['size'][$i];    
		        if($this->upload->do_upload('images'))
		        {
		        	$dataInfo[$i] = $this->upload->data();
		        	$obsr_images[$i] = 'assets/uploads/medicalrecord/booking'.$booking_id.'/'.$dataInfo[$i]['file_name'];
		        }
		        else
		        {
		        	$error = array('error' => $this->upload->display_errors('', '')); 
					$res_img = array(
					"status"=> "error",
					"error"=> "Upload Error",
					"msg"=> load_language('image_upload_error',true)/*.$error['error']*/
					);	
					print json_encode($res_img);
					exit();
					
		        }

 			}
 		}
 		
 		
		if(!empty($obsr_images))
 		{
 			$insert_array['images'] = json_encode($obsr_images,JSON_UNESCAPED_SLASHES);
 		}

 		if(!empty($_POST['obsr']))
 		{
 			$insert_array['other_observations'] = encrypt_data($_POST['obsr']);
 		}

 		if(!empty($_POST['main_complaint']))
 		{
 			$insert_array['main_complaint'] = encrypt_data($_POST['main_complaint']);
 		}

 		if(!empty($insert_array))
 		{

	 		$update = $this->Doctor_model->update_records($_POST['booking_id'],$insert_array);
			if($update)
			{
				
				$res= array('status' => 'success','msg'=> load_language('success',true),'booking_id'=>$booking_id );
			}
			else
			{
				$res= array('status' => 'error','msg'=> load_language('updation_failed',true) );
				
			}
		}
		else
		{
			$res= array('status' => 'success','msg'=> load_language('success',true),'booking_id'=>$booking_id );
		}
		print json_encode($res);

	}
}

/*Desc:FUNCTION FOR RETURNING MEDICINE DETAILS FOR GIVEN MEDICINE NAME - SERVICE*/
public function get_medicine_details()
{
	$name = $_POST['medicine_name'];
	$medicine = $this->Doctor_model->get_medicine_for_name($name);
	print json_encode($medicine);
}

/*Desc:FUNCTION FOR RETURNING EXAM DETAILS FOR GIVEN EXAM NAME - SERVICE*/
public function get_exam_details()
{
	$name = $_POST['exam_name'];
	$exam = $this->Doctor_model->get_exam_for_name($name);
	//echo $this->db->last_query();
	print json_encode($exam);
}

/*Desc:FUNCTION FOR RETURNING EXAM DETAILS FOR GIVEN EXAM NAME - SERVICE*/
public function get_budget_details()
{
	$name = $_POST['procedure_name'];
	$budget = $this->Doctor_model->get_budget_for_name($name);
	print json_encode($budget);
}

/*CONTROLLER - EDIT PROFILE*/
public function editProfile()
{
	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="DOCTOR")
 	{
 		$userdata = $this->session->userdata('UserData');
 		$template['page'] = "doctor_editprofile";
		$template['page_title'] = "Edit Profile";
		$template['data'] = "Doctor page";
		$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);	
		$speciality_list = $this->Home_model->get_speciality();
		$template['speciality_list'] = $speciality_list;
		$template['doctor_data'] = $doctor_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 CHECK USERNAME AVAILABLE - 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_doc($data);
		print json_encode($check_result);
	}
	
}

/*FUNCTION FOR UPDATING PROFILE - 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/doctors/'); 
			$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' => 'Profile Photo Cant be Uploaded, Try Again', 'title' => 'Error', 'class' => 'danger'));
				//header('Location: '.base_url().'Doctor/editProfile');
				redirect(base_url().'Doctor/editProfile');
			}	
			else 
			{ 
				$imagedata = $this->upload->data(); 
				$fullfilepath='assets/uploads/profilepic/doctors/'.$imagedata['file_name'];
				//$picdata = array('profile_pic'=>$fullfilepath);
				$update_data['profile_pic'] = $fullfilepath;
			}
		}
		else
		{
			unset($update_data['profile_pic']);
		}
		//print_r($update_data);die();


		/*encryption*/
		//$update_data['name'] = $this->encrypt->encode($update_data['name']);
		$update_data['rg'] = $this->encrypt->encode($update_data['rg']);
		//$update_data['cpf'] = $this->encrypt->encode($update_data['cpf']);
		//$update_data['telephone'] = $this->encrypt->encode($update_data['telephone']);
		$update_data['gender'] = $this->encrypt->encode($update_data['gender']);
		$update_data['cep'] = $this->encrypt->encode($update_data['cep']);
		$update_data['street_address'] = $this->encrypt->encode($update_data['street_address']);
		$update_data['locality'] = $this->encrypt->encode($update_data['locality']);
		$update_data['number'] = $this->encrypt->encode($update_data['number']);
		$update_data['complement'] = $this->encrypt->encode($update_data['complement']);
		$update_data['about'] = $this->encrypt->encode($update_data['about']);
		$update_data['crm'] = $this->encrypt->encode($update_data['crm']);
		/*encryption*/


	
		$update = $this->Doctor_model->update_profile($userdata['id'],$update_data);
		if($update['status']=='success')
		{
			$doctor_data = $this->Doctor_model->get_single_doctor_row($userdata['id']);
			//print_r($doctor_data);

			$new_userdata = array(
								"type"=>"DOCTOR",
								"id"=> $doctor_data['id'],
								"name"=> $doctor_data['name'],
								"username"=> $doctor_data['username'],
								"email"=> $doctor_data['email'],
								"password" => $doctor_data['password'],
								"specialization" => $doctor_data['specialization'],
								"telphone" => $doctor_data['telephone'],
								"cpf" => $doctor_data['cpf'],
								"rg" => $doctor_data['rg'],
								"dob" => $doctor_data['dob'],
								"gender" => $doctor_data['gender'],
								"price" => $doctor_data['price'],
								"zip_code" => $doctor_data['cep'],
								"street_address" => $doctor_data['street_address'],
								"locality" => $doctor_data['locality'],
								"number" => $doctor_data['number'],
								"landmark" =>$doctor_data['complement'],
								"profile_photo" => $doctor_data['profile_pic'],
								"bio" => $doctor_data['about']
								);

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

		}	
		else
		{


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

		}

	}
	
}

/*FUNCTION FOR VALIDATION UPLOADING FILE TYPE*/
function is_valid_type($file,$valid_types)
{
	if (in_array($file['type'], $valid_types))
		return 1;
	return 0;
}

/*FUNCTION FOR UPDATING CONSULTATION CONFIGURATION - DOCTOR DASH*/
public function addConsultConfig()
{
	$data = $_POST;
	//print_r($data);
	$userdata = $this->session->userdata('UserData');
	$update = $this->Doctor_model->update_profile($userdata['id'],$data);
	print json_encode($update);
}


/*FUNCTION FOR VIEWING ALL NOTIFICATION FOR CURRENT DOCTOR - NOTIFICATIONS*/
public function notification()
{
		if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="DOCTOR")
 	{
 		$userdata = $this->session->userdata('UserData');

 		//CODE FOR SUMMARY IN NUMBERS
		$no_of_attendance = $this->Doctor_model->get_doctor_num_attendance($userdata['id']);
		$no_of_billed = $this->Doctor_model->get_doctor_num_billed($userdata['id']);
		$no_of_patients = $this->Doctor_model->get_doctor_num_patients($userdata['id']);
		$no_of_profileview = $this->Doctor_model->get_doctor_num_profileview($userdata['id']);

		if(empty($no_of_billed['amount']))
		{
			$no_of_billed['amount'] = 0;
		}

		$dash_view = array('no_of_attendance' => $no_of_attendance['count'],'no_of_billed'=>$no_of_billed['amount'],'no_of_patients' => $no_of_patients['count'],'no_of_profileview'=>$no_of_profileview['count']);

		
		
		$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
		$speciality_list = $this->Home_model->get_speciality();

		$page = 1;
		$notifications = $this->Doctor_model->get_notifications($userdata['id'],$page);
		$notifications_total_count = $this->Doctor_model->get_notifications_total_count($userdata['id']);


		$aniversaries = $this->Doctor_model->get_aniversaries_list($userdata['id']);
		//echo "<pre>";
		//print_r($aniversaries);die();
		//print_r(strtotime(date('Y-m-d H:i:s')));
		//echo "<pre>";print_r($notifications);die();


		$template['speciality_list'] = $speciality_list;
		$template['doctor_data'] = $doctor_data;
		$template['dash_view'] = $dash_view;
		$template['notifications'] = $notifications;
		$template['notifications_total_count'] = $notifications_total_count[0];
		//print_r($notifications_total_count);die();
		$template['notifications_page_no'] = $page;

		$template['aniversaries'] = $aniversaries;


 		$template['page'] = "doctor_notifications_aniversaries";
		$template['page_title'] = "Notification";
		$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());
	}
}

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

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

/*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->Doctor_model->get_doctor_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->Doctor_model->get_doctor_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->Doctor_model->disable_doctor_account($userdata['id']);
	}
	else
	{
		$res = array('status' => 'error','msg'=>load_language('invalid_code',true));
	}
	print json_encode($res);
}

/*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->Doctor_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 DOCTOR CHAT*/
 public function chat()
 {
 	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR" or $this->session->userdata('UserData')['type']=="COLLABORATOR"))
 	{

 		$userdata = $this->session->userdata('UserData');

 		if($this->session->userdata('UserData')['type']=="COLLABORATOR")
 		{
 			$my_capabilities = $this->Doctor_model->get_capabilities_of_collaborator($userdata['c_id']);

 			$capabilities = explode(',', $my_capabilities['capabilities']);
 			$find_capability = in_array("Doctor/chat",$capabilities);
 			if(!$find_capability)
 			{
 				redirect(base_url().'Home/error');
 			}
 		}
 		$userdata = $this->session->userdata('UserData');
 		if(!empty($this->uri->segment(3)))
 		{
 			$patient_id = $this->uri->segment(3);
 			$patient_data = $this->Patient_model->get_single_patient($patient_id);
 			$opponent = array('pat_name' =>$patient_data['pt_name'],
 							'patient_id' => $patient_data['patientid'],
 							'pat_pic' => $patient_data['pt_pic']);
 			$this->session->set_userdata('opponentData',$opponent);
 			//print_r($this->session->userdata('oppenontData'));die();
 			redirect(base_url().'Doctor/chat');
 		}
 		$template['page'] = 'chat';
 		$template['page_title'] = "Chat";
		$this->load->view('template/template', $template);
 	}
 	else
 	{
 		redirect(base_url());
 	}
 }

 public function sentBroadcast()
 {
 	$DEFAULT_PATH = '/chats/';
 	$userdata = $this->session->userdata('UserData');
 	$time = (int)time().'000';
 	//print_r($time);die();
 	$jsonData = json_decode($_POST['json_obj']);
 	$nowin_server = date("Y-m-d TH:i:s");
 	//print_r($jsonData);

 	foreach ($jsonData as $key => $val) 
 	{
 		$chatid = 'P'.$val->patient_id.'@_@D'.$userdata['id'];
 		//print_r($chatid);
 		$firebaseobject = array('doctor_id' => (int)$userdata['id'],
 							'doctor_name' => $userdata['name'],
 							'doctor_photo' => $userdata['profile_photo'],
 							'message' => $_POST['message'],
 							'sender_type' =>1,
 							'patient_id' =>(int)$val->patient_id,
 							'patient_name' =>$val->pat_name,
 							'patient_photo' =>$val->pat_pic,
 							'photo_url' =>'',
 							//'time' =>strtotime(local_time_in_server(time(),'H:i:s')),
 							'time' => $time,
 							'type' =>0,
 							'video_url' =>'');
 		//print_r($firebaseobject);die();

 		//UPDATING RECENT MSG IN MYSQL DB
	   	$recent_obj =  array('chat_id' => $chatid,
						  'patient_id' => $val->patient_id,
						  'doctor_id' => $userdata['id'],
						  'sender_type' =>1,
						   'msg' => $_POST['message'],
						   'photo_url' => '', 
						   'video_url' => '',
							'type'=> 0, 
						   //'time' =>strtotime(local_time_in_server(time(),'H:i:s'))
							'time' => $time
						);
	   	//print_r($recent_obj);
	   	$result  = firebase()->push($DEFAULT_PATH .'/'.$chatid.'/', "");
	   	$token = json_decode($result);
	   	$firebaseobject['id'] = $token->name;
	    //print_r($token->name);die();
	   	firebase()->set($DEFAULT_PATH .'/'.$chatid.'/'.$token->name,$firebaseobject);   
	   	$update = $this->Home_model->update_recent_chat($recent_obj);


	   			$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
	     		$text_pat = ''.$doctor_data['dr_name'].' :'.$_POST['message'];

				$fcm_user = $this->Home_model->get_patient_fcm($val->patient_id);
				if(!empty($fcm_user['fcm_token']))
					{
						//print_r($fcm_user['fcm_token']);die();
						$pat_push_obj['id'] = $val->patient_id;
						$pat_push_obj['type'] = "New Message";
						$pat_push_obj['booking_id'] = '';
						$pat_push_obj['booking_date'] = '';
						$pat_push_obj['doctor_id'] = $userdata['id'];
						$pat_push_obj['doctor_name'] = $doctor_data['dr_name'];
						$pat_push_obj['doctor_specialization'] = $doctor_data['dr_specialization'];
						$pat_push_obj['message'] = $_POST['message'];
						$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);
					}
	     	
 	}

	print json_encode($update);
 }

/*FUNCTION FOR ADDING COLABORATOR - DOCTOR DASHBOARD*/
 public function addColaborator()
 {
 	if($this->session->userdata('UserData')&&$this->session->userdata('UserData')['type']=="DOCTOR")
 	{
 		$template['page'] = 'doctor_dash_add_colaborator';
		$template['page_title'] = "Add Colaborator";
		$this->load->view('template/template', $template);
	}
 	else
 	{
 		redirect(base_url());
 	}
 }

 /*FUNCTION FOR EDITING COLABORATOR - DOCTOR DASHBOARD*/
 public function editColaborator()
 {
 	if($this->session->userdata('UserData')&&($this->session->userdata('UserData')['type']=="DOCTOR")&&(!empty($this->uri->segment(3))))
 	{
 		$userdata = $this->session->userdata('UserData');
 		$id = $this->uri->segment(3);
 		$collaborator_data = $this->Doctor_model->get_collaboator_byid_doc_id($id,$userdata['id']);
 		//print_r($collaborator_data);die();
 		if(!empty($collaborator_data))
 		{
 			$template['collaborator_data'] = $collaborator_data;
 			$template['page'] = 'doctor_dash_edit_colaborator';
			$template['page_title'] = "Edit Colaborator";
			$this->load->view('template/template', $template);
 		}
 		else
 		{
 			redirect(base_url());
 		}
 		
	}
 	else
 	{
 		redirect(base_url());
 	}
 	
 }



/*FUNCTION FOR SAVING COLABORATOR - ADD COLLABORATOR*/
 public function saveColaborator()
 {
 	
 	
 	//print_r($_FILES);
 	//die();
 	$userdata = $this->session->userdata('UserData');
    if(!empty($_POST['data']))
    {
    	parse_str($_POST['data'], $req_data);	
    	$insertarray = array('name' => $req_data['name'],'email' => $req_data['email'],'password' => md5($req_data['password']),'telephone' => $req_data['telephone'],'cpf' => $req_data['cpf'],'doctor_id' => $userdata['id'] );
    }
    $colaborator = $this->Doctor_model->add_colaborator($insertarray);
    if($colaborator>0)
    {
		$fileName = $colaborator.'_'.$_FILES['image']['name'];
		$config = set_upload_options('./assets/uploads/profilepic/doctor_collaborator/'); 
		$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->Doctor_model->delete_registration_collaborator($colaborator);	
		}	
		else 
		{ 
			$imagedata = $this->upload->data(); 
			$fullfilepath='assets/uploads/profilepic/doctor_collaborator/'.$imagedata['file_name'];
			$picdata = array('image'=>$fullfilepath);
			$this->Doctor_model->update_colaborator($colaborator,$picdata);
			$cpf_obj = array('cpf' => $insertarray['cpf'] ,'user_type' =>2,'user_id'=>$colaborator);
			$this->Home_model->insertcpfunique($cpf_obj);
			$res = array('status' =>'success','colaborator' => $colaborator);
			//Updating collaborator data in session - header display
			$collaborator_data = $this->Doctor_model->get_all_collaborator_for_doctor($userdata['id']);
			$this->session->set_userdata('CollaboratorData',$collaborator_data);
		}
    	
    }
    else
    {
    	$res = array('status' => 'error' );
    }
    print json_encode($res);
 }

/*FUNCTION FOR UPDATING COLABORATOR DATA- SETTING AUTHORIZATION, EDIT COLLABORATOR*/
 public function updateColaborator()
 {
 	$userdata = $this->session->userdata('UserData');
 	//print_r($_POST);
 	//print_r($_FILES);
 	//die();
 	$update_array = array();

 	if($_POST['section']=='authorizeaccess')
 	{
 		$update_array['capabilities'] = '';
 		if(!empty($_POST['access']) and isset($_POST['access']))
	 	{
	 		$update_array['capabilities'] = implode(",",$_POST['access']);
	 	}
 	}

 	elseif($_POST['section']=='profile')
 	{
 		parse_str($_POST['data'], $req_data);	
    	$update_array = array('name' => $req_data['name'],'telephone' => $req_data['telephone'],'cpf' => $req_data['cpf']);
    	//print_r($_POST);
    	//print_r($_FILES);die();
    	if(!empty($_FILES['image']))
    	{
    		$fileName = $_POST['colabor_id'].'_'.$_FILES['image']['name'];
			$config = set_upload_options('./assets/uploads/profilepic/doctor_collaborator/'); 
			$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->Doctor_model->delete_registration_collaborator($colaborator);	
			}	
			else 
			{ 
				$imagedata = $this->upload->data(); 
				$fullfilepath='assets/uploads/profilepic/doctor_collaborator/'.$imagedata['file_name'];
				$update_array['image'] = $fullfilepath;
			}
    	}
    	
 	}


 	if(!empty($update_array) and empty($res['error']))
 	{
 		$update = $this->Doctor_model->update_colaborator($_POST['colabor_id'],$update_array);
 		if($update)
 			{
 				$res = array('status' => 'success' );

 				//Updating collaborator data in session - header display
				$collaborator_data = $this->Doctor_model->get_all_collaborator_for_doctor($userdata['id']);
				$this->session->set_userdata('CollaboratorData',$collaborator_data);
			}
 		else
 			{$res = array('status'=>'error');}
 	}
 	print json_encode($res);

 }

 public function collaborator()
 {
 	if($this->session->userdata('UserData') and $this->session->userdata('UserData')['type']=='COLLABORATOR')
 	{
 		$userdata = $this->session->userdata('UserData');
 		$my_capabilities = $this->Doctor_model->get_capabilities_of_collaborator($userdata['c_id']);
 		//print_r($my_capabilities);die();
		$clinic_list = $this->Doctor_model->get_doctor_clinic_list($userdata['id']);
		$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],'null');
		foreach ($day_appointment as $key => $value) 
		{
			$times = explode('-', $value['booking_time']);
			$day_appointment[$key]['time_start'] = $times[0];
			$day_appointment[$key]['time_end'] = $times[1];
		}

		//CODE FOR SUMMARY IN NUMBERS
		$no_of_attendance = $this->Doctor_model->get_doctor_num_attendance($userdata['id']);
		$no_of_billed = $this->Doctor_model->get_doctor_num_billed($userdata['id']);
		$no_of_patients = $this->Doctor_model->get_doctor_num_patients($userdata['id']);
		$no_of_profileview = $this->Doctor_model->get_doctor_num_profileview($userdata['id']);

		if(empty($no_of_billed['amount']))
		{
			$no_of_billed['amount'] = 0;
		}

		$dash_view = array('no_of_attendance' => $no_of_attendance['count'],'no_of_billed'=>$no_of_billed['amount'],'no_of_patients' => $no_of_patients['count'],'no_of_profileview'=>$no_of_profileview['count']);	

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

		//PASSING VALUES TO VIEW
		$template['my_capabilities'] = $my_capabilities;
		$template['recent'] = $recent;
		//$template['doctor_data'] = $doctor_data;
		$template['clinic_list'] = $clinic_list;
		$template['day_appointment'] = $day_appointment;
		$template['dash_view'] = $dash_view;
		

	 	$template['page'] = "collaborator_dash";
		$template['page_title'] = "Error";
		$this->load->view('template/template', $template);

 	}
 	else
 	{
 		redirect(base_url().'Home/error');
 	}
 	
 	//print_r($userdata);
 }

 /*FUNCTION TO DELETE COLLABORATOR PROFILE*/
 public function removeColaborator()
 {
 	$userdata = $this->session->userdata('UserData');
 	//print_r($_POST);die();
 	if(!empty($_POST['collaborator_id']))
 	{
 		$delete = $this->Home_model->removeColaborator($_POST['collaborator_id']);
	 	if($delete)
	 	{
	 		$res = array('status' => 'success' ,'message' =>'Collaborator Excluded');

	 		$this->Home_model->remove_cpfunique($_POST['collaborator_id'],'c'); //remove cpf
	 		
	 		//Updating collaborator data in session - header display
			$collaborator_data = $this->Doctor_model->get_all_collaborator_for_doctor($userdata['id']);
			//print_r($collaborator_data);die();
			$this->session->set_userdata('CollaboratorData',$collaborator_data);
	 	}
	 	else
	 	{
	 		$res = array('status' => 'failed' , 'message' => load_language('collaborator_exclusion_failed',true));
	 	}
 	}
 	else
 	{
 		$res = array('status' => 'failed' , 'message' => load_language('facing_technical_issues',true));
 	}
 	
 	print json_encode($res);
 }

 public function wallet()
 {
 	if($this->session->userdata('UserData') and $this->session->userdata('UserData')['type']=='DOCTOR' and empty($this->uri->segment(3)))
 	{

 		$userdata = $this->session->userdata('UserData');
 		$wallet = $this->Doctor_model->get_wallet_for_doctor($userdata['id']);
 		$banks = $this->Home_model->get_all_banks($userdata['id'],$userdata['type']);
 		$last_redemption = $this->Home_model->get_last_redemption($userdata['id'],$userdata['type']);
 		if(empty($last_redemption))
 		{
 			$last_redemption = array('amount' => '0');
 		}
 		$next_release = $this->Home_model->get_next_release($userdata['id'],$userdata['type']);
  		$ipok_settings = $this->Home_model->get_ipok_settings();
  		$next_release_amount = $next_release['total_sum'] - (($next_release['total_sum'] * $ipok_settings['ipok_fee'])/100);
  		if(empty($next_release))
  		{
  			$next_release_amount = 0;
  		}
  		//print_r($next_release_amount);die();

  		$template['banks'] = $banks;
  		$template['last_redemption'] = $last_redemption['amount'];
  		$template['next_release_amount'] = $next_release_amount;
 		//print_r($wallet);die();
 		$template['wallet'] = $wallet;
 		$template['page'] = "wallet";
		$template['page_title'] = "Wallet";


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

 	}
 	else if($this->session->userdata('UserData') and $this->session->userdata('UserData')['type']=='DOCTOR' and !empty($this->uri->segment(3)) and $this->uri->segment(3)=='redemptionhistory')
 	{
 		$userdata = $this->session->userdata('UserData');
 		$redemptiondata = $this->Home_model->redemptionhistory($userdata['id']);
 		//echo "<pre>";
 		//print_r($redemptiondata);die();
 		$template['page'] = "wallet_redemptionhistory";
		$template['page_title'] = "Wallet";
		$template['redemptiondata'] = $redemptiondata;
		$this->load->view('template/template', $template);
 	}
 	else if($this->session->userdata('UserData') and $this->session->userdata('UserData')['type']=='DOCTOR' and !empty($this->uri->segment(3)) and $this->uri->segment(3)=='futurereleases')
 	{
 		$userdata = $this->session->userdata('UserData');
 		$futurereleases = $this->Home_model->futurereleases($userdata['id']);
 		//echo "<pre>";
 		//print_r($futurereleases);die();
 		$template['page'] = "wallet_futurereleases";
		$template['page_title'] = "Wallet";
		$template['futurereleases'] = $futurereleases;
		
		$this->load->view('template/template', $template);
 	}
 	else
 	{
 		redirect(base_url().'Home/error/url');
 	}

 }


	
	
}
