<?php

use Config\ForeignCharacters;

// Extending Text Helpers

if (! function_exists('__')) {

    function __(string $str, string $textdomain): string
    {
        return $str;
    }
}

if ( ! function_exists('get_gps'))
{
    
	/**
	* Get Latitude/Longitude/Altitude based on an address
	* @param string $address The address for converting into coordinates
	* @return array An array containing Latitude/Longitude/Altitude data
	*/
	function get_gps($address = '')
	{
        static $results = array();
        $address = str_replace(' ','+',$address);

        if(getenv('GOOGLE_API_KEY') ==''){
            $url = 'https://nominatim.openstreetmap.org/search?format=json&q=' . $address;
        } else {
            $url = 'https://maps.google.com/maps/api/geocode/json?address=' . $address.'&key='.getenv('GOOGLE_API_KEY');
        }

        $data = getURL($url);

		if(!$data) return FALSE;

		$resp = json_decode($data, true);

        if(getenv('GOOGLE_API_KEY') =='')
        {
            if(empty($resp[0]['lat']))
                return FALSE;

            return array('lat' => $resp[0]['lat'], 'lng' => $resp[0]['lon'], 'alt' => 0);
        }
        else
        {
            $lat = $resp['results'][0]['geometry']['location']['lat'];
            $lng = $resp['results'][0]['geometry']['location']['lng'];
            if (!empty($lat) && !empty($lng)){
                return array('lat' => $lat, 'lng' => $lng, 'alt' => 0);
            }
        }

        return FALSE;
	}
}


    
/**
* Reads an URL to a string
* @param string $url The URL to read from
* @return string The URL content
*/
function getURL($url){
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8) AppleWebKit/535.6.2 (KHTML, like Gecko) Version/5.2 Safari/535.6.2');
    curl_setopt($ch, CURLOPT_URL, $url);
    $tmp = curl_exec($ch);
    curl_close($ch);
    if ($tmp != false){
        return $tmp;
    }
}