<?php

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



class Home extends CI_Controller {



	function __construct() 

	{

        parent::__construct();

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

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

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

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

        $this->load->library('facebook'); // Load facebook library

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

        if(!$this->session->userdata('language')) {

         $langSet="pr";

         $this->session->set_userdata('language',$langSet);

		}

    }



/*HOME CONTROLLER - LANDING CONTROLLER*/

	public function index()

	{

		//print_r($this->config->item('id'));die();

		

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

		$template['page_title'] = "Home Page";

		$template['data'] = "Home page";

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

		//print_r($speciality_list);die();

		$template['speciality_list'] = $speciality_list;

		/*FB LOGIN BEGINS*/

		if(isset($_REQUEST['status']))

			{	

				$template['FBLoginStatus'] = $_REQUEST['status'];

			}

		else 

			{

				$template['FBLoginStatus'] = 'fail';

			}

		$fbuser = '';

        $template['FBauthUrl'] =  $this->facebook->login_url();

        /*FB LOGIN ENDS*/



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

		{

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

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

			{

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

			}

			else

			{

				header('Location: '.base_url().'Doctor');

			}



		}

		else

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



	}
	/*FUNCTION FOR SEARCH DOCTOR - PATIENT REGISTRATION*/

	public function search_doctor_data(){
		//print_r($this->session->userdata('language'));exit();
		$data = $_POST;
		$speciality_list = $this->Home_model->get_speciality_data($data);
		$results = '';
		/*if($speciality_list){
			$results = '<ul>';
			foreach($speciality_list['data'] as $key => $value) 
	        {  
	        	if($value['type'] =='speciality'){
	        		 $results .= '<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a></li>';
	        	}elseif($value['type'] == 'clinic'){
	        		 $results .= '<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a></li>';
	        	}elseif($value['type'] == 'doctor'){
	        		  $results .= '<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a></li>';
	        	}
	        }  
	        $results .= '</ul>';
		}*/     
		if(isset($speciality_list['doctor']) && !empty($speciality_list['doctor'])){
			$results .= '<li><h4><b>'.load_language('doctor',true).'</b></h4></li>';
			foreach ($speciality_list['doctor'] as $key => $value) {
				$results .= '<li role="displayCountries" class="li-top" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a><input type="hidden" value="'.$value['type'].'" name="doctor-type" id="doctorstype'.$key.'" class="doctorarea"></li>';
			}
		}
		if(isset($speciality_list['clinic']) && !empty($speciality_list['clinic'])){
			$results .= '<li><h4><b>'.load_language('clinis',true).'</b></h4></li>';
			foreach ($speciality_list['clinic'] as $key => $value) {
				$results .= '<li role="displayCountries" class="li-top" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a><input type="hidden" value="'.$value['type'].'" name="doctor-type" id="clinictype'.$key.'" class="doctorarea"></li>';
			}
		}
		if(isset($speciality_list['speciality']) && !empty($speciality_list['speciality'])){
			$results .= '<li><h4><b>'.load_language('specialities',true).'</b></h4></li>';
			foreach ($speciality_list['speciality'] as $key => $value) {
				$results .= '<li role="displayCountries" class="li-top"><a role="menuitem dropdownCountryli" class="dropdownlivalue">'.$value['specialization_name'].'</a><input type="hidden" value="'.$value['type'].'" name="doctor-type" id="specialitytype'.$key.'" class="doctorarea"></li>';
			}
		}

		echo json_encode($results) ;
	}

	/*FUNCTION FOR CHECKING EMAIL EXIST - PATIENT REGISTRATION*/

	public function check_email()

	{

		$data = $_POST;

		$check_result = $this->Home_model->emailExist($data);

		//print_r($check_result);die();

		print json_encode($check_result);

	}



	/*FUNCTION FOR CHECKING USERNAME EXIST - PATIENT REGISTRATION*/

	public function check_username()

	{

		$data = $_POST;

		$check_result = $this->Home_model->usernameExist($data);

		//print_r($check_result);die();

		print json_encode($check_result);

	}



	/*FUNCTION FOR VALIDATING CEP CODE - PATIENT REGISTRATION*/

	public function check_cep()

	{

		$data = $_POST;

		$result= check_cep_viacep($data['cep']); //common helper

		print ($result);

	}

