<?php
session_start();
$id_map_sel = $_SESSION['id_map_sel'];
$id_user = $_SESSION['id_user'];
$map = get_map($id_map_sel,$id_user);
$boundaries = true;
if($user_info['role']=='editor') {
    $editor_permissions = get_editor_permissions($_SESSION['id_user'],$id_map_sel);
    if($editor_permissions['boundaries']==0) {
        $boundaries=false;
    }
}
?>

<?php if(!$boundaries): ?>
    <div class="text-center">
        <div class="error mx-auto" data-text="401">401</div>
        <p class="lead text-gray-800 mb-5"><?php echo _("Permission denied"); ?></p>
        <p class="text-gray-500 mb-0"><?php echo _("It looks like you found a glitch in the matrix..."); ?></p>
        <a href="index.php?p=dashboard">← <?php echo _("Back to Dashboard"); ?></a>
    </div>
<?php die(); endif; ?>

<div class="row">
    <div class="col-md-12">
        <div class="card shadow mb-2">
            <div class="card-body p-0">
                <div id="map" style="width:100%; height:100vh;">
                    <button onclick="" title="<?php echo _("ADD BOUNDARIES"); ?>" id="btn_add_boundaries" style="position:absolute;top:10px;right:10px;z-index:10;" class="btn btn-circle btn-success <?php echo ($demo) ? 'disabled_d' : ''; ?>"><i class="fas fa-plus"></i></button>
                    <button onclick="" title="<?php echo _("REMOVE BOUNDARIES"); ?>" id="btn_remove_boundaries" style="position:absolute;top:56px;right:10px;z-index:10;" class="btn btn-circle btn-danger <?php echo ($demo) ? 'disabled_d' : ''; ?>"><i class="fas fa-xmark"></i></button>
                    <div class="switch_style">
                        <img onclick="change_map_style('default_style');" id="default_style" style="display: none" src="../viewer/images/street.jpg" />
                        <img onclick="change_map_style('satellite_style');" id="satellite_style" src="../viewer/images/satellite.jpg" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    (function($) {
        "use strict";
        window.id_user = '<?php echo $id_user; ?>';
        window.id_map = '<?php echo $id_map_sel; ?>';
        window.markers_size = <?php echo $map['markers_size']; ?>;
        window.enable_map_street = <?php echo ($map['enable_map_street']) ? 1 : 0; ?>;
        window.enable_map_satellite = <?php echo ($map['enable_map_satellite']) ? 1 : 0; ?>;
        window.default_view = '<?php echo $map['default_view']; ?>';
        window.map_style = '<?php echo $map['map_style']; ?>';
        window.openfreemap_street_url = '<?php echo $map['window.openfreemap_street_url']; ?>';
        window.map_style_satellite = '<?php echo $map['map_style_satellite']; ?>';
        window.street_maxzoom = <?php echo $map['street_maxzoom']; ?>;
        window.satellite_maxzoom = <?php echo $map['satellite_maxzoom']; ?>;
        window.street_basemap = '<?php echo $map['street_basemap']; ?>';
        window.satellite_basemap = '<?php echo $map['satellite_basemap']; ?>';
        window.maptiler_api = '<?php echo $map['maptiler_api']; ?>';
        window.maptiler_api_satellite = '<?php echo $map['maptiler_api_satellite']; ?>';
        window.here_api = '<?php echo $map['here_api']; ?>';
        window.here_api_satellite = '<?php echo $map['here_api_satellite']; ?>';
        window.here_lang = '<?php echo $map['here_lang']; ?>';
        window.here_lang_satellite = '<?php echo $map['here_lang_satellite']; ?>';
        window.google_api = '<?php echo $map['google_api']; ?>';
        window.google_api_satellite = '<?php echo $map['google_api_satellite']; ?>';
        window.google_lang = '<?php echo $map['google_lang']; ?>';
        window.google_lang_satellite = '<?php echo $map['google_lang_satellite']; ?>';
        window.map_street_provider = '<?php echo $map['map_street_provider']; ?>';
        window.map_satellite_provider = '<?php echo $map['map_satellite_provider']; ?>';
        window.extent = '<?php echo $map['extent']; ?>';
        var rectangleFeature, drawInteraction, source_extent, transformInteraction;
        $(document).ready(function () {
            $('#btn_add_boundaries').tooltipster({side:'left'});
            $('#btn_remove_boundaries').tooltipster({side:'left'});
            var container_h = $('#content-wrapper').height() - 155;
            $('#map').css('height',container_h+'px');
            default_style = get_map_default_style();
            satellite_style = get_map_satellite_style();
            var initial_layer=default_style;
            if(window.enable_map_street==0 || window.enable_map_satellite==0) {
                if(window.enable_map_street==1) {
                    initial_layer=default_style;
                }
                if(window.enable_map_satellite==1) {
                    initial_layer=satellite_style;
                }
            }
            map = new ol.Map ({
                target: 'map',
                controls : ol.control.defaults.defaults({
                    attribution : false,
                    zoom : true,
                }),
                view: new ol.View ({
                    zoom: 1,
                    center: [0, 0]
                }),
                layers: [initial_layer]
            });
            if(window.enable_map_street==0 && window.enable_map_satellite==1) {
                change_map_style('satellite_style');
            } else if(window.enable_map_street==1 && window.enable_map_satellite==1 && window.default_view=='satellite') {
                change_map_style('satellite_style');
            }
            get_markers();
            source_extent = new ol.source.Vector();
            var vectorLayer = new ol.layer.Vector({
                source: source_extent
            });
            vectorLayer.setZIndex(11);
            map.addLayer(vectorLayer);
            transformInteraction = new ol.interaction.Transform({
                enableRotatedTransform: false,
                translate: true,
                scale: true,
                rotate: false
            });
            map.addInteraction(transformInteraction);
            if(window.extent!==null && window.extent!='' && window.extent!='null' && window.extent!=undefined) {
                var savedExtent = JSON.parse(window.extent);
            } else {
                var savedExtent = false;
            }
            if (savedExtent) {
                drawRectangle(savedExtent);
            } else {
                $('#btn_add_boundaries').removeClass('disabled');
                $('#btn_remove_boundaries').addClass('disabled');
            }
            if (rectangleFeature) {
                transformInteraction.setSelection([rectangleFeature]);
            }
            transformInteraction.on(['translateend', 'scaleend'], function(evt) {
                var newExtent = rectangleFeature.getGeometry().getExtent();
                t_save_boundaries(JSON.stringify(newExtent));
            });
        });

        var features = [], markers_source = null;
        function get_markers() {
            $.ajax({
                url: "../viewer/ajax/get_markers.php",
                type: "POST",
                data: {
                    id_map: window.id_map,
                    order_by: 'priority'
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    var markers = rsp.markers;
                    jQuery.each(markers, function(index, marker) {
                        features.push(new ol.Feature({
                            id: index,
                            latitude: marker.lat,
                            longitude: marker.lon,
                            color_hex: marker.color_hex,
                            darker_color_hex: marker.darker_color_hex,
                            icon_color_hex: marker.icon_color_hex,
                            size: parseFloat(marker.marker_size),
                            icon: marker.icon,
                            icon_image: marker.icon_image,
                            icon_base64: marker.icon_base64,
                            geometry: new ol.geom.Point(ol.proj.fromLonLat([marker.lon,marker.lat]))
                        }));
                    });
                    setTimeout(function () {
                        add_markers(false);
                        var previousMaxZoom = map.getView().getMaxZoom();
                        map.getView().setMaxZoom(18);
                        if(window.extent!==null && window.extent!='' && window.extent!='null' && window.extent!=undefined) {
                            var extent = JSON.parse(window.extent);
                            map.getView().fit(extent, {
                                padding: [100, 100, 100, 100],
                                duration: 500,
                                nearest: true
                            });
                        } else {
                            map.getView().fit(markers_source.getExtent(), {
                                padding: [100, 100, 100, 100],
                                duration: 500,
                                nearest: true
                            });
                        }
                        setTimeout(function() {
                            map.getView().setMaxZoom(previousMaxZoom);
                        },1500);
                    },200);
                }
            });
        }

        function add_markers() {
            markers_source = new ol.source.Vector({
                features: features
            });
            var clusterSource = new ol.source.Cluster({
                distance: 0.01,
                source: markers_source
            });
            var clusters_layer = new ol.layer.Vector({
                source: clusterSource,
                style: function(feature) {
                    var icon = feature.get('features')[0].get('icon');
                    var icon_image = feature.get('features')[0].get('icon_image');
                    var icon_base64 = feature.get('features')[0].get('icon_base64');
                    var color_hex = feature.get('features')[0].get('color_hex');
                    var darker_color_hex_m = feature.get('features')[0].get('darker_color_hex');
                    var icon_color_hex = feature.get('features')[0].get('icon_color_hex');
                    var marker_size = feature.get('features')[0].get('size');
                    if(icon_base64!='') {
                        if(marker_size==0) {
                            var scale = window.markers_size;
                        } else {
                            var scale = marker_size;
                        }
                    } else {
                        if(marker_size==0) {
                            var scale = window.markers_size/10;
                        } else {
                            var scale = marker_size/10;
                        }
                    }
                    var radius = 140*scale;
                    var font_size = 120*scale;
                    var opacity = 1;
                    if(color_hex!='') {
                        var darker_color_rgb = hexToRgbA(darker_color_hex_m,opacity);
                        var main_color_rgb = hexToRgbA(color_hex,opacity);
                    } else {
                        var darker_color_rgb = hexToRgbA('#000000',0);
                        var main_color_rgb = hexToRgbA('#000000',0);
                    }
                    if(icon_color_hex!='') {
                        var icon_color_rgb = hexToRgbA(icon_color_hex,opacity);
                    } else {
                        var icon_color_rgb = hexToRgbA('#ffffff',opacity);
                    }
                    if(icon_image=='') {
                        var style = new ol.style.Style({
                            image: new ol.style.Circle({
                                radius: radius,
                                stroke: new ol.style.Stroke({
                                    color: darker_color_rgb,
                                    width: 3
                                }),
                                fill: new ol.style.Fill({
                                    color: main_color_rgb,
                                    weight: 1
                                })
                            }),
                            text: new ol.style.Text({
                                text: String.fromCharCode("0x" + icon),
                                textAlign: "center",
                                textBaseline: "middle",
                                font: '900 '+font_size+'px "Font Awesome 7 Free"',
                                fill: new ol.style.Fill({
                                    color: icon_color_rgb
                                })
                            })
                        });
                    } else {
                        if(icon_image.includes('.gif')) {
                            const gifUrl = '../viewer/icons/'+icon_image;
                            const gif = gifler(gifUrl);
                            var style = '';
                            gif.frames(
                                document.createElement('canvas'),
                                function (ctx, frame) {
                                    if (!feature.getStyle()) {
                                        feature.setStyle(
                                            new ol.style.Style({
                                                image: new ol.style.Icon({
                                                    anchor: [0.5, 150],
                                                    anchorXUnits: 'fraction',
                                                    anchorYUnits: 'pixels',
                                                    scale: scale,
                                                    opacity: opacity,
                                                    img: ctx.canvas,
                                                    imgSize: [frame.width, frame.height]
                                                }),
                                            })
                                        );
                                    }
                                    ctx.clearRect(0, 0, frame.width, frame.height);
                                    ctx.drawImage(frame.buffer, frame.x, frame.y);
                                    map.render();
                                }, true);
                        } else {
                            if(icon_base64!='') {
                                var style = new ol.style.Style({
                                    image: new ol.style.Icon({
                                        anchor: [0.5, 0.5],
                                        anchorXUnits: 'fraction',
                                        anchorYUnits: 'fraction',
                                        scale: 1,
                                        opacity: opacity,
                                        src: icon_base64,
                                    })
                                });
                            } else {
                                var style = new ol.style.Style({
                                    image: new ol.style.Icon({
                                        anchor: [0.5, 0.5],
                                        anchorXUnits: 'fraction',
                                        anchorYUnits: 'fraction',
                                        scale: scale,
                                        opacity: opacity,
                                        src: '../viewer/icons/'+icon_image,
                                    })
                                });
                            }
                        }
                    }
                    return style;
                }
            });
            map.addLayer(clusters_layer);
            clusters_layer.setZIndex(10);
        }

        function hexToRgbA(hex,opacity){
            var c;
            if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
                c= hex.substring(1).split('');
                if(c.length== 3){
                    c= [c[0], c[0], c[1], c[1], c[2], c[2]];
                }
                c= '0x'+c.join('');
                return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+','+opacity+')';
            }
            return 'rgba(0,0,0,'+opacity+')';
        }

        $(window).resize(function () {
            var container_h = $('#content-wrapper').height() - 155;
            $('#map').css('height',container_h+'px');
        });

        function drawRectangle(extent) {
            $('#btn_add_boundaries').addClass('disabled');
            $('#btn_remove_boundaries').removeClass('disabled');
            rectangleFeature = new ol.Feature({
                geometry: ol.geom.Polygon.fromExtent(extent)
            });
            source_extent.addFeature(rectangleFeature);
            transformInteraction.setSelection([rectangleFeature]);
        }

        document.getElementById('btn_add_boundaries').addEventListener('click', function() {
            const view = map.getView();
            const center = view.getCenter();
            const resolution = view.getResolution();
            const paddingMapUnits = 200 * resolution;
            const extent = [
                center[0] - paddingMapUnits,
                center[1] - paddingMapUnits,
                center[0] + paddingMapUnits,
                center[1] + paddingMapUnits
            ];
            drawRectangle(extent);
            t_save_boundaries(JSON.stringify(extent));
        });

        document.getElementById('btn_remove_boundaries').addEventListener('click', function() {
            source_extent.clear();
            transformInteraction.setSelection([]);
            rectangleFeature = null;
            t_save_boundaries(null);
            $('#btn_add_boundaries').removeClass('disabled');
            $('#btn_remove_boundaries').addClass('disabled');
        });

        var timeout_save = null;
        window.t_save_boundaries = function(extent) {
            clearTimeout(timeout_save);
            timeout_save = setTimeout(function() {
                save_boundaries(extent);
            },1000);
        }
    })(jQuery);
</script>
