<?php

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



class Searchdoctor extends CI_Controller {





	function __construct() 

	{

        parent::__construct();

        $this->load->model('Search_doctor_model');

        $this->load->model('Home_model');

        $this->load->model('Doctor_model');       

        $this->load->model('Patient_model');    

        $this->config->load('iugu');   

    }



   /*FUNCTION :REDIRECTS TO SEARCH FUNCTION AFTER SETTING LOCAL STORAGE OF SEARCH DATA - DOCTOR SEARCH*/

   /*DESCRIPTION : Search data is saved in local storage for showing the previous search data while 

   						user navigates through search screens*/

	public function index()

	{

		if(isset($_POST)&&(!empty($_POST)))

		{

			$request = $_POST;

			//print_r($request);die();

			$this->session->set_userdata('DoctorSearchData',$request);

			

		}

		header('Location: '.base_url().'Searchdoctor/search');

	}

	



   /*FUNCTION : SEARCH FUNCTION FOR FILTERING DOCTORS - DOCTOR SEARCH*/

   /*DESCRIPTION : Search data from the local storage is used to filter the search based on various

   					factors*/

	public function search()

	{

		$speciality_list = $this->Home_model->get_speciality();

		$template['speciality_list'] = $speciality_list;



		if($this->session->userdata('DoctorSearchData'))

		{

			$request = $this->session->userdata('DoctorSearchData');

			//echo "<pre>";print_r($request);

			//die();

			

			

			if((isset($request['doctor-search-date']))&&(!empty($request['doctor-search-date'])))

			{

				//$date = str_replace('/', '-', $request['doctor-search-date']);

				$request['doctor-search-date'] = strtotime($request['doctor-search-date']);

				//print_r($request);die();



			}

			

			$all_doctors = $this->Search_doctor_model->filter_search($request);
			// echo "<pre>";
			// print_r($all_doctors);die();

			$price_min =  $this->Search_doctor_model->get_doc_min_price();

			$price_max =  $this->Search_doctor_model->get_doc_max_price();



			$distance_min =  $this->Search_doctor_model->get_doc_min_distance($request);

			$distance_max =  $this->Search_doctor_model->get_doc_max_distance($request);

			//print_r($distance_max[0]['dist']);die();



			/*$filter_autoload = array('price_min' =>$price_min[0]['price'] ,'price_max'=>$price_max[0]['price'],'distance_min'=>$distance_min[0]['dist'],'distance_max'=>$distance_max[0]['dist']);*/

			$filter_autoload = array('price_min' =>$price_min[0]['price'] ,'price_max'=>$price_max[0]['price'],'distance_min'=>'0','distance_max'=>'15');

			//print_r($filter_autoload);die();

			if(!empty($all_doctors))

			{

				$template['doctors_list'] = $all_doctors;

			}



			$template['page'] = "search_doctor";

			$template['page_title'] = "Search Doctor";

			$template['searchdata'] = $request;

			$template['filter_autoload'] = $filter_autoload;

			

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

			

		}

		else

		{

			$template['page'] = "search_doctor";

			$template['page_title'] = "Search Doctor";

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

		}

		

	}





   /*FUNCTION : FILTER FUNCTION FOR FILTERING DOCTORS - DOCTOR SEARCH*/

   /*DESCRIPTION : Search data from the local storage is used to filter the search based on various

   					factors.here the additional filters from search page is also included*/

	public function filter_search()

	{

		if(isset($_POST)&&(!empty($_POST)))

		{

			$request = $_POST;

			$this->session->set_userdata('DoctorSearchData',$request);

			//print_r($request);die();

			if((isset($request['doctor-search-date']))&&(!empty($request['doctor-search-date'])))

			{

				$request['doctor-search-date'] = strtotime($request['doctor-search-date']);

			}

			$template['searchdata'] = $request;

			$all_doctors = $this->Search_doctor_model->filter_search($request);

			$template['doctors_list'] = $all_doctors;
			//echo "<pre>";
			//print_r($all_doctors);die();

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

		}

	}



	/*FUNCTION : VIEW DOCTOR COMPLETE PROFILE - DOCTOR SEARCH*/

