<?php 
//part of ProjectMaps
//ProjectMaps is free software under the terms of the GPLv3
//written by Hartmut Noack zettberlin@linuxuse.de for ungeo.de
//general tools 

//pm_gis_layers_features has to be an array fetched from Geoserver with its data under index 0
//please be aware, that some procedures require JS objects to be set beforehand such as icons for the SLD functions
//all these higher stuff is optional, just give an empty array for optiions and it will work with the defaults...
//mail me for further information
//Bhardo stu te
function pm_make_leafletgisobjects_byrequest($pm_gis_layers_features,$pm_store_name,$pm_style,$options){

 global $pm_view;
 global $pm_section;

 $map_id="pmMap";
 if (isset($options['custom_map_id'])){
   $map_id=$options['custom_map_id'];
 }
 $pm_width=3;
 if (isset($options['width'])){
 $pm_width=$options['width'];
 }
 
 $pm_click=true;
 
 if (isset($options['click'])){
   $pm_click=$options['click'];
}
 
 $pm_fill="white";
 
 if (isset($options['fill_color'])){
  $pm_fill=$options['fill_color'];
 }
 
 $pm_opacity=0.5;
 
 if (isset($options['opacity'])){
  $pm_opacity=$options['opacity'];
 }
 
 $pm_fill_opacity=0.2;
 if (isset($options['fill_opacity'])){
  $pm_fill_opacity=$options['fill_opacity'];
 } 
 
 $pm_weight=2;
  if (isset($options['weight'])){
  $pm_weight=$options['weight'];
 } 
 
 
 if (isset($options['map_id'])){
  $map_id=$options['map_id'];
 }
 if (isset($options['MarkerCluster'])){
 echo "
 var markerClusters = L.markerClusterGroup({
	spiderfyOnMaxZoom: true,
    maxClusterRadius: 80
});
 ";
 }
 
 if (isset($options['sld'])){
 
  $sld_file_source=$options['sld'];
  $section=$options['sld_section'];
  $sld_rules_digest=pm_sld2array($sld_file_source,$section);
 
 }
 
 $pm_leafletGroup="";
  //the function may return a array, that holds all objects grouped by GIS ID
  $objects=array();
 $pm_objectGroups=array();
 $layer_objects="";
 $gisoid_number=0;
 if(is_array($pm_gis_layers_features)){
 foreach($pm_gis_layers_features as $pm_feature_info){ 

 $layer_objects="";
  $gisoid_number=0;
  
  if(is_array($pm_feature_info)){
  foreach($pm_feature_info['features'] as $feature){  
  
   $fields="";
   $icon="smallIcon";
   if (isset($options['icon'])){
    $icon=$options['icon'];
   }
   $pm_gis_head="";
    $fieldsUIC="";
   foreach($feature['properties'] as $fieldname => $val){
    //properties is the realm that has to be checked for filtering 
     $filtered=true;
     if (isset($options['prop_begins_with'])){
       $filtered=false;
       $prop_begins_with=$options['prop_begins_with'];
       
       if ($fieldname == $prop_begins_with[0]){
         if (startsWith($val,$prop_begins_with[1])){
    
          echo "
            console.log('$fieldname $val');
          ";
         $filtered=true;
         $go="";
         
         //default action for filtered object
         $pm_weight=2;
         //specific stuff
         if (isset($prop_begins_with[2])){
           if ($prop_begins_with[2] == "enlarge_border"){
             $pm_weight=8;
          }
           
        }
         }
         else {
           unset($go);
        }

      }

    }
              
    if ($filtered or isset($go)){
     
    //and special effects:
     if($fieldname=="spec" and $val =="fagro"){
       $pm_style="#fffbd2";
       $pm_fill="#fffbd2";
     }
     elseif($fieldname=="spec" and $val =="heco"){
       $pm_style="#0dff00";
       $pm_fill="#0dff00";
    }
     
    
    if (isset($sld_rules_digest)){

     if ($fieldname == "Single symbol"){
      $sld_ruled_fill=explode(":",$sld_rules_digest[$val][0]);
      $sld_ruled_color=explode(":",$sld_rules_digest[$val][1]);
      $sld_ruled_width=explode(":",$sld_rules_digest[$val][2]);
      $pm_fill=$sld_ruled_fill[1];
      $pm_style=$sld_ruled_color[1];
      $pm_width=$sld_ruled_width[1];
   
     }
    
    }
   if ($fieldname != "bbox" and $fieldname != "path"){
     if ($val != "" and $fieldname != "ID"){
       
       $fieldname=pm_replace_names($fieldname);
      if ($fieldname=="UIC" or $fieldname=="uic"){
       $fields = $fields."<li><h3>$fieldname: $val</h3></li>";
       $fieldsUIC=$val;
      }
      else{
      $fields = $fields."<li>$fieldname: $val</li>";
      }
     }
     elseif($val == "") {
      $fields = $fields."<li>$fieldname: na</li>";
     }
    }
    else{
     if ($fieldname != "path"){
     $fields = $fields."<li><strong>Bounding Box</strong>:".$feature['properties']['bbox'][0].",".$feature['properties']['bbox'][1]." / ".$feature['properties']['bbox'][2].",".$feature['properties']['bbox'][3] ."</li>";
     }
    }
    }//end if filtered
   }// end foreach($feature['properties']
   //repeat filtering for the whole rest
   if ($filtered or isset($go)){
   
   //try to order the input array
   
   //now we render the given shape
   
   
   if ($feature['geometry']['type'] == "MultiPolygon"){
   
   $points="";
   foreach ($feature['geometry']['coordinates'][0] as $latlongs){
    //$latlong=pm_longlat2latlong("$longlat[0]");
     foreach ($latlongs as $latlong){
      $latlong=$latlong[1].",".$latlong[0];
      $points = $points."[$latlong], "; 
     }
    
    }
     $points = $points."&";
     $points = str_replace(", &","",$points);
     
     $fields = str_replace("\r","",$fields);
     $fields = str_replace("\n","",$fields);
     $fields = str_replace("'","&apos;",$fields);
     $pm_gis_single_object_id = $feature['id'];
     //current GIS ID will be the individual identifier of the object
     $gisID_stripped=str_replace(".","",$pm_gis_single_object_id);
     //echo "// GIS ID stripped: $gisID_stripped";
    ?>
     
     var feature_geom_type='<?php echo $feature['geometry']['type'];?>';
     
     var latLonExtraVectors<?php echo $gisoid_number?>=[<?php echo $points;?>];
     var vector<?php echo $gisID_stripped?> = new L.Polygon(latLonExtraVectors<?php echo $gisoid_number?>, {
      <?php if (isset($options['noclick']) and $options['noclick']){ echo "interactive:false, ";} ?>
      color: '<?php echo $pm_style;?>',
      weight: <?php echo $pm_weight;?>,
      opacity: <?php echo $pm_opacity?>,
      fillColor:'<?php echo $pm_fill;?>' ,
      fillOpacity: <?php echo $pm_fill_opacity;?>,
      smoothFactor: 1
     });
     <?php if (!isset($options['noclick']) or !$options['noclick']){?>
     
     var pm_ObjectID<?php echo $gisID_stripped?>='<?php echo $pm_gis_single_object_id;?>';
     
     var pm_UIC='<?php echo $fieldsUIC;?>';
     <?php if (!isset($options['nopop'])){ ?>
     vector<?php echo $gisID_stripped?>.bindPopup('<div style="min-width:20em;"><h3><?php// echo $pm_gis_single_object_id;?></h3><p></p><ul style="position:relative;" class="popup-list"><?php echo $fields;?></ul><div class="pm_popup_toolbar"><a onclick="pm_ObjectDetails(pm_ObjectID<?php echo $gisID_stripped;?>,pm_UIC)">View Details </a> </div></div>');
     <?php }//END nopop?>
     vector<?php echo $gisID_stripped?>.on('click', function() {pm_MapclickTobox('<?php echo $fieldsUIC;?>');})
     vector<?php echo $gisID_stripped?>.on('click', onMapClick);
     
     <?php } //End if not noclick ?>
     
    <?php
    //collect multiline objects
    $pm_leafletGroup=$pm_leafletGroup."vector".$gisID_stripped.",";
    if (!isset($options['hidden']) or !$options['hidden']){
    ?>
     vector<?php echo $gisID_stripped?>.addTo(<?php echo $map_id; ?>);
 <?php
     }//END hidden
    }//end if feature['geometry']['type'] == "MultiPolygon"
    elseif ($feature['geometry']['type'] == "MultiLineString"){
   $points="";
   foreach ($feature['geometry']['coordinates'][0] as $latlong){
    //$latlong=pm_longlat2latlong("$longlat[0]");
    $latlong=$latlong[1].",".$latlong[0];
    $points = $points."[$latlong], "; 
    }
     $points = $points."&";
     $points = str_replace(", &","",$points);
     
     $fields = str_replace("\r","",$fields);
     $fields = str_replace("\n","",$fields);
     $fields = str_replace("'","",$fields);
     $pm_gis_single_object_id = $feature['id'];
     
     $gisID_stripped=str_replace(".","",$pm_gis_single_object_id);
     //echo "// GIS ID stripped: $gisID_stripped";
    ?>
     
     var feature_geom_type='<?php echo $feature['geometry']['type'];?>';
     
     var latLonExtraVectors<?php echo $gisoid_number?>=[<?php echo $points;?>];
     var vector<?php echo $gisID_stripped?> = new L.Polyline(latLonExtraVectors<?php echo $gisoid_number?>, {
      color: '<?php echo $pm_style;?>',
      weight: <?php echo $pm_weight;?>,
      opacity: 0.6,
      fillOpacity: 0.1,
      smoothFactor: 1
     });
     vector<?php echo $gisID_stripped?>.bindPopup('<h3><?php echo $pm_gis_single_object_id;?></h3><p></p><ul style="position:relative;"><?php echo $fields;?></ul><div class="pm_popup_toolbar"><a onclick="pm_ObjectDetails(pm_ObjectID<?php echo $gisID_stripped?>)">View Details</a></div>');
     
     
    <?php
    //collect multiline objects
    $pm_leafletGroup=$pm_leafletGroup."vector".$gisID_stripped.",";
    
    if (!isset($options['hidden'])){
    ?>
     vector<?php echo $gisID_stripped?>.addTo(<?php echo $map_id; ?>);
 <?php
     }
    }//end if feature['geometry']['type'] == "MultiLineString"
   elseif($feature['geometry']['type'] == "Point" or $feature['geometry']['type'] == "MultiPoint"){
   //crude: need to do nothing, if the dataset is no complete
 
    if(isset($feature['geometry']['coordinates'][0])){
    
     if ($feature['geometry']['type'] == "MultiPoint"){
          $theGeom_long=$feature['geometry']['coordinates'][0][0];
          $theGeom_lat=$feature['geometry']['coordinates'][0][1];
          $latlong = $theGeom_lat.",".$theGeom_long;   
         }
         else{    
          $theGeom_long=$feature['geometry']['coordinates'][0];
          $theGeom_lat=$feature['geometry']['coordinates'][1];
          $latlong = $theGeom_lat.",".$theGeom_long;
         }
     
     $fields = str_replace("\r","",$fields);
     $fields = str_replace("\n","",$fields);
     $fields = str_replace("'","&apos;",$fields);
     $pm_gis_single_object_id=$feature['id'];
     $pm_store_name="na";
     
     $gisID_stripped=str_replace(".","",$pm_gis_single_object_id);
     //echo "// GIS ID stripped: $gisID_stripped";
     
    if (isset($_GET['pm_gis_store'])){
     $pm_store_name=pm_sanitizer($_GET['pm_gis_store'],"");
    }
     echo "
     // Single object ID: $pm_gis_single_object_id";
   ?>
   
    var latLonExtra<?php echo $gisoid_number?>=[<?php echo $latlong;?>];
    marker<?php echo $gisID_stripped;?> = L.marker(latLonExtra<?php echo $gisoid_number;?>, {icon: <?php echo $icon;?>});
    
    marker<?php echo $gisID_stripped;?>.bindPopup('<h3><?php echo $pm_gis_head; ?></h3></div><ul><?php echo $fields;?><li><small>ID SIG:<br><?php echo $pm_gis_single_object_id;?></small></li></ul><div><a onclick="pm_ObjectDetails(pm_ObjectID<?php echo $gisID_stripped?>)">View Details</a> </div>');
   
    marker<?php echo $gisID_stripped;?>.on('click', function () {
    marker<?php echo $gisID_stripped;?>.openPopup
    });
    
    <?php
    if (isset($options['flag'])){?>
     marker<?php echo $gisID_stripped;?>.bindTooltip("<?php echo $pm_gis_head?>",
     {  permanent: true, 
        direction: 'right'
    });
    <?php } ?>
    
    <?php if (!isset($options['hidden'])){?>
    marker<?php echo $gisID_stripped;?>.addTo(<?php echo $map_id; ?>);
    <?php } ?>
    
    <?php if (isset($options['MarkerCluster'])){?>
    markerClusters.addLayer( marker<?php echo $gisID_stripped;?> );
    <?php } ?>
   
   <?php
    //create array sections to collect groups by feature id
    $layer_id=explode(".",$pm_gis_single_object_id);
    $pm_leafletGroup=$pm_leafletGroup."marker".$gisID_stripped.", ";
   
    }//end if $feature['geometry']['coordinates'][1]
    else{
    echo "//no coords0
    ";
    }
   }
   }//end if filtered again
   $gisoid_number++;
   //array_push($objectGroups[$layer_id[0]],"marker".$gisoid_number.", ");

   }//end foreach $pm_feature_info['features'] as $feature
  }//end if array feature_info
 }//end $pm_gis_layers_features as $pm_feature_info
 }//end if is_array $pm_gis_layers_features
 //return collected objects
 if (isset($options['MarkerCluster'])){?>
 
  <?php echo $map_id; ?>.addLayer( markerClusters );

 <?php } 
 return $pm_leafletGroup;
}
