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

class ManageClinic extends CI_Controller {

	public function __construct() {
		parent::__construct();
		if(!can_access_page()) {
			redirect(base_url()."error");
		}
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		
		}
		$this->load->model('Webservice_model');
		$this->load->model('Clinic_model');
		$this->load->model('Doctor_model');
		//date_default_timezone_set("Asia/Kolkata");
		global  $string;  
		$this->load->helper('file');
		$string = read_file('commonData.php');
		$this->string = json_decode($string);
		$this->logData = $this->session->userdata('logged_in');	 
 	}
	
	public function index() {
	    
		if(isset($_POST) && !empty($_POST)){
			$Newdata =array();
			$data = $_POST;
			//print_r($data);exit();
			$Newdata['email'] = $data['reg_clnc_email'];	
    		$Newdata['cep'] = $data['reg_clnc_cep'];
    		$Newdata['street_address'] = $data['reg_clnc_streetadd'];
    		$Newdata['locality'] = $data['reg_clnc_locality'];
    		$Newdata['number'] = $data['reg_clnc_number'];
    		$Newdata['complement'] = $data['reg_clnc_complement'];
    		$Newdata['name'] = $data['reg_clnc_name'];
    		$Newdata['username'] = $data['reg_clnc_username'];
    		$Newdata['password'] = $data['reg_clnc_password'];
    		$Newdata['about'] = $data['reg_clnc_about'];
    		$Newdata['location_lattitude'] = $data['clnc_latitude'];
    		$Newdata['location_longitude'] = $data['clnc_longitude'];  		   	
			$res = $this->main_Registration($Newdata);
			if($res['status'] == 'success'){
				$this->session->set_flashdata('message', array('message' => 'Successfully Registered', 'title' => 'Success !', 'class' => 'success'));
			}
			else{
				$this->session->set_flashdata('message', array('message' => $res['message'], 'title' => 'Warning !', 'class' => 'warning'));
			}
		}
		$allCilinics = $this->Clinic_model->get_all_clinic();
		$template['page'] = "ManageClinic/addClinic";
		$template['page_title'] = "Add Clinic Page";
		$template['data'] = $allCilinics;
		$this->load->view('template', $template);
	}
	function main_Registration($data){

				$check_result = $this->Clinic_model->dataExist($data);
				if($check_result['message'] == 'success')
				{	
					$data['password'] = md5($data['password']);
					$result = $this->Clinic_model->register($data);
					if($result['status'] == 'success'){
						$fileName = $result['userdata']['id'].'_'.$_FILES['profile_pic']['name'];
						$config = set_upload_options('../assets/uploads/profilepic/clinic'); 
			         	$config['file_name'] = $fileName;
			         	$this->load->library('upload', $config);
				         if ( ! $this->upload->do_upload('profile_pic')) {
				            $error = array('error' => $this->upload->display_errors('', '')); 
				            $res = array(
									"status"=> "error",
									"error"=> "Upload Error",
									"message"=> "Sorry! Profile Photo not uploaded".$error['error']
								);	
				            $this->Clinic_model->delete_registration($result['userdata']['id']);
				         }	
				         else { 
				            $imagedata = $this->upload->data(); 
				            $fullfilepath='assets/uploads/profilepic/clinic/'.$imagedata['file_name'];	           
				            $res=$this->mainFn($result,$fullfilepath,'');				              
						}
					}
					else{
						$res = array(
										"status"=> "error",
										"error"=> "Insertion is failed",
										"message"=> "Sorry! Insertion is failed"
									);			
					}
				}
				else{
					$res = array(
									"status"=> "error",
									"error"=> "already exist",
									"message"=> $check_result['message']
								);
				}
				return $res;
	 		}

		 	function mainFn($result,$fullfilepath,$fullfilepath_bystander){

				//date_default_timezone_set("Asia/Kolkata");
				$static_string = 'IPOK_Clinic'.time();
				$authToken = uniqid($static_string);
				$result_authtoken = $this->Clinic_model->authtoken_registration($authToken,$result['userdata']['id']);
				if($result_authtoken){
					$picdata = array('profile_photo'=>$fullfilepath);
					$this->Clinic_model->updatePic($picdata,$result['userdata']['id']);					
					$res = array(
						"status"=> "success",
						"data"=>array(
							"auth_token"=>$authToken,
							"user"=>array(						
								
							)
						)
					);
				}
				return $res;
			}
			function addDoctor(){
				
				$id = $_GET['id'];
				$alldoctors = $this->Doctor_model->get_all_doctor();
				$all_existdoctors = $this->Clinic_model->get_exist_doctor($id);
				
				foreach ($alldoctors as $key => $value) {
					
					foreach ($all_existdoctors as $keyy => $valuee) {
						if($value['id'] == $valuee['doctor_id']){					
							$newkey = array_search($value['id'], array_column($alldoctors, 'id'));		
							array_splice($alldoctors,$newkey,1);							
						}
					}
				}				
				$template['page'] = "ManageClinic/addDoctors";
				$template['page_title'] = "Assign Doctor Page";
				$template['data'] = $alldoctors;
				$template['data_id'] = $id;
				$this->load->view('template', $template);
			}
			function exist(){
				$data = $_POST;
				$check_result = $this->Clinic_model->dataExist($data);
				print json_encode($check_result);
			}
			/*function assignDoctors(){
				if(isset($_POST) && !empty($_POST)){
                 
					$insert_array = array();
					$not_available_day = array();
					$flag = 0;
					$request = $_POST;	
					$this->Clinic_model->update_duration($request['doctors'],$request['duration']);
					if(!empty($request['day'])){
						$result = $this->Clinic_model->checkDoctorExist($request['doctors'],$request['clinicId']);
						//print_r($result);exit();
						if(!empty($result)){					

							foreach ($result as $key => $value) {
								
									//foreach ($request['doctors'] as $key_docId => $value_docId) {
										
										if($value['doctor_id'] == $request['doctors']){
											$insert_array_exist = array();
											foreach ($request['day'] as $key_day => $value_day) {
												if(isset($value['date'])){
												  
													$decode_time = json_decode($value['date'],true);
													$startTime = $value_day.'_startTime';
													$endTime = $value_day.'_endTime';
													//$interval = $value_day.'_intervalTime';
													$breakfrom = $value_day.'_Breakfrom';
													$breakto = $value_day.'_Breakto';
													if($request[$breakfrom] != ''){
														$break_from = $request[$breakfrom];
													}
													else{
														$break_from = '';
													}

													if($request[$breakto] != ''){
														$break_to = $request[$breakto];
													}
													else{
														$break_to = '';
													}									
													if(!empty($decode_time)){
													    foreach ($decode_time as $k => $v) {
														if($value_day == $v['day']){
															if((strtotime($this->string->default_date.$v['time']['start']) <= strtotime($this->string->default_date.$request[$startTime ]) && strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['end'])) || (strtotime($this->string->default_date.$v['time']['start']) <= strtotime($this->string->default_date.$request[$endTime]) && strtotime($this->string->default_date.$request[$endTime ]) <= strtotime($this->string->default_date.$v['time']['end'])) || (strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['start']) && strtotime($this->string->default_date.$v['time']['start']) <=strtotime($this->string->default_date.$request[$endTime])) || (strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['end']) && strtotime($this->string->default_date.$v['time']['end']) <= strtotime($this->string->default_date.$request[$endTime]))){
															
																array_push($not_available_day , array('day'=>$value_day,'id'=>$request['doctors']));

																$flag = 1;

															}
															else{
																
																$res = array('day'=>$value_day,
																			'time'=>array('start'=>$request[$startTime ],
																					'end'=>$request[$endTime],
																					'interval'=>$request['duration'],
																					'break_from'=>$break_from,
																					'break_to'=>$break_to));
																array_push($insert_array_exist,$res);

																
															}
														}
														else if(!in_array($value_day, $v)){
																$res = array('day'=>$value_day,
																			'time'=>array('start'=>$request[$startTime ],
																					'end'=>$request[$endTime],
																					'interval'=>$request['duration'],
																					'break_from'=>$break_from,
																					'break_to'=>$break_to));
																array_push($insert_array_exist,$res);
														}
													}
													}		
																					
												}										
											}
										}
									//}
							}
							if($flag ==0 && !empty($insert_array_exist))
							{
											
								$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
								$this->Clinic_model->set_new_consultation($insert_array_exist,$request['clinicId'],$request['doctors']);
								$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
							redirect(base_url()."ManageClinic/view");
							}
							else
							{	
							  
								$this->session->set_flashdata('message', array('message' => 'Selected Doctors are not available at this time schedule', 'title' => 'Error !', 'class' => 'danger'));
								redirect(base_url()."ManageClinic/addDoctor?id=".$request['clinicId']);
							}											
												
						}
						else{
							foreach ($request['day'] as $key_elseDay => $value_elseDay) {
								
								$start = $value_elseDay.'_startTime';
								$end = $value_elseDay.'_endTime';
								$interval = $value_elseDay.'_intervalTime';
								
								$res = array('day'=>$value_elseDay,
											'time'=>array('start'=>$request[$start],
												'end'=>$request[$end],
												'interval'=>$request[$interval]));
								array_push($insert_array, $res);
							}
							$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
							$this->Clinic_model->set_new_consultation($insert_array,$request['clinicId'],$request['doctors']);
							$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
							if($this->session->userdata('logged_in')['uType'] != 'clinic'){

							redirect(base_url()."ManageClinic/view");
							}
							else{
								redirect(base_url()."ManageDoctors/view");
							}
						}
					}
					else{

						$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
						$this->Clinic_model->set_new_consultation('',$request['clinicId'],$request['doctors']);
						$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
						if($this->session->userdata('logged_in')['uType'] != 'clinic'){

							redirect(base_url()."ManageClinic/view");
						}
						else
						{
							redirect(base_url()."ManageDoctors/view");
						}
					}				
				}
				else{
					redirect(base_url()."error");
				}
			}*/

	function assignDoctors(){
		if(isset($_POST) && !empty($_POST)){
                 
			$insert_array = array();
			$not_available_day = array();
			$flag = 0;
			$request = $_POST;	
	//	echo"<pre>";	print_r($request); echo"</pre>";exit();
		if($request['doctors'] == '0'){
			$this->session->set_flashdata('message', array('message' => 'All Field is required', 'title' => 'Error !', 'class' => 'danger'));
			redirect(base_url()."ManageClinic/addDoctor?id=".$request['clinicId']);
		}else{
			if(isset($request['duration']) && $request['duration'] != ''){
				$this->Clinic_model->update_duration($request['doctors'],$request['duration']);
			}
			else{
				$dur = $this->Clinic_model->get_doctor_duration($request['doctors']);
				$request['duration'] = $dur->consultation_duration;
			}
			if(!empty($request['day'])){
			//echo "no"; exit();
				$result = $this->Clinic_model->checkDoctorExist($request['doctors'],$request['clinicId']);
				if(!empty($result)){
					foreach ($result as $key => $value) {
						if($value['doctor_id'] == $request['doctors']){
							$insert_array_exist = array();
							foreach ($request['day'] as $key_day => $value_day) {
								//print_r($key_day);echo "new";print_r($value_day);
								if(isset($value['date']) && $value['date'] != '""'){
									$decode_time = json_decode($value['date'],true);
									//echo"<pre>";print_r($decode_time); echo "</pre>";
									$startTime = $value_day.'_startTime';
									$endTime = $value_day.'_endTime';
									$breakfrom = $value_day.'_Breakfrom';
									$breakto = $value_day.'_Breakto';
									if(isset($request[$breakfrom])){
										$break_from = $request[$breakfrom];
									}
									else{
										$break_from = 'null';
									}

									if(isset($request[$breakto])){
										$break_to = $request[$breakto];
									}
									else{
										$break_to = 'null';
									}	
                                     $result = array();
                                   foreach ($decode_time as $k => $v) {
                                   		if($value_day == $v['day']){ 
                                   			if((strtotime($this->string->default_date.$v['time']['start']) <= strtotime($this->string->default_date.$request[$startTime ]) && strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['end'])) || (strtotime($this->string->default_date.$v['time']['start']) <= strtotime($this->string->default_date.$request[$endTime]) && strtotime($this->string->default_date.$request[$endTime ]) <= strtotime($this->string->default_date.$v['time']['end'])) || (strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['start']) && strtotime($this->string->default_date.$v['time']['start']) <=strtotime($this->string->default_date.$request[$endTime])) || (strtotime($this->string->default_date.$request[$startTime ]) <= strtotime($this->string->default_date.$v['time']['end']) && strtotime($this->string->default_date.$v['time']['end']) <= strtotime($this->string->default_date.$request[$endTime]))){
																
												array_push($not_available_day , array('day'=>$value_day,'id'=>$request['doctors']));
												$flag = 1;

											}
											else{
												//echo "enter else no";
												$res = array('day'=>$value_day,
															'time'=>array('start'=>$request[$startTime ],
																	'end'=>$request[$endTime],
																	'interval'=>$request['duration'],
																	'break_from'=>$break_from,
																	'break_to'=>$break_to
																));
												array_push($insert_array_exist,$res);
											}
									
										}
										$result[] = $v['day'];
                                   }
                                   if(!in_array($value_day, $result)){
                                   		$res = array('day'=>$value_day,
															'time'=>array('start'=>$request[$startTime ],
																	'end'=>$request[$endTime],
																	'interval'=>$request['duration'],
																	'break_from'=>$break_from,
																	'break_to'=>$break_to
																));
										array_push($insert_array_exist,$res);
                                    }
								}
						//if schedule for that doctor in that clinic is null
								if( $value['date'] == '""'){
									$startTime = $value_day.'_startTime';
									$endTime = $value_day.'_endTime';
									$breakfrom = $value_day.'_Breakfrom';
									$breakto = $value_day.'_Breakto';
									if(isset($request[$breakfrom])){
										$break_from = $request[$breakfrom];
									}
									else{
										$break_from = 'null';
									}

									if(isset($request[$breakto])){
										$break_to = $request[$breakto];
									}
									else{
										$break_to = 'null';
									}
									$res = array('day'=>$value_day,
															'time'=>array('start'=>$request[$startTime ],
																	'end'=>$request[$endTime],
																	'interval'=>$request['duration'],
																	'break_from'=>$break_from,
																	'break_to'=>$break_to
																));
									array_push($insert_array_exist,$res);
								}
							}
						}
					}
					// echo"<pre>";print_r($insert_array_exist);echo"</pre>";exit();
					 //echo "<br>"; echo $flag;
					if($flag ==0 && !empty($insert_array_exist))
						{		
							// echo"<pre>";print_r($insert_array_exist);echo"</pre>";
							$this->Clinic_model->get_doctor_specialization($request['doctors'],$request['clinicId']);
							$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
							$this->Clinic_model->set_new_consultation($insert_array_exist,$request['clinicId'],$request['doctors']);
							$this->Clinic_model->set_notification($request['doctors'],$request['clinicId']);
							$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
							redirect(base_url()."ManageClinic/view");
						}
						else
						{	
						 // echo "no";exit();
							$this->session->set_flashdata('message', array('message' => 'Selected Doctors are not available at this time schedule', 'title' => 'Error !', 'class' => 'danger'));
							redirect(base_url()."ManageClinic/addDoctor?id=".$request['clinicId']);
						}				
				}else{
					foreach ($request['day'] as $key_elseDay => $value_elseDay) {
						$start = $value_elseDay.'_startTime';
						$end = $value_elseDay.'_endTime';
						$breakfrom = $value_elseDay.'_Breakfrom';
						$breakto = $value_elseDay.'_Breakto';
						if(isset($request[$breakfrom])){
							$break_from = $request[$breakfrom];
						}
						else{
							$break_from = 'null';
						}
						
						if(isset($request[$breakto])){
							$break_to = $request[$breakto];
						}
						else{
							$break_to = 'null';
						}
						
						$res = array('day'=>$value_elseDay,
						'time'=>array('start'=>$request[$start],
						'end'=>$request[$end],
						'interval'=>$request['duration'],
						'break_from'=>$break_from,
						'break_to'=>$break_to
					));
						
						array_push($insert_array, $res);
						//print_r($insert_array);exit();
					}
					$this->Clinic_model->get_doctor_specialization($request['doctors'],$request['clinicId']);
					$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
					$this->Clinic_model->set_new_consultation($insert_array,$request['clinicId'],$request['doctors']);
					$this->Clinic_model->set_notification($request['doctors'],$request['clinicId']);
					$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
					if($this->session->userdata('logged_in')['uType'] != 'clinic'){
						
						redirect(base_url()."ManageClinic/view");
					}
					else{
						redirect(base_url()."ManageDoctors/view");
					}
				}
			}else{
			//echo "yes"; exit();
				$this->Clinic_model->get_doctor_specialization($request['doctors'],$request['clinicId']);
				$this->Clinic_model->assignDoctors($request['doctors'],$request['clinicId']);
				$this->Clinic_model->set_new_consultation('',$request['clinicId'],$request['doctors']);
				$this->Clinic_model->set_notification($request['doctors'],$request['clinicId']);
				$this->session->set_flashdata('message', array('message' => 'Successfully assigned', 'title' => 'Success !', 'class' => 'success'));
				if($this->session->userdata('logged_in')['uType'] != 'clinic'){

					redirect(base_url()."ManageClinic/view");
				}
				else
				{
					redirect(base_url()."ManageDoctors/view");
				}
			}
		}
		}else{
			redirect(base_url()."error");
		}
	}

			function view(){
				$allCilinics = $this->Clinic_model->get_all_clinic();
				$template['page'] = "ManageClinic/viewClinic";
				$template['page_title'] = "View Clinic Page";
				$template['data'] = $allCilinics;
				$this->load->view('template', $template);
			}
			function delete(){
				$clinicid = $_GET['id'];
				$delete = $this->Clinic_model->deleteClinic($clinicid);
				if($delete){
					$this->session->set_flashdata('message', array('message' => 'Successfully Deleted', 'title' => 'Success !', 'class' => 'success'));
					redirect(base_url()."ManageClinic/view");
				}
				else if(!$delete){
					$this->session->set_flashdata('message', array('message' => 'Database Error', 'title' => 'Error !', 'class' => 'danger'));
					redirect(base_url()."ManageClinic/view");
				}
			}

			public function get_doctor_duration(){
				$result = $this->Clinic_model->get_doctor_duration($_POST['id']);

/*
				if($result->consultation_duration == '0'){
					$results = '<option value="-1">Select Duration</option>';
				}else{
				$results = '';
			        foreach ($result as $sub) {
			            $results .= '<option value="' . $result->consultation_duration . '">' . $result->consultation_duration . ' </option>';
			        }
		   		}*/
		        echo $result->consultation_duration;
			}

			function edit(){
				$clinicid = $_GET['id'];	
				if($clinicid == ''){
					redirect(base_url()."ManageClinic/view");
				}else{	
					if(isset($_POST) && !empty($_POST)){					
						$data = $_POST;
						//print_r($data);exit();
						$Newdata['email'] = $data['reg_clnc_email'];		
			    		$Newdata['cep'] = $data['reg_clnc_cep'];
			    		$Newdata['street_address'] = $data['reg_clnc_streetadd'];
			    		$Newdata['locality'] = $data['reg_clnc_locality'];
			    		$Newdata['number'] = $data['reg_clnc_number'];
			    		$Newdata['complement'] = $data['reg_clnc_complement'];
			    		$Newdata['name'] = $data['reg_clnc_name'];
			    		$Newdata['about'] = $data['reg_clnc_about'];
			    		$Newdata['location_lattitude'] = $data['clnc_latitude'];
			    		$Newdata['location_longitude'] = $data['clnc_longitude'];    		
				   		$check_result = $this->Clinic_model->updateClinic($Newdata,$clinicid);
						if($check_result['message'] == 'success')
						{						
							if(isset($_FILES['profile_pic']['name']) && strlen($_FILES['profile_pic']['name'])){
									$fileName = $clinicid.'_'.$_FILES['profile_pic']['name'];
									$config = set_upload_options('../assets/uploads/profilepic/clinic'); 
				         			$config['file_name'] = $fileName;
				         			$this->load->library('upload', $config);
					         		if ( $this->upload->do_upload('profile_pic')) {
					            		$imagedata = $this->upload->data(); 
					            		$fullfilepath='assets/uploads/profilepic/clinic/'.$imagedata['file_name'];
					            		$picdata = array('profile_photo'=>$fullfilepath);
										$this->Clinic_model->updatePic($picdata,$clinicid);
					         		}
							}
							$this->session->set_flashdata('message', array('message' => 'Successfully Update Clinic', 'title' => 'Success !', 'class' => 'success'));
						}
						else{
							$this->session->set_flashdata('message', array('message' => 'Email Id already exist', 'title' => 'Warning !', 'class' => 'warning'));
						}					
					}
				
					$get_single_clinic = $this->Clinic_model->get_single_clinic($clinicid);
					if($get_single_clinic['status'] == 'success'){
						$template['page'] = "ManageClinic/editClinic";
						$template['page_title'] = "Edit Clinic Page";
						$template['data'] = $get_single_clinic['data'];
						$this->load->view('template', $template);
					}
				}
			}
			function bookingList(){
					
					$booking_list = $this->Clinic_model->get_bookinglist($this->logData['id']);
					//print_r($booking_list);die();
					$template['page'] = "ManageClinic/bookingList";
					$template['page_title'] = "Booking List Page";
					$template['data'] = $booking_list;
					$this->load->view('template', $template);
			}
}