<?php

class Facet_Wp_Remote_Data_Shortcodes {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}

	public function google_map( $atts, $content = null ) {
		$atts = shortcode_atts(
			[
				'location' => 'New York, NY',
				'price' => '$0',
			],
			$atts,
			'map'
		);

		$google_api_key = get_option( 'facetwp_remote_data_google_api_key', false );

        if ( empty( $google_api_key ) ) return;

		ob_start();
		?>

		<div id="property_map" class="w-full h-[400px] mt-[10px]"></div>
		<p class="mt-5 text-[1rem] mb-1">Get Directions to Property:</p>
		<form class="prevent-default flex ">
			<input aria-label="Starting Address" id="origin" type="text" placeholder="Enter starting address" class="!border-r-0 h-[56px] w-full text-input p-[8px]">
			<button class="whitespace-nowrap button button-black" onclick="generateDirections(event)">Generate Directions</button>
		</form>
		<div id="directionsPanel" class="mt-[10px]"></div>

		<script>
            function initMap() {
                const location = "<?php echo esc_js( $atts['location'] ); ?>";
                const priceLabel = "<?php echo esc_js( $atts['price'] ); ?>";
                const geocoder = new google.maps.Geocoder();
                const directionsService = new google.maps.DirectionsService();
                const directionsRenderer = new google.maps.DirectionsRenderer();

                geocoder.geocode({ address: location }, function(results, status) {
                    if (status === 'OK') {
                        const map = new google.maps.Map(document.getElementById('property_map'), {
                            zoom: 14,
                            center: results[0].geometry.location,
                            mapId: "9d93315b01ec6e8d"
                        });

                        const markerContent = document.createElement('div');
                        markerContent.innerHTML = `<div class="bg-white p-[10px] text-[1rem] rounded-[5px]" style="box-shadow:0 2px 5px rgba(0,0,0,0.3);">${priceLabel}</div>`;

                        new google.maps.marker.AdvancedMarkerElement({
                            position: results[0].geometry.location,
                            map: map,
                            content: markerContent
                        });

                        directionsRenderer.setMap(map);
                        directionsRenderer.setPanel(document.getElementById('directionsPanel'));

                        // Initialize Autocomplete for the input field
                        const originInput = document.getElementById('origin');
                        const autocomplete = new google.maps.places.Autocomplete(originInput, {
                            types: ['geocode'], // Restrict to geocodable addresses
                            componentRestrictions: { country: "us" } // Restrict to US (optional)
                        });

                        // Generate directions function
                        window.generateDirections = function(event) {
                            event.preventDefault();

                            const origin = originInput.value;

                            if (!origin) {
                                alert('Please enter a starting address.');
                                return;
                            }

                            directionsService.route({
                                origin: origin,
                                destination: results[0].geometry.location,
                                travelMode: 'DRIVING'
                            }, function(response, status) {
                                if (status === 'OK') {
                                    directionsRenderer.setDirections(response);
                                } else {
                                    alert('Directions request failed due to ' + status);
                                }
                            });
                        }
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }
		</script>
		<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?php echo esc_attr( $google_api_key ); ?>&callback=initMap&libraries=places,marker&map_ids=9d93315b01ec6e8d"></script>
		<?php
		return ob_get_clean();
	}
}