<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	if (!function_exists('formateDate')){

		function formateDate($date){
			$date=date_create($date);
			return date_format($date,"m/d/Y");
		}
	}
	if (!function_exists('base64_enc')){
		function base64_enc($str)
		{
			return urlencode(base64_encode($str));
		}
	}
	if (!function_exists('base64_dec')){
		function base64_dec($str)
		{
			return base64_decode(urldecode($str));
		}
	}
	function _na($data, $msg="N/A")
	{
		if ($data == '' || $data == NULL) {
			return $msg;
		}
		else{
			return $data;
		}
	}

	function _die($data = 'test')
	{
		echo "<pre>";
		print_r($data);
		die();
	}
	function pre($data){
		echo "<pre>";
		print_r($data);
	}
	if (!function_exists('activity_log')){
		function activity_log($data){

			$data['activity_time']=date ('Y-m-d H:i:s', now());

			$CI = &get_instance();

			$CI->load->model('home/Home_model');

			$CI->Home_model->activity_log($data);

		}
	}
	if(!function_exists('generateRandomString')){
		function generateRandomString($length=10,$characters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'){
		    $charLength=strlen($characters);
		    $randomString='';
		    for($i=0; $i<$length;$i++){
		        $randomString .= $characters[rand(0, $charLength - 1)];
		    }
		    return $randomString;
		}
	}
	if(!function_exists('validateCaptcha')){
		function validateCaptcha($recaptcha){
			$recaptcha_verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".RECAPTCHA_SECRET_KEY."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
			$recaptcha_result=json_decode($recaptcha_verify,true);
		    return $recaptcha_result;
		}
	}
	if(!function_exists('alpha_numeric_number_validation')){
		function alpha_numeric_number_validation($string,$length=10){
			if(preg_match_all('/\d+/', $string, $matches)) {
			    $number=implode('', $matches[0]);
			}else{
			    $number='';
			}
			if(strlen($number)===$length){
				return TRUE;
			}else{
				return FALSE;
			}
	    }
	}
	if(!function_exists('set_custom_error_message')){
		function set_custom_error_message($form_validation){
			$form_validation->set_message('alpha_numeric_number_validation', 'The Phone Number field must be at least 10 digits.');
	    }
	}
	if(!function_exists('extract_number_from_string')){
		function extract_number_from_string($string){
			if(preg_match_all('/\d+/', $string, $matches)) {
			    $number=implode('', $matches[0]);
			}else{
			    $number='';
			}
			return $number;
	    }
	}
	if(!function_exists('calc_rate_prcntg')){
		function calc_rate_prcntg($new,$old){
            try{
                $response=(object)[
                    'new'=>$new,
                    'old'=>$old,
                    'rate'=>0,
                    'growth'=>'',
                ];
                if($response->new>0 && $response->old>0){
                    $response->rate=number_format((($response->new-$response->old)/$response->old)*100,0);
                }else if($response->new<=0 && $response->old>0){
                    $response->rate=number_format(-100,0);
                }else if($response->new>0 && $response->old<=0){
                    $response->rate=number_format(100,0);
                }
                if($response->rate>0){
                    $response->growth='increased';
                }else if($response->rate<0){
                    $response->growth='decreased';
                }else{
                    $response->growth='none';
                }
                return $response;
            }catch(Exception $e){
                $getMsg="common_helper - calc_rate_prcntg: ".$e->getMessage();
                echo $getMsg;
            }
        }
	}
	if(!function_exists('geo_address_by_ip')){
		function geo_address_by_ip($ip=null){
            try{
            	$apiKey='7cba03079a814ebcbd04059e7830e2fa';
		        if($ip){
		            $url="https://api.ipgeolocation.io/ipgeo?apiKey=".$apiKey."&ip=".$ip;
		        }else{
				    $url="https://api.ipgeolocation.io/ipgeo?apiKey=".$apiKey."";
		        }
				$ch=curl_init();
				curl_setopt($ch,CURLOPT_URL,$url);
				curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
				$responseJson=curl_exec($ch);
				curl_close($ch);
		        $response=json_decode($responseJson);
		        return $response;
            }catch(Exception $e){
                $getMsg="common_helper - geo_address_by_ip: ".$e->getMessage();
                echo $getMsg;
            }
        }
	}

	#function for Push Notification
	if (!function_exists('sendNotification')){

		function sendNotification($fcm_token,$post_title,$post_message,$type)
		{
			$token = $fcm_token; // push token
			$message = $post_message;
			
			//echo $message;exit;

			$CI =& get_instance();
     		$CI->load->library('fcm'); // load library

			$CI->fcm->setTitle($post_title);
			$CI->fcm->setMessage($message);
	
			
			$CI->fcm->setIsBackground(false);
	
			
			$payload = array('notification'=> '');
			$CI->fcm->setPayload($payload);
	
			
			//$CI->fcm->setImage('https://firebase.google.com/_static/9f55fd91be/images/firebase/lockup.png');
	
			/**
			 * Get the compiled notification data as an array
			*/
			// $json = $CI->fcm->getPush();
			$msg = array
			(
				'body' 	=> $post_message,
				'title'	=> $post_title,
				'icon'	=> 'myicon',/*Default Icon*/
				'sound' => 1,/*Default sound*/
				'priority'=> 'high',
				'show_in_foreground'=> true,
			);
	
			// $json = json_encode($msg);
		
			// _die($json);
	
			$p = $CI->fcm->send($token, $msg);
	
			// print_r($p);
			return $p;
	 	}
	}
 
	#function for Push Notification
	#-----------------------------------------------
	if (!function_exists('gettingNameFromShortCode')){
		function gettingNameFromShortCode($data){

			

			$CI = &get_instance();

			$CI->load->model('home/Home_model');

			$name= $CI->Home_model->getting_name_from_short_code($data);
			// _die($name);
			return $name;

		}
	}

	if (!function_exists('getCitizenList')){
		function getCitizenList($data){

			$CI = &get_instance();

			$CI->load->model('home/Home_model');

			$name= $CI->Home_model->getCitizenList($data);
			// _die($name);
			return $name;

		}
	}

	if (!function_exists('getCitizenName')){
		function getCitizenName($data){
			$CI = &get_instance();

			$CI->load->model('home/Home_model');

			$name= $CI->Home_model->getCitizenName($data);
			// _die($name);
			return $name;

		}
	}
	if(!function_exists('gettingDocumentFromDocId')){
		function gettingDocumentFromDocId($id){
			$CI=&get_instance();
			$CI->load->model('home/Home_model');
			$data=$CI->Home_model->getting_document_from_docId($id);
			return $data;

		}
	}
	// Getting Nearest City
