<?php
function exwf__getdistance_routers($apiKey,$mode,$from,$to){
	// The API endpoint
	$url = "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix";
	$from = exwf__getLatLong($from,$apiKey);
	$to = exwf__getLatLong($to,$apiKey);
	$requestPayload = [
	    'origins' => [
	        [
	            'waypoint' => ['location' => ['latLng' => ['latitude' => $from['latitude'], 'longitude' => $from['longitude']]]]
	        ]
	    ],
	    'destinations' => [
	        [
	            'waypoint' => ['location' => ['latLng' => ['latitude' => $to['latitude'], 'longitude' => $to['longitude']]]] 
	        ]
	    ],
	    'travelMode' => ($mode == 'walking ' ? ($mode =='bicycling ' ? 'BICYCLE'  :'WALK' ): 'DRIVE')
	];//print_r($requestPayload);exit;
	// Initialize cURL
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, [
	    'Content-Type: application/json',
	    'X-Goog-Api-Key: ' . $apiKey,
	    'X-Goog-FieldMask: distanceMeters,duration'
	]);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestPayload));
	// Execute the request
	$response = curl_exec($ch);
	// Check for errors
	if (curl_errno($ch)) {
		$data['distance'] = '';
	    $data['mes'] = 'Error:' . curl_error($ch);
	} else {
	    // Decode the response
	    $data = json_decode($response, true);
	    if (isset($data[0]['distanceMeters'])) {
		    $data['distance'] = $data[0]['distanceMeters'];
		    $data['destination_addresses'] = $to['address_components'];
			$data['fromaddress_components'] = $from['address_components'];
		} else {
			$data['distance'] = '0';
			$data['mes'] = $data[0]['error']['message'];
		}
	    //echo '<pre>';print_r($data);exit;
	}
	// Close the connection
	curl_close($ch);
	return $data;
}
function exwf__getLatLong($address,$api=false) {
	$ifll_add = str_replace("\u{202F}", " ", $address);
	$ifll_add = preg_replace('/\s+/u', ' ', $address);
	$ifll_add = trim($ifll_ad);
	if (preg_match('/^(-?\d{1,3}\.\d+)\s*,\s*(-?\d{1,3}\.\d+)$/', $ifll_add, $matches)) {
	    return array(
	        'latitude' => floatval($matches[1]),
	        'longitude' => floatval($matches[2]),
	        'address_components' => ''
	    );
	}
	if(isset($api) && $api!=''){ $apiKey = $api;}else{
	    $apiKey = exwoofood_get_option('exwoofood_gg_distance_api','exwoofood_shpping_options');
	}
    $address = urlencode($address);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$apiKey";


	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Timeout in seconds
	$response = curl_exec($ch);
	if (curl_errno($ch)) {
	    $context = stream_context_create([ 'http' => [ 'method' => 'GET', 'timeout' => 10,  ] ]);
	    $response = file_get_contents($url,false,$context);
	}
	$json = json_decode($response, true);
	curl_close($ch);
    if ($json['status'] == 'OK') {
        $latitude = $json['results'][0]['geometry']['location']['lat'];
        $longitude = $json['results'][0]['geometry']['location']['lng'];
        return array('latitude' => $latitude, 'longitude' => $longitude, 'address_components' => $json['results'][0]);
    } else {
        return false;
    }
}
add_action('exwf_after_pu_address', 'exwf_pu_html_after_addr');
function exwf_pu_html_after_addr($api) {
	if($api!=''){?>
	    <div class="exwf-sladd">
	    	<a href="javascript:;" id="exwf-sl-addr" onclick="exwf_openModal()"><i class="ion-map"></i> <?php esc_html_e('Select from map','woocommerce-food');?></a>
	    </div>
    <?php }
}
add_action('exwf_after_pu_odmethod', 'exwf_pickup_autocomplete_html');
function exwf_pickup_autocomplete_html($api) {
    if($api!=''){
    	$distace_api = exwoofood_get_option('exwoofood_gg_distance_api','exwoofood_shpping_options');
    	if($distace_api==''){$distace_api = $api;}
    	$ctcode = exwoofood_get_option('exwoofood_autocomplete_limit','exwoofood_shpping_options');
        $store_address = get_option( 'woocommerce_store_address', '' );
		$store_address = apply_filters('exwf_default_store_address',$store_address);
		//$center = exwf__getLatLong($store_address,$distace_api);
		$center = array('latitude' => '42.9869502', 'longitude' => '-81.243177');
		$map_lang = urlencode(apply_filters('exwf_map_lang','en'));
		wp_enqueue_script( 'exwf-auto-address', '//maps.googleapis.com/maps/api/js?key='.esc_attr($api).'&language='.$map_lang.'&libraries=places&callback=Function.prototype');
		?>
        <style>
            .exwf-ggmaps-pu #exwf-map {height: 100%;width: 100%;}
            .exwf-ggmaps-pu {
              display: none;
              position: fixed;
              z-index: 99999;
              left: 50%;
              transform: translateX(-50%);
              top: 10%;
              width: 90%;
              max-width: 800px;
              height: 80%;
              overflow: auto;
              background-color: rgba(0, 0, 0, 0.4);
            }
            .exwf-ggmaps-pu .exwf-ggmaps-content {
                background-color: #fefefe; margin: auto; padding: 0; border: 1px solid #888; width: 100%; height: 100%; box-sizing: border-box; position: relative;
            }
            .exwf-ggmaps-pu .close {color: #aaa; font-size: 28px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%);line-height: 1; padding: 0;}
            .exwf-ggmaps-pu .close:hover,
            .exwf-ggmaps-pu .close:focus {color: black;text-decoration: none;cursor: pointer;}
            .exwf-ggmaps-pu #exwf-ggmaps-ctmarker {
                position: absolute;
                top: 50%;
                left: 50%;
                height: 38px;
                width: 22px;
                transform: translateY(-50%);
                margin-left: -11px;
                z-index: 1;
                text-align: center;
            }
            .exwf-ggmaps-pu #exwf-ggmaps-ctmarker i { margin: -18px 0 0 0; width: 100%; height: 100%; line-height: 1; font-size: 40px; color: #e51534; }
            .exwf-ggmaps-pu .exwf-ggmaps-tt { position: absolute; z-index: 9; left: 0; right: 0; text-align: center; top: 0; padding: 15px 30px; background: #fff; }
            .exwf-ggmaps-pu .exwf-ggmaps-tt h3{ font-size: 20px; margin: 0 }
            .exwf-ggmaps-cf { position: absolute; bottom: 0px; top: auto; left: 0; right: 0; background: #fff; text-align: center; padding: 10px 20px 15px 20px}
            #exwf-puaddress { margin-bottom: 5px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
            .exwf-ggmaps-cf .exwf-button { cursor: pointer; }
        </style> 
        <div class="exwf-ggmaps-pu" id="exwf-ggmaps-pu">
            <div class="exwf-ggmaps-content">
                <div class="exwf-ggmaps-tt">
                	<h3><?php esc_html_e('Select your location to delivery','woocommerce-food');?></h3>
                	<span class="close" onclick="exwf_closeModal()">&times;</span>
            	</div>
            	<div id="exwf-map"></div>
            	<div id="exwf-ggmaps-ctmarker"><i class="icon ion-ios-location"></i></div>
	            <div class="exwf-ggmaps-cf">
	                <div id="exwf-puaddress"><?php esc_html_e('Move the map to select a location','woocommerce-food');?></div>
	                <div class="exwf-button exwf-cfbt" onclick="exwf_gg_cfadd()"><?php esc_html_e('Deliver here','woocommerce-food');?></div>
	            </div>
            </div>
        </div>
        <script>
            let map;
            let centerMarker;
            let geocoder;
            let addressDiv = document.getElementById('exwf-puaddress');
            let centerMarkerDiv = document.getElementById('exwf-ggmaps-ctmarker');
            let mcenter =  { lat: <?php echo esc_attr($center['latitude'])?>, lng: <?php echo esc_attr($center['longitude'])?> }
            async function initMap() {
                const useraddress = document.getElementById("exwf-user-address");
                let user_latlang;
                if(useraddress.value){
                	addressDiv.textContent = useraddress.value;
	                try {
	                    user_latlang = await exwfgetLatLngFromAddress(useraddress.value);
	                } catch (error) {
	                    console.error("Error fetching latitude and longitude:", error);
	                }
	            }
                if(user_latlang){ mcenter =  user_latlang;}else
                if(addressDiv.getAttribute("data-center") && addressDiv.getAttribute("data-center")!=''){ 
                	mcenter = JSON.parse(addressDiv.getAttribute("data-center"));
                }else{
	                const st_loc = document.querySelector(".exwf-del-log select.ex-logreq");
	                if(st_loc){
		                let selectedOption = st_loc.options[st_loc.selectedIndex];
						let data_ct = selectedOption.getAttribute("data-latlng");
						if(data_ct!=''){
							const [lat, lng] = data_ct.split(',').map(Number);
							mcenter = { lat: lat, lng: lng };
						}
						//let data_addrs = selectedOption.getAttribute("data-addr");
					}else {
						try {
	                    	user_latlang = await exwfgetLatLngFromAddress('<?php echo $store_address; ?> ');
		                } catch (error) {
		                    console.error("Error fetching latitude and longitude:", error);
		                }
		                if(user_latlang){ mcenter =  user_latlang;}
					}
				}
	            map = new google.maps.Map(document.getElementById('exwf-map'), {
	              center: mcenter,
	              zoom: 13,
	              gestureHandling: 'greedy'
	            });
	            centerMarker = new google.maps.Marker({
	              map: map,
	              position: map.getCenter(),
	              icon: '<?php echo EX_WOOFOOD_PATH?>css/img/transparent.png'
	            });

	            geocoder = new google.maps.Geocoder();

	            google.maps.event.addListener(map, 'idle', function() {
	              
	            });
	            google.maps.event.addListener(map, 'dragend', function() {
	              //centerMarker.setVisible(false);
	              const center = map.getCenter();
	              centerMarker.setPosition(center);
	              exwf_geocodeLatLng(center);
	            });
	            google.maps.event.addListener(map, 'zoom_changed', function() {
	              //centerMarker.setVisible(false);
	              const center = map.getCenter();
	              centerMarker.setPosition(center);
	              exwf_geocodeLatLng(center);
	            });
            }
            function exwf_geocodeLatLng(latLng) {
	            geocoder.geocode({ 'location': latLng }, function(results, status) {
	              if (status === 'OK') {
	                if (results[0]) {
	                  addressDiv.textContent = results[0].formatted_address;
	                  addressDiv.setAttribute("data-center",JSON.stringify(latLng));
	                } else {
	                  addressDiv.textContent = 'No results found';
	                }
	              } else {
	                addressDiv.textContent = 'Geocoder failed due to: ' + status;
	              }
	            });
            }
            function exwf_openModal() {
                const modal = document.getElementById("exwf-ggmaps-pu");
                const st_loc = document.querySelector(".exwf-del-log select.ex-logreq");
                if(st_loc && st_loc.value==''){
					jQuery('.exwf-del-log .exwf-add-error').fadeIn();
                }else{
	                modal.style.display = "block";
	                initMap(); // Initialize the map here when the modal is opened
	            }
            }
            function exwf_closeModal() {
                const modal = document.getElementById("exwf-ggmaps-pu");
                modal.style.display = "none";
            }
            window.onclick = function(event) {
                const modal = document.getElementById("exwf-ggmaps-pu");
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }
            /* close if click outsite
            window.onclick = function(event) {
			    const modal = document.getElementById("exwf-ggmaps-pu");
			    const exwf_openModalButton = document.getElementById("exwf-sl-addr");
			    // Check if the click is outside the modal and not on the button to open the modal
			    if (!modal.contains(event.target) && event.target !== exwf_openModalButton) {
			        modal.style.display = "none";
			    }
			};*/
			function exwf_gg_cfadd() {
				const modal = document.getElementById("exwf-ggmaps-pu");
                const cfaddress = document.getElementById("exwf-puaddress");
                const useraddress = document.getElementById("exwf-user-address");
                if(cfaddress.textContent!='<?php esc_html_e('Move the map to select a location','woocommerce-food');?>'){
                	useraddress.value = cfaddress.textContent;
                	modal.style.display = "none";
                }else{

                }
            }
            async function exwfgetLatLngFromAddress(address) {
			    try {
			        const response = await fetch(
			            `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=<?php echo $distace_api; ?>`
			        );
			        const data = await response.json();
			        if (data.status === "OK") {
			            const location = data.results[0].geometry.location;
			            return { lat: location.lat, lng: location.lng };
			        } else {
			            console.error("Error fetching geocoding data:", data.status);

			        }
			    } catch (error) {
			        console.error("An error occurred:", error);
			    }
			}
        </script>  
    <?php }
}
add_action('woocommerce_after_checkout_form', 'exwf_ck_autocomplete_html');
function exwf_ck_autocomplete_html(){
	if(exwoofood_get_option('exwoofood_autocomplete_cko','exwoofood_shpping_options')=='yes'){ return;}
	$api = exwoofood_get_option('exwoofood_gg_api','exwoofood_shpping_options');
	exwf__autocomplete_html($api,'billing_address_1');
	exwf__autocomplete_html($api,'shipping_address_1','hide');
}

add_action('exwf_after_pu_odmethod', 'exwf__autocomplete_html');
function exwf__autocomplete_html($api,$idel=false,$css=false) {
    if($api!=''){
    	$distace_api = exwoofood_get_option('exwoofood_gg_distance_api','exwoofood_shpping_options');
    	if($distace_api==''){$distace_api = $api;}
    	$ctcode = exwoofood_get_option('exwoofood_autocomplete_limit','exwoofood_shpping_options');
    	$rslcode = exwoofood_get_option('exwoofood_autocomplete_rslcode','exwoofood_shpping_options');
		if(isset($css) && $css=='hide'){}else{?>
	        <style>
				.exwf-order-method .exwf-del-field:not(.exwf-deli-field) div > .exwf-sugges-list{ padding: 0 }
				div[id^='exwf-sugges-'].exwf-sugges-list { list-style-type: none; padding: 0; background-color: #fff; position: absolute !important; z-index: 1000; border-radius: 2px; font-family: Arial, sans-serif; -webkit-box-shadow: 0 2px 6px rgba(0, 0, 0, .3); box-shadow: 0 2px 6px rgba(0, 0, 0, .3); -webkit-box-sizing: border-box; box-sizing: border-box; overflow: hidden; max-width: 100%; margin: 0 }
				.exwf-order-method .exwf-del-field:not(.exwf-deli-field) div > .exwf-sugges-list span{padding: 10px 15px 10px 30px; }
				div[id^='exwf-sugges-'].exwf-sugges-list span { cursor: pointer; border: 0; border-bottom: 1px solid #e6e6e6; padding: 10px 15px 10px 30px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; line-height: 30px; text-align: left; color: #515151; line-height: 1.2;position: relative;  margin: 0;display: block;}
				div[id^='exwf-sugges-'].exwf-sugges-list span:before { content: "\f456"; font-family: "Ionicons"; position: absolute; width: 20px; height: 20px; left: 10px; top: 50%; transform: translateY(-50%); z-index: 9; font-size: 17px; }
	        </style>
	    <?php }?>
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                const input = document.getElementById("<?php echo (isset($idel) && $idel!='' ? $idel : 'exwf-user-address')?>");
                if(!input){ return;}
                const divsugg = document.createElement("div");
                const divsuggid  = "exwf-sugges-list-<?php echo rand(100,100000);?>";
                divsugg.className  = "exwf-sugges-list"; 
                divsugg.id = divsuggid; 
                input.parentNode.appendChild(divsugg); 
                //const suggestionsList = document.getElementById("exwf-addsug-list");
                const suggestionsList = document.getElementById(divsuggid);

                input.addEventListener("input", async () => {
                    const query = input.value;
                    // Only start searching if at least 3 characters are entered
                    if (query.length < 2) {
                        suggestionsList.innerHTML = "";
                        return;
                    }
                    try {
                        // Send request to the API
                        const response = await fetch(`<?php echo EX_WOOFOOD_PATH?>inc/map-api/autocomplete.php?input=${encodeURIComponent(query)}&key=<?php echo $distace_api; ?>&code=<?php echo ($ctcode)?>&rslcode=<?php echo ($rslcode)?>`);
                        const data = await response.json();//console.log(data);
                        // Clear previous suggestions
                        suggestionsList.innerHTML = "";
                        if (data && Array.isArray(data.suggestions)) {
                            data.suggestions.forEach(suggestion => {
                                const prediction = suggestion.placePrediction;
                                // Extract the main text (address) and secondary text (location)
                                const mainText = prediction.structuredFormat.mainText.text;
                                const secondaryText = prediction.structuredFormat.secondaryText.text;
                                // Create the suggestion list item
                                const span = document.createElement("span");
                                span.textContent = `${mainText}, ${secondaryText}`;
                                span.addEventListener("click", async () => {
                                    input.value = `${mainText}, ${secondaryText}`;
                                    suggestionsList.innerHTML = "";
                                    if(input.id!='exwf-user-address'){
	                                    try {
						                    user_latlang = await getdetailsAddress(input.value);
						                    exwf_address_details(user_latlang,input.id);
						                } catch (error) {
						                    console.log(error);
						                }
						            }
                                });
                                suggestionsList.appendChild(span);
                            });
                        } else {
                            console.log("Invalid response format or no suggestions:", data);
                        }
                    } catch (error) {
                        console.error("Error fetching autocomplete suggestions:", error);
                    }
                });
                document.addEventListener("click", (event) => {
			        if (!input.contains(event.target) && !suggestionsList.contains(event.target)) {
			            suggestionsList.innerHTML = ""; // Clear the suggestions
			        }
			    });
			    async function getdetailsAddress(address) {
				    try {
				        const response = await fetch(
				            `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=<?php echo $distace_api; ?>`
				        );
				        const data = await response.json();
				        if (data.status === "OK") {
				            const location = data.results[0];
				            return location;
				        } else {
				            console.error("Error fetching geocoding data:", data.status);

				        }
				    } catch (error) {
				        console.error("An error occurred:", error);
				    }
				}
				function exwf_address_details(place,idel){
					var data_address = place.address_components;
		            var i;var $name ='';var $st_nb ='';var $rout ='';var $neig ='';var $city ='';var $country ='';var $postcode =''; var $state ='';
		            for (i = 0; i < data_address.length; ++i) {
		            	if(jQuery.inArray("street_number", data_address[i].types) !== -1){
		            		$st_nb = data_address[i].long_name;
		            	}else if(jQuery.inArray("route", data_address[i].types) !== -1){
		            		$rout = data_address[i].long_name;
		            	}else if(jQuery.inArray("neighborhood", data_address[i].types) !== -1){
		            		$neig = data_address[i].long_name;
		            	}else if(jQuery.inArray("locality", data_address[i].types) !== -1){
		            		$city = data_address[i].long_name;
		            	}else if($city=='' && jQuery.inArray("administrative_area_level_1", data_address[i].types) !== -1){
		            		$city = data_address[i].long_name;
		            	}else if(jQuery.inArray("administrative_area_level_1", data_address[i].types) !== -1 && jQuery.inArray("political", data_address[i].types) !== -1){
		            		$state = data_address[i].short_name;
		            	}else if(jQuery.inArray("country", data_address[i].types) !== -1){
		            		$country = data_address[i].short_name;
		            	}else if(jQuery.inArray("postal_code", data_address[i].types) !== -1){
		            		$postcode = data_address[i].long_name;
		            	}
					}
					var $pos_st =  $st_nb!='' ? place.formatted_address.indexOf($st_nb) : 0;
	        		if($pos_st > 0){
	            		$name = ($rout)+' '+ $st_nb + ($neig!='' ? ' '+$neig : '');
	            	}else{
	            		$name =  $st_nb+' '+($rout) + ($neig!='' ? ' '+$neig : '');
	            	}
	            	if(idel=='billing_address_1'){
						($name.replace(/\s+/g, "")!='' ? jQuery('#billing_address_1').val($name) :'');
					    jQuery('select#billing_country').val($country).trigger('change');
					    jQuery('#billing_city').val($city);
					    jQuery('#billing_state').val($state).trigger('change');
					    jQuery('#billing_postcode').val($postcode);
					}else{
						($name.replace(/\s+/g, "")!='' ? jQuery('#shipping_address_1').val($name) :'');
					    jQuery('select#shipping_country').val($country).trigger('change');
					    jQuery('#shipping_city').val($city);
					    jQuery('#shipping_state').val($state).trigger('change');
					    jQuery('#shipping_postcode').val($postcode);
					}
				}
            });
        </script>  
    <?php }
}

//add_filter('woocommerce_general_settings', 'exwf_general_settings_latlng');
function exwf_general_settings_latlng($settings) {
    $key = 0;

    foreach( $settings as $values ){
        $new_settings[$key] = $values;
        $key++;

        // Inserting array just after the post code in "Store Address" section
        if($values['id'] == 'woocommerce_store_postcode'){
            $new_settings[$key] = array(
                'title'    => __('Latitude and Longitude'),
                'desc'     => __('Physical address of your store location, you can see how to find physical address here: https://support.google.com/maps/answer/18539. Enter Latitude and Longitude, separated by a comma. Ex for London: 42.9869502,-81.243177'),
                'id'       => 'exwe_store_latlng', // <= The field ID (important)
                'default'  => '',
                'type'     => 'text',
                'desc_tip' => true, // or false
            );
            $key++;
        }
    }
    return $new_settings;
}