	public function get_url_data(){
		$data = $_POST;
		$ch = curl_init();
		$area = $data['cep'];
		$url = "https://maps.googleapis.com/maps/api/geocode/json?address=${area}&key=AIzaSyDMcP8sMKFPmLROvIf3g1U86_Vg5ur41nQ";
		//print_r($url);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$result = curl_exec($ch);
		$json = json_decode($result, TRUE);
	  	print json_encode($json);
	}



	/*FUNCTION FOR CHECKING USERNAME EXIST - DOCTOR REGISTRATION*/

	public function check_username_doc()

	{

		$data = $_POST;

		$check_result = $this->Home_model->usernameExist_doc($data);

		//print_r($check_result);die();

		print json_encode($check_result);

	}

	/*FUNCTION FOR CHECKING EMAIL EXIST - DOCTOR REGISTRATION*/

	public function check_email_doc()

	{

		$data = $_POST;

		$check_result = $this->Home_model->emailExist_doc($data);

		//print_r($check_result);die();

		print json_encode($check_result);

	}



	/*FUNCTION FOR PATIENT REGISTRATION - HOME*/

	public function reg_patient()

	{	

		parse_str($_REQUEST['data'], $output);	

		$reg_data = array('email' => $output['reg_pat_email'],'name' => $output['reg_pat_name'],'username' => $output['reg_pat_username'],'password' => md5($output['reg_pat_password']),'cpf' => $output['reg_pat_cpf'],'rg' => $output['reg_pat_rg'],'dob' =>strtotime($output['reg_pat_dob']),'gender' => $output['reg_pat_gender'],'weight' => $output['reg_pat_weight'],'height' => $output['reg_pat_height'],'blood_group' => $output['reg_pat_bloodgrp'],'zip_code' => $output['reg_pat_cep'],'street_address' => $output['reg_pat_streetadd'],'locality' => $output['reg_pat_locality'],'number' => $output['reg_pat_number'],'landmark' => $output['reg_pat_complement'],'occupation' => $output['reg_pat_occupation']	);

		//print_r($reg_data);die();

		$result = $this->Home_model->registration($reg_data);

		if($result['status'] == 'success')

		{ 

			if(isset($_FILES['pic']))

			{

				$fileName = $result['userdata']['id'].'_'.$_FILES['pic']['name'];

				$config = set_upload_options('./assets/uploads/profilepic/patient/'); 

	         	$config['file_name'] = $fileName;

	         	$this->load->library('upload', $config);

		        if ( ! $this->upload->do_upload('pic')) 

		        {

		            $error = array('error' => $this->upload->display_errors('', '')); 

		            $res = array(

							"status"=> "failure",

							"error"=> "Upload Error",

							"message"=> "Profile Image Upload Error!, ".$error['error']

						);	

		            $this->Home_model->delete_registration($result['userdata']['id']);

		        }	

		        else

		        {

		        	$imagedata = $this->upload->data(); 

					$fullfilepath='assets/uploads/profilepic/patient/'.$imagedata['file_name'];

				}

			}

			else

			{

				$fullfilepath = $output['reg_pat_profilepic'];

			}

				

			if(isset($fullfilepath))

			{

				$static_string = 'IPOK_User'.time();

				$authToken = uniqid($static_string);

				$result_authtoken = $this->Home_model->authtoken_registration($authToken,$result['userdata']['id']);

				if($result_authtoken)

				{

					

					$picdata = array('profile_photo'=>$fullfilepath);

					$finalResult = $this->Home_model->updatePic($picdata,$result['userdata']['id']);

					if($finalResult)

					{	

						$res = array('status'=>'success');

						$cpf_obj = array('cpf' => $reg_data['cpf'] ,'user_type' =>0,'user_id'=>$result['userdata']['id']);

						$this->Home_model->insertcpfunique($cpf_obj);

					} //final success

					else

					{	

						$res = array(

							"status"=> "failure",

							"error"=> "Database Error",

							"message"=> load_language('image_upload_error',true)

						);		

					}

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

					{	unset($_SESSION['FBData']); }



	         	}

			}



			

	         	

		}

		else

		{

			$res = array(

							"status"=> "failure",

							"error"=> "Database Error",

							"message"=> load_language('patient_registration_failed',true)

						);	

		}



		print json_encode($res);

	

	}



