<?php echo $info_res; ?>
<?php
if (count($fiches)>0) :
    $js = '';

    $GLOBALS['wiki']->AddCSSFile('styles/vendor/leaflet/leaflet.css');
    $GLOBALS['wiki']->AddCSSFile('tools/bazar/presentation/styles/bazarcarto.css');
    $GLOBALS['wiki']->AddCSSFile('javascripts/vendor/leaflet-draw/leaflet.draw.css');
    $GLOBALS['wiki']->AddJavascriptFile('tools/bazar/presentation/javascripts/bazar.js', true, true);
    $GLOBALS['wiki']->AddJavascriptFile('javascripts/vendor/leaflet/leaflet.min.js');
    $GLOBALS['wiki']->AddJavascriptFile('javascripts/vendor/leaflet-providers/leaflet-providers.js');
    $GLOBALS['wiki']->AddJavascriptFile('javascripts/vendor/leaflet-draw/leaflet.draw.js', false, true);

    ?>

    <div id="osmmap<?php echo $params['nbbazarliste']; ?>"
         class="no-dblclick"
         style="<?php echo 'width:'.$params['width'].'; height:'.$params['height']; ?>"></div>
    <?php
    $tablinktitle = array();

    if ($params['spider'] == 'true' or $params['spider'] == '1') {
        $GLOBALS['wiki']->AddJavascriptFile('tools/bazar/libs/vendor/leaflet/spiderfier/oms.min.js');
        $markersjs = 'var popups = Array();'."\n".'oms = new OverlappingMarkerSpiderfier(map'.$params['nbbazarliste'].');'."\n".
        'var popup = new L.Popup();
        oms.addListener("click", function(marker) {
            marker.openPopup();
        });
        oms.addListener(\'spiderfy\', function(markers) {
          map'.$params['nbbazarliste'].'.closePopup();
        });'."\n";
    } elseif ($params['cluster'] == 'true' or $params['cluster'] == '1') {
        $GLOBALS['wiki']->AddCSSFile('styles/vendor/leaflet-markercluster/leaflet.markercluster.css');
        $GLOBALS['wiki']->AddJavascriptFile('javascripts/vendor/leaflet-markercluster/leaflet-markercluster.min.js');
        $markersjs = 'var markerscluster = new L.MarkerClusterGroup();'."\n";
    } else {
        $markersjs = '';
    }

    if ($params['fullscreen'] == 'true' || $params['fullscreen'] == '1') {
        $params['fullscreen'] = 'true';
        $GLOBALS['wiki']->AddCSSFile('styles/vendor/leaflet-fullscreen/leaflet-fullscreen.css');
        $GLOBALS['wiki']->AddJavascriptFile('javascripts/vendor/leaflet-fullscreen/leaflet-fullscreen.js');
    } else {
        $params['fullscreen'] = 'false' ;
    }

    $i = 0;
    $vAllGeometries = $geometriesWithoutMarker = [];

    $vGeolocationField = $params['geolocationfield']??'bf_geolocation';

    foreach ($fiches as $fiche) :?>
			<?php

            $vGeolocation = $fiche[$vGeolocationField] ?? [];

            $vLatitude = $vGeolocation ['latitude'] ?? '';
            $vLongitude = $vGeolocation ['longitude'] ?? '';
            $vGeometries = $vGeolocation ['geometries'] ?? '';
            $vGeometries = str_replace(
                '"type":"FeatureCollection"',
                '"id":"'.$fiche['id_fiche'].'","type":"FeatureCollection"',
                $vGeometries
            );


            // couleur de marqueur
            $color = getCustomValueForEntry($params['color'], $params['colorfield'], $fiche, $GLOBALS['wiki']->config['baz_marker_color']);

            //icone de marqueur
            $icon = $params['iconprefix']
                    .getCustomValueForEntry($params['icon'], $params['iconfield'], $fiche, $GLOBALS['wiki']->config['baz_marker_icon']);

           if (is_numeric($vLatitude) && is_numeric($vLongitude)) {
               // on genere le point marqueur sur la carte
               $markersjs .= '
				i++;
				var markerLocation = new L.LatLng('.$vLatitude.', '.$vLongitude.');
				marker[i] = new L.Marker(
						markerLocation,
						{
								icon: L.divIcon({
										iconSize: '.$params['iconSize'].',
										iconAnchor: '.$params['iconAnchor'].',
										popupAnchor: '.$params['popupAnchor'].',
										className: \'bazar-marker'.$params['smallmarker'].'\',
										html: \'<div class="bazar-entry" '
                                        .str_replace('\'', '', $fiche['html_data']).' style="color:'.$color.';">'
                                        .(!empty($icon) ? '<i class="fa-fw '.$icon.'"></i>' : '')
                                        .'</div>\'
								}),
								title: \''.addslashes($fiche['bf_titre']).'\'
						});
				marker[i].bindPopup(\''.preg_replace("(\r\n|\n|\r|)", '', addslashes(baz_voir_fiche($params['barregestion'], $fiche))).'\');
				';
               if ($params['spider'] == 'true' or $params['spider'] == '1') {
                   $markersjs .= 'map'.$params['nbbazarliste'].'.addLayer(marker[i]);'."\n".'oms.addMarker(marker[i]);'."\n";
               } elseif ($params['cluster'] == 'true' or $params['cluster'] == '1') {
                   $markersjs .= 'markerscluster.addLayer(marker[i]);'."\n";
               } else {
                   $markersjs .= 'map'.$params['nbbazarliste'].'.addLayer(marker[i]);'."\n";
               }
               $i++;
           } elseif (!empty($vGeometries)) {
               // fake marker for facetted search
               // TODO: this is way too hacky, need to find a way to search on marker and geometries in a better way
               $geometriesWithoutMarker[$fiche['id_fiche']] = '<div class="bazar-entry" '.str_replace('\'', '', $fiche['html_data']).'></div>';
           }
        if (!empty($vGeometries)) {
            $vAllGeometries[$fiche['id_fiche']] = $vGeometries;
        }
endforeach;


?>

	<?php
    if ($params['cluster'] == 'true' or $params['cluster'] == '1') {
        $markersjs .= 'map'.$params['nbbazarliste'].'.addLayer(markerscluster);'."\n";
    }
    $js .=
            '// Init leaflet map
		var map'.$params['nbbazarliste'].' = new L.Map(\'osmmap'.$params['nbbazarliste'].'\', {
				scrollWheelZoom:'.$params['zoom_molette'].',
				zoomControl:'.$params['navigation'].',
		fullscreenControl:'.$params['fullscreen'].',
				iconAnchor:   [6, 20]
		});';


    // Pas de L.control.layers
    if (empty($params['providers']) && empty($params['layers'])) {
        $js .=
            '
			var provider = L.tileLayer.provider("'.$params['provider'].'"'.$params['provider_credentials'].');
			';
    } else {
        // Avec un L.control.layers
        // Si param['provider'] existe, ce sera le baseLayer activé par défaut, sinon ce sera le 1er de la liste $paramss['providers'].

        $js .= 'var provider; var baseLayers = {};' ;
        /*if( ! empty($params['provider']) ){
            $js.= 'provider = L.tileLayer.provider("'.$params['provider'].'");' ;
            $js.= 'baseLayers["'.$params['provider'].'"] = provider ;' ;
        }*/
        if (empty($params['providers'])) {
            $params['providers'] = array($params['provider']);
        }
        foreach ($params['providers'] as $provider) {
            $js.= 'baseLayers["'.$provider.'"] = L.tileLayer.provider("'.$provider.'");' ;
            if (empty($params['provider'])) {
                $js.= 'if(provider==null) provider=baseLayers["'.$provider.'"];' ;
            } elseif ($provider==$params['provider']) {
                $js.= 'provider=baseLayers["'.$provider.'"];' ;
            }
        }


        $js .= 'var layers = {};' ;
        if (is_array($params['layers'])) {
            $leafletajaxIncluded = false ;
            foreach ($params['layers'] as $layer) {
                @list($layerLabel, $layerType, $layerOptions, $layerUrl) = explode('|', $layer);
                if ($layerUrl == null) {
                    $layerUrl = $layerOptions ;
                    $layerOptions = null ;
                }
                $layerType = strtolower($layerType);
                if (! in_array($layerType, array('tiles','geojson'))) {
                    $js.= 'alert("Erreur paramètre \\"layers\\": le type \\"'.$layerType.'\\" est inconnu")';
                }
                switch ($layerType) {
                    case 'tiles':
                        $js.= 'layers["'.$layerLabel.'"] = L.tileLayer("'.$layerUrl.'");' ;
                        break;
                    case 'geojson':
                        // URL: Attention au Blocage d’une requête multi-origines (Cross-Origin Request).
                        // Le plus simple est de recopier les data GeoJson dans une page du Wiki puis de l'appeler avec le handler "/raw".
                        // STYLE:
                        //	http://leafletjs.com/reference.html#path-options
                        //	http://leafletjs.com/reference.html#marker-options

                        if (! $leafletajaxIncluded) {
                            $leafletajaxIncluded = true ;
                            $GLOBALS['wiki']->AddJavascriptFile('tools/bazar/libs/vendor/leaflet/ajax/dist/leaflet.ajax.min.js');
                        }

                        $styleJs = '' ;
                        $isVisibleByDefault = false;
                        if ($layerOptions!=null) {
                            // extract 'visiblebydefault'
                            if (preg_match_all("/visiblebydefault\\s*;?/i", $layerOptions, $matches)) {
                                $isVisibleByDefault = true;
                                foreach ($matches[0] as $key => $value) {
                                    $layerOptions = str_replace($value, '', $layerOptions);
                                }
                            }
                            $layerOptions = str_replace(';', ',', $layerOptions);
                            $styleJs.='
							style: function (feature, latlng) {
								// pour les lignes et polygones
								if( feature.geometry.type=="Point" )
									return ;
								return {'.$layerOptions.'};
							},
							pointToLayer: function (feature, latlng) {
								// pour les points
								// parsing de layerOptions pour distinguer les options de marker et celles pour construire un icon pour le marker.
								var layerOptions = "'.$layerOptions.'".split(",");
								var markerOptions = {} , iconClass=null, color=null ;
								for( opt in layerOptions )
								{
									opt = layerOptions[opt].split(":");
									switch(opt[0].trim()) {
										case "opacity":
										case "clickable":
											// les options pour le marker http://leafletjs.com/reference.html#marker
											markerOptions[opt[0].trim()] = opt[1].trim();
											break;
										case "icon":
											// pour le html du L.divIcon http://leafletjs.com/reference.html#divicon
											// supprimer les éventuels apostrhophes
											iconClass = opt[1].trim().replace(/\'/g, "");
											break;
										case "color":
											// pour le html du L.divIcon
											color = opt[1].trim();
											break;
									}
								}

								if( iconClass!=null || color!=null ) {
									// Construit un L.divIcon pour le marker, sinon ce sera par défaut la goutte bleu.
									markerOptions["icon"] = L.divIcon({
											iconSize: '.$params['iconSize'].',
											iconAnchor: '.$params['iconAnchor'].',
											popupAnchor: '.$params['popupAnchor'].',
											className: "bazar-marker'.$params['smallmarker'].'",
											html: "<div class=\"bazar-entry "+ (color==null?"":"icon-"+color)+"\" '.addslashes($fiche['html_data']).'>" + (iconClass==null?"":"<i class=\""+iconClass+"\"></i>") + "</div>"
									});
								}

								return L.marker(latlng, markerOptions);
							},
							';
                        }

                        $js.= 'layers["'.$layerLabel.'"] = L.geoJson.ajax("'.$layerUrl.'",
						{
              interactive: false,
							'.$styleJs.'
							onEachFeature: function (feature, layer) {
								//layer.bindPopup(feature.properties.NOM + feature.properties.NOM_QP);
								var str = "" ;
								for( var prop in feature.properties){
									if( prop.toLowerCase() == "url" ) {
										str+= prop +": <a href=\""+ feature.properties[prop] + "\" target=\"_blank\" >" + feature.properties[prop] +"<br/>";
									} else {
										str+= prop +": "+ feature.properties[prop] +"<br/>";
									}
								}
								//layer.bindPopup( str );
							}
						} );' ;
                        if ($isVisibleByDefault) {
                            // add layer to the map
                            $js.= 'layers["'.$layerLabel.'"].addTo(map'.$params['nbbazarliste'].');' ;
                        }
                        break;
                }
            }
        }

        $js.= 'L.control.layers(baseLayers, layers).addTo(map'.$params['nbbazarliste'].');' ;
    }
  $geometriesModuleJs = '';
 if (!empty($vAllGeometries)) {
     $geometriesModuleJs .= "

    var drawnFeatures = new L.FeatureGroup()
    map".$params['nbbazarliste'].".addLayer(drawnFeatures)\n";
     foreach ($vAllGeometries as $id => $g) {
         $geometriesModuleJs .= "const geo{$id} = ". $g ."\n";
         $geometriesModuleJs .= 'var popup = \''.preg_replace("(\r\n|\n|\r|)", '', addslashes(baz_voir_fiche($params['barregestion'], $id))).'\''."\n";

         $geometriesModuleJs .= "drawnFeatures = drawGeometries(drawnFeatures, geo{$id}.features, popup, '{$id}')\n";
     }
     if (!empty($geometriesWithoutMarker)) {
         $js .= 'L.Control.geometriesPanel = L.Control.extend({
    onAdd: function(map) {
        const div = L.DomUtil.create(\'div\', \'info-panel\');
        div.innerHTML = \''.implode("", $geometriesWithoutMarker).'\';
        div.style.background = \'transparent\';
        div.style.padding = \'0\';
        
        // Prevent clicks from reaching the map
        L.DomEvent.disableClickPropagation(div);
        
        return div;
    }
});

  new L.Control.geometriesPanel({ position: \'topright\' }).addTo(map'.$params['nbbazarliste'].');';
     }
 }
  $GLOBALS['wiki']->AddJavascript(
      '
import { drawGeometries } from "./tools/bazar/presentation/javascripts/leaflet-draw.helper.js"

var map'.$params['nbbazarliste'].';	
$(document).ready(function() {
    if ($(\'#osmmap'.$params['nbbazarliste'].'\').length>0) {
		'.$js.'
		// N\'ajoute pas un doublon de layer, mais active la sélection du layer.
		map'.$params['nbbazarliste'].'.addLayer(provider);
		map'.$params['nbbazarliste'].'.setView(new L.LatLng('.$params['latitude'].', '.$params['longitude'].'), '.$params['zoom'].');
		var i = 0;
		var marker = Array();
    '. $markersjs .'
    }
    '.$geometriesModuleJs.'
	});',
      true
  );

endif;