   /*DESCRIPTION : Controller to view doctor profile from doctor search*/

	public function doctorprofile()

	{

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

		$clinic_id = $this->uri->segment(4);

		$doctor_data = $this->Search_doctor_model->get_single_doctor_clinic($doctor_id,$clinic_id);

		

		$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($doctor_id,date('y-m-d',strtotime('+'.$i.'day')));      

		}



		$check_profile_view_entry = $this->Search_doctor_model->check_profile_view_entry($doctor_id);

		if($check_profile_view_entry['count']==0)

		{

			$this->Search_doctor_model->insert_profile_view_count($doctor_id);	

		}



		$template['week_appointments'] = $week_appointments;

		$template['page'] = "search_doctor_complete_profile";

		$template['page_title'] = "Doctor Profile";

		$template['doctor_data'] = $doctor_data;

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

	}



	/*FUNCTION : VIEW BOOKING PAGE - DOCTOR SEARCH*/

   /*DESCRIPTION : Controller to view booking page from doctor search*/

	public function confirmbooking()

	{

	

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

		$clinic_id = $this->uri->segment(4);

		$doctor_data = $this->Search_doctor_model->get_single_doctor_clinic($doctor_id,$clinic_id);



		$policy = $this->Patient_model->get_policy();

		

		//$template['time_slot'] = $res_new;

		$template['page'] = "search_doctor_confirm_booking";

		$template['page_title'] = "Booking";

		$template['doctor_data'] = $doctor_data;

		$template['policy'] = $policy['waiting_policy'];

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

 

		

	}



	/*FUNCTION : GET DOCTOR TIMESLOT FOR GIVEN CLINIC - DOCTOR SEARCH*/

   /*DESCRIPTION : Returns doctor timeslot for the scheduled agenda excluding the break time*/

	public function getDoctorClinic_timeslot()

	{

		//print_r($_POST['clinic_id']);die();

		$result_availability = $this->Search_doctor_model->doctor_availability($_POST['doctor_id'],$_POST['clinic_id']);

		$consult_duration = $this->Doctor_model->check_consult_duration($_POST['doctor_id']);

		//print_r($_POST);



		$res_new = array();



		$nowin_server = date("Y-m-d TH:i:s");

		

		if($_POST['UTCoffset']['sign']=='+')

		{

			//$clienttime_UTC = date("Y-m-d H:i:s",strtotime($_POST['currenttime']." -".$_POST['UTCoffset']['hour']." hours -".$_POST['UTCoffset']['minute']." minutes"));

			//print_r($clienttime_UTC);



			$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']=='-') 

		{

			//$clienttime_UTC = date("Y-m-d H:i:s",strtotime($_POST['currenttime']." +".$_POST['UTCoffset']['hour']." hours +".$_POST['UTCoffset']['minute']." minutes"));

			//print_r($clienttime_UTC);



			$nowin_server_addoffset = date('Y-m-d H:i:s',strtotime('-'.$_POST['UTCoffset']['hour'].' hour -'.$_POST['UTCoffset']['minute'].' minutes',strtotime($nowin_server)));

		}



		//$clienttime_UTC_add1hr = date("Y-m-d H:i:s",strtotime($clienttime_UTC." + 1hours "));

		//if(strtotime($clienttime_UTC_add1hr)>strtotime($nowin_server))

		//{



			/*print_r($clienttime_UTC);

			print_r($clienttime_UTC_add1hr);

			print_r($nowin_server);

			print_r($nowin_server_addoffset);*/

		//}

		

		

		if($result_availability['data']['active_schedule']=='0')

		{

			$schedule = $result_availability['data']['date'];

		}

		else

		{

			$schedule = $result_availability['data']['date_secondary'];

		}





		if(($result_availability['status']) == 'success' and ($schedule!='""'))

		{

			$day = date('D',strtotime($_POST['book_date']));

			$res = array();

			//print_r(strtotime($_POST['currenttime']));die();

			$schedule = json_decode($schedule,true);

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

				if($value['day'] == strtolower($day))

				{



					$interval_time = $consult_duration['consultation_duration']*60;

					

					$start_time = strtotime($_POST['book_date'].' '.$value['time']['start']);

					$end_time = strtotime($_POST['book_date'].' '.$value['time']['end']);

					$break_start = strtotime($_POST['book_date'].' '.$value['time']['break_from']);

					$break_end = strtotime($_POST['book_date'].' '.$value['time']['break_to']);



					//echo "break_from : ".$break_start."|break_to : ".$break_end."||";

					

					

					for ($i=$start_time; $i<=$end_time; $i=$i+$interval_time) 

					{ 

						

						$initial = $i;

						$end = $i+$interval_time;

				

						if(isset($value['time']['break_from']) && isset($value['time']['break_to']) && ($value['time']['break_from'] != 'null' ) && ($value['time']['break_to'] != 'null') && strlen($value['time']['break_from']) && strlen($value['time']['break_to']))

						{

							

							

							if(!((($initial <= $break_start) &&($end > $break_start))||(($initial < $break_end) &&($end >= $break_end))||(($initial > $break_start) &&($end < $break_end)))&&($initial>strtotime($nowin_server_addoffset)))

							{

									//print_r("12");die();

								

								if($end <= $end_time && ($initial>strtotime($nowin_server_addoffset)))

								{

									array_push($res, array('time'=>date('h:i a',$initial).' - '.date('h:i a',$end),'start'=>$initial,'end'=>$end));

								}

							}

						}

						else

						{

							

							if(($end <= $end_time)&&($initial>strtotime($nowin_server_addoffset)))

							{

								array_push($res, array('time'=>date('h:i a',$initial).' - '.date('h:i a',$end),'start'=>$initial,'end'=>$end));

							}

						}

						

					}

				}

			}

	

			$res_new = array_values(array_unique($res,SORT_REGULAR));

			//$res_new['msg'] = load_language('time_slot',true);



			if(empty($res_new))

			{

				$res_new_print = array('status' => 'error', 'msg' => load_language('no_time_slot_available',true),'arr' =>$res_new);

			}

			else

			{

				$res_new_print = array('status' => 'success', 'msg' => load_language('time_slot',true),'arr' =>$res_new );

			}

			//echo "<pre>";

			//print_r($res_new);die();

		}else{
			$res_new_print = array('status' => 'error', 'msg' => load_language('no_time_slot_available',true),'arr' =>$res_new);
		}

		print json_encode($res_new_print);

	}



	/*FUNCTION : CHECK AVAILABILITY OF A DOCTOR - DOCTOR SEARCH*/

   /*DESCRIPTION : Returns whether the booking for given date and timeslot is available or return 

   					if the doctor is on leave for given date */

	public function checkDoctorAvailability()

	{

		$check_leave = $this->Search_doctor_model->checkDoctorLeave($_POST);

		$times = explode('-', $_POST['confirm-book-time']);

		$book_start_time = strtotime($_POST['confirm-book-date'].' '.$times[0]);

		if(strtotime($_POST['currenttime'])<$book_start_time)

		{

			if($check_leave['count']==0)

			{

				$check_booking = $this->Search_doctor_model->checkDoctorBooking($_POST);

				//print_r($check_booking);die();

				if($check_booking['count']==0)

				{	

					if($this->session->userdata('UserData'))

					{

						$res = array('status' => 'success', 'msg' => 'booking success','isLogin' =>'true');

					}

					else

					{

						$res = array('status' => 'success', 'msg' => 'booking success','isLogin' =>'false');

					}

				}

				elseif($check_booking['count']==1)

				{

					if($this->session->userdata('UserData'))

					{

						$res = array('status' => 'waiting', 'msg' => load_language('booking_full_waiting_list_available',true),'isLogin' =>'true');

					}

					else

					{

						$res = array('status' => 'waiting', 'msg' => load_language('booking_full_waiting_list_available',true),'isLogin' =>'false');

					}

				}

				else

				{

					$res = array('status' => 'fail', 'type' => 'booking slot','msg' => load_language('booking_slot_unavailable',true));

				}	

			}

			else

			{

				$res = array('status' => 'fail','type' => 'doctor leave', 'msg' => load_language('doctor_unavailable',true) );

			}

		}

		else

		{

			$res = array('status' => 'fail','type' => 'booking slot', 'msg' => load_language('invalid_booking_slot',true));

		}

		//print_r($res);die();

		print json_encode($res);

	}



	/*FUNCTION : MARK BOOKING FOR A DOCTOR - DOCTOR SEARCH*/

   /*DESCRIPTION : Mark an entry in booking table and goes to payment page in confirm booking */

	public function markbooking()

	{

		if($this->session->userdata('UserData'))

		{

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

			if($userdata['type']=="PATIENT")

			{	

				/*CODE FOR DATA STARTS*/

				$now = new DateTime();

				$times = explode('-', $_POST['confirm-book-time']);	



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

				}

				

				$date = date('y-m-d');

				$book_start_time = strtotime($_POST['confirm-book-date'].' '.$times[0]);

				$book_end_time = strtotime($_POST['confirm-book-date'].' '.$times[1]);

				$doctor_price = $this->Search_doctor_model->getDoctorPrice($_POST['confirm-book-doctor']);

				$doctor_data = $this->Doctor_model->get_single_doctor($_POST['confirm-book-doctor']);



				$data = array('doctor_id' =>$_POST['confirm-book-doctor'] ,'clinic_id' =>$_POST['confirm-book-clinic'] ,'clinic_id' =>$_POST['confirm-book-clinic'],'patient_id' =>$userdata['id'] ,'date' =>strtotime($_POST['confirm-book-date']),'time' =>$_POST['confirm-book-time'],'amount'=>$doctor_price['price'],'requested_date'=>$now->getTimestamp(),'time_start'=>$book_start_time,'time_end'=>$book_end_time,'visit_type'=>0);



				if(isset($_POST['book-status'])&&$_POST['book-status']=="0")

				{

					$data['booking_status'] = 0;

				}

				else

				{

					$data['booking_status'] = 1;

				}

				$data['total_sum'] = $doctor_price['price'];

				if(($_POST['promocode-status']=='1') and ($_POST['promocode-name']!='0'))

				{

					$data['promo_name'] = $_POST['promocode-name'];

					$promo_value = $this->Search_doctor_model->get_promocode_value($_POST['promocode-name']);

					$offeramount = ($promo_value['amount']/100) * $doctor_price['price'];

					$data['promo_amount'] = $offeramount;

					$data['total_sum'] = $doctor_price['price'] - $offeramount;

				}

				/*CODE FOR DATA ENDS*/

				$return_inclusive = $this->Search_doctor_model->get_doc_retrun_inclusive($_POST['confirm-book-doctor']);



				

				if($return_inclusive['accept_return']=='1')

				{

					$check_previous_book = $this->Search_doctor_model->get_previous_book($_POST,$return_inclusive['return_timeperiod'],$userdata['id']);

					//print_r($check_previous_book);die();

					if($check_previous_book['visit_type']=='0' and $check_previous_book['free_visit_status']=='0') //Free Visit Found

					{

						

						$data['visit_type']=1; //New Booking is Free

						$data['payment_status'] = 1; //Setting payment done true

						$data['free_visit_status']=2; //Setting free status->not applicable

						$this->Search_doctor_model->mark_freevisit_status($check_previous_book['id']); //MARKING FREE VISIT STATUS OF PREVIOUS BOOKING TO USED



						

					}

					

				}



				$ipok_settings = $this->Home_model->get_ipok_settings();

				$data['ipok_fee'] = $ipok_settings['ipok_fee'];

				

				//print_r($check_return_book);

				//print_r($data);

				//die();

				$inserted_id = $this->Search_doctor_model->insertBooking($data); //MARK BOOKING



				if($data['visit_type']==1)

				{

					if($data['booking_status'] == 0)

					{

						/*CODE FOR SENTING WAITING LIST NOTIFICATION FOR FREE VISIT - PATIENT NOTIFICATION*/

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

						$text_pat = 'Your appointment was scheduled in the system as waiting, on '.date('d.m.Y',$book_start_time).' at '.date('H:i a',$book_start_time).', doctor '.$doctor_data['dr_name'];



						$notification_pat = array('patient_id' => $userdata['id'],'type'=>1,'message'=>$text_pat,'read_status'=>0,'time'=>strtotime($nowin_server),'booking_id' => $inserted_id);

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



						$fcm_user = $this->Home_model->get_patient_fcm($data['patient_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'] = "Waiting List";

							$pat_push_obj['booking_id'] = $inserted_id;

							$pat_push_obj['booking_date'] = $data['date'];

							$pat_push_obj['doctor_id'] = $data['doctor_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);

						}

						

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

					}

					else

					{

						/*CODE FOR SENTING NOTIFICATION FOR FREE VISIT - DOCTOR NOTIFICATION*/

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

						$text = 'A new appointment was scheduled in the system, on '.date('d.m.Y',$book_start_time).' at '.date('H:i a',$book_start_time).', patient '.$userdata['name'];



						$notification = array('doctor_id' => $data['doctor_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($data['doctor_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);

						}

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



						/*CODE FOR SENTING NOTIFICATION FOR FREE VISIT - PATIENT NOTIFICATION*/

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

						$text_pat = 'Your appointment was scheduled in the system, on '.date('d.m.Y',$book_start_time).' at '.date('H:i a',$book_start_time).', doctor '.$doctor_data['dr_name'];



						$notification_pat = array('patient_id' => $userdata['id'],'type'=>0,'message'=>$text_pat,'read_status'=>0,'time'=>strtotime($nowin_server),'booking_id' => $inserted_id);

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



						$fcm_user = $this->Home_model->get_patient_fcm($data['patient_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'] = $inserted_id;

							$pat_push_obj['booking_date'] = $data['date'];

							$pat_push_obj['doctor_id'] = $data['doctor_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);

						}

						

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

					}

					

				}



				$res = array('booking_id' =>$inserted_id , 'payment_required'=>$data['visit_type'],'booking_date'=>date('d/m/Y',strtotime($_POST['confirm-book-date'])),'booking_slot'=>$_POST['confirm-book-time']);

				print json_encode($res);

			}

		}

		

	}



	/*FUNCTION : PROMOCODE VALIDATION IN BOOKING MODULE - DOCTOR SEARCH*/

   /*DESCRIPTION : Function will check for validity of applied promocode,checks if its valid for passed doctor id*/

	public function promocode_validate()

	{

		//print_r($_POST);

		$validation = $this->Search_doctor_model->checkPromocode($_POST);

		$doc_list = explode(",",$validation['doctor_id']);

		if (in_array($_POST['doctorid'], $doc_list))

		  {

		  	$doctor_price = $this->Search_doctor_model->getDoctorPrice($_POST['doctorid']);

		  	$offeramount = ($validation['amount']/100) * $doctor_price['price'];

		  	$res = array('status' => 'success' ,'msg'=>load_language('promotion_success',true),'offeramount' =>$offeramount,'code'=>$validation['promo_name']);

 		  }

 		  else

 		  {

 		  	$res = array('status' => 'error','msg'=>load_language('invalid_promocode',true) );

 		  }

 		print json_encode($res);

	}



	/*FUNCTION : PAYMENT CONTROLLER IN BOOKING MODULE - DOCTOR SEARCH*/

   /*DESCRIPTION : Function will update the payment in booking table for respective booking entry*/

	public function booking_payment()

	{

		$check_markbooking = $this->Search_doctor_model->checkBooking($_POST['booking_id']);
		$booking_details = $this->Search_doctor_model->get_booking_details($_POST['booking_id']);
		$patient_data = $this->Patient_model->get_single_patient($booking_details['patient_id']);
		$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doctor_id']);
		//print_r($booking_details);die();
		parse_str($_POST['data'], $card_detail);	
		//print_r($card_detail);die();



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

		}



/*$payment_post = array('email' => 'jithin@techware.in' ,'due_date'=>'2018-05-18','items_total_cents' => 1000);




$payment_post['payer'] = array('cpf_cnpj' => $patient_data['pt_cpf'],'name' =>$patient_data['pt_name'],'email' => $patient_data['pt_email'] );

$payment_post['payer']['address'] = array('zip_code' => $patient_data['pt_zip_code'],'street'=>$patient_data['pt_street_add'],'number'=>$patient_data['pt_number'],'complement'=>$patient_data['pt_complement']);*/

//echo "<pre>";

$payment_token = array('account_id' => $this->config->item('id'),'method'=>'credit_card','test'=>true, );
$payment_token['data'] = array('number' => $card_detail['cardnumber'],'verification_value'=> $card_detail['cvv'],'first_name'=>$card_detail['firstname'],'last_name'=>$card_detail['lastname'],'month'=>$card_detail['month'],'year'=>$card_detail['year']);

/*print_r($payment_token);die();*/


	$request = load_curl('https://api.iugu.com/v1/payment_token',$payment_token);
	$token = json_decode($request);
if($check_markbooking['count']!=1)
{
	$res = array('status' => 'fail', 'payment_status'=>'0','message'=>load_language('no_booking_found/session_invalid',true));
}
elseif(!empty($token->errors->number))
{
	$res = array('status' => 'fail', 'payment_status'=>'0','message'=>load_language('invalid_credit_card',true));
}
else
{

	if(empty($patient_data['pt_customer_id']))
	{
		$create_customer = array('email'=>$patient_data['pt_email'],'name'=>$patient_data['pt_name'],'cpf_cnpj'=>$patient_data['pt_cpf'],'zip_code' => $patient_data['pt_zip_code'],'street'=>$patient_data['pt_street_add'],'number'=>$patient_data['pt_number'],'complement'=>$patient_data['pt_complement']);
		$request = load_curl('https://api.iugu.com/v1/customers',$create_customer);
		$customer = json_decode($request);	
		$this->Patient_model->update_profile($patient_data['patientid'],array('customer_id' => $customer->id ));
		$patient_data['pt_customer_id'] = $customer->id;
	}
	
	//print_r($patient_data);die();

	
	$create_payment_method = array('description' => 'Booking Payment','token'=> $token->id );
	$request = load_curl('https://api.iugu.com/v1/customers/'.$patient_data['pt_customer_id'].'/payment_methods',$create_payment_method);
	$payment_method = json_decode($request);
	//print_r($payment_method->id);


	$create_charge = array('customer_payment_method_id'=>$payment_method->id,'customer_id'=>$patient_data['pt_customer_id'],'email' =>$patient_data['pt_email']);

	$items = array('description' =>'Doctor Visit','price_cents' =>$booking_details['total_sum']*100,'quantity' => 1 );

	$create_charge['items'] = $items;
	$create_charge['payer'] = array('cpf_cnpj' => $patient_data['pt_cpf'],'name' =>$patient_data['pt_name'],'email' => $patient_data['pt_email'] );
	$create_charge['payer']['address'] = array('zip_code' => $patient_data['pt_zip_code'],'street'=>$patient_data['pt_street_add'],'number'=>$patient_data['pt_number'],'complement'=>$patient_data['pt_complement']);
	//print_r($create_charge);die();
	$request = load_curl('https://api.iugu.com/v1/charge',$create_charge);
	$charge =json_decode($request);
	//print_r($charge);
	

//print_r($res);
//die();

		if(isset($charge->success) and isset($charge->LR) and ($charge->success==true) and ($charge->LR=='00'))
		{

			/*CODE FOR DOCTOR NOTIFICATION ON CONFIRMED CONSULTATION*/

			/*CODE FOR WALLET INSERTION*/

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

			$wallet = $this->Doctor_model->get_wallet_for_doctor($booking_details['doctor_id']);

			if(empty($wallet))

			{

				$wallet = array('reedem_earn' => 0,'future_earn' => 0 ,'total_earn' => 0 );

			}

			$earn = $booking_details['total_sum'] - (($booking_details['total_sum'] * $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['doctor_id'],$wallet);

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



  			if($booking_details['booking_status'] == 0)

			{

				/*CODE FOR SENTING WAITING LIST NOTIFICATION FOR PAID VISIT - PATIENT NOTIFICATION*/

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

				$text_pat = 'Your appointment was scheduled in the system as waiting, on '.date('d.m.Y',$booking_details['time_start']).' at '.date('H:i a',$booking_details['time_start']).', doctor '.$doctor_data['dr_name'];



				$notification_pat = array('patient_id' => $booking_details['patient_id'],'type'=>0,'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['patient_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'] = "Waiting List";

					$pat_push_obj['booking_id'] = $_POST['booking_id'];

					$pat_push_obj['booking_date'] = $booking_details['date'];

					$pat_push_obj['doctor_id'] = $booking_details['doctor_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);

				}

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



			}

			else

			{

		  	/*CODE FOR SENTING NOTIFICATION - DOCTOR NOTIFICATION*/

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

			$text = 'A new appointment was scheduled in the system, on '.date('d.m.Y',$booking_details['time_start']).' at '.date('H:i a',$booking_details['time_start']).', patient '.$patient_data['pt_name'];



			$notification = array('doctor_id' => $booking_details['doctor_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['doctor_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);

			}

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



			/*CODE FOR SENTING NOTIFICATION  - PATIENT NOTIFICATION*/

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

			$text_pat = 'Your appointment was 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'];



			$notification_pat = array('patient_id' => $booking_details['patient_id'],'type'=>0,'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['patient_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'] = $_POST['booking_id'];

				$pat_push_obj['booking_date'] = $booking_details['date'];

				$pat_push_obj['doctor_id'] = $booking_details['doctor_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);

			}

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

			}

			$result = $this->Search_doctor_model->set_payment_status($_POST['booking_id']);

			$res = array('status' => 'success', 'payment_status'=>'1','message'=>'payment success','booking_date'=>date('d/m/Y',$check_markbooking['booking_date']),'booking_slot'=>$check_markbooking['booking_slot']);
		}
		else

		{

			// $res = array('status' => 'fail', 'payment_status'=>'0','message'=>$charge->message);
			$res = array('status' => 'fail', 'payment_status'=>'0','message'=>$charge->errors);

		}
	}

		//print_r($res);die();

		print json_encode($res);

	}



	/*FUNCTION : FETCH APPIONTMENTS IN DOCTOR PROFILE VIEW - DOCTOR SEARCH*/

   /*DESCRIPTION : Fetching all next appointments*/

	public function doctor_complete_profile_appointments_week_next()
	{
		$day_appointments = array();
		for ($i=0; $i < 7; $i++) 
		{ 
			$day = date('D',strtotime('+'.$i.'day', strtotime($_POST['enddate'])));
			$dayno = date('d',strtotime('+'.$i.'day', strtotime($_POST['enddate'])));
			$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($_POST['doctor_id'],date('y-m-d',strtotime('+'.$i.'day', strtotime($_POST['enddate']))));    
		}

		//print_r($week_appointments);

		$template['week_appointments'] = $week_appointments;

		$template['start_day'] = $_POST['enddate'];

		$template['doctorid'] = $_POST['doctor_id'];

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

	}



	/*FUNCTION : FETCH APPIONTMENTS IN DOCTOR PROFILE VIEW - DOCTOR SEARCH*/

   /*DESCRIPTION : Fetching all prev appointments*/

	public function doctor_complete_profile_appointments_week_prev()

	{

		$day_appointments = array();

		for ($i=6; $i >=0; $i--) 

		{ /*date('y-m-d', strtotime('-7 days'))*/

			$day = date('D',strtotime('+'.$i.'day', strtotime($_POST['startdate'])));

			$dayno = date('d',strtotime('+'.$i.'day', strtotime($_POST['startdate'])));

			$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($_POST['doctor_id'],date('y-m-d',strtotime('-'.$i.'day', strtotime($_POST['startdate'],strtotime('-7 days')))));

			/*print_r(date('y-m-d',strtotime('-'.$i.'day', strtotime($_POST['startdate']))));      */

		}

		//print_r($week_appointments);die();

		$template['week_appointments'] = $week_appointments;

		$template['start_day'] = date('y-m-d',strtotime('-6day', strtotime($_POST['startdate'])));

		//print_r($template);die();

		$template['doctorid'] = $_POST['doctor_id'];

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

	}

	

	

	

	

}

