<?php
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/queries.php';

function wosmpl_create_popup_content($content, $cat) {
    $popup_content = "<h2><strong><a  href=\"{$content->url}\" target=\"_blank\"> {$content->title} <i class=\"fa fa-external-link wo-icon\"> </i></a></strong></h2>";
    if(isset($cat['name'])) {
        $popup_content .= '<p class="cat">'.$cat['name'].'<p/>';
    }
    /** TODO : Input user settings to know if picture has to be shown
    if (strlen($content->picture_url) > 0) {
        $picture_url = str_replace('.','-125.',$content->picture_url);
        $popup_content .= '<img src="'.$picture_url.'" alt="" />';
    }
    **/
    if (strlen($content->post_addr) > 0) {
        $popup_content .= '<p class="open_hours">'.$content->post_addr.'</p>';
    }
    if (strlen($content->open_hours) > 0) {
        $popup_content .= '<p class="open_hours">'.nl2br($content->open_hours).'</p>';
    }
    if (strlen($content->specialty) > 0) {
        $popup_content .= '<p class="specialty">'.nl2br($content->specialty).'</p>';
    }
    
    return $popup_content;
}
/* TODO Traiter les points trop proches pour les mettre en cluster
<script type="text/javascript">

        var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 18,
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Points &copy 2012 LINZ'
            }),
            latlng = L.latLng(-37.82, 175.24);

        var map = L.map('map', {center: latlng, zoom: 13, layers: [tiles]});

        var markers = L.markerClusterGroup();
        
        for (var i = 0; i < addressPoints.length; i++) {
            var a = addressPoints[i];
            var title = a[2];
            var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
            marker.bindPopup(title);
            markers.addLayer(marker);
        }

        map.addLayer(markers);

    </script>
*/

function wosmpl_create_geojson($contents){
    $points = [];
    $geo_cats = get_option('wosmpl_geo_cats', []);
    $filtered_cat = NULL;
    if (isset($_GET['code_categorie']) && is_numeric($_GET['code_categorie'])) {
        $filtered_cat = $_GET['code_categorie'];
    }
    foreach ($contents as $c) {
        if ($filtered_cat === NULL || $filtered_cat == $c->cat) {
            
            list($lat,$lon) = explode(',', $c->latlon) + [null, null];
            if ($lat) {
                $p = new StdClass();
                $p->type = "Feature";
                $p->geometry = [
                                'type'=>'Point',
                                'coordinates' => [$lon,$lat]
                               ];
                $cat = [];
                foreach ($geo_cats as $gc) {
                    if ($gc['id'] == $c->cat) {
                        $cat = $gc;
                    }
                }
                $p->cat = $cat;
                
                $properties = [
                                'name'=>$c->title,
                                'popupContent'=>
                                wosmpl_create_popup_content($c, $cat)
                              ];
                if(isset($cat['id'])) {
                    $properties['cat'] = $cat['id'];
                }
                $p->properties = $properties;
                $points[] = $p;
            }
            
        }
        
    }
    return json_encode($points);
}

function wosmpl_cat_list_html($by_cat_content) {
    $o  = '<div class="wosmpl-box partner_list">';
    foreach ($by_cat_content as $catname =>$elts) {
        $add_it = TRUE;
        $show_name = TRUE;
        if (isset($_GET['code_categorie']) && is_numeric($_GET['code_categorie'])) {
            if ($_GET['code_categorie'] == $elts['id']) {
                $add_it = TRUE;
                $show_name = FALSE;
            } else {
                $add_it = FALSE;
            }
        }
        if ($add_it == TRUE){
            $o .= '<div class="wosmpl_categ" data-catid="'.$elts['id'].'">';
            if ($show_name == TRUE) {
                $o .= '<h2><img width="35" src="'.wosmpl_get_cat_marker_icon($elts['id']).'" alt=""/>'.$catname.'</h2>';
            }
            foreach ($elts['contents'] as $c) {
                //var_dump($c);
                $o .= '<div class="partner_sum_up">';
                $o .= '<h3><a href="'.$c->url.'" target="_blank">'.$c->title.'  <i class="fa fa-external-link wo-icon"></i></a></h3>';
                $o .= "<span class=\"presta-type\">{$c->presta_type}</span>";
                $o .= '</div>';
            }
            $o .= '</div>';

        }
        
    }
    $o .= '</div>';
    return $o;
}