	/*FACEBOOK LOGIN CONTROLLER - HOME(PATIENT REGISTRATION)*/

	public function facebook_login()

	{

		$FBuserData = array();

		if(isset($_REQUEST['error']) and $_REQUEST['error']=='access_denied' and isset($_REQUEST['error_code']) and $_REQUEST['error_code']==200)

		{

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

			redirect(base_url());

		}

        else if($this->facebook->is_authenticated()) // Check if user is logged in

        {

            // Get user facebook profile details

            $userProfile = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,gender,locale,picture');



            // Preparing data for database insertion

            $FBuserData['oauth_provider'] = 'facebook';

            $FBuserData['oauth_uid'] = $userProfile['id'];

            $FBuserData['first_name'] = $userProfile['first_name'];

            $FBuserData['last_name'] = $userProfile['last_name'];

            $FBuserData['email'] = $userProfile['email'];

            $FBuserData['gender'] = $userProfile['gender'];

            $FBuserData['locale'] = $userProfile['locale'];

            $FBuserData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];

            $FBuserData['picture_url'] = $userProfile['picture']['data']['url'];



           // print_r($FBuserData);die();

			

			if($FBuserData)

			{

				$check_result = $this->Home_model->emailExist(array('email' =>$FBuserData['email']));

					if($check_result['message']=="success")	

					{

						$status = 'success';

						$this->session->set_userdata('FBData',$FBuserData);

						header('Location: '.base_url().'Home/index?status='.$status);

					}

					else

					{

						//print_r("already registered"); die();

						$this->session->set_flashdata('message', array('message' => load_language('account_exist_with',true).$FBuserData['email'], 'title' => 'Warning', 'class' => 'info'));

						header('Location: '.base_url());

					}

					

					//redirect('Home/index');

				die(); 

			}

            // Get logout URL

            $data['logoutUrl'] = $this->facebook->logout_url();

        }

        

	}



	/*FUNCTION FOR LOGIN (DOCTOR AND PATIENT) - HOME*/

	public function login()

	{

		//parse_str($_REQUEST['LoginData'], $request);

		//print_r($_POST);die();

		$request = $_POST;

		$result=$this->Home_model->login($request);

		//print_r($result);die();

		if(($result['status']=='success')&&($result['userdata']['account_status']==0))

		{

			//if(($result['status']=='success')&&($request['login_type']=="PATIENT"))
			if(($result['status']=='success')&&($result['type']=="PATIENT"))

			{

				//print_r($result);die();

				$update_location = $this->Home_model->location_update($result['userdata'],$request);

				if($update_location['status']=='success')

				{

					$res = array(

							"status"=> "success",

							"data"=>array(

									"type"=>"PATIENT",

									"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" => $result['userdata']['profile_photo']



									)

								

							);

					$dependent_data = $this->Patient_model->get_all_dependent_for_patient($result['userdata']['id']);

					if(!empty($dependent_data)){$this->session->set_userdata('DependentData',$dependent_data);}

				}

				else

				{

					$res = array(

								"status"=> "error",

								"error"=> "Location Update Failed",

								"message"=> load_language('check_location_credentials',true)

							);

				}

				

			}

			//else if(($result['status']=='success')&&($request['login_type']=="DOCTOR"))
			else if(($result['status']=='success')&&($result['type']=="DOCTOR"))

			{

				$update_location = $this->Home_model->location_update_doctor($result['userdata'],$request);

				if($update_location['status']=='success')

				{

					$res = array(

							"status"=> "success",

							"data"=>array(

									"type"=>"DOCTOR",

									"id"=> $result['userdata']['id'],

									"name"=> $result['userdata']['name'],

									"username"=> $result['userdata']['username'],

									"email"=> $result['userdata']['email'],

									"password" => $result['userdata']['password'],

									"specialization" => $result['userdata']['specialization'],

									"telphone" => $result['userdata']['telephone'],

									"cpf" => $result['userdata']['cpf'],

									"rg" => $result['userdata']['rg'],

									"dob" => $result['userdata']['dob'],

									"gender" => $result['userdata']['gender'],

									"price" => $result['userdata']['price'],

									"zip_code" => $result['userdata']['cep'],

									"street_address" => $result['userdata']['street_address'],

									"locality" => $result['userdata']['locality'],

									"number" => $result['userdata']['number'],

									"landmark" =>$result['userdata']['complement'],

									"profile_photo" => $result['userdata']['profile_pic'],

									"bio" => $result['userdata']['about']

									)

								

							);

					$collaborator_data = $this->Doctor_model->get_all_collaborator_for_doctor($result['userdata']['id']);

					$this->session->set_userdata('CollaboratorData',$collaborator_data);

				}

				else

				{

					$res = array(

								"status"=> "error",

								"error"=> "Location Update Failed",

								"message"=> load_language('check_location_credentials',true)

							);

				}

				

			}

			//else if(($result['status']=='success')&&($request['login_type']=="COLLABORATOR"))
			else if(($result['status']=='success')&&($result['type']=="COLLABORATOR"))

			{

				

				//print_r($result);die();

				$doctor_data = $this->Doctor_model->get_single_doctor($result['userdata']['doctor_id']);

				//print_r($doctor_data);die();

				$res = array(

						"status"=> "success",

						"data"=>array(

								"type"=>"COLLABORATOR",

								"id"=> $doctor_data['doctorid'],

								"name"=> $doctor_data['dr_name'],

								"username"=> $doctor_data['dr_username'],

								"email"=> $doctor_data['dr_email'],

								"specialization_id" => $doctor_data['dr_specialization_id'],

								"specialization" => $doctor_data['dr_specialization'],

								"telphone" => $doctor_data['dr_telephone'],

								"cpf" => $doctor_data['dr_cpf'],

								"rg" => $doctor_data['dr_rg'],

								"dob" => $doctor_data['dr_dob'],

								"gender" => $doctor_data['dr_gender'],

								"price" => $doctor_data['dr_price'],

								"zip_code" => $doctor_data['dr_cep'],

								"street_address" => $doctor_data['dr_rua'],

								"locality" => $doctor_data['dr_neighbourhood'],

								"number" => $doctor_data['dr_number'],

								"landmark" =>$doctor_data['dr_complement'],

								"profile_photo" => $doctor_data['dr_pic'],

								"bio" => $doctor_data['dr_bio'],

								"c_id" => $result['userdata']['id'],

								"c_name" => $result['userdata']['name'],

								"c_email" => $result['userdata']['email'],

								"c_telephone" => $result['userdata']['telephone'],

								"c_cpf" => $result['userdata']['cpf'],

								"c_capabilities" => $result['userdata']['capabilities']

								)

							

						);



				$collaborator_data = $this->Doctor_model->get_all_collaborator_for_doctor($result['userdata']['id']);

				if(!empty($collaborator_data)){$this->session->set_userdata('CollaboratorData',$collaborator_data);}

				

				

			

			}

		}	

		else if(($result['status']=='success')&&($result['userdata']['account_status']==1))

		{

			$res = array(

							"status"=> "error",

							"error"=> "Login Failed",

							"message"=> load_language('account_disabled',true)

						);

		}

		else if($result['status']=='fail')

		{

			$res = array(

							"status"=> "error",

							"error"=> "Login Failed",

							"message"=> load_language('invalid_username_or_password',true)

						);

		}



		if(($res['status']=="success"))

		{

			$this->session->set_userdata('UserData',$res['data']);

		}



		print json_encode($res);

		

	}



	/*FUNCTION FOR LOGOUT - HOME*/

	public function logout()

	{

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

	     {

	     	unset($_SESSION['UserData']);

	     }

	     

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

	     {

	     	unset($_SESSION['DependentData']);

	     }



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

	     {

	     	unset($_SESSION['notifications']);

	     } 

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

	     {

	     	unset($_SESSION['CollaboratorData']);

	     }

	     header('Location: '.base_url());

	}



	/*CONTROLLER - DOCTOR REGISTRATION*/

	public function RegisterDoctor()

	{

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

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

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

		//print_r($speciality_list);die();

		$template['speciality_list'] = $speciality_list;

		//$template['data'] = "Home page";

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

	}



	/*FUNCTION FOR INSERTING DOCTOR DATA INTO DB - DOCTOR REGISTRATION*/

	public function doRegister()

	{

			//print_r($_POST);die();

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

		{

			$data = $_POST;

			//print_r($data);exit();
			$newdob = $data['year'].'-'.$data['month'].'-'.$data['day'];

			$data['password'] = md5($data['password']);

			$data['dob'] = strtotime($newdob);

			$this->Doctor_model->assignDoctors_default($this->session->userdata('UserData')['id'],'');

			$result = $this->Home_model->register_doctor($data);

			//print_r($result);

			if($result['status'] == 'success')

			{	

				$fileName = $result['data']['id'].'_'.$_FILES['profile_pic']['name'];

				$config = set_upload_options('./assets/uploads/profilepic/doctors/'); 

				$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"=> load_language('image_upload_error',true)/*.$error['error']*/

					);	

					$this->Home_model->delete_registration_doctor($result['data']['id']);

					$this->session->set_flashdata('message', array('message' => load_language('image_upload_error',true), 'title' => 'Error', 'class' => 'danger'));

					redirect(base_url().'Home/RegisterDoctor');

				}	

				else 

				{ 

					//print_r($this->input->post('name'));

					//print_r($_POST['username']);

					$static_string = 'IPOK_Doctor'.time();

					$authToken = uniqid($static_string);

					$result_authtoken = $this->Home_model->authtoken_registration_doctor($authToken,$result['data']['id']);

					$imagedata = $this->upload->data(); 

					$fullfilepath='assets/uploads/profilepic/doctors/'.$imagedata['file_name'];



					$picdata = array('profile_pic'=>$fullfilepath);

					$this->Home_model->updatePic_doctor($picdata,$result['data']['id']);



					$cpf_obj = array('cpf' => $data['cpf'] ,'user_type' =>1,'user_id'=>$result['data']['id']);

					$this->Home_model->insertcpfunique($cpf_obj);

					

					$this->session->set_flashdata('message', array('message' => load_language('register_success_message',true), 'title' => 'Success', 'class' => 'success'));

					header('Location: '.base_url().'Home/RegisterDoctor');



				}

			}

			else

			{

				$this->session->set_flashdata('message', array('message' => load_language('register_failed_message',true), 'title' => 'Error', 'class' => 'danger'));

				redirect(base_url().'Home/RegisterDoctor');	

			}



	 	

			

		}



	}



	/*FUNCTION FOR REDIRECTING INTO USER(PATIENT/DOCTOR) DASHBOARD - HOME*/

	public function Dashboard()

	{

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

		if($userdata['type']=='DOCTOR')

		{

			header('Location: '.base_url().'Doctor');

		}

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

		{

			header('Location: '.base_url().'Patient');

		}

	}



	/*FUNCTION FOR CHECKING USER CREDENTIALS AND SENT RESET PASSWORD MAIL TO USER*/

	public function forgotpassword()

	{

		//print_r($_POST);

		if(!empty($_POST))

		{

			$check_authentic = $this->Home_model->check_valid_email_forgot($_POST['email'],$_POST['type']);

			//print_r($check_authentic);die();

			if($check_authentic['count']==1)

			{

				//send_mail('test','test','test');	

				$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

				$result = '';

			    for ($i = 0; $i < 24; $i++)

			        $result .= $characters[mt_rand(0, 61)];

			    $link = base_url().'Home/resetpassword/?i='.$check_authentic['id'].'&c='.$result.'&t=';

				

			    if($_POST['type']=='DOCTOR')

			    {

			    	$link = $link.'2';

					$this->Doctor_model->set_confirmation_code($check_authentic,$result);

			    }

			    else

			    {

			    	$link = $link.'1';

			    	$this->Patient_model->set_confirmation_code($check_authentic,$result);

			    }

		     	$msg = "Hi ".$check_authentic['name'].",<br><br>Your request for resetting password has been accepted. Use the following link to reset password. ".$link.". Please Do not share with anyone<br><br>Ipok Team";

			    //print_r($msg);

			    send_mail($msg,$_POST['email'],'Reset Password');

			    //sent email

				$res = array('status' => 'success','msg' => load_language('valid_email_address',true));

			}

			else

			{

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

			}

			print json_encode($res);

		}

	}





	/*FUNCTION FOR RESETING USER PASSWORD FROM MAIL*/

	public function resetpassword()

	{

		//print_r($_GET["t"]);die();

		if(!empty($_GET["t"]) and !empty($_GET["c"]) and !empty($_GET["i"]))

		{

			$type=$_GET["t"]; //0->Patient 1->Doctor

			$code=$_GET["c"];

			$id=$_GET["i"];

			

			$db_code = $this->Home_model->check_confirmation_id($id,$code,$type);

			// /print_r($db_code);die();

			if($db_code['confirmation_code']==$code)

			{

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

			}

			else

			{

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

			}



			$template['type'] = $type;

			$template['id'] = $id;

			$template['page_title'] = "Reset Password";

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

		}

		else

		{

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

			$template['page_title'] = "Reset Password";

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

		}

		//load the page reseting password both from web and mobile

	}



	/*FUCTION FOR AJAX CALL IN SAVING NEW PASSWAORD*/

	public function sav_reset()

	{

		//print_r($_POST);

		$update = array('password' => md5($_POST['password']),'confirmation_code' =>'');

		$status = $this->Home_model->update_profile($_POST['id'],$_POST['type'],$update);

		if($status)

		{

			$res = array('status' =>'success');

		}

		else

		{

			$res = array('status' =>'error');

		}

		print json_encode($res);

		

	}







	/*FUNCTION FOR RETRIVING SESSION  DATA TO CHAT JS*/

	public function get_session()

	{

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

		{

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

	        //header('Content-type: application/json');

	       	print json_encode($userdata);

      	} 

      	else 

      	{ 

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

      		print json_encode($array);

      	}

	}



	/*FUNCTION FOR RETRIVING OPPONENT DATA TO CHAT JS*/

	public function get_opponentData()

	{

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

		{

	     	$data = $this->session->userdata('opponentData');

	        //print_r($data);die();

	        unset($_SESSION['opponentData']);

	       	print json_encode($data);

      	} 

      	else 

      	{ 

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

      		print json_encode($array);

      	}

	}



	/*FUNCTION FOR RETRIVING RECENT CHAT DATA TO CHAT JS*/

	public function get_recent_chat()

	{

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

		{

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

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

	     	//print_r($recent);die();

	        //header('Content-type: application/json');

	       	print json_encode($recent);

      	} 

      	else 

      	{ 

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

      		print json_encode($array);

      	}

	}



	/*FUNCTION FOR RETRIVING ALL CHAT USERS TO CHAT JS*/

	public function get_all_chat_users()

	{

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

		{

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

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

	     	//print_r($allusers);die();

	        //header('Content-type: application/json');

	       	print json_encode($allusers);

      	} 

      	else 

      	{ 

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

      		print json_encode($array);

      	}

	}



	/*FUNCTION FOR UPDATING RECENT CHAT DATA TO CHAT JS*/

	public function update_recent_chat()

	{

		if($this->session->userdata('UserData') and !empty($_POST)) 

		{

			//print_r($_POST);die();

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

	     	$this->Home_model->update_recent_chat($_POST);

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

	     	//print_r($recent);die();

	        //header('Content-type: application/json');

	       	print json_encode($recent);

      	} 

      	else 

      	{ 

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

      		print json_encode($array);

      	}

	}



	/*FUNCTION FOR CHECKING EMAIL EXIST - DOCTOR REGISTRATION*/

	public function check_email_colabor()

	{

		$data = $_POST;

		$check_result = $this->Home_model->emailExist_colabor($data);

		//print_r($check_result);die();

		print json_encode($check_result);

	}



	/*FUNCTION TO DISPLAY NOT AUTHORIZED ERROR PAGE*/

	public function error()

	{

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

		

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

		if($this->uri->segment(3) and $this->uri->segment(3)=='url')

		{

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

		}



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

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

	}

	



	/*FUNCTION FOR SENTING CONFRIMATION CODE FOR ACCOUNT DELETION - PATIENT AND DOCTOR*/

	/*public function sentConfirmationcode($user)

	{

		$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	    $result = '';

	    for ($i = 0; $i < 8; $i++)

	        $result .= $characters[mt_rand(0, 35)];

		$msg = "Hi Jithin,</br></br>Your Confirmation Code for Ipok Account Deactivation is ".$result.".



				</br></br>Ipok Team";

		$this->send_mail($msg,'jithin@techware.in','Account Deactivation');

		//print_r($msg);

	}



	public function send_mail($msg,$email,$sub){

 	$settings = $this->db->get('settings')->row();

 	//print_r($settings);

   

    $configs = array(

		'protocol'=>'smtp',

		'smtp_host'=>$settings->smtp_host,

		'smtp_user'=>$settings->smtp_username,

		'smtp_pass'=>$settings->smtp_password,

		'smtp_port'=>'587',

		'smtp_timeout'=>20,

        'mailtype' => 'html',

        'charset' => 'iso-8859-1',

        'wordwrap' => TRUE

		); 



		$this->load->library('email', $configs);

		$this->email->initialize($configs);

		$this->email->set_newline("\r\n");

		$this->email

			->from($settings->admin_email, 'Ipok')

			->to($email)

			->subject($sub)

			->message($msg);

		$this->email->send();

  }

*/



  /*FUCNTION TO ADD BANK DETAILS TO CURRENT USER*/

  public function addBank()

  {

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

  		{

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

  			$insert_array = array('account_no' => encrypt_data($_POST['account']),'account_holder' =>encrypt_data($_POST['name']),'bank_name' => $_POST['bank'],'agency' => $_POST['agency']);

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

  			{

  				$insert_array['type']=0;

  				$insert_array['type_id'] = $userdata['id'];

  			}

  			elseif($userdata['type']=="DOCTOR")

  			{

  				$insert_array['type']=1;

  				$insert_array['type_id'] = $userdata['id'];

  			}

  			$insert = $this->Home_model->insert_bank_account($insert_array);

  			if($insert)

  			{

  				$res = array('status' => 'success','message' => load_language('bank_added',true));

  			}

  			else

  			{

  				$res = array('status' => 'error','message' => load_language('insertion_failed',true));

  			}

  			print json_encode($res);

  		}

  }



  /*FUNCTION TO RETURN ALL SAVED BANKS FOR CURRENT USER*/

  public function getAllBanks()

  {



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

  		{

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

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

  			$template['banks'] = $banks;

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

  		}

  }



   /*FUNCTION TO RETURN ALL SAVED BANKS - Wallet display*/

  public function refreshBankList()

  {



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

  		{

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

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

  			$template['banks'] = $banks;

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

  		}

  }



