<?php
/**
* ChronoForms 8
* Copyright (c) 2023 ChronoEngine.com, All rights reserved.
* Author: (ChronoEngine.com Team)
* license:     GNU General Public License version 2 or later; see LICENSE.txt
* Visit http://www.ChronoEngine.com for regular updates and information.
**/
defined('_JEXEC') or die('Restricted access');
?>
<?php
	echo '<script src="https://maps.googleapis.com/maps/api/js?key='.Chrono::getVal($this->settings, "google_address.api_key").'&libraries=places&callback=initAutocomplete" async defer></script>';
	
	$address = [];
	foreach($element['address'] as $name => $value){
		if(!empty($value)){
			$address[] = $name.': "'.$value.'"';
		}
	}
	
	Chrono::addHeaderTag('<script type="text/javascript">'.'
		var placeSearch, autocomplete;
		var componentForm = {
			'.implode(',', $address).'
		};
		'.(!empty($element['geolocate']) ? 'geolocate();' : '').'

		function initAutocomplete(){
			autocomplete = new google.maps.places.Autocomplete(
				(document.getElementById("'.$element['field_id'].'")),
				{types: ["geocode"]}
			);
			
			autocomplete.addListener("place_changed", fillInAddress);
		}

		function fillInAddress() {
			var place = autocomplete.getPlace();
			'.(!empty($element['formatted_field_id']) ? 'document.querySelector("#'.$element['formatted_field_id'].'").value = place.formatted_address;' : '').'
			
			for(var i = 0; i < place.address_components.length; i++){
				var addressType = place.address_components[i].types[0];
				if(componentForm[addressType]){
					document.querySelector("#"+componentForm[addressType]).val(place.address_components[i]["long_name"]);
				}
			}
		}
		
		function geolocate(){
			if (navigator.geolocation){
				navigator.geolocation.getCurrentPosition(function(position) {
					var geolocation = {
						lat: position.coords.latitude,
						lng: position.coords.longitude
					};
					var circle = new google.maps.Circle({
						center: geolocation,
						radius: position.coords.accuracy
					});
					autocomplete.setBounds(circle.getBounds());
				});
			}
		}
	'.'</script>');