<?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',
				'lat' => '',
				'lng' => '',
				'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 '';

		$lat = is_numeric( $atts['lat'] ) ? (float) $atts['lat'] : null;
		$lng = is_numeric( $atts['lng'] ) ? (float) $atts['lng'] : null;

		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 id="gm-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 id="google-map-inline">
            (function () {
                const GMAPS_URL =
                    "https://maps.googleapis.com/maps/api/js?key=<?php echo esc_js( $atts['google_api_key'] ); ?>&libraries=places,marker&map_ids=9d93315b01ec6e8d";

                const location   = "<?php echo esc_js( $atts['location'] ); ?>";
                const priceLabel = "<?php echo esc_js( $atts['price'] ); ?>";
                const lat        = <?php echo $lat !== null ? wp_json_encode( $lat ) : 'null'; ?>;
                const lng        = <?php echo $lng !== null ? wp_json_encode( $lng ) : 'null'; ?>;

                // --- Single shared Promise across the page ---
                if (!window.__gmapsLoader) {
                    window.__gmapsLoader = (function () {
                        let promise;
                        return function ensureGoogleMaps() {
                            // Already loaded?
                            if (window.google && window.google.maps) return Promise.resolve();

                            // Already loading?
                            if (promise) return promise;

                            // If a loader script is already present (from another block), don't add another
                            const exists = !!document.querySelector('script[src*="maps.googleapis.com/maps/api/js"]');

                            promise = new Promise(function (resolve, reject) {
                                if (!exists) {
                                    const s = document.createElement('script');
                                    s.src = GMAPS_URL;
                                    s.async = true;
                                    s.defer = true;
                                    s.onload = () => resolve();
                                    s.onerror = () => reject(new Error("Failed to load Google Maps"));
                                    document.head.appendChild(s);
                                } else {
                                    // Poll until the existing one finishes
                                    (function waitForIt() {
                                        if (window.google && window.google.maps) resolve();
                                        else setTimeout(waitForIt, 50);
                                    })();
                                }
                            });

                            return promise;
                        };
                    })();
                }

                async function initMap() {
                    const ensureGoogleMaps = window.__gmapsLoader;
                    await ensureGoogleMaps();

                    const mapEl           = document.getElementById('property_map');
                    const directionsPanel = document.getElementById('directionsPanel');
                    const originInput     = document.getElementById('origin');
                    if (!mapEl) return;

                    const directionsService = new google.maps.DirectionsService();
                    const directionsRenderer= new google.maps.DirectionsRenderer();

                    function renderMap(position) {
                        const map = new google.maps.Map(mapEl, {
                            zoom: 14,
                            center: position,
                            mapId: "9d93315b01ec6e8d"
                        });

                        try {
                            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);"><?php echo esc_js( $atts['price'] ); ?></div>';
                            new google.maps.marker.AdvancedMarkerElement({
                                position: position,
                                map,
                                content: markerContent
                            });
                        } catch (e) {
                            new google.maps.Marker({position: results[0].geometry.location, map, title: priceLabel});
                        }

                        directionsRenderer.setMap(map);
                        directionsRenderer.setPanel(directionsPanel);

                        if (originInput) {
                            try {
                                new google.maps.places.Autocomplete(originInput, {
                                    types: ['geocode'],
                                    componentRestrictions: {country: "us"}
                                });
                            } catch (_) {
                            }
                        }

                        window.generateDirections = function (event) {
                            if (event && event.preventDefault) event.preventDefault();
                            const origin = (originInput && originInput.value || '').trim();
                            if (!origin) {
                                alert('Please enter a starting address.');
                                return;
                            }
                            directionsService.route({
                                origin,
                                destination: position,
                                travelMode: 'DRIVING'
                            }, function (response, status) {
                                if (status === 'OK') directionsRenderer.setDirections(response);
                                else alert('Directions request failed due to ' + status);
                            });
                        };

                        const form = document.getElementById('gm-form');
                        if (form && !form.__gmBound) {
                            form.__gmBound = true;
                            form.addEventListener('submit', window.generateDirections);
                        }
                    }

                    const hasCoords =
                        Number.isFinite(lat) && lat >= -90 && lat <= 90 &&
                        Number.isFinite(lng) && lng >= -180 && lng <= 180;

                    if (hasCoords) {
                        renderMap({ lat, lng });
                    } else if (location) {
                        const geocoder = new google.maps.Geocoder();
                        geocoder.geocode({ address: location }, function (results, status) {
                            if (status === 'OK' && results[0]) {
                                renderMap(results[0].geometry.location);
                            } else {
                                alert('Geocode was not successful for the following reason: ' + status);
                            }
                        });
                    } else {
                        alert('No valid coordinates or address provided.');
                    }
                }

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', initMap, { once: true });
                } else {
                    initMap();
                }
            })();
        </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();
    }

}
