<?php
$default_map_color = get_option('wcmlim_default_map_color') ?: '#187dc7';
?>

<style>
    :root {
        --default-map-color: <?php echo $default_map_color; ?>;
    }

    .marker-btn-1, .marker-btn-2, .locator-store-block h4, .wcmlim-map-sidebar-list button, .wcmlim-top-map-widgets {
        background: var(--default-map-color) !important;
    }
    .wcmlim-map-sidebar-list h4 {
        color: var(--default-map-color) !important;
    }
</style>

<?php
$api_key = get_option('wcmlim_google_api_key');
$default_list_align = get_option('wcmlim_default_list_align');
$default_origin_center = get_option('wcmlim_default_origin_center');
$filter_visibility_shortcode = get_option('wcmlim_filter_visibility_shortcode');
$default_origin_center_modify = str_replace(' ', '+', $default_origin_center);

// Fetch taxonomy terms
$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
$store_on_map_arr = [];
$mapid = 1;

// Fetch coordinates for the origin location
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($default_origin_center_modify) . '&sensor=false&key=' . $api_key,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => "GET",
));
$geocode = curl_exec($curl);
$output = json_decode($geocode);
curl_close($curl);

$originlatitude = $output->results[0]->geometry->location->lat ?? 0;
$originlongitude = $output->results[0]->geometry->location->lng ?? 0;

$origin_store_on_map_str = array(
    "<div class='locator-store-block'><h4>" . esc_html($default_origin_center) . "</h4></div>",
    floatval($originlatitude),
    floatval($originlongitude),
    intval($mapid),
    'origin'
);
$store_on_map_arr[] = $origin_store_on_map_str;
$mapid = 2;

// Fetch coordinates for each term
foreach ($terms as $term) {
    $slug = $term->slug;
    $term_meta = get_option("taxonomy_{$term->term_id}", []);
    $address = implode(' ', array_filter([
        $term_meta['wcmlim_street_number'] ?? '',
        $term_meta['wcmlim_route'] ?? '',
        $term_meta['wcmlim_locality'] ?? '',
        $term_meta['wcmlim_administrative_area_level_1'] ?? '',
        $term_meta['wcmlim_country'] ?? '',
        $term_meta['wcmlim_postal_code'] ?? ''
    ]));
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false&key=' . $api_key,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CUSTOMREQUEST => "GET",
    ));
    $geocode = curl_exec($curl);
    $output = json_decode($geocode);
    curl_close($curl);

    $latitude = $output->results[0]->geometry->location->lat ?? 0;
    $longitude = $output->results[0]->geometry->location->lng ?? 0;

    $titletext = "<div class='locator-store-block'><h4>" . esc_html($term->name) . "</h4>";
    $titletext .= isset($term_meta['wcmlim_email']) ? "<p><span class='far fa-envelope'></span> " . esc_html($term_meta['wcmlim_email']) . "</p>" : "";
    $titletext .= "<p><span class='far fa-map'></span> " . esc_html($address) . "</p>";
    $titletext .= "<a class='marker-btn-1 btn btn-primary' target='_blank' href='https://www.google.com/maps/dir//$address'> Direction </a>";
    $titletext .= "<a class='marker-btn-2 btn btn-primary' target='_blank' href='" . esc_url(get_site_url()) . "?locations={$slug}'> Shop Now </a></div>";
    
    $store_on_map_str = [
        $titletext,
        floatval($latitude),
        floatval($longitude),
        intval($mapid),
        intval($term->term_id)
    ];
    $store_on_map_arr[] = $store_on_map_str;
    $mapid++;
}

update_option("store_on_map_arr", json_encode($store_on_map_arr), false);
?>

<div class="wcmlim-map-widgets list-view-locations" style="display:none;">
    <div class="wcmlim-top-map-widgets">
        <?php if (!empty($filter_visibility_shortcode) && $filter_visibility_shortcode === 'on') : ?>
            <div class="search-filter-toggle_parameter">
                <button class="map-search-by-btn" id="btn-filter-toggle_parameter2"><?php _e('Search By Product Category', 'wcmlim'); ?></button>
                <button class="map-search-by-btn" id="btn-filter-toggle_parameter1"><?php _e('Search By Product', 'wcmlim'); ?></button>
            </div>
            <!-- Product category and product search filters here -->
        <?php endif; ?>

        <div class="search-bar">
            <label>Search Location</label>
            <input type="text" id="elementIdGlobalMaplist" class="form-control" placeholder="Enter Location">
            <button class="geolocation-marker" id="my_current_location_list" title="Use Current Location">
                <i class="fa fa-map-marker" aria-hidden="true"></i>
            </button>
        </div>

        <div class="distance-bar">
            <label>Distance Range</label>
        </div>
        <div class="range-bar">
            <input type="range" id="rangeInputList" style="margin-top: 2rem;">
            <span style="font-weight: 800;" id="rangedisplay"></span>
        </div>
    </div>

    <div class="block-1" <?php echo ($default_list_align === 'left') ? "style='float: right;'" : ""; ?>>
        <div id="map" style="width: 100%; height: 452px;"></div>
    </div>

    <div class="wcmlim-map-sidebar-widgets block-2">
        <div class="filter-form">
            <div class="form-control">
                <?php foreach ($terms as $term) : ?>
                    <?php
                    $term_meta = get_option("taxonomy_{$term->term_id}", []);
                    $address = implode(' ', array_filter([
                        $term_meta['wcmlim_street_number'] ?? '',
                        $term_meta['wcmlim_route'] ?? '',
                        $term_meta['wcmlim_locality'] ?? '',
                        $term_meta['wcmlim_administrative_area_level_1'] ?? '',
                        $term_meta['wcmlim_country'] ?? '',
                        $term_meta['wcmlim_postal_code'] ?? ''
                    ]));
                    ?>
                    <div class="wcmlim-map-sidebar-list" id="<?php echo esc_attr($term->term_id); ?>">
                        <h4><?php echo esc_html($term->name); ?></h4>
                        <p class="location-address">
                            <span class='far fa-building'></span> <span><?php echo esc_html($address); ?></span><br />
                            <?php if (isset($term_meta['wcmlim_email'])) : ?>
                                <span class='far fa-envelope-open'></span> <span><?php echo esc_html($term_meta['wcmlim_email']); ?></span>
                            <?php endif; ?>
                        </p>
                        <button class="btn btn-primary" onclick="window.open('https://www.google.com/maps/dir//<?php echo urlencode($address); ?>', '_blank');">
                            Direction
                        </button>
                        <button class="btn btn-primary" onclick="window.open('<?php echo esc_url(get_site_url()) . '?locations=' . $term->slug; ?>', '_blank');">
                            Shop Now
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
