load->database(); $this->load->library(array('ion_auth','form_validation','linkedin')); $this->load->helper(array('url','language')); $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth')); $this->lang->load('auth'); //$this->load->model('website_settings/Website_Settings_model'); $this->load->model('website_settings/Website_model'); $this->load->model('caregivers/Caregiver_model'); $this->load->model('addcaregiver/Addcaregiver_model'); $this->load->model('referral/Referral_model'); //$this->load->model('home/Home_model'); $this->indeed_redirect_uri = urlencode(indeed_oauth_redirect_uri); } //redirect if needed, otherwise display the user list function index() { /*LinkedIn login*/ $data['linkedInUri'] = $this->linkedin->getAuthUrl(); if($_GET['code'] != '') { $accessToken = $this->linkedin->getAccessToken($_GET['code']); $profile = $this->linkedin->getPerson(); $Profemail = $this->linkedin->getEmail(); $data['code'] = "?code=".$_GET['code']; // pre($data['profile']); $profEmail = (array) $Profemail->elements[0]; $data['linkedInEmail'] = $profEmail['handle~']->emailAddress; $data['linkedInFname'] = $profile->firstName->localized->en_US; $data['linkedInLname'] = $profile->lastName->localized->en_US; $data['oauth_uid'] = $profile->id; $data['oauth_provider'] = 'linkedin'; // echo "
";print_r($data);die;
			$emailID = $data['linkedInEmail'];
			$remember = false;
			$this->session->set_userdata('accessToken',$accessToken);
			if ($this->ion_auth->loginLinkedin($emailID, $remember))
			{
				//if the login is successful
				//redirect them back to the home page
				
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect('/home', 'refresh');
			}
		}
		/*LinkedIn login end*/

		/**
		 * Indeed login
		 */
		$data['indeedUri'] = "https://secure.indeed.com/oauth/v2/authorize?client_id=".INDEED_CLIENT_ID."&redirect_uri=".$this->indeed_redirect_uri."&response_type=code&state=employer1234&scope=email+offline_access+employer_access";
		
		
		// echo $_GET['code'];die;
		/*********************/

		$data['banner']=$this->Website_model->getBannerList();
		$data['content']=$this->Website_model->getContentList();
		$data['basic']=$this->Website_model->getbasicInfo();
		$data['specialities']=$this->Website_model->getSpecialitiesList();
		$data['caregiver_skill_list']=$this->Website_model->caregiver_skill_list();
			
		$this->load->view('frontend/header',$data);
		$this->load->view('frontend/index',$data);
		$this->load->view('frontend/footer',$data);
		
		//echo 'test';die;
		/*
		if (!$this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('auth/login', 'refresh');
		}
		/*	
		elseif (!$this->ion_auth->is_admin()) //remove this elseif if you want to enable this for non-admins
		{
			//redirect them to the home page because they must be an administrator to view this
			return show_error('You must be an administrator to view this page.');
		}
        
		else
		{
			//set the flash data error message if there is one
			$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

			//list the users
			$data['users'] = $this->ion_auth->users()->result();
			foreach ($data['users'] as $k => $user)
			{
				$data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
			}

			// $this->_render_page('auth/index', $data);
                        redirect('home', 'refresh');
		}
		*/
	}
	function page(){
		try{
			$pageRequestBy=$this->input->get('pg');
			if(in_array($pageRequestBy,['seekingcare','employment'])){
				$preferred_lang=get_cookie('pref_language');
				$preferred_lang=$preferred_lang!=''?$preferred_lang:'english';

				$merchant_details=$this->Website_model->getbasicInfo();
				$merchant_details->logo=base_url().'common/frontend/assets/images/logo 1.png';
				$merchant_details->logo_footer=base_url().'common/frontend/assets/images/logo_2.png';

				$website_content=$this->Website_model->getContentList();
				$our_specialities=$this->Website_model->getSpecialitiesList();

				$top_nurses=$this->Website_model->getTopNursesList();

				if($pageRequestBy=='seekingcare'){
					$dataComponents=(object)[
					  	'navbar'=>(object)[
						  	'navs'=>[
							    'home',
							    'about',
							    'services',
							    'login'
							]
					  	],
					  	'intro'=>(object)[
					  		'logo'=>isset($website_content[17]->image)&&$website_content[17]->image!=''?base_url().$website_content[17]->image:'',
					  		'title'=>isset($website_content[17]->heading)?$website_content[17]->heading:'',
					  		'sub_title'=>isset($website_content[17]->sub_heading)?$website_content[17]->sub_heading:'',
					  		'text'=>isset($website_content[17]->description)?json_decode($website_content[17]->description)->{$preferred_lang}:''
					  	],
					  	'whyus'=>(object)[
						  	'title'=>isset($website_content[6]->heading)?$website_content[6]->heading:'',
						  	'sub_title'=>isset($website_content[6]->sub_heading)?$website_content[6]->sub_heading:'',
						  	'text'=>isset($website_content[6]->description)?json_decode($website_content[6]->description)->{$preferred_lang}:'',
						  	'cards'=>[
						    	(object)[
						      		// 'logo'=>base_url().'common/frontend/assets/images/landing/icon_1.png',
						      		'logo'=>isset($website_content[20]->image)&&$website_content[20]->image!=''?base_url().$website_content[20]->image:'',
						      		'title'=>isset($website_content[20]->heading)?$website_content[20]->heading:''
						    	],(object)[
						      		'logo'=>isset($website_content[19]->image)&&$website_content[19]->image!=''?base_url().$website_content[19]->image:'',
						      		'title'=>isset($website_content[19]->heading)?$website_content[19]->heading:''
						    	],(object)[
						      		'logo'=>isset($website_content[8]->image)&&$website_content[8]->image!=''?base_url().$website_content[8]->image:'',
						      		'title'=>isset($website_content[8]->heading)?$website_content[8]->heading:''
						    	],(object)[
						      		'logo'=>isset($website_content[18]->image)&&$website_content[18]->image!=''?base_url().$website_content[18]->image:'',
						      		'title'=>isset($website_content[18]->heading)?$website_content[18]->heading:''
						    	]
						  	]
						],
						'about'=>(object)[
							'logo'=>isset($website_content[21]->image)&&$website_content[21]->image!=''?base_url().$website_content[21]->image:'',
						  	'title'=>isset($website_content[21]->heading)?$website_content[21]->heading:'',
						  	'sub_title'=>isset($website_content[21]->sub_heading)?$website_content[21]->sub_heading:'',
						  	'text'=>isset($website_content[21]->description)?json_decode($website_content[21]->description)->{$preferred_lang}:''
						],
					  	'services'=>(object)[
					  		'title'=>isset($our_specialities[0]->heading)?$our_specialities[0]->heading:'',
						  	'sub_title'=>isset($our_specialities[0]->description)?$our_specialities[0]->description:'',
						  	'text'=>lang('The_WeCuro_platform_connectivitscreening_quality_medical_providers_capabilities'),
						  	'cards'=>[
						    	(object)[
						      		'logo'=>isset($our_specialities[1]->image)&&$our_specialities[1]->image!=''?base_url().$our_specialities[1]->image:'',
						      		'title'=>isset($our_specialities[1]->heading)?$our_specialities[1]->heading:'',
						      		'text'=>isset($our_specialities[1]->description)?$our_specialities[1]->description:'',
						      		'order'=>1
						    	],(object)[
						      		'logo'=>isset($our_specialities[2]->image)&&$our_specialities[2]->image!=''?base_url().$our_specialities[2]->image:'',
						      		'title'=>isset($our_specialities[2]->heading)?$our_specialities[2]->heading:'',
						      		'text'=>isset($our_specialities[2]->description)?$our_specialities[2]->description:'',
						      		'order'=>2
						    	],(object)[
						      		'logo'=>isset($our_specialities[3]->image)&&$our_specialities[3]->image!=''?base_url().$our_specialities[3]->image:'',
						      		'title'=>isset($our_specialities[3]->heading)?$our_specialities[3]->heading:'',
						      		'text'=>isset($our_specialities[3]->description)?$our_specialities[3]->description:'',
						      		'order'=>3
						    	]
						  	]
					  	],
					  	'footer'=>(object)[
					  		'logo_group_social'=>base_url().'common/frontend/assets/images/group-social-share.svg',
					  		'logo_google_play'=>base_url().'common/frontend/assets/images/google-play.svg',
					  		'logo_app_store'=>base_url().'common/frontend/assets/images/app-store.svg',
						  	'navs'=>[
						    	'about',
						    	'whyus',
						    	'services',
						    	'privacy_policy',
						    	'terms_conditions'
						  	]
						]
					];
					$data=(object)[
						'data'=>(object)[
						  	'components'=>$dataComponents,
						  	'page'=>'seekingcare',
						  	'merchant_details'=>$merchant_details,
						  	'preferred_lang'=>$preferred_lang
						]
					];
					$this->load->view('frontend/pages/seekingcare',$data);
				}
				else if($pageRequestBy=='employment'){
					$dataComponents=(object)[
					  	'navbar'=>(object)[
						  	'navs'=>[
							    'home',
							    'about',
							    'process',
							    'login'
							]
					  	],
					  	'intro'=>(object)[
					  		'logo'=>isset($website_content[22]->image)&&$website_content[22]->image!=''?base_url().$website_content[22]->image:'',
					  		'title'=>isset($website_content[22]->heading)?$website_content[22]->heading:'',
					  		'sub_title'=>isset($website_content[22]->sub_heading)?$website_content[22]->sub_heading:'',
					  		'text'=>isset($website_content[22]->description)?json_decode($website_content[22]->description)->{$preferred_lang}:''
					  	],
					  	'whyus'=>(object)[
						  	'title'=>isset($website_content[6]->heading)?$website_content[6]->heading:'',
						  	'sub_title'=>isset($website_content[6]->sub_heading)?$website_content[6]->sub_heading:'',
						  	'text'=>isset($website_content[6]->description)?json_decode($website_content[6]->description)->{$preferred_lang}:'',
						  	'cards'=>[
							    (object)[
							      'logo'=>isset($website_content[7]->image)&&$website_content[7]->image!=''?base_url().$website_content[7]->image:'',
							      'title'=>isset($website_content[7]->heading)?$website_content[7]->heading:''
							    ],(object)[
							      'logo'=>isset($website_content[23]->image)&&$website_content[23]->image!=''?base_url().$website_content[23]->image:'',
							      'title'=>isset($website_content[23]->heading)?$website_content[23]->heading:''
							    ],(object)[
							      'logo'=>isset($website_content[24]->image)&&$website_content[24]->image!=''?base_url().$website_content[24]->image:'',
							      'title'=>isset($website_content[24]->heading)?$website_content[24]->heading:''
							    ],(object)[
							      'logo'=>isset($website_content[8]->image)&&$website_content[8]->image!=''?base_url().$website_content[8]->image:'',
							      'title'=>isset($website_content[8]->heading)?$website_content[8]->heading:''
							    ]
						  	]
						],
						'about'=>(object)[
							'logo'=>isset($website_content[21]->image)&&$website_content[21]->image!=''?base_url().$website_content[21]->image:'',
						  	'title'=>isset($website_content[21]->heading)?$website_content[21]->heading:'',
						  	'sub_title'=>isset($website_content[21]->sub_heading)?$website_content[21]->sub_heading:'',
						  	'text'=>isset($website_content[21]->description)?json_decode($website_content[21]->description)->{$preferred_lang}:''
						],
					  	'nurses'=>(object)[
					  		'title'=>isset($website_content[26]->heading)?$website_content[26]->heading:'',
						  	'sub_title'=>isset($website_content[26]->sub_heading)?$website_content[26]->sub_heading:'',
						  	'text'=>isset($website_content[26]->description)?json_decode($website_content[26]->description)->{$preferred_lang}:'',
						  	'cards'=>[
							    (object)[
							      'logo'=>isset($top_nurses[0]->image)&&$top_nurses[0]->image!=''?base_url().$top_nurses[0]->image:'',
							      'name'=>isset($top_nurses[0]->name)?$top_nurses[0]->name:'',
							      'address'=>isset($top_nurses[0]->address)?$top_nurses[0]->address:''
							    ],(object)[
							      'logo'=>isset($top_nurses[1]->image)&&$top_nurses[1]->image!=''?base_url().$top_nurses[1]->image:'',
							      'name'=>isset($top_nurses[1]->name)?$top_nurses[1]->name:'',
							      'address'=>isset($top_nurses[1]->address)?$top_nurses[1]->address:''
							    ],(object)[
							      'logo'=>isset($top_nurses[2]->image)&&$top_nurses[2]->image!=''?base_url().$top_nurses[2]->image:'',
							      'name'=>isset($top_nurses[2]->name)?$top_nurses[2]->name:'',
							      'address'=>isset($top_nurses[2]->address)?$top_nurses[2]->address:''
							    ],(object)[
							      'logo'=>isset($top_nurses[3]->image)&&$top_nurses[3]->image!=''?base_url().$top_nurses[3]->image:'',
							      'name'=>isset($top_nurses[3]->name)?$top_nurses[3]->name:'',
							      'address'=>isset($top_nurses[3]->address)?$top_nurses[3]->address:''
							    ]
						  	]
					  	],
					  	'process'=>(object)[
					  		'logo'=>isset($website_content[25]->image)&&$website_content[25]->image!=''?base_url().$website_content[25]->image:'',
					  		'title'=>isset($website_content[25]->heading)?$website_content[25]->heading:'',
						  	'sub_title'=>isset($website_content[25]->sub_heading)?$website_content[25]->sub_heading:'',
						  	'text'=>isset($website_content[25]->description)?json_decode($website_content[25]->description)->{$preferred_lang}:'',
					  		'cards'=>[
							    (object)[
							      'logo'=>base_url().'common/frontend/assets/images/landing/useredit.svg',
							      'title'=>'Signup',
							      'order'=>1
							    ],(object)[
							      'logo'=>base_url().'common/frontend/assets/images/landing/i3dcubescan.svg',
							      'title'=>'Personalize',
							      'order'=>2
							    ],(object)[
							      'logo'=>base_url().'common/frontend/assets/images/landing/verify.svg',
							      'title'=>'Verification',
							      'order'=>3
							    ],(object)[
							      'logo'=>base_url().'common/frontend/assets/images/landing/clipboardtext.svg',
							      'title'=>'Onboarding',
							      'order'=>4
							    ],(object)[
							      'logo'=>base_url().'common/frontend/assets/images/landing/tickcircle.svg',
							      'title'=>'Apply',
							      'order'=>5
							    ]
						  	]
					  	],
					  	'footer'=>(object)[
					  		'logo_group_social'=>base_url().'common/frontend/assets/images/group-social-share.svg',
					  		'logo_google_play'=>base_url().'common/frontend/assets/images/google-play.svg',
					  		'logo_app_store'=>base_url().'common/frontend/assets/images/app-store.svg',
						  	'navs'=>[
						    	'about',
						    	'whyus',
						    	'nurses',
						    	'process',
						    	'privacy_policy',
						    	'terms_conditions'
						  	]
						]
					];
					$data=(object)[
						'data'=>(object)[
						  	'components'=>$dataComponents,
						  	'page'=>'employment',
						  	'merchant_details'=>$merchant_details,
						  	'preferred_lang'=>$preferred_lang,
						  	'caregiver_skill_list'=>$this->Website_model->caregiver_skill_list()
						]
					];
					$this->load->view('frontend/pages/employment',$data);
				}
			}else{
				redirect('/');
			}
		}catch(Exception $e){
            $getMsg="Auth - seekingcare: ".$e->getMessage();
            echo $getMsg;
        }
	}
	function  checkEmail()
	{
        //$email=$this->input->input_stream('email');
		$email=$this->input->get('email');
        $result=$this->Caregiver_model->checkEmail($email);
        echo $result;
    }

	//log the user in
	function login()
	{
		$data['indeedUri'] = "https://secure.indeed.com/oauth/v2/authorize?client_id=".INDEED_CLIENT_ID."&redirect_uri=".$this->indeed_redirect_uri."&response_type=code&state=employer1234&scope=email+offline_access+employer_access";
		//$data['linkedInUriLgn'] = $this->linkedin->getAuthUrl("http://52.229.31.187/app/auth/loginLinkedin");
		$data['linkedInUriLgn'] = $this->linkedin->getAuthUrl();
        // echo $data['linkedInUriLgn']; die;   
        if ($this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('home');
		}

		$data['title'] = "Login";

		//validate form input
		$this->form_validation->set_rules('identity', 'Identity', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');

		if ($this->form_validation->run() == true)
		{
			/*
			| check to see if the user is logging in
			| check for "remember me"
			*/
			$remember = (bool) $this->input->post('remember');

			if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
			{
				/*
				| if the login is successful
				| redirect them back to the home page
				*/
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect('/home', 'refresh');
			}
			else
			{
				/*
				| if the login is un-successful
				| redirect them back to the login page
				*/
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect('auth/login', 'refresh'); #use redirects instead of loading views for compatibility with MY_Controller libraries
			}
		}
		else
		{
			/*
			| the user is not logging in so display the login page
			| set the flash data error message if there is one
			*/
			$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

			$data['identity'] = array(
				'name' => 'identity',
				'id' => 'identity',
				'type' => 'text',
				'value' => $this->form_validation->set_value('identity'),
			);
			$data['password'] = array(
				'name' => 'password',
				'id' => 'password',
				'type' => 'password',
			);

			$this->_render_page('auth/login', $data);
		}
	}
	//log the user in using linkedin
	function loginLinkedin()
	{
		$data['indeedUri'] = "https://secure.indeed.com/oauth/v2/authorize?client_id=".INDEED_CLIENT_ID."&redirect_uri=".$this->indeed_redirect_uri."&response_type=code&state=employer1234&scope=email+offline_access+employer_access";
		$data['linkedInUriLgn'] = $this->linkedin->getAuthUrl("http://beta.wecuro.com/auth/loginLinkedin");  
        if ($this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('home');
		}
		$data['title'] = "Login";

		if($_GET['code'] != '')
		{
			$accessToken = $this->linkedin->getAccessToken($_GET['code']);
			$profile = $this->linkedin->getPerson();
			$Profemail = $this->linkedin->getEmail();
			// pre($data['profile']);

			$profEmail = (array) $Profemail->elements[0];
			$data['linkedInEmail'] = $profEmail['handle~']->emailAddress;
			$data['linkedInFname'] = $profile->firstName->localized->en_US;
			$data['linkedInLname'] = $profile->lastName->localized->en_US;
		}
			$emailID = $data['linkedInEmail'];


			//check to see if the user is logging in
			//check for "remember me"
			$remember = false;

			if ($this->ion_auth->loginLinkedin($emailID, $remember))
			{
				//if the login is successful
				//redirect them back to the home page
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect('/home', 'refresh');
			}
			else
			{
				//if the login was un-successful
				//redirect them back to the login page
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect('auth/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
			}
	}

	function register_with_linkedin()
	{
		$url = $this->linkedin->getAuthUrl();
		redirect($url);
	}

	function loginIndeed()
	{
		if(isset($_GET['code']) && $_GET['code']!="")
		{
			// $ch = curl_init();
			// $headers = array(
			// 'Accept: application/json',
			// "Content-Type: application/x-www-form-urlencoded"
			// );
			// $code = $_GET['code'];
			// curl_setopt($ch, CURLOPT_URL,"https://apis.indeed.com/oauth/v2/tokens?code={$code}&client_id=967561e900e24529b708e3797e5170d4e266f0e9ad9c9961ad120c7b395702c9&client_secret=rphUR318JIN6hn1xiksAeSqkZzwFTauJU6nYXqq9D58wky9aQ4Bf9UO6lDWPUAt0&redirect_uri=http%3A%2F%2Flocalhost%2Fhospital-management%2Fauth%2FloginIndeed&grant_type=authorization_code");
			// curl_setopt($ch, CURLOPT_POST, 1);
			// curl_setopt($ch, CURLOPT_POSTFIELDS,
			// 			"postvar1=value1&postvar2=value2&postvar3=value3");
	
			// // Receive server response ...
			// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
			// $server_output = curl_exec($ch);
			// $x = json_decode($server_output);
			// // echo $x->id_token;
			// // $data = json_decode($server_output);
			// $indData = $this->jwt_request($x->access_token);

			$code = $_GET['code'];
			$details=$this->getIndeedAccessToken($code);
			$indData = $this->jwt_request($details->access_token);
			// _die($indData);
			
		}


				/**
		 * Indeed login
		 */
		$data['indeedUri'] = "https://secure.indeed.com/oauth/v2/authorize?client_id=".INDEED_CLIENT_ID."&redirect_uri=".$this->indeed_redirect_uri."&response_type=code&state=employer1234&scope=email+offline_access+employer_access";
		$data['indData'] = $indData;
		$data['indeedEmail'] = $indeedEmail = $indData->email;
		
		$remember = false;
			if ($this->ion_auth->loginLinkedin($indeedEmail, $remember))
			{
				//if the login is successful
				//redirect them back to the home page
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect('/home', 'refresh');
			}
		// _die($indData->email);
		/*********************/
		header('Content-Type: text/html');

		$data['banner']=$this->Website_model->getBannerList();
		$data['content']=$this->Website_model->getContentList();
		$data['basic']=$this->Website_model->getbasicInfo();
	
		$this->load->view('frontend/header',$data);
		$this->load->view('frontend/index',$data);
		$this->load->view('frontend/footer',$data);

	}
	public function getIndeedAccessToken($code)
    {
        $url = "https://apis.indeed.com/oauth/v2/tokens";
        $params = [
            'client_id' => INDEED_CLIENT_ID,
            'client_secret' => INDEED_CLIENT_SECRET,
            'redirect_uri' => indeed_oauth_redirect_uri,
            'code' => $code,
            'grant_type' => INDEED_GRANT_TYPE,
        ];
        $response = $this->postcurl($url,$params);
        $accessDetails = json_decode($response);
        return $accessDetails;
    }
	protected function postcurl($url, $parameters)
    { 
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

		$headers = array(
		"Content-Type: application/x-www-form-urlencoded",
		);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		$postvars = '';
		foreach($parameters as $key=>$value) {
			$postvars .= $key . "=" . $value . "&";
		}

		curl_setopt($curl, CURLOPT_POSTFIELDS, $postvars);

		//for debug only!
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

		$result = curl_exec($curl);
        return $result;
    }

	function jwt_request($token, $post=array()) 
	{
		header('Content-Type: application/json'); // Specify the type of data
		$ch = curl_init('https://secure.indeed.com/v2/api/userinfo'); // Initialise cURL
		$post = json_encode($post); // Encode the data array into a JSON string
		$authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
		$result = curl_exec($ch); // Execute the cURL statement
		curl_close($ch); // Close the cURL connection
		return json_decode($result); // Return the received data
	}



	//log the user out
	function logout()
	{
		$data['title'] = "Logout";

		//log the user out
		$logout = $this->ion_auth->logout();
		//$linkdinLogout = $this->linkdinLogoutUrl();
		// $homepage = file_get_contents('https://www.linkedin.com/m/logout');
		
		$accessToken = $this->session->userdata('accessToken');
		// $data=$this->linkedin->linkdinLogoutUrl($accessToken);
		// echo $data;die;
		//redirect them to the login page
		$this->session->set_flashdata('message', $this->ion_auth->messages());
		redirect('auth/login', 'refresh');
	}
	// function linkdinLogoutUrl(){
	// 	return curl_init("https://www.linkedin.com/m/logout");
	// }

	//change password
	function change_password()
	{
		$this->form_validation->set_rules('old', $this->lang->line('change_password_validation_old_password_label'), 'required');
		$this->form_validation->set_rules('new', $this->lang->line('change_password_validation_new_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
		$this->form_validation->set_rules('new_confirm', $this->lang->line('change_password_validation_new_password_confirm_label'), 'required');

		if (!$this->ion_auth->logged_in())
		{
			redirect('auth/login', 'refresh');
		}

		$user = $this->ion_auth->user()->row();

		if ($this->form_validation->run() == false)
		{
			//display the form
			//set the flash data error message if there is one
			$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

			$data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
			$data['old_password'] = array(
				'name' => 'old',
				'id'   => 'old',
				'type' => 'password',
			);
			$data['new_password'] = array(
				'name' => 'new',
				'id'   => 'new',
				'type' => 'password',
				'pattern' => '^.{'.$data['min_password_length'].'}.*$',
			);
			$data['new_password_confirm'] = array(
				'name' => 'new_confirm',
				'id'   => 'new_confirm',
				'type' => 'password',
				'pattern' => '^.{'.$data['min_password_length'].'}.*$',
			);
			$data['user_id'] = array(
				'name'  => 'user_id',
				'id'    => 'user_id',
				'type'  => 'hidden',
				'value' => $user->id,
			);

			//render
			$this->_render_page('auth/change_password', $data);
		}
		else
		{
			$identity = $this->session->userdata('identity');

			$change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));

			if ($change)
			{
				//if the password was successfully changed
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				$this->logout();
			}
			else
			{
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect('auth/change_password', 'refresh');
			}
		}
	}

	//forgot password
	function forgot_password()
	{
		//setting validation rules by checking wheather identity is username or email
		if($this->config->item('identity', 'ion_auth') == 'username' )
		{
		   $this->form_validation->set_rules('email', $this->lang->line('forgot_password_username_identity_label'), 'required');
		}
		else
		{
		   $this->form_validation->set_rules('email', $this->lang->line('forgot_password_validation_email_label'), 'required|valid_email');
		}


		if ($this->form_validation->run() == false)
		{
			//setup the input
			$data['email'] = array('name' => 'email',
				'id' => 'email',
			);

			if ( $this->config->item('identity', 'ion_auth') == 'username' ){
				$data['identity_label'] = $this->lang->line('forgot_password_username_identity_label');
			}
			else
			{
				$data['identity_label'] = $this->lang->line('forgot_password_email_identity_label');
			}

			//set any errors and display the form
			$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
			$this->_render_page('auth/forgot_password', $data);
		}
		else
		{
			// get identity from username or email
			if ( $this->config->item('identity', 'ion_auth') == 'username' ){
				$identity = $this->ion_auth->where('username', strtolower($this->input->post('email')))->users()->row();
			}
			else
			{
				$identity = $this->ion_auth->where('email', strtolower($this->input->post('email')))->users()->row();
			}
	            	if(empty($identity)) {

	            		if($this->config->item('identity', 'ion_auth') == 'username')
		            	{
                                   $this->ion_auth->set_message('forgot_password_username_not_found');
		            	}
		            	else
		            	{
		            	   $this->ion_auth->set_message('forgot_password_email_not_found');
		            	}

		                $this->session->set_flashdata('message', $this->ion_auth->messages());
                		redirect("auth/forgot_password", 'refresh');
            		}

			//run the forgotten password method to email an activation code to the user
			$forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')});

			if ($forgotten)
			{
				//if there were no errors
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect("auth/login", 'refresh'); //we should display a confirmation page here instead of the login page
			}
			else
			{
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect("auth/forgot_password", 'refresh');
			}
		}
	}

	//reset password - final step for forgotten password
	public function reset_password($code = NULL)
	{
		if (!$code)
		{
			show_404();
		}

		$user = $this->ion_auth->forgotten_password_check($code);

		if ($user)
		{
			//if the code is valid then display the password reset form

			$this->form_validation->set_rules('new', $this->lang->line('reset_password_validation_new_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
			$this->form_validation->set_rules('new_confirm', $this->lang->line('reset_password_validation_new_password_confirm_label'), 'required');

			if ($this->form_validation->run() == false)
			{
				//display the form

				//set the flash data error message if there is one
				$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

				$data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
				$data['new_password'] = array(
					'name' => 'new',
					'id'   => 'new',
				'type' => 'password',
					'pattern' => '^.{'.$data['min_password_length'].'}.*$',
				);
				$data['new_password_confirm'] = array(
					'name' => 'new_confirm',
					'id'   => 'new_confirm',
					'type' => 'password',
					'pattern' => '^.{'.$data['min_password_length'].'}.*$',
				);
				$data['user_id'] = array(
					'name'  => 'user_id',
					'id'    => 'user_id',
					'type'  => 'hidden',
					'value' => $user->id,
				);
				$data['csrf'] = $this->_get_csrf_nonce();
				$data['code'] = $code;

				//render
				$this->_render_page('auth/reset_password', $data);
			}
			else
			{
				// do we have a valid request?
				if ($this->_valid_csrf_nonce() === FALSE || $user->id != $this->input->post('user_id'))
				{

					//something fishy might be up
					$this->ion_auth->clear_forgotten_password_code($code);

					show_error($this->lang->line('error_csrf'));

				}
				else
				{
					// finally change the password
					$identity = $user->{$this->config->item('identity', 'ion_auth')};

					$change = $this->ion_auth->reset_password($identity, $this->input->post('new'));

					if ($change)
					{
						//if the password was successfully changed
						$this->session->set_flashdata('message', $this->ion_auth->messages());
						redirect("auth/login", 'refresh');
					}
					else
					{
						$this->session->set_flashdata('message', $this->ion_auth->errors());
						redirect('auth/reset_password/' . $code, 'refresh');
					}
				}
			}
		}
		else
		{
			//if the code is invalid then send them back to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("auth/forgot_password", 'refresh');
		}
	}


	//activate the user
	function activate($id, $code=false)
	{
		if ($code !== false)
		{
			$activation = $this->ion_auth->activate($id, $code);
		}
		else if ($this->ion_auth->is_admin())
		{
			$activation = $this->ion_auth->activate($id);
		}

		if ($activation)
		{
			//redirect them to the auth page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect("auth", 'refresh');
		}
		else
		{
			//redirect them to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("auth/forgot_password", 'refresh');
		}
	}

	//deactivate the user
	function deactivate($id = NULL)
	{
		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			//redirect them to the home page because they must be an administrator to view this
			return show_error('You must be an administrator to view this page.');
		}

		$id = (int) $id;

		$this->load->library('form_validation');
		$this->form_validation->set_rules('confirm', $this->lang->line('deactivate_validation_confirm_label'), 'required');
		$this->form_validation->set_rules('id', $this->lang->line('deactivate_validation_user_id_label'), 'required|alpha_numeric');

		if ($this->form_validation->run() == FALSE)
		{
			// insert csrf check
			$data['csrf'] = $this->_get_csrf_nonce();
			$data['user'] = $this->ion_auth->user($id)->row();

			$this->_render_page('auth/deactivate_user', $data);
		}
		else
		{
			// do we really want to deactivate?
			if ($this->input->post('confirm') == 'yes')
			{
				// do we have a valid request?
				if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
				{
					show_error($this->lang->line('error_csrf'));
				}

				// do we have the right userlevel?
				if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
				{
					$this->ion_auth->deactivate($id);
				}
			}

			//redirect them back to the auth page
			redirect('auth', 'refresh');
		}
	}

	//create a new user
	function create_user()
	{
		$data['title'] = "Create User";

		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			redirect('auth', 'refresh');
		}

		$tables = $this->config->item('tables','ion_auth');

		//validate form input
		$this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required');
		$this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'));
		$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique['.$tables['users'].'.email]');
		$this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required');
		$this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'));
		$this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
		$this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');

		if ($this->form_validation->run() == true)
		{
			$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
			$email    = strtolower($this->input->post('email'));
			$password = $this->input->post('password');

			$additional_data = array(
				'first_name' => $this->input->post('first_name'),
				'last_name'  => $this->input->post('last_name'),
				'company'    => $this->input->post('company'),
				'phone'      => $this->input->post('phone'),
			);
		}
		if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
		{
			//check to see if we are creating the user
			//redirect them back to the admin page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect("auth", 'refresh');
		}
		else
		{
			//display the create user form
			//set the flash data error message if there is one
			$data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

			$data['first_name'] = array(
				'name'  => 'first_name',
				'id'    => 'first_name',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('first_name'),
			);
			$data['last_name'] = array(
				'name'  => 'last_name',
				'id'    => 'last_name',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('last_name'),
			);
			$data['email'] = array(
				'name'  => 'email',
				'id'    => 'email',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('email'),
			);
			$data['company'] = array(
				'name'  => 'company',
				'id'    => 'company',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('company'),
			);
			$data['phone'] = array(
				'name'  => 'phone',
				'id'    => 'phone',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('phone'),
			);
			$data['password'] = array(
				'name'  => 'password',
				'id'    => 'password',
				'type'  => 'password',
				'value' => $this->form_validation->set_value('password'),
			);
			$data['password_confirm'] = array(
				'name'  => 'password_confirm',
				'id'    => 'password_confirm',
				'type'  => 'password',
				'value' => $this->form_validation->set_value('password_confirm'),
			);

			$this->_render_page('auth/create_user', $data);
		}
	}

	//edit a user
	function edit_user($id)
	{
		$data['title'] = "Edit User";

		if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id)))
		{
			redirect('auth', 'refresh');
		}

		$user = $this->ion_auth->user($id)->row();
		$groups=$this->ion_auth->groups()->result_array();
		$currentGroups = $this->ion_auth->get_users_groups($id)->result();

		//validate form input
		$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required');
		$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required');
		$this->form_validation->set_rules('phone', $this->lang->line('edit_user_validation_phone_label'), 'required');
		$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required');

		if (isset($_POST) && !empty($_POST))
		{
			// do we have a valid request?
			if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
			{
				show_error($this->lang->line('error_csrf'));
			}

			//update the password if it was posted
			if ($this->input->post('password'))
			{
				$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
				$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
			}

			if ($this->form_validation->run() === TRUE)
			{
				$data = array(
					'first_name' => $this->input->post('first_name'),
					'last_name'  => $this->input->post('last_name'),
					'company'    => $this->input->post('company'),
					'phone'      => $this->input->post('phone'),
				);

				//update the password if it was posted
				if ($this->input->post('password'))
				{
					$data['password'] = $this->input->post('password');
				}



				// Only allow updating groups if user is admin
				if ($this->ion_auth->is_admin())
				{
					//Update the groups user belongs to
					$groupData = $this->input->post('groups');

					if (isset($groupData) && !empty($groupData)) {

						$this->ion_auth->remove_from_group('', $id);

						foreach ($groupData as $grp) {
							$this->ion_auth->add_to_group($grp, $id);
						}

					}
				}

			//check to see if we are updating the user
			   if($this->ion_auth->update($user->id, $data))
			    {
			    	//redirect them back to the admin page if admin, or to the base url if non admin
				    $this->session->set_flashdata('message', $this->ion_auth->messages() );
				    if ($this->ion_auth->is_admin())
					{
						redirect('auth', 'refresh');
					}
					else
					{
						redirect('/', 'refresh');
					}

			    }
			    else
			    {
			    	//redirect them back to the admin page if admin, or to the base url if non admin
				    $this->session->set_flashdata('message', $this->ion_auth->errors() );
				    if ($this->ion_auth->is_admin())
					{
						redirect('auth', 'refresh');
					}
					else
					{
						redirect('/', 'refresh');
					}

			    }

			}
		}

		//display the edit user form
		$data['csrf'] = $this->_get_csrf_nonce();

		//set the flash data error message if there is one
		$data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

		//pass the user to the view
		$data['user'] = $user;
		$data['groups'] = $groups;
		$data['currentGroups'] = $currentGroups;

		$data['first_name'] = array(
			'name'  => 'first_name',
			'id'    => 'first_name',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('first_name', $user->first_name),
		);
		$data['last_name'] = array(
			'name'  => 'last_name',
			'id'    => 'last_name',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('last_name', $user->last_name),
		);
		$data['company'] = array(
			'name'  => 'company',
			'id'    => 'company',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('company', $user->company),
		);
		$data['phone'] = array(
			'name'  => 'phone',
			'id'    => 'phone',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('phone', $user->phone),
		);
		$data['password'] = array(
			'name' => 'password',
			'id'   => 'password',
			'type' => 'password'
		);
		$data['password_confirm'] = array(
			'name' => 'password_confirm',
			'id'   => 'password_confirm',
			'type' => 'password'
		);

		$this->_render_page('auth/edit_user', $data);
	}

	// create a new group
	function create_group()
	{
		$data['title'] = $this->lang->line('create_group_title');

		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			redirect('auth', 'refresh');
		}

		//validate form input
		$this->form_validation->set_rules('group_name', $this->lang->line('create_group_validation_name_label'), 'required|alpha_dash');

		if ($this->form_validation->run() == TRUE)
		{
			$new_group_id = $this->ion_auth->create_group($this->input->post('group_name'), $this->input->post('description'));
			if($new_group_id)
			{
				// check to see if we are creating the group
				// redirect them back to the admin page
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect("auth", 'refresh');
			}
		}
		else
		{
			//display the create group form
			//set the flash data error message if there is one
			$data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

			$data['group_name'] = array(
				'name'  => 'group_name',
				'id'    => 'group_name',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('group_name'),
			);
			$data['description'] = array(
				'name'  => 'description',
				'id'    => 'description',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('description'),
			);

			$this->_render_page('auth/create_group', $data);
		}
	}

	//edit a group
	function edit_group($id)
	{
		// bail if no group id given
		if(!$id || empty($id))
		{
			redirect('auth', 'refresh');
		}

		$data['title'] = $this->lang->line('edit_group_title');

		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			redirect('auth', 'refresh');
		}

		$group = $this->ion_auth->group($id)->row();

		//validate form input
		$this->form_validation->set_rules('group_name', $this->lang->line('edit_group_validation_name_label'), 'required|alpha_dash');

		if (isset($_POST) && !empty($_POST))
		{
			if ($this->form_validation->run() === TRUE)
			{
				$group_update = $this->ion_auth->update_group($id, $_POST['group_name'], $_POST['group_description']);

				if($group_update)
				{
					$this->session->set_flashdata('message', $this->lang->line('edit_group_saved'));
				}
				else
				{
					$this->session->set_flashdata('message', $this->ion_auth->errors());
				}
				redirect("auth", 'refresh');
			}
		}

		//set the flash data error message if there is one
		$data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

		//pass the user to the view
		$data['group'] = $group;

		$readonly = $this->config->item('admin_group', 'ion_auth') === $group->name ? 'readonly' : '';

		$data['group_name'] = array(
			'name'  => 'group_name',
			'id'    => 'group_name',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('group_name', $group->name),
			$readonly => $readonly,
		);
		$data['group_description'] = array(
			'name'  => 'group_description',
			'id'    => 'group_description',
			'type'  => 'text',
			'value' => $this->form_validation->set_value('group_description', $group->description),
		);

		$this->_render_page('auth/edit_group', $data);
	}

	function _get_csrf_nonce()
	{
		$this->load->helper('string');
		$key   = random_string('alnum', 8);
		$value = random_string('alnum', 20);
		$this->session->set_flashdata('csrfkey', $key);
		$this->session->set_flashdata('csrfvalue', $value);

		return array($key => $value);
	}

	function _valid_csrf_nonce()
	{
		if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
			$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}

	function _render_page($view, $data=null, $render=false)
	{

		$this->viewdata = (empty($data)) ? $data: $data;

		$view_html = $this->load->view($view, $this->viewdata, $render);

		if (!$render) return $view_html;
	}

	function register() {
        // _die($_POST);
        $id = $this->input->post('id');
        //print_r($id);die;
        $form_status = $this->input->post('form_status');
        $form_mode = $this->input->post('form_mode');
        $fname = $this->input->post('fname');        
        $lname = $this->input->post('lname');        
        $email = $this->input->post('email');        
        $phone = $this->input->post('phone');
        $password = $this->input->post('password');
        $qualification_type = $this->input->post('qualification_type');
        $oauth_uid = $this->input->post('oauth_uid');
        $oauth_provider = $this->input->post('oauth_provider');
        $hire_type = "New Hire";

        /*recaptcha validation*/
            $recaptcha=$this->input->post('g-recaptcha-response');
            $recaptcha_result=validateCaptcha($recaptcha);
			if(intval($recaptcha_result["success"])!==1){
				redirect(base_url()."auth/page?pg=employment&captcha=invalid");
				exit(0);
			}
		/*recaptcha validation*/

        #if patient do not have email then create custom one
            if($email==""){
                for($i=1; $i<99999; $i++){
                    $email=strtolower($fname).'.'.generateRandomString(12)."@hms.com";
                    $checkEmail=$this->Referral_model->checkMail($email);
                    if($checkEmail==0){if($this->ion_auth->email_check($email)){continue;}else{break;}}else{continue;}
                } 
            }
        #if patient do not have email then create custom one
        
            $data = array();
            if(empty($id)){
                if ($this->ion_auth->email_check($email)) {
                    $this->session->set_flashdata('feedback_error', 'This Email Address Is Already Registered');
                    redirect('caregivers/addNewCaregiver');
                }else{
                    if($hire_type=='Re-Hire' && $date_of_re_hire==''){
						echo 'else er if:'.$email.'
';die; $this->session->set_flashdata('feedback_error', 'Enter re-hire daate.'); redirect('caregivers/addNewCaregiver'); }else{ $username = $this->input->post('fname'); $dfg = 6; $this->ion_auth->register($username, $password, $email,$dfg,$oauth_uid,$oauth_provider); $ion_user_id = $this->db->get_where('users', array('email' => $email))->row()->id; } } $application_date=date ('Y-m-d', now()); if(isset($_POST['fname'])){ $data['fname'] = $fname; } if(isset($_POST['mid_name'])){ $data['mid_name'] = $_POST['mid_name']; } if(isset($_POST['lname'])){ $data['lname'] = $lname; } if(isset($_POST['email'])){ $data['email'] = $email;} //if(isset($_POST['dependents'])){ $data['dependents'] = $dependents; } if(isset($_POST['qualification_type'])){ $data['qualification_type'] = $_POST['qualification_type']; } if(isset($_POST['hire_type'])){ $data['hire_type'] = $hire_type; } if(isset($_POST['date_of_re_hire'])){ $data['date_of_re_hire'] = $date_of_re_hire; } if(isset($_POST['phone'])){ $data['phone'] = $phone; } $data['caregiver_id']=''.str_pad($ion_user_id, 6, "0", STR_PAD_LEFT); $data['ion_user_id'] = $ion_user_id; $data['application_date'] = $application_date; $data['created_by'] = ''; $data['form_status'] = 1; $data['status'] = 1; $pctg = array(); $pctg['form1']=0;$pctg['form2']=0;$pctg['form3']=0;$pctg['form4']=0;$pctg['form5']=0;$pctg['form6']=0;$pctg['form7']=0;$pctg['form8']=0;$pctg['form9']=0;$pctg['form10']=0;$pctg['form11']=0; $data['from_tab_status_pctg'] = json_encode($pctg); // _die($data); $cargiverId=$this->Caregiver_model->insertNurse($data); // _die($cargiverId); $this->session->set_flashdata('caregiver_created', 'Caregiver created successfully.'); // _die($cargiverId); // EMAIL TO CAREGIVER $name=$fname." ".$lname; $designation="caregiver"; $company="Hospital Management System"; $emaildata['emaildata'] = array( 'name' => $name, 'email' => $email, 'password' => $password, 'designation' => $designation, 'link' => base_url(), 'company' => $company ); $message= $this->load->view('email_template_management/email_caregiver',$emaildata,TRUE); $from = array( 'name' => 'HMS Admin', 'email' => 'admin@hms.com' ); $subject ='Caregiver Account confirmation'; send_email($from,$email,$subject,$message); sleep(3); $remember = false; if ($this->ion_auth->loginLinkedin($email, $remember)) { redirect('/home'); } else{ echo "
auth fail---------------------------------------------------";die; } redirect('/'); } } /* | updated on 07-09-2021 |------------------------ | this contactMessage method was transfered | here from website_setting controller */ function contactMessage() { $data['name']=$_POST['name']; $data['email']=$_POST['email']; $data['subject']=$_POST['subject']; $data['message']=$_POST['message']; // pre($data); if(!empty($data)) { $success=$this->Website_model->saveContactMessage($data); if($success>0) { $this->session->set_flashdata('msg_success', 'Your message has been sent.'); } else { $this->session->set_flashdata('msg_error', 'Your message not sent'); } redirect('/#contact-section'); } } function setLanguageCookie() { $lang = $this->input->get('lang'); $this->load->helper(array('cookie')); set_cookie('pref_language',$lang,'3600'); echo get_cookie('pref_language'); } function register_patient(){ // pre($this->input->post());die(); $pid=$this->input->post("pid"); if($pid==''){ $email=$this->input->post('email'); $fname=$this->input->post('fname'); $lname=$this->input->post('lname'); $oauth_uid=$this->input->post('oauth_uid'); $oauth_provider=$this->input->post('oauth_provider'); $oauth_provider=$oauth_provider!=''?$oauth_provider:"general"; /*recaptcha validation*/ $recaptcha=$this->input->post('g-recaptcha-response'); $recaptcha_result=validateCaptcha($recaptcha); if(intval($recaptcha_result["success"])!==1){ redirect(base_url()."auth/page?pg=seekingcare&captcha=invalid"); exit(0); } /*recaptcha validation*/ #if patient do not have email then create custom one if($email==""){ for($i=1; $i<99999; $i++){ $email=strtolower($fname).'.'.generateRandomString(12)."@hms.com"; $checkEmail=$this->Referral_model->checkMail($email); if($checkEmail==0){if($this->ion_auth->email_check($email)){continue;}else{break;}}else{continue;} } } #if patient do not have email then create custom one #Registration to the patient_details table & to the other tables related to the patient $data = array(); $data["patient_email"]=$email; if($this->input->post('fname')!=""){ $data['first_name']=$this->input->post('fname'); }if($this->input->post('lname')!=""){ $data['last_name']=$this->input->post('lname'); }if($this->input->post('phone')!=""){ $data['telephone']=$this->input->post('phone'); // $len_tel=strlen($data['telephone']); // $telephone=""; // for($i=0;$i<$len_tel;$i++){ // $k=$data['telephone'][$i]; // if(is_numeric($k)){$telephone.=$data['telephone'][$i];} // } } $data['patient_id']=rand(10000,99999); $pctg = array(); $pctg['form1']=0;$pctg['form2']=0;$pctg['form3']=0;$pctg['form4']=0;$pctg['form5']=0;$pctg['form6']=0; if($this->input->post('form_status')!=""){ $data['from_tab_status']=json_encode(array($this->input->post('form_status'))); $data['from_tab_status_pctg']=json_encode($pctg); }if($this->ion_auth->email_check($email)){ $this->session->set_flashdata('feedback_error','This Email Address Is Already Registered'); redirect('/'); } $pid=$this->Referral_model->insertNewReferral($data); #Registration to the patient_details table & to the other tables related to the patient #registration to the user $username=$fname; if($this->input->post('confirmpass')!=""){$password=$this->input->post('confirmpass');} else{$password=mt_rand(100000, 999999);} $dfg=5; $this->ion_auth->register($username,$password,$email,$dfg,$oauth_uid,$oauth_provider); $ion_user_id=$this->db->get_where('users', array('email' => $email))->row()->id; #registration to the user #update the patient table with ion_user_id $data=array(); $data['ion_user_id']=$ion_user_id; $this->Referral_model->updateReferralTable($data,'patient_details',$pid); #update the patient table with ion_user_id #After Registration Send an activation Mail to the Patient Registered Email Id $name=$fname." ".$lname; $designation="patient"; $company="Hospital Management System"; $emaildata['emaildata']=array( 'name' => $name, 'email' => $email, 'password' => $password, 'designation' => $designation, 'link' => base_url(), 'company' => $company ); $message = $this->load->view('email_template_management/email_patient',$emaildata,TRUE); $from=array( 'name' => 'HMS Admin', 'email' => 'admin@hms.com' ); $subject ='Patient Account confirmation'; send_email($from,$email,$subject,$message); #After Registration Send an activation Mail to the Patient Registered Email Id #redirection to the login page redirect(base_url()."auth/login"); #redirection to the login page } } #authentication-registration function hms_check_user_email(){ try{ $request=(object)($this->input->get()); $email=isset($request->email)?trim($request->email):''; if($email!=""){ if($this->ion_auth->email_check($email)){ $response=json_encode([ 'status'=>200, 'msg'=>'email exists' ]); }else{ $response=json_encode([ 'status'=>200, 'msg'=>'email does not exist' ]); } }else{ $response=json_encode([ 'status'=>400, 'msg'=>'invalid email' ]); } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_check_user_email: ".$e->getMessage(); echo $getMsg; } } function hms_check_patient_email(){ try{ $request=(object)($this->input->get()); $email=isset($request->email)?trim($request->email):''; if($email!=""){ if($this->ion_auth->email_check($email) || $this->ion_auth->patient_email_check($email)){ $response=json_encode([ 'status'=>200, 'msg'=>'email exists' ]); }else{ $response=json_encode([ 'status'=>200, 'msg'=>'email does not exist' ]); } }else{ $response=json_encode([ 'status'=>400, 'msg'=>'invalid email' ]); } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_check_patient_email: ".$e->getMessage(); echo $getMsg; } } function hms_check_nurse_email(){ try{ $request=(object)($this->input->get()); $email=isset($request->email)?trim($request->email):''; if($email!=""){ if($this->ion_auth->email_check($email) || $this->ion_auth->nurse_email_check($email)){ $response=json_encode([ 'status'=>200, 'msg'=>'email exists', 'data'=>true ]); }else{ $response=json_encode([ 'status'=>200, 'msg'=>'email does not exist', 'data'=>false ]); } }else{ $response=json_encode([ 'status'=>400, 'msg'=>'invalid email' ]); } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_check_nurse_email: ".$e->getMessage(); echo $getMsg; } } function hms_patient_sign_up(){ try{ $request=(object)($this->input->post()); $req_data=(object)[]; $req_data->fname=isset($request->fname)?trim($request->fname):''; $req_data->lname=isset($request->lname)?trim($request->lname):''; $req_data->via=isset($request->via)?trim($request->via):''; $req_data->email=isset($request->email)?trim($request->email):''; $req_data->phone=isset($request->phone)?trim($request->phone):''; $req_data->group=5; $req_data->password=isset($request->password)?trim($request->password):''; $req_data->confirm_password=isset($request->confirmpass)?trim($request->confirmpass):''; $req_data->oauth_uid=isset($request->oauth_uid)?trim($request->oauth_uid):null; $req_data->oauth_provider=isset($request->oauth_provider)?trim($request->oauth_provider):'general'; $req_data->form_status=isset($request->form_status)?trim($request->form_status):"0"; #validations $errors=[]; $recaptcha=isset($request->{'g-recaptcha-response'})?trim($request->{'g-recaptcha-response'}):''; $resCaptcha=(object)(validateCaptcha($recaptcha)); if(isset($resCaptcha->success) && intval($resCaptcha->success)!==1){ $errors[]="Invalid re-captcha."; } $this->load->library('form_validation'); $this->form_validation->set_rules('fname', 'First Name', 'required|trim'); $this->form_validation->set_rules('lname', 'Last Name', 'required|trim'); if(in_array($req_data->via,['email','phone'])){ if($req_data->via=='email'){ $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); if($this->ion_auth->email_check($req_data->email) || $this->ion_auth->patient_email_check($req_data->email) ){ $errors[]='Email Id already exists.'; } } if($req_data->via=='phone'){ $this->form_validation->set_rules('phone', 'Phone Number', 'required|alpha_numeric_number_validation'); set_custom_error_message($this->form_validation); } }else{ $errors[]="Please choose between email or phone to get register."; } $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]'); $this->form_validation->set_rules('confirmpass', 'Confirm Password', 'required|min_length[6]'); if($this->form_validation->run()===FALSE) { $basic_errors=preg_split('/\n/', strip_tags(validation_errors()), -1, PREG_SPLIT_NO_EMPTY); $errors=array_merge($errors,$basic_errors); // $errors=[...$errors,...$basic_errors]; } if($req_data->password!==$req_data->confirm_password){ $errors[]="The Confirm Password didn't match the password."; } #validations if(isset($errors) && !empty($errors) && count($errors)>0){ $response=json_encode([ 'status'=>400, 'msg'=>'validations failed', 'data'=>$errors ]); }else{ if($req_data->via=='phone'){ $req_data->email=$this->ion_auth->generate_unique_user_mail($req_data->fname); } $resData=$this->ion_auth->push_user_verfification($req_data); if($resData['status']==200){ $resLink=$this->hms_user_verification_send_link($resData['data']['inserted_id']); $response=json_encode($resLink); }else{ $response=json_encode($resData); } } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_patient_sign_up: ".$e->getMessage(); echo $getMsg; } } function hms_caregiver_sign_up(){ try{ $request=(object)($this->input->post()); $req_data=(object)[]; $req_data->fname=isset($request->fname)?trim($request->fname):''; $req_data->lname=isset($request->lname)?trim($request->lname):''; $req_data->via=isset($request->via)?trim($request->via):''; $req_data->email=isset($request->email)?trim($request->email):''; $req_data->phone=isset($request->phone)?trim($request->phone):''; $req_data->qualification_type=isset($request->qualification_type)?intval($request->qualification_type):''; $req_data->group=6; $req_data->password=isset($request->password)?trim($request->password):''; $req_data->confirm_password=isset($request->confirmpass)?trim($request->confirmpass):''; $req_data->oauth_uid=isset($request->oauth_uid)?trim($request->oauth_uid):null; $req_data->oauth_provider=isset($request->oauth_provider)?trim($request->oauth_provider):'general'; $req_data->form_status=isset($request->form_status)?trim($request->form_status):"0"; #validations $errors=[]; $recaptcha=isset($request->{'g-recaptcha-response'})?trim($request->{'g-recaptcha-response'}):''; $resCaptcha=(object)(validateCaptcha($recaptcha)); if(isset($resCaptcha->success) && intval($resCaptcha->success)!==1){ $errors[]="Invalid re-captcha."; } $this->load->library('form_validation'); $this->form_validation->set_rules('fname', 'First Name', 'required|trim'); $this->form_validation->set_rules('lname', 'Last Name', 'required|trim'); if(in_array($req_data->via,['email','phone'])){ if($req_data->via=='email'){ $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); if($this->ion_auth->email_check($req_data->email) || $this->ion_auth->nurse_email_check($req_data->email) ){ $errors[]='Email Id already exists.'; } } if($req_data->via=='phone'){ $this->form_validation->set_rules('phone', 'Phone Number', 'required|alpha_numeric_number_validation'); set_custom_error_message($this->form_validation); } }else{ $errors[]="Please choose between email or phone to get register."; } $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]'); $this->form_validation->set_rules('confirmpass', 'Confirm Password', 'required|min_length[6]'); if($this->form_validation->run()===FALSE) { $basic_errors=preg_split('/\n/', strip_tags(validation_errors()), -1, PREG_SPLIT_NO_EMPTY); $errors=array_merge($errors,$basic_errors); // $errors=[...$errors,...$basic_errors]; } if($req_data->password!==$req_data->confirm_password){ $errors[]="The Confirm Password didn't match the password."; } #validations if(isset($errors) && !empty($errors) && count($errors)>0){ $response=json_encode([ 'status'=>400, 'msg'=>'validations failed', 'data'=>$errors ]); }else{ if($req_data->via=='phone'){ $req_data->email=$this->ion_auth->generate_unique_user_mail($req_data->fname); } $resData=$this->ion_auth->push_user_verfification($req_data); if($resData['status']==200){ $resLink=$this->hms_user_verification_send_link($resData['data']['inserted_id']); $response=json_encode($resLink); }else{ $response=json_encode($resData); } } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_caregiver_sign_up: ".$e->getMessage(); echo $getMsg; } } function hms_user_verification_send_link($id){ try{ $data=$this->ion_auth->get_user_verification_details_byid($id); $data->activation_link=base_url().$data->link.'?token='.$data->token; $send=isset($data->send)&&$data->send!=""?json_decode($data->send):(object)[]; $via=isset($send->via)?$send->via:''; $code=isset($send->via)?$send->code:''; if($via=='email' && $code!=""){ /*send email*/ // $email="naran@sentientgeeks.com"; $email=$code; $emaildata['emaildata']=array( 'otp'=>$data->otp, 'link'=>$data->activation_link ); $mailBody=$this->load->view('email_template_management/user_verification_link',$emaildata,TRUE); $message=html_entity_decode($mailBody); $from=array( 'name'=>'WeCuro', 'email'=>'info@wecuro.com' ); $subject='Email Verification Code:'.$data->otp; $email_res=send_email($from,$email,$subject,$message); /*send email*/ $response=[ 'status'=>200, 'msg'=>'email sent with verification link and otp', 'data'=>[ 'link'=>$data->activation_link, 'to'=>$code, 'email_res'=>$email_res ] ]; } else if($via=='phone' && $code!=""){ $this->load->helper('sms_helper'); $phone=extract_number_from_string($code); $message='Your WeCuro verification code is: '.$data->otp; $sms_res=send_sms(''.COUNTRY_CODE,$phone,$message); $response=[ 'status'=>200, 'msg'=>'sms sent with verification link and otp', 'data'=>[ 'link'=>$data->activation_link, 'to'=>$phone, 'sms_res'=>$sms_res ] ]; } else{ $response=[ 'status'=>400, 'msg'=>"verification link and otp couldn't be sent" ]; } return $response; }catch(Exception $e){ $getMsg="Auth - hms_user_verification_send_link: ".$e->getMessage(); echo $getMsg; } } function verification(){ try{ $requestToken=$this->input->get('token'); $fetchData=$this->ion_auth->get_user_verification_details_bytoken($requestToken); $data=(object)[ 'verification_details'=>(object)[ 'token'=>isset($fetchData->token)?$fetchData->token:null, 'send'=>isset($fetchData->send)?$fetchData->send:null, 'created_on'=>isset($fetchData->created_on)?$fetchData->created_on:null, 'expiration_on'=>isset($fetchData->expiration_on)?$fetchData->expiration_on:null ] ]; $this->load->view('frontend/pages/verification',$data); }catch(Exception $e){ $getMsg="Auth - verification: ".$e->getMessage(); echo $getMsg; } } function hms_user_verification_resend_otp(){ try{ $requestToken=$this->input->post('token'); $update=$this->ion_auth->update_user_verification_otp_bytoken($requestToken); if($update){ $fetchData=$this->ion_auth->get_user_verification_details_bytoken($requestToken); $resLink=$this->hms_user_verification_send_link($fetchData->id); $response=json_encode($resLink); } else{ $response=json_encode([ 'status'=>400, 'msg'=>'otp not resend' ]); } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_user_verification_resend_otp: ".$e->getMessage(); echo $getMsg; } } function hms_user_verification_authenticate(){ try{ $request=(object)($this->input->post()); $token=isset($request->token)?trim($request->token):''; $otp=isset($request->otp)?intval($request->otp):0; $fetchData=$this->ion_auth->get_user_verification_details_bytoken($token); $update=$this->ion_auth->user_verification_authenticate($token,$otp); if($update){ $guest_details=isset($fetchData->details)&&$fetchData->details!=""?json_decode($fetchData->details):(object)[]; $send_details=isset($fetchData->send)&&$fetchData->send!=""?json_decode($fetchData->send):(object)[]; if(isset($guest_details->group) && intval($guest_details->group)==5){ $auth_ion_res=$this->hms_register_guest_as_patient($guest_details,$send_details); }else if(isset($guest_details->group) && intval($guest_details->group)==6){ $auth_ion_res=$this->hms_register_guest_as_caregiver($guest_details,$send_details); } if($auth_ion_res>0){ $this->ion_auth->loginLinkedin($guest_details->email, false); } $response=json_encode([ 'status'=>200, 'msg'=>'authenticated successfully' ]); } else{ $response=json_encode([ 'status'=>400, 'msg'=>'invalid otp' ]); } echo $response; }catch(Exception $e){ $getMsg="Auth - hms_user_verification_authenticate: ".$e->getMessage(); echo $getMsg; } } function hms_register_guest_as_patient($details,$send){ try{ if(!$this->ion_auth->email_check($details->email)){ $ion_user_id=$this->ion_auth->register( $details->first_name, 123, $details->email, $details->group, $details->oauth_uid, $details->oauth_provider ); $this->db->where('id', $ion_user_id); $this->db->update('users', ['password'=>$details->confirm_password]); $data=array(); $data["patient_email"]=$details->email; $data['first_name']=$details->first_name; $data['last_name']=$details->last_name; $data['telephone']=$details->phone; $data['patient_id']=rand(10000,99999); $data['from_tab_status']=json_encode([$details->form_status]); $data['from_tab_status_pctg']=json_encode([ 'form1'=>0, 'form2'=>0, 'form3'=>0, 'form4'=>0, 'form5'=>0, 'form6'=>0 ]); $data['ion_user_id']=$ion_user_id; $pid=$this->Referral_model->insertNewReferral($data); if($ion_user_id>0 && $pid>0){ $ion_username=$this->db->get_where('users', array('id' =>$ion_user_id))->row()->username; if($send->via=='email'){ #send-email $emaildata['emaildata']=array( 'name'=>$details->first_name." ".$details->last_name, 'username'=>$ion_username ); $message=$this->load->view('email_template_management/email_patient',$emaildata,TRUE); $from=array( 'name'=>'WeCuro', 'email'=>'info@wecuro.com' ); $subject='Patient Account Confirmation'; send_email($from,$send->code,$subject,$message); #send-email }else if($send->via=='phone'){ #send-sms $this->load->helper('sms_helper'); $phone=extract_number_from_string($send->code); $message='WeCuro account has been created successfully as a Patient. Your Username is: '.$ion_username; send_sms(''.COUNTRY_CODE,$phone,$message); #send-sms } } return $ion_user_id; }else{ return false; } }catch(Exception $e){ $getMsg="Auth - hms_register_guest_as_patient: ".$e->getMessage(); echo $getMsg; } } function hms_register_guest_as_caregiver($details,$send){ try{ if(!$this->ion_auth->email_check($details->email)){ $ion_user_id=$this->ion_auth->register( $details->first_name, 123, $details->email, $details->group, $details->oauth_uid, $details->oauth_provider ); $this->db->where('id', $ion_user_id); $this->db->update('users', ['password'=>$details->confirm_password]); $data=array(); $data["email"]=$send->via=='email'?$details->email:''; $data['fname']=$details->first_name; $data['lname']=$details->last_name; $data['phone']=$details->phone; $data['qualification_type']=$details->qualification_type; $data['hire_type']='New Hire'; $data['caregiver_id']=''.str_pad($ion_user_id, 6, "0", STR_PAD_LEFT); $data['ion_user_id']=$ion_user_id; $data['application_date']=date('Y-m-d',now()); $data['created_by']=''; // $data['form_status']=$details->form_status; $data['status']=1; $data['from_tab_status_pctg']=json_encode([ 'form1'=>0, 'form2'=>0, 'form3'=>0, 'form4'=>0, 'form5'=>0, 'form6'=>0, 'form7'=>0, 'form8'=>0, 'form9'=>0, 'form10'=>0, 'form11'=>0 ]); $cid=$this->Caregiver_model->insertNurse($data); if($ion_user_id>0 && $cid>0){ $ion_username=$this->db->get_where('users', array('id' =>$ion_user_id))->row()->username; if($send->via=='email'){ #send-email $emaildata['emaildata']=array( 'name'=>$details->first_name." ".$details->last_name, 'username'=>$ion_username ); $message=$this->load->view('email_template_management/email_caregiver',$emaildata,TRUE); $from=array( 'name'=>'WeCuro', 'email'=>'info@wecuro.com' ); $subject='Caregiver Account Confirmation'; send_email($from,$send->code,$subject,$message); #send-email }else if($send->via=='phone'){ #send-sms $this->load->helper('sms_helper'); $phone=extract_number_from_string($send->code); $message='WeCuro account has been created successfully as a Caregiver. Your Username is: '.$ion_username; send_sms(''.COUNTRY_CODE,$phone,$message); #send-sms } } return $ion_user_id; }else{ return false; } }catch(Exception $e){ $getMsg="Auth - hms_register_guest_as_caregiver: ".$e->getMessage(); echo $getMsg; } } #authentication-registration }