<?php
/**
 * Rotary Club Map Display Function with Ad Blocker Compatibility
 * 
 * Creates a map showing Rotary club locations with popup information.
 * Designed to work even with ad blockers enabled.
 */
function dacdb_map($atts) {
    global $fDebug, $data_path, $options;
    $options = get_mmp_options();    
    
    // Ensure jQuery is loaded
    wp_enqueue_script('jquery');
    
    // Load map assets
    wp_enqueue_style('dacdbplus-map');
    wp_enqueue_script('dacdbplus-map');
    
    // Retrieve global variables
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $style = isset($atts['style']) ? $atts['style'] : 1;
    $layout = isset($atts['layout']) ? $atts['layout'] : ''; // Default to empty for backward compatibility
    
    // Generate unique IDs
    $map_id = 'map_canvas_' . uniqid();
    
    // Display a message if the Google Map API key is missing
    if (empty($options['map_api'])) {
        return "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>Google Map API Key missing. Please configure it in the plugin settings.</div>";
    }
    
    // Debug information
    $debug_info = '';
    if ($fDebug && dacdb_is_admin()) {
        $map .= "=================================================================<BR>";
        $map .= "function dacdb_map called<br>";
        $map .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $map .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $map .= "ApiKey=" . $options['map_api'] . "<br>";
        $map .= "Style=" . $style . "<br>";
        $map .= "=================================================================<BR>";
    }

    // Generate a unique ID for the map canvas to prevent conflicts on pages with multiple maps
    $map_id = 'map_canvas_' . uniqid();

    // Generate HTML and JavaScript code for the map
    $map .= '
        <div id="Map"></div>
        <div id="' . $map_id . '" style="min-height:600px;"></div>
        <div id="MapData" style="display:none;"></div>
        <script>
            // Ensure we\'re not redefining variables if the function is called multiple times
            window.mmpMapVars = window.mmpMapVars || {};
            // Global callback to receive popup HTML
            function showPopUpData(json) {
                var container = document.getElementById("MapData");
                if (container) {
                    container.innerHTML = json.text;
                }
            }

            // Define map-specific variables with unique identifier
            window.mmpMapVars["' . $map_id . '"] = {
                map: null,
                xslResponse: null,
                popUpResponse: null,
                apiLoaded: false,
                apiLoading: false
            };
            
            // Check if Google Maps API is already loaded
            if (typeof google !== "undefined" && typeof google.maps !== "undefined") {
                window.mmpMapVars["' . $map_id . '"].apiLoaded = true;
                // console.log("Google Maps API already loaded");
            }
            
            // This function runs after Google Maps API is loaded
            function initMap_' . $map_id . '() {
                // console.log("Google Maps API initialized for ' . $map_id . '.");
                window.mmpMapVars["' . $map_id . '"].apiLoaded = true;
                
                // If we already have XSL data, process it now
                if (window.mmpMapVars["' . $map_id . '"].xslResponse) {
                    processMapData_' . $map_id . '();
                }
            }
            
            // Process the XSL-generated JavaScript
            function processMapData_' . $map_id . '() {
                var vars = window.mmpMapVars["' . $map_id . '"];
                
                if (!vars.apiLoaded || !vars.xslResponse) {
                    return; // Wait until both API and data are available
                }
                
                try {
                    // console.log("Processing map data for ' . $map_id . '...");
                    
                    // Get the script text and replace element ID
                    var scriptText = vars.xslResponse.text;
                    scriptText = scriptText.replace(/"map_canvas"/g, "\"' . $map_id . '\"");
                    
                    // Keep AdvancedMarkerElement instead of downgrading to Marker
                    // This follows Google\'s recommendation moving forward
                    
                    // Execute the modified script
                    (function() {
                        /* Create a scope where mmpEntityMap and markerPositions are accessible */
                        var mmpEntityMap = null;
                        var markerPositions = []; // Ensure this is declared in this scope
                        eval(scriptText);
                        
                        /* Store the created map in our variables */
                        if (mmpEntityMap) {
                            window.mmpMapVars["' . $map_id . '"].map = mmpEntityMap;

                            // Fit map bounds to markers
                            // Escape single quotes around \'undefined\' for PHP single-quoted string
                            if (markerPositions.length > 0 && typeof google !== \'undefined\' && google.maps && google.maps.LatLngBounds) {
                                var bounds = new google.maps.LatLngBounds();
                                for (var i = 0; i < markerPositions.length; i++) {
                                    bounds.extend(markerPositions[i]);
                                }

                                // Avoid over-zooming with fitBounds for a single marker
                                if (markerPositions.length > 1) {
                                    mmpEntityMap.fitBounds(bounds);
                                } else {
                                    mmpEntityMap.setCenter(bounds.getCenter());
                                    // Optionally set a default zoom for single markers if desired
                                    // mmpEntityMap.setZoom(14); 
                                }
                                // console.log("Map bounds adjusted for ' . $map_id . '.");
                            } else if (markerPositions.length === 0) {
                                // console.log("No marker positions found to adjust bounds for ' . $map_id . '.");
                                // Keep default center/zoom or set a specific one if no markers
                                mmpEntityMap.setCenter({ lat: 39.50, lng: -98.35 });
                                mmpEntityMap.setZoom(5);
                            }
                        } else {
                             console.error("mmpEntityMap not created after eval for ' . $map_id . '.");
                        }
                    })();
                } catch (e) {
                    console.error("Error executing generated script or fitting bounds:", e);
                    
                    // Fallback map initialization if script fails
                    if (!window.mmpMapVars["' . $map_id . '"].map) {
                        window.mmpMapVars["' . $map_id . '"].map = new google.maps.Map(
                            document.getElementById("' . $map_id . '"), 
                            {
                                center: { lat: 39.50, lng: -98.35 }, // Default center
                                zoom: 5, // Default zoom
                                mapId: "44be97c5795092fc"
                            }
                        );
                    }
                }
            }
            
            // Function called by AJAX when club data from wp_entityInteractive.xsl is available
            function showMap(json) {
                // console.log("Received map data for ' . $map_id . '");
                window.mmpMapVars["' . $map_id . '"].xslResponse = json;
                
                // If Google Maps API is already loaded, process the data immediately
                if (window.mmpMapVars["' . $map_id . '"].apiLoaded) {
                    processMapData_' . $map_id . '();
                }
                // Otherwise, it will be processed when the API loads
            }
            
            // popUp responses now handled by global showPopUpData()

            // Load the Google Maps API if it\'s not already loaded
            if (!window.mmpMapVars["' . $map_id . '"].apiLoaded && !window.googleMapsApiLoading) {
                // Set a global flag to prevent multiple API loading attempts
                window.googleMapsApiLoading = true;
                
                // Create and append the script element
                (function() {
                    var script = document.createElement("script");
                    script.src = "https://maps.googleapis.com/maps/api/js?key=' . esc_js($options['map_api']) . '&loading=async&callback=initMap_' . $map_id . '&libraries=marker";
                    script.async = false;
                    script.defer = true;
                    document.head.appendChild(script);
                })();
            } else if (window.mmpMapVars["' . $map_id . '"].apiLoaded) {
                // If API is already loaded, call the init function directly with a small delay
                setTimeout(function() {
                    initMap_' . $map_id . '();
                }, 10);
            }
            
            // Hide the unused containers
            jQuery(document).ready(function($) {
                $("#Map").hide();
                $("#MapData").hide();
            });
        </script>
        
        <!-- Load data files -->
        <script src="' . esc_url(
            $data_path . 'wp_entityMap.cfm?AccountID=' . $account_id . '&xsl=wp_entityInteractive.xsl' . '&mapId=44be97c5795092fc&callback=showMap&zlevel=0'
        ) . '" type="text/javascript"></script>
        <!-- Load marker popup data -->
        <script src="' . esc_url(
            $data_path . 'wp_entityMarker.cfm?AccountID=' . $account_id . '&xsl=wp_entityMarker.xsl&callback=showPopUpData&zlevel=0'
        ) . '" type="text/javascript"></script>
    ';

    return $map;
}