/*  FUNCTION TO REMOVE BANK FOR GIVEN BANK ID*/

public function removeBank()

{

	if(!empty($_POST['bank_id']) and !empty($this->session->userdata('UserData')))

	{

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

		$this->Home_model->remove_bank($_POST['bank_id']);

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

		$template['banks'] = $banks;

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

	}

}



/*FUNCTION TO PROCESS REDEMPTION REQUEST*/

public function redemptionrequest()

{

	if(!empty($this->session->userdata('UserData')) and !empty($_POST))

	{

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

		$get_account_balance = $this->Home_model->get_redemption_balance($userdata['id']);

		$check_valid_bank = $this->Home_model->get_bank_valid($userdata['id'],$_POST['redemption_bank']);

		//print_r($check_valid_bank);die();

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



		if($get_account_balance['reedem_earn']>=$_POST['redemption_amount'] and $check_valid_bank['count']==1)

		{

			$withdrawal_insert = array('bank_id' => $_POST['redemption_bank'], 'amount'=>$_POST['redemption_amount'], 'date'=>time(),'status'=>0,'doctor_id' =>$userdata['id'],'previous_reedem_earn'=>$get_account_balance['reedem_earn']);

			$this->Home_model->add_redemption_request($withdrawal_insert);

			$res = array('status' => 'success','message' => load_language('redemption_requested',true));



		}

		elseif($get_account_balance['reedem_earn']<=$_POST['redemption_amount'] and $check_valid_bank['count']==1)

		{

			$withdrawal_insert = array('bank_id' => $_POST['redemption_bank'], 'amount'=>$_POST['redemption_amount'], 'date'=>time(),'status'=>3,'doctor_id' =>$userdata['id'],'previous_reedem_earn'=>$get_account_balance['reedem_earn']);

			$this->Home_model->add_redemption_request($withdrawal_insert);



			$res = array('status' => 'error','message' => load_language('error_insufficient_balance',true));

		}

		else

		{

			$res = array('status' => 'error','message' => load_language('invalid_bank_account',true) );

		}

		//print_r($withdrawal_insert);

		

	}

	else

	{

		$res = array('status' => 'error','message' => load_language('facing_technical_issues',true));

		

	}



	print json_encode($res);

}



public function test()

{

	/*$cpf_obj = array('cpf' => '456884' ,'user_type' =>1,'user_id'=>$result['data']['id']);

	$this->Home_model->insertcpfunique($cpf_obj);*/

}



public function check_cpfunique()

{

	$cpf = $_POST['cpf'];

	$result  = $this->Home_model->check_cpfunique($cpf);

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

	{

		$res = array('status' => 'success','unique' => 'true');

	}

	else

	{

		$res = array('status' => 'error','unique' => 'false');

	}

	print json_encode($res);

	

}



/*CRON JOBS FOR IPOK*/

public function cron_jobs()

{

	/*FUNCTION FOR CANCELING ALL UNPAID BOOKINGS*/
	$check_payments_booking = $this->Home_model->get_booking_for_payment_cron();
	print_r($check_payments_booking);
	if(!empty($check_payments_booking))
	foreach ($check_payments_booking as $key => $value) {
		
		$this->Doctor_model->change_booking_status($value['id'],4); //canceling all unpaid bookings
	}
	die();

	/*FUNCTION FOR SENTING CONSULTATION REMINDER*/

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

	//print_r($nowin_server);die();

	$todays_booking = $this->Home_model->get_todays_booking();

	//echo "<pre>";

	//print_r($todays_booking);



	if(!empty($todays_booking))

	{

		foreach ($todays_booking as $key => $booking) 

		{

			//print_r($booking['id']);die();

			/*CODE FOR SENTING NOTIFICATION  - PATIENT NOTIFICATION*/

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

			$booking_details = $this->Search_doctor_model->get_booking_details($booking['id']);

			$doctor_data = $this->Doctor_model->get_single_doctor($booking_details['doctor_id']);

			$text_pat = 'You have a scheduled appointment in the system today, at '.date('H:i a',$booking_details['time_start']).', doctor '.$doctor_data['dr_name'];



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

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

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

		}

	}





	

}



