<?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 property_google_map( $atts, $content = null ) {
		$atts = shortcode_atts(
			[
				'location' => 'New York, NY',
				'price' => '$0',
                'google_api_key' => get_option( 'facetwp_remote_data_google_api_key', false ),
			],
			$atts,
			'property_google_map'
		);

        if ( empty( $atts['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( $atts['google_api_key'] ); ?>&callback=initMap&libraries=places,marker&map_ids=9d93315b01ec6e8d"></script>
		<?php
		return ob_get_clean();
	}

    public function property_payment_calculator( $atts, $content = null ) {
	    $atts = shortcode_atts(
		    [
			    'price' => 0,
			    'default_down_payment' => 0,
			    'default_down_payment_percentage' => 0,
                'default_length_of_mortgage' => 0,
                'default_interest_rate' => 0,
		    ],
		    $atts,
		    'property_payment_calculator'
	    );

        extract( $atts );

        ob_start();
        ?>

        <div class="bg-off-white p-[1.5rem] flex flex-col gap-5">
            <button class="button button-blue w-full flex items-center justify-center gap-1">
                <img src="<?php echo plugin_dir_url( __FILE__ ); ?>images/smartphone-white.svg" class="h-[1.5rem] w-auto" alt="Cell Phone Icon">VIDEO TOUR FROM HOME
            </button>
            <button class="button button-black w-full block">
                CONTACT AGENT
            </button>
        </div>
        <div class="bg-off-white p-[1.5rem] text-black flex flex-col gap-5 text-off-black form-mask">
            <p class="uppercase font-bold text-[1rem]">Payment Calculator</p>
            <div class="flex flex-col gap-1">
                <p class="text-[0.875rem]"><label for="property-price">Property Price</label></p>
                <input id="property-price" type="number" class="text-input" value="<?php echo (int) $price; ?>">
            </div>
            <div class="flex flex-col gap-1">
                <p class="text-[0.875rem]"><label for="down-payment">Down Payment</label></p>
                <div class="flex max-w-full">
                    <input id="down-payment" type="number" class="text-input w-[65%] border-r-transparent " value="<?php echo (float) $default_down_payment; ?>">
                    <input id="down-payment-percentage" aria-label="Down Payment Percentage" type="number" class="text-input w-[35%]  grow-0" value="<?php echo (float) $default_down_payment_percentage; ?>">
                </div>
            </div>
            <div class="flex flex-col gap-1">
                <p class="text-[0.875rem]"><label for="length-of-mortgage">Length of Mortgage</label></p>
                <input id="length-of-mortgage" type="number" class="text-input " value="<?php echo (int) $default_length_of_mortgage; ?>" data-inputmask="'mask': '99 ye\\ars', 'numericInput': true, 'placeholder': ''" >
            </div>
            <div class="flex flex-col gap-1">
                <p class="text-[0.875rem]"><label for="interest-rate">Annual Interest Rate</label></p>
                <input id="interest-rate" type="number" class="text-input " value="<?php echo (float) $default_interest_rate; ?>" data-inputmask="'mask': '99%', 'numericInput': true, 'placeholder': ''" >
            </div>
            <div id="monthly-payment"></div>

            <canvas id="mortgage-payment-chart"></canvas>

        </div>

	    <?php
	    return ob_get_clean();
    }

    public function latest_listings( $atts, $content = null ) {
	    $atts = shortcode_atts(
		    [
			    'posts_per_page' => 12,
			    'paged' => 1,
		    ],
		    $atts,
		    'Latest_Listings'
	    );

	    $template_path = apply_filters(
		    'facet_wp_remote_data_latest_listings_template_path',
		    ( new Facet_Wp_Remote_Data_Handler )->get_template_path( 'latest-listings-template' )
	    );

	    extract( $atts );

	    ob_start();

	    include $template_path;

	    return ob_get_clean();
    }

}