if (!function_exists('nearestCity')){
	function getNearCityByIp(){
		// echo "hi";
        $ip=getIP();
        // return $ip;
        // echo 'getNearCityByIp';
        if($ip=='::1')
            $ip='34.77.181.223';
        $response=json_decode(file_get_contents('http://getnearbycities.geobytes.com/GetNearbyCities?radius=100&locationcode='.$ip), true);
        // return $output;
        $output=[];
        if($response){
            $i=0;
            foreach ($response as $set) {
               
               $output[$i]['city']=$set[1]; 
               $output[$i]['Kilometres']=$set[7]; 
               $output[$i]['Miles']=$set[11]; 
               $i++;
            }
            // pre($output);
            return $output;
        }
    }
}
if (!function_exists('getIP')){
	function getIP() {
		foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
		if (array_key_exists($key, $_SERVER) === true) {
			foreach (explode(',', $_SERVER[$key]) as $ip) {
				if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
					return $ip;
				}
			}
		}
		}
	}
}

if (!function_exists('getExtensionByType')){
	function getExtensionByType($type){
		$doc_type=array('CTZ1','CTZ2','SSC','RSM','REF','DPR','MIC','EHA','HBV','PPD','CXR','RRM','CPX','TDAP','FLV','CVD','LIC','CPR','DSC','MMR','DTUQ','RRF','102','103','PCA');
		$image_type=array('PROFILE');
		if(in_array($type,$doc_type))
			return array('gif','jpg','png','jpeg','pdf','doc','docx');
		if(in_array($type,$image_type))
			return array('gif','jpg','png','jpeg');
		return false;
	}
}

if (!function_exists('objToArray')){
	function objToArray($obj){
		if (!is_object($obj)) {
			return false;
		}
		$data=[];
		foreach ($obj as $key => $value) {
			$data[$key]=$value;
		}
		return $data;
	}
}

?>