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

 	if (isset($_SERVER['HTTP_ORIGIN'])) {
       header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
       header('Access-Control-Allow-Credentials: true');
       header('Access-Control-Max-Age: 86400');    // cache for 1 day
   	}    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");        exit(0);
    }

class Webservice extends CI_Controller {

	
	public function __construct() {
		parent::__construct();
		
//		date_default_timezone_set("Asia/Kolkata");
		header('Content-Type: application/json');
		$this->load->model('Webservice_model');
		$this->load->helper(array('form', 'url')); 
		$this->load->library('email');
		
 	}
/*............................................... IPOK PATIENT API ...............................................*/

/*......................................... For User Registration ................................................*/

 	function main_Registration($data){

		$check_result = $this->Webservice_model->dataExist($data);
		if($check_result['message'] == 'success')
		{	
			$data['password'] = md5($data['password']);
			$result = $this->Webservice_model->registration($data);
			if($result['status'] == 'success'){
				$fileName = $result['userdata']['id'].'_'.$_FILES['profile_photo']['name'];
				$config = set_upload_options('./assets/uploads/profilepic/'); 
	         	$config['file_name'] = $fileName;
	         	$this->load->library('upload', $config);
		        if ( ! $this->upload->do_upload('profile_photo')) {
		            $error = array('error' => $this->upload->display_errors('', '')); 
		            $res = array(
							"status"=> "error",
							"error"=> "Upload Error",
							"message"=> "Sorry! Profile Photo not uploaded".$error['error']
						);	
		            $this->Webservice_model->delete_registration($result['userdata']['id']);
		        }	
		        else { 
		         	
		            $imagedata = $this->upload->data(); 
		            $fullfilepath='assets/uploads/profilepic/'.$imagedata['file_name'];
		            if(isset($_FILES['bystander_profile_photo'])){
		            	$fileName = $result['userdata']['id'].'_'.$_FILES['bystander_profile_photo']['name'];
		            	$config = set_upload_options('./assets/uploads/profilepic/bystander/'); 
			         	$config['file_name'] = $fileName;
			         	$this->upload->initialize($config);
			         	$this->load->library('upload', $config);
			        	if(! $this->upload->do_upload('bystander_profile_photo')){
			        		 $error = array('error' => $this->upload->display_errors('', '')); 
				            $res = array(
									"status"=> "error",
									"error"=> "Upload Error",
									"message"=> "Sorry! ByStander Profile Photo not uploaded".$error['error']
								);	    
				            $this->Webservice_model->delete_registration($result['userdata']['id']); 
			        	}
			        	else{
			        		$imagedata_bystander = $this->upload->data(); 
		            		$fullfilepath_bystander = 'assets/uploads/profilepic/bystander/'.$imagedata_bystander['file_name'];
		            		$res=$this->mainFn($result,$fullfilepath,$fullfilepath_bystander);
			        	}
		            }
		            else{
		            	$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_User'.time();
		$authToken = uniqid($static_string);
		$result_authtoken = $this->Webservice_model->authtoken_registration($authToken,$result['userdata']['id']);
		if($result_authtoken){
			$picdata = array('profile_photo'=>$fullfilepath);
			$this->Webservice_model->updatePic($picdata,$result['userdata']['id']);
			if($fullfilepath_bystander){
				$picdata_bystander = array('bystander_profile_photo'=>$fullfilepath_bystander);
				$this->Webservice_model->updatePic($picdata_bystander,$result['userdata']['id']);
			}
			$res = array(
				"status"=> "success",
				"data"=>array(
					"auth_token"=>$authToken,
					"user"=>array(
						"user_id"=> $result['userdata']['id'],
						"name"=> $result['userdata']['name'],
						"username"=> $result['userdata']['username'],
						"email"=> $result['userdata']['email'],
						"password" => $result['userdata']['password'],
						"cpf" => $result['userdata']['cpf'],
						"rg" => $result['userdata']['rg'],
						"dob" => $result['userdata']['dob'],
						"gender" => $result['userdata']['gender'],
						"weight" => $result['userdata']['weight'] ,
						"height" => $result['userdata']['height'], 
						"blood_group" => $result['userdata']['blood_group'],
						"zip_code" => $result['userdata']['zip_code'],
						"street_address" => $result['userdata']['street_address'],
						"locality" => $result['userdata']['locality'],
						"number" => $result['userdata']['number'],
						"landmark" =>$result['userdata']['landmark'],
						"profile_photo" => $fullfilepath,
						"bystander_name" => $result['userdata']['bystander_name'],
						"bystander_relation" => $result['userdata']['bystander_relation'],
						"bystander_cpf" => $result['userdata']['bystander_cpf'],
						"bystander_dob" => $result['userdata']['bystander_dob'],
						"bystander_profile_photo" => $fullfilepath_bystander
					)
				)
			);
		}
		return $res;
	}


	public function registration(){
		//header('Content-type: application/json');
	//	$data =(array) json_decode(file_get_contents("php://input"));
		$data = $_POST;		
		//print_r($data);die();
		if(isset($data['name']) && strlen($data['name']) && isset($data['username']) && strlen($data['username']) && isset($data['email']) && strlen($data['email']) && isset($data['password']) && strlen($data['password']) && isset($data['dob']) && strlen($data['dob']) && isset($data['gender']) && strlen($data['gender']) && isset($data['zip_code']) && strlen($data['zip_code']) && isset($data['street_address']) && strlen($data['street_address']) && isset($data['locality']) && strlen($data['locality']) && isset($data['number']) && strlen($data['number']) && isset($_FILES['profile_photo']))
		{
			$res = $this->main_Registration($data);
		}
		else{
			$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Sorry! Registration is failed"
							);
		}			
		print json_encode($res);
	}
	
/*..............................................................................................................*/	



/*................................................. User Login ..................................................*/


	function login(){
		$data =(array) json_decode(file_get_contents("php://input"));
		//$data=$_POST;

		if(isset($data['username']) && strlen($data['username']) && isset($data['password']) && strlen($data['password']))
		{
			$result=$this->Webservice_model->login($data);
			if($result['status']=='success'){
				$res = array(
							"status"=> "success",
							"data"=>array(
								"auth_token"=>$result['userdata']['authtoken'],
								"user"=>array(
									"user_id"=> $result['userdata']['userid'],
									"name"=> $result['userdata']['name'],
									"username"=> $result['userdata']['username'],
									"email"=> $result['userdata']['email'],
									"password" => $result['userdata']['password'],
									"cpf" => $result['userdata']['cpf'],
									"rg" => $result['userdata']['rg'],
									"dob" => $result['userdata']['dob'],
									"gender" => $result['userdata']['gender'],
									"weight" => $result['userdata']['weight'] ,
									"height" => $result['userdata']['height'], 
									"blood_group" => $result['userdata']['blood_group'],
									"zip_code" => $result['userdata']['zip_code'],
									"street_address" => $result['userdata']['street_address'],
									"locality" => $result['userdata']['locality'],
									"number" => $result['userdata']['number'],
									"landmark" =>$result['userdata']['landmark'],
									"profile_photo" => $result['userdata']['profile_photo'],
									"bystander_name" => $result['userdata']['bystander_name'],
	                                "bystander_relation" => $result['userdata']['bystander_relation'],
	                                "bystander_cpf" => $result['userdata']['bystander_cpf'],
	                                "bystander_dob" => $result['userdata']['bystander_dob'],
	                                "bystander_profile_photo" => $result['userdata']['bystander_profile_photo'],

									)
								)
							);
			}
			else{
				$res = array(
								"status"=> "error",
								"error"=> "Login Failed",
								"message"=> "Invalid username or Password"
							);
			}
		}
		else{
			$res = array(
								"status"=> "error",
								"error"=> "Login Failed",
								"message"=> "Invalid username or Password"
							);
		}
		print json_encode($res);

	}

/*........................................................................................................... */


/*.......................................... Facebook Registration/Login .................................... */


	function facebook_login() {
		$data =(array) json_decode(file_get_contents("php://input"));
		//$data=$_POST;
		if(isset($data['uid']) && strlen($data['uid']) && isset($data['access_token']) && strlen($data['access_token']) && isset($data['name']) && strlen($data['name']) && isset($data['gender']) && strlen($data['gender'])  && isset($data['email']) && strlen($data['email']) && isset($data['profile_photo']) && strlen($data['profile_photo']))
		{
			$check_result = $this->Webservice_model->email_exist($data['email']);
			if($check_result['status'] == 'exist'){
				$userData = $this->Webservice_model->get_userdata($data['email']);
				if($userData['status']=='success'){
					$res = array(
							"status"=> "success",
							"data"=>array(
								"auth_token"=>$userData['userdata']['authtoken'],
								"user"=>array(
									"user_id"=> $userData['userdata']['userid'],
									"name"=> $userData['userdata']['name'],
									"username"=> $userData['userdata']['username'],
									"email"=> $userData['userdata']['email'],
									"password" => $userData['userdata']['password'],
									"cpf" => $userData['userdata']['cpf'],
									"rg" => $userData['userdata']['rg'],
									"dob" => $userData['userdata']['dob'],
									"gender" => $userData['userdata']['gender'],
									"weight" => $userData['userdata']['weight'] ,
									"height" => $userData['userdata']['height'], 
									"blood_group" => $userData['userdata']['blood_group'],
									"zip_code" => $userData['userdata']['zip_code'],
									"street_address" => $userData['userdata']['street_address'],
									"locality" => $userData['userdata']['locality'],
									"number" => $userData['userdata']['number'],
									"landmark" =>$userData['userdata']['landmark'],
									"profile_photo" => $userData['userdata']['profile_photo'],
									"bystander_name" => $userData['userdata']['bystander_name'],
	                                "bystander_relation" => $userData['userdata']['bystander_relation'],
	                                "bystander_cpf" => $userData['userdata']['bystander_cpf'],
	                                "bystander_dob" => $userData['userdata']['bystander_dob'],
	                                "bystander_profile_photo" => $userData['userdata']['bystander_profile_photo'],
	                                "is_registration_completed" => true

									)
								)
							);
				}
				else if($userData['status'] == 'fail'){
					$res = array(
								"status"=> "error",
								"error"=> "Invalid data",
								"message"=> "Social Login Failed"
							);
				}
			}
			else if($check_result['status'] == 'not exist')
			{					
				$res = array(
							"status"=> "success",
							"data"=>array(
								"auth_token"=>"",
								"user"=>array(
									"user_id"=> "",
									"name"=> "",
									"username"=> "",
									"email"=> "",
									"password" => "",
									"cpf" => "",
									"rg" => "",
									"dob" => "",
									"gender" => "",
									"weight" => "" ,
									"height" => "", 
									"blood_group" =>"",
									"zip_code" => "",
									"street_address" => "",
									"locality" => "",
									"number" => "",
									"landmark" => "",
									"profile_photo" => "",
									"bystander_name" => "",
									"bystander_relation" => "",
									"bystander_cpf" => "",
									"bystander_dob" => "",
									"bystander_profile_photo" => "",
									"is_registration_completed" => false
								)
							)
						);
			}
		}
		else{
			$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Facebook Login is failed"
						);
		}
		print json_encode($res);
	}


/*........................................................................................................... */


/*..................................... Check Email and Username Availability ................................ */


	function check_availability(){

		$data =(array) json_decode(file_get_contents("php://input"));
		//$data = $_POST;
		//print json_encode($data);die();

	 	//print_r($data);die();
		// if(isset($data['username']) && strlen($data['username'])){
			
		// }
		// if(isset($data['username']) && strlen($data['username']) && isset($data['email']) && strlen($data['email']))
		// {
		$check_result = $this->Webservice_model->dataExist($data);
		if(!isset($data['username'])){
			$data['username'] = '';
		}
		if(!isset($data['email'])){

			$data['email'] = '';
		}
		$res = '';
		$return_data = array(
							"email"=> $data['email'],
							"username" =>  $data['username'],
							"is_email_avaliable" => true,
							"is_username_avaliable" => true
						);
		if($check_result['message'] == 'success'){
			$return_data = $return_data;
		}
		else if( $check_result['message'] == 'username and email are already exist'){
			
			$return_data["is_email_avaliable"] = false;
			$return_data["is_username_avaliable"] = false;

		}
		else if( $check_result['message'] == 'username already exist'){
			
			$return_data["is_username_avaliable"] = false;

		}
		else if( $check_result['message'] == 'email already exist'){
			
			$return_data["is_email_avaliable"] = false;
			
		}
	
		else{
			$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Data is required for checking"
							);
		}
		if($res == ''){
			$res = array(
					"status"=> "success",
					"data"=> $return_data
					);
		}
		print json_encode($res);

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


/*............................................ Update User Profile   ........................................ */

	 function facebook_registration(){

	 	$data =(array) json_decode(file_get_contents("php://input"));
	 	//$data = $_POST;
	 	if(isset($data['name']) && strlen($data['name']) && isset($data['username']) && strlen($data['username']) && isset($data['email']) && strlen($data['email'])  && isset($data['dob']) && strlen($data['dob']) && isset($data['gender']) && strlen($data['gender']) && isset($data['zip_code']) && strlen($data['zip_code']) && isset($data['street_address']) && strlen($data['street_address']) && isset($data['locality']) && strlen($data['locality']) && isset($data['number']) && strlen($data['number']) && isset($_FILES['profile_photo']))
		{

			$res = $this->main_Registration($data);
			       
		}
		else{
			$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Sorry! Registration is failed"
							);
		}
		print json_encode($res);
	

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

/*......................................... ... Update User Profile   ....................................... . */


	function forgot_password(){

		//$data =(array) json_decode(file_get_contents("php://input"));
	 	$data = $_POST;

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

	 		$check_result = $this->Webservice_model->email_exist($data['email']);
	 		if($check_result['status'] == 'exist'){
	 			  $configs = array(
                        'protocol'=>'smtp',
                        'smtp_host'=>"mail.techlabz.in",
                        'smtp_user'=>'no-reply@techlabz.in',
                        'smtp_pass'=>'k4$_a4%eD?Hi',
                        'smtp_port'=>'587'
                        ); 

                 $this->email->initialize($configs);
				
				$this->email->from('no-reply@techlabz.in', 'Reeba');
				$this->email->to('reebamary0@gmail.com');


				$this->email->subject('Email Test');
				$this->email->message('Testing the email class.');
				//print_r($this->email);die();

				 if($this->email->send()) {        
                  $res =  "EmailSend";
                  }
                  else
                  {
                  $res =  "error";
                  }
                  echo $this->email->print_debugger();
	 		}
	 		else if($check_result['status'] == 'not exist'){

	 			$res = array(
								"status"=> "error",
								"error"=> "Not Exist",
								"message"=> "Sorry! Email is not exist"
							);			

	 		}

	 	}
	 	print json_encode($res);

	}

/*..............................................................................................................*/

/*......................................... ... Home Details   ....................................... . */

	function home_details(){

		$headers = apache_request_headers();
		//$data =  $_GET['auth_token']; 
		//print_r(apache_request_headers());  exit;

		if(isset($headers['Auth-Token']) && strlen($headers['Auth-Token'])){

			$check_result = $this->Webservice_model->get_auth_token($headers['Auth-Token']);
			if($check_result['status'] == 'success'){
				$res = array("status"=> "success",
								"data"=> array(
									"name" => $check_result['userdata']['name'],
									"profile_photo" => $check_result['userdata']['profile_photo'],
									"no_of_professionals"=> 0,
									"no_of_clinics"=> 0,
									"no_of_schedules" => 0,
									"no_of_moreservices" =>  0,
									"no_of_notification" => 0
								)
									
						);
			}
			else{
				$res = array(
								"status"=> "error",
								"error"=> "Not Exist",
								"message"=> "Authtoken is not exist"
							);			

			}
		}
		else{
			$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Authtoken is required"
							);
		}
		print json_encode($res);
	}


/*..............................................................................................................*/

/*............................................ Update User Location   ....................................... . */