function wosmpl_map_shortcode($atts = [], $content = null, $tag = '')
{
    $o = '';
    //Retrieve geolocalized contents
    $contents = wosmpl_get_geolocalized_contents();
    if (count($contents) > 0) {
        $cat_icon_path = get_option('wosmpl_cat_icon_path');
        $cat_icon_name_prefix = get_option('wosmpl_cat_icon_name_prefix');
        wosmpl_leaflet_activate();
        // normalize attribute keys, lowercase
        $atts = array_change_key_case((array)$atts, CASE_LOWER);
     
        // override default attributes with user attributes
        $wosmpl_atts = shortcode_atts([
                                         'title' => '',
                                         'cat_filter' => 'true'
                                     ], $atts, $tag);
        $geo_cats = get_option('wosmpl_geo_cats', []);
        $cat_filter = '';
        $by_cat_content = wosmpl_get_array_by_category($contents);
        $gcats = wosmpl_get_categories_with_nb();
        $options = get_option( 'wosmpl_options' );
        //var_dump($by_cat_content);
        if (isset($_GET['code_categorie']) && is_numeric($_GET['code_categorie'])) {
            
            foreach ($geo_cats as $gc) {
                if ($gc['id'] == $_GET['code_categorie']) {
                    $wosmpl_atts['title'] = $gc['name'];
                }
            }
        } else if (isset($wosmpl_atts['cat_filter']) && $wosmpl_atts['cat_filter'] == 'true'){
            
            if (count($gcats) > 0) {
                $cat_filter = '<div class="wosmpl_map_cat_filter">';
                if (isset($options['wosmpl_main_map_cat_legend'])) {
                    $cat_filter .= '<p>'.$options['wosmpl_main_map_cat_legend'].'</p>';
                }
                $cat_filter .= '<div class="wospml_cat_choice" data-catid="0" ><div class="icon" title="Toutes les catégories"><img width="50" src="'.wosmpl_get_cat_marker_icon(0).'" alt=""/></div></div>';
                foreach ($gcats as $gc) {
                    if ($gc['nb'] > 0) {
                        $cat_filter .= '<div class="wospml_cat_choice" data-catid="'.$gc['id'].'" >'."\n";
                        $cat_filter .= '<div class="icon" title="'.$gc['name'].'">';
                        $cat_filter .= '<img width="50" src="'.wosmpl_get_cat_marker_icon($gc['id']).'" alt=""/>';
                        $cat_filter .= '</div>';
                        $cat_filter .= '</div>'."\n";
                    }
                }
                $cat_filter .= '<div class="clear"></div>';
                $cat_filter .= '</div>';
                
            }
            
        }

        
        //var_dump($contents);
        // start output
        if (strlen($wosmpl_atts['title']) > 0) {
            $o .= '<h2>' . esc_html__($wosmpl_atts['title'], 'wosmpl') . '</h2>';
        }
        
     
        $o .= '<a name="map"></a>';
        $o .= '<div class="wosmpl-box map">';
     
        
        $o .= '</div>';
        $o .= $cat_filter;
        $o .= wosmpl_cat_list_html($by_cat_content);
        
        

        $o .= '<script type="text/javascript">';
        $o .= 'top.cat_icon_path = "'.$cat_icon_path.'";';
        $o .= 'top.cat_icon_name_prefix = "'.$cat_icon_name_prefix.'";';
        $o .= 'top.contents_to_show = '.wosmpl_create_geojson($contents). ';';
        if (isset($options['wosmpl_main_map_size_ref'])) {
            $map_size_ref = $options['wosmpl_main_map_size_ref'];
            if (strlen($map_size_ref) > 0) {
                $o .= "top.map_size_ref = '$map_size_ref';";
            } 
            
        }
        $o .= '</script>';
    }
    
    
    // return output
    return $o;
}
 
function wosmpl_shortcodes_init()
{
    add_shortcode('wosmpl_map', 'wosmpl_map_shortcode');
}
 
add_action('init', 'wosmpl_shortcodes_init');