/*FUNCTION FOR LANGUAGE SETTINGS CHANGE*/

public function langSettings() 

{

    

	$data = $_POST;

	$lval=$data['lval'];



	$this->session->set_userdata('language', $lval);

	echo  $a= $this->session->userdata('language');



}

/*FUNCTION FOR CHECK LOGIN*/

public function islogedin() 

{
	//print_r($this->session->userdata('user_time'));



	if(auto_logout("user_time"))

    {

        $result = array('status' => 'error');

        $this->session->set_userdata('logout', 'autologoff');

        $this->session->set_userdata('user_time', time());

    }    

    else

    {

    	$result = array('status' => 'success');

    } 



	print json_encode($result);

}


/*FUNCTION FOR PRIVACY POLICY*/
public function privacy() 
{
	//print_r($this->session->userdata('user_time'));
		$template['page'] = "privacy_policy";
		$template['page_title'] = "Privacy Policy";
		$this->load->view('template/template', $template);
}

/*FUNCTION FOR ABOUT US*/
public function about() 
{
	//print_r($this->session->userdata('user_time'));
		$template['page'] = "aboutus";
		$template['page_title'] = "About US";
		$this->load->view('template/template', $template);
}

/*FUNCTION FOR CONTACTUS*/
public function contact() 
{
	//print_r($this->session->userdata('user_time'));
		$template['page'] = "contactus";
		$template['page_title'] = "Contact US";
		$this->load->view('template/template', $template);
}


/*FUNCTION FOR SEND CONTACTUS MAIL*/
public function send_contactus() 
{
	//print_r($this->session->userdata('user_time'));
	//print_r($_POST);die();
 	$settings = $this->db->get('settings')->row();
 	//print_r($msg);die();
    $configs = array(
		'protocol'=>'smtp',
		'smtp_host'=>$settings->smtp_host,
		'smtp_user'=>$settings->smtp_username,
		'smtp_pass'=>$settings->smtp_password,
		'smtp_port'=>'587',
		'smtp_timeout'=>20,
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
		); 
		$this->load->library('email', $configs);
		$this->email->initialize($configs);
		$this->email->set_newline("\r\n");
		$this->email
			->from($_POST['email'], $_POST['name'])
			->to($settings->admin_email)
			->subject($_POST['checkbox-contactus'])
			->message($_POST['description']);
		$sent = $this->email->send();
		if($sent)
		{
			print json_encode(array('status' => 'success' ));
		}
		else
		{
			print json_encode(array('status' => 'error' ));
		}
}













}

	

	