	function location_update(){		
		//$data =(array) json_decode(file_get_contents("php://input"));
		$data= $_GET;
		$headers = apache_request_headers();
		
		if(isset($headers['auth-token']) && strlen($headers['auth-token'])){

			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			
			if($check_authToken){

				if(isset($data['location_name']) && strlen($data['location_name']) && isset($data['location_latitude']) && strlen($data['location_latitude']) && isset($data['location_longitude']) && strlen($data['location_longitude'])){
		
    				$result = $this->Webservice_model->location_update($data,$headers);
    				
    				if($result['status'] == 'success'){
    						$res = array(
    										"status" => "success",
    										"data" => array(
    														  "location_name"=>$data['location_name'],
    														  "location_latitude"=>$data['location_latitude'],
    														  "location_longitude"=>$data['location_longitude']
    														)
    									);
    				}
    				else if($result['status'] == 'fail'){
    					$res = array(
    									"status"=> "error",
    									"error"=> "Updation is failed",
    									"message"=> "Location Updation is Failed"
    								);
    				}
				}
				else{
					$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "location name or latitude or longitude is required"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res = array(
							"status"=> "error",
							"error"=> "required",
							"message"=> "Authtoken is required"
						);
		}
		print json_encode($res);
	}

/*..............................................................................................................*/

/*..............................................  Find Location ............................................... */

	function location()
	{
		$data = array();
		$headers = apache_request_headers();
		$postData = $_GET;

		
		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				if(isset($postData['latitude']) && strlen($postData['latitude']) && isset($postData['longitude']) && strlen($postData['longitude'])){

						$result = $this->Webservice_model->get_closest_location($postData['latitude'],$postData['longitude']);
						if(empty($result)){
							$res = array(
										"status"=> "error",
										"error"=> "No results",
										"message"=> "No Results Found"
									);
						}
						else{
							foreach ($result as $key => $value) {
								
								$res = array(	"status"=> "success");

								$data1 =	array(
													//"location_id"=>$key,
													"location_name"=>$value['location_name'],
													"location_latitude"=>$value['location_lattitude'],
													"location_longitude"=>$value['location_longitude']
												);
													
											
											
								array_push($data,$data1);
							}
							$res['data']['location'] = array_values(array_unique($data,SORT_REGULAR));

						}				
				}
				else
				{
						$res = array(
										"status"=> "error",
										"error"=> "required",
										"message"=> "latitude or longitude is required"
									);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res = array(
									"status"=> "error",
									"error"=> "required",
									"message"=> "Authtoken is required"
								);
		}
		print json_encode($res);
	}

/*..............................................................................................................*/

/*............................................ Update FCM Token   ........................................ */

	function update_fcm_token(){

		//$data = $_POST;
		$headers =  apache_request_headers();
		$data =(array) json_decode(file_get_contents("php://input"));
		if(isset($data['fcm_token']) && strlen($data['fcm_token']) && isset($headers['auth_token']) && strlen($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				$result = $this->Webservice_model->update_fcm_token($data,$headers);
				if($result['status'] == 'success'){
					$res = array("status"=>'success');
				}
				else if($result['status'] == 'fail'){
					$res = array(
									"status"=> "error",
									"error"=> "updation failed",
									"message"=> "updation failed"
								);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res = array(
							"status"=> "error",
							"error"=> "required",
							"message"=> "FCM Token or Authtoken is required"
						);
		}
		print json_encode($res);
	}

/*..............................................................................................................*/

/*............................................ Doctor specialization   ........................................ */


	function doctor_specialisation(){
		$headers =  apache_request_headers();
		if(isset($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				$result_doctor_specialisation = $this->Webservice_model->get_doctor_specialisation();
				if($result_doctor_specialisation['status'] == 'success'){
					//print_r($result_doctor_specialisation['data']);
					$specialization = array();
					foreach ($result_doctor_specialisation['data'] as $key => $value) 
					{
							$specialisation_data = 	array(
								"specialization_id"=>$value['specialization_id'],
								"specialization_name" => $value['specialization_name']
								);							
							array_push($specialization, $specialisation_data);
					}
					$res = 	array(
						"status"=> "success",
						"data"=>array(
							"specialization"=>$specialization
							)
						);
				}
				else{

					$res =  array(
						"status"=> "error",
						"error"=> "No data",
						"message"=> "No data"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}
		print json_encode($res);
	}

/*..............................................................................................................*/

/*............................................ Doctor profile   ........................................ */


	function doctor_profile(){

		//$data = (array) json_decode(file_get_contents("php://input"));
		$data = $_GET;
		//print_r($data);die();
		$value_photos = array();
		$value_phone = array();
		$headers =  apache_request_headers();
		if(isset($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){	
				if(isset($data['doctor_id']) && strlen($data['doctor_id']) && isset($data['clinic_id']) && strlen($data['clinic_id'])){

					$result = $this->Webservice_model->get_doctor_profile($data['doctor_id'],$data['clinic_id']);
					if($result['status'] == 'success'){
						if($result['data']['online_status'] == 0){
							$online = false;
						}
						else if($result['data']['online_status'] == 1){
							$online = true;
						}
						foreach (explode(',',$result['data']['phone']) as $key => $value) {
										$dd_phn = $value;
										 array_push($value_phone, $dd_phn);
									}
						foreach (explode(',',$result['data']['photos']) as $key => $value) {
										$dd_pic = $value;
										 array_push($value_photos, $dd_pic);
									}
						$res = array(
							"status" => "success",
							"data" => array(
								"doctor_id" => $result['data']['id'],
								"doctor_name" => $result['data']['name'],
								"doctor_specialization" => $result['data']['specialization_name'],
								"doctor_photo" => $result['data']['profile_pic'],
								"no_of_reviews" => $result['data']['reviewcount'],
								"online"=> $online,
								"fare"=> $result['data']['price'],

								"latitude" => $result['data']['location_lattitude'],
								"longitude" => $result['data']['location_longitude'],
								"about" => $result['data']['about'],
								"address" => $result['data']['street_address'].','.$result['data']['locality'].','.$result['data']['number'],

								"phone" => $value_phone,
								"specialization" => explode(',',$result['data']['sub_name']),
								"photos" =>$value_photos
								
								)
							);
					}
					else{
						$res =  array(
									"status"=> "error",
									"error"=> "No data",
									"message"=> "No data"
								);
					}
				}
				else
				{
					$res =  array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Doctor id or clinic id is required"
							);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}
		print json_encode($res);
	}


/*..............................................................................................................*/

/*............................................  Filter Others  ................................................  */

	function filter_others(){


		$headers =  apache_request_headers();
		if(isset($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				$filterData = filteredData();
				$res = array("status" => "success",
					"data" => array("others" => $filterData
						)
					);
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}

		
		print json_encode($res);
	}
/*..............................................................................................................*/

/*............................................  List Reviews  ................................................  */


	function review_list(){
		//$data = (array) json_decode(file_get_contents("php://input"));
		$data = $_GET;
		$headers =  apache_request_headers();
		if(isset($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){	
				if((isset($data['doctor_id']) && strlen($data['doctor_id']))|| (isset($data['clinic_id']) && strlen($data['clinic_id']))){

					if(isset($data['page']) && strlen($data['page'])){
						$currentpage =  $data['page'];
						$start = ($currentpage * 10) + (($currentpage - 2)*10);
					}
					else{
						$currentpage = 1;
						$start = 0;
					}
					if(isset($data['doctor_id']) && strlen($data['doctor_id'])){

						$result = $this->Webservice_model->review_list($data['doctor_id']);
					}
					else if(isset($data['clinic_id']) && strlen($data['clinic_id'])){
						$result = $this->Webservice_model->review_list_clinic($data['clinic_id']);
					}
					
					if($result['status'] =='success'){
						$reviews = array();
						$total = count($result['data']);
						if($total >= 20){

							$totalPages = $total / 20;
						}
						else{
							$totalPages = $total;
						}
						
						foreach (array_slice($result['data'],$start,20) as $key => $value) {
							$pushData = array('id'=>$value['review_id'],
								'name' => $value['name'],
								'date' => floatval($value['date']),
								'review' => $value['review'],
								'profile_photo' => $value['profile_photo']);
							array_push($reviews, $pushData);

						}
						$res = array('status' => 'success',
							'data' => array(
								'reviews' => $reviews
								),
							'meta' => array('total_pages' => $totalPages,
								'total' => $total,
								'current_page' => $currentpage,
								'per_page' => 20)
							);
					}
					else{
						$res = array(
								"status"=> "error",
								"error"=> "No data",
								"message"=> "No data"
							);
					}
				}
				else{
						$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Doctor id is required"
							);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}
		print json_encode($res);

	}

/*..............................................................................................................*/

/*.............................................  Doctor Booking  ................................................*/


	function doctor_booking(){
		//$data = $_POST;
		$headers =  apache_request_headers();
		$data = (array) json_decode(file_get_contents("php://input"));

		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){

				if(isset($data['doctor_id']) && strlen($data['doctor_id']) && isset($data['clinic_id']) && strlen($data['clinic_id']) && isset($data['date']) && strlen($data['date']) && isset($data['time']) && strlen($data['time']) && isset($data['amount']) && strlen($data['amount']) && isset($data['booking_status']) && strlen($data['booking_status'])){

					$result = $this->Webservice_model->doctor_booking($data,$headers['auth_token']);
					if($result['status'] == 'success'){
						$res = array('status' => 'success','data' => array('Booking_id' => $result['data']));
					}
					else if($result['status'] == 'fail'){
						$res = array(
								"status"=> "error",
								"error"=> "insertion error",
								"message"=> $result['msg']
							);
					}
				}
				else{
					$res = array(
								"status"=> "error",
								"error"=> "required",
								"message"=> "Doctor id or date or time or amount or booking status are required"
							);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}
		print json_encode($res);
	}


/*..............................................................................................................*/

/*............................................ clinic specialization ............................................*/


	function clinic_specialisation(){

		//$data = (array) json_decode(file_get_contents('php://input'));
		$data = $_POST;
		$headers =  apache_request_headers();
		if(isset($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
		
				$result_clinic_specialisation = $this->Webservice_model->get_clinic_specialisation();
				if($result_clinic_specialisation['status'] == 'success'){					
					$specialization = array();
					foreach ($result_clinic_specialisation['data'] as $key => $value) 
					{
							$specialisation_data = 	array(
								"specialization_id"=>$value['id'],
								"specialization_name" => $value['specialization_name']
								);							
							array_push($specialization, $specialisation_data);
					}
					$res = 	array(
						"status"=> "success",
						"data"=>array(
							"specialization"=>$specialization
							)
						);
				}
				else{

					$res =  array(
						"status"=> "error",
						"error"=> "No data",
						"message"=> "No data"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "Required",
					"message"=> "Auth token is required"
					);
		}
		print json_encode($res);



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

/*................................................ Search doctor ...............................................*/

 	function search_doctor(){
 		// $data = json_decode(file_get_contents('php://input'));
 		$headers =  apache_request_headers();
 		$data = $_GET;
 		

		if(isset($headers['auth_token'])){
		 	$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){	
		 		if((isset($data['query']) && strlen($data['query'])) || (isset($data['speciality']) && strlen($data['speciality'])) || (isset($data['clinic_id']) && strlen($data['clinic_id'])) || (isset($data['date']) && strlen($data['date'])) || (isset($data['others']) && strlen($data['others'])) || (isset($data['location_name']) && strlen($data['location_name']) && isset($data['location_latitude']) && strlen($data['location_latitude']) && isset($data['location_longitude']) && strlen($data['location_longitude'])))
		 		{
		 			if(isset($data['page']) && strlen($data['page'])){
						$currentpage =  $data['page'];
						$start = ($currentpage * 10) + (($currentpage - 2)*10);
					}
					else{
						$currentpage = 1;
						$start = 0;
					}
					$allDoctors = array(); 
			 		$search_query_result = $this->search_doctor_query($data,$headers);
			 		if($search_query_result['status'] == 'success'){
			 			foreach ($search_query_result['data'] as $key => $value) {
			 				if($value['online'] == 0){
			 					
			 					$search_query_result['data'][$key]['online'] = false;
			 				}
			 				else if($value['online'] == 1){
			 					
			 					$search_query_result['data'][$key]['online'] = true;
			 				}
			 			
			 			}
				 			$doctorsArray = array();
							$total = count($search_query_result['data']);
							if($total >= 20){

								$totalPages = (int)($total / 20);
							}
							else{
								$totalPages = 1;
							}
							
							foreach (array_slice($search_query_result['data'],$start,20) as $key => $value) {
								
								array_push($doctorsArray, $value);

							}
				 		$res = array('status' => 'success',
								'data' => array(
									'doctor' => $doctorsArray
									),
								'meta' => array('total_pages' => $totalPages,
									'total' => $total,
									'current_page' => $currentpage,
									'per_page' => 20)
								);
			 		}	 				 			
			 		else if($search_query_result['status'] == 'fail'){
			 			$res =  array(
									"status"=> "error",
									"error"=> "No data",
									"message"=> "No data"
								);
			 		}
			 		else if($search_query_result == null){
			 			$res =  array(
									"status"=> "error",
									"error"=> "Can't fetch your Location",
									"message"=> "Location error"
								);
			 		}

			 	}
		 		else{

		 			$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "Atleast one parameter is required"
						);
		 		}
		 	}
		 	else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
	 	}
	 	else{
	 		$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
	 	}
 		print json_encode($res);
 	}


 	function search_doctor_query($data,$headers){
 		
 		$get_location = $this->Webservice_model->get_location($headers['auth_token']);
 		if($get_location['status'] == 'success'){

	 		$result = $this->Webservice_model->search_doctor_query($data,$get_location['data']['location_latitude'],$get_location['data']['location_longitude']);

 		}
 		else{
 			$result = null;
 		}


 		return $result;

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

/*................................................ Search clinic ...............................................*/

 	function search_clinic(){

 		// $data = json_decode(file_get_contents('php://input'));
 		$headers =  apache_request_headers();
 		$data = $_GET;
 		$res =array('status'=>'success');

		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){

			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){

		 		if((isset($data['query']) && strlen($data['query'])) || (isset($data['speciality']) && strlen($data['speciality'])) || (isset($data['date']) && strlen($data['date'])) || (isset($data['others']) && strlen($data['others'])) || (isset($data['location_name']) && strlen($data['location_name']) && isset($data['location_latitude']) && strlen($data['location_latitude']) && isset($data['location_longitude']) && strlen($data['location_longitude'])))
		 		{
	 				$res['data']['clinic'] = array();


			 		$search_query_result = $this->search_clinic_query($data,$headers);
			 			if($search_query_result['status'] == 'success'){	
					 			foreach ($search_query_result['data'] as $key => $value) {
			 				
			 						array_push($res['data']['clinic'], $value);
			 					}
			 				
					 			$res['data']['no_of_clinics'] = count($res['data']['clinic']);
			 			}
					 	else if($search_query_result['status'] == 'fail'){
					 		$res =  array(
										"status"=> "error",
										"error"=> "No data",
										"message"=> "No data"
									);
					 	}			 						 		
			 	}
		 		else{

		 			$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "Atleast one parameter is required"
						);
		 		}
		 		
		 		//$res['data']['clinic'] = array_unique($res['data']['clinic'],SORT_REGULAR); // for contain unique data in array
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}	 		
	 	}
	 	else{
	 		$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
	 	}

 		print json_encode($res);
 	}


 	function search_clinic_query($data,$headers){
 		
 		$get_location = $this->Webservice_model->get_location($headers['auth_token']);
 		if($get_location['status'] == 'success'){

	 		$result = $this->Webservice_model->search_clinic_query($data,$get_location['data']['location_latitude'],$get_location['data']['location_longitude']);

 		}
 		else{
 			$result = null;
 		}

 		return $result;

 	}
 	
 	function search_clinic_lowervalue($data,$headers,$field){
 		
 		$get_location = $this->Webservice_model->get_location($headers['auth_token']);
 		if($get_location['status'] == 'success'){

	 		$result = $this->Webservice_model->search_clinic_lowervalue($get_location['data']['location_latitude'],$get_location['data']['location_longitude'],$field);

 		}
 		else{
 			$result = null;
 		}
 		return $result;

 	}



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

	function doctor_availability(){

		$headers =  apache_request_headers();
		$data = $_GET;

		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){		

			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				if(isset($data['doctor_id']) && strlen($data['doctor_id']) && isset($data['clinic_id']) && strlen($data['clinic_id']) && isset($data['date']) && strlen($data['date'])){
					$result_availability = $this->Webservice_model->doctor_availability($data);
					if($result_availability['status'] == 'success'){
						$day = date('D',$data['date']);					

						$res = array('status' => 'success',
							'data' => array('time_interval' =>array()));
						$result_availability['data']['date'] = json_decode($result_availability['data']['date'],true);
						foreach ($result_availability['data']['date'] as $key => $value) {
							
							if($value['day'] == strtolower($day)){							
							
								$interval_time = $value['time']['interval']*60;
								$start_time = strtotime($value['time']['start']);
								$end_time = strtotime($value['time']['end']);
								for ($i=$start_time; $i <= $end_time; $i=$i+$interval_time) { 
									$initial = $i;
									$end = $i+$interval_time;
									array_push($res['data']['time_interval'], array('time'=>date('h:i:sa',$initial).' - '.date('h:i:sa',$end)));
								}
							}
						}						
						$res['data']['time_interval'] = array_values(array_unique($res['data']['time_interval'],SORT_REGULAR));
					}
				}
				else{
					$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "Doctor id or clinic id is required"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
		}
		print json_encode($res);
	}
/*................................................................................................................*/
/*............................................ Clinic Profile ....................................................*/

	function clinic_profile(){
        
		$data = $_GET;
		$headers = apache_request_headers();

		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){		

			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				if (isset($data['clinic_id']) && strlen($data['clinic_id'])) {
					
					$result_data = $this->Webservice_model->clinic_profile($data['clinic_id']);
					if($result_data['status'] == 'success'){						
						$result_data['data']['address'] = $result_data['data']['cep'].','.$result_data['data']['street_address'].','.$result_data['data']['locality'];
						unset($result_data['data']['cep']);
						unset($result_data['data']['street_address']);
						unset($result_data['data']['locality']);
						unset($result_data['data']['number']);
						$res = array("status" => "success",
									"data"=>$result_data['data']);
					}
					else if($result_data['status'] == 'fail'){
						$res =  array(
										"status"=> "error",
										"error"=> "No data",
										"message"=> "No data"
									);
					}					
				}
				else{
					$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "clinic id is required"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
		}
		print json_encode($res);
	}
/*.................................................................................................................*/
/*............................................ Doctor available dates .............................................*/


	function available_dates(){

		$data = $_GET;
		$headers = apache_request_headers();
		
		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){		

			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				if(isset($data['doctor_id']) && strlen($data['doctor_id']) && isset($data['month']) && strlen($data['month']) && isset($data['year']) && strlen($data['year']) && isset($data['time_interval']) && strlen($data['time_interval'])){
					$result_booked = $this->Webservice_model->get_doctor_dates($data);					
					if($result_booked['status'] == 'success'){
						$res = array("status" => "success",
							"data" => array("booked"=>array(),"not_available" =>array()));						
						foreach ($result_booked['data'] as $key => $value) {							
							array_push($res['data']['booked'], date('j',strtotime($value['date'])));
							if(!is_null($value['start_date']) && !is_null($value['end_date'])){

								if(date('F',$value['start_date']) == $data['month']){

									array_push($res['data']['not_available'], date('j',strtotime($value['date'])));
								}
								if(date('F',$value['end_date']) == $data['month']){
									array_push($res['data']['not_available'], date('j',strtotime($value['date'])));
								}
							}							
						}
					}
					else if($result_booked['status'] == 'fail'){
						$res =  array(
										"status"=> "error",
										"error"=> "No data",
										"message"=> "No data"
									);
					}					
				}
				else{
					$res =  array(
						"status"=> "error",
						"error"=> "required",
						"message"=> "doctor id or month or year or time_interval is required"
						);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
		}
		print json_encode($res);
	}

/*.................................................................................................................*/
/*................................................... booking .....................................................*/
	
    function bookig_list(){

		$data = $_GET;
		$headers = apache_request_headers();
        

		if(isset($headers['auth_token']) && strlen($headers['auth_token'])){
			$check_authToken = $this->Webservice_model->check_auth_token($headers['auth_token']);
			if($check_authToken){
				$result_booking_list = $this->Webservice_model->get_booking_list($headers['auth_token']);
				if($result_booking_list['status'] == 'success'){
					$res = array("status"=>'success',
						'data'=>array('booking_list'=>$result_booking_list['data']));
				}
				else{
				    	$res =  array(
					"status"=> "error",
					"error"=> "No Data",
					"message"=> "No Data"
					);
				}
			}
			else{
				$res =  array(
					"status"=> "error",
					"error"=> "Not Valid",
					"message"=> "Authtoken is not valid"
					);
			}
		}
		else{
			$res =  array(
					"status"=> "error",
					"error"=> "required",
					"message"=> "Authtoken is required"
					);
		}
		print json_encode($res);
	}
}