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

<?php if(!$live_tracking): ?>
    <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; ?>

<?php if($demo) : ?>
<style>
    .btn_delete_live_tracking {
        opacity: 0.5 !important;
        pointer-events: none !important;
    }
</style>
<?php endif; ?>

<div class="row mt-2">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-body">
                <table class="table table-bordered table-hover" id="live_tracking_table" width="100%" cellspacing="0">
                    <thead>
                    <tr>
                        <th><?php echo _("Date"); ?></th>
                        <th><?php echo _("Name"); ?></th>
                        <th><?php echo _("Duration"); ?></th>
                        <th><?php echo _("Distance"); ?></th>
                        <th><?php echo _("Speed"); ?></th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-2">
            <div class="card-body p-0">
                <div id="map" style="width:100%; height:100vh;">
                    <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_map = '<?php echo $id_map_sel; ?>';
        window.map = null;
        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.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']; ?>';
        var source;
        $(document).ready(function () {
            $('#live_tracking_table').DataTable({
                "order": [[ 0, "desc" ]],
                "columnDefs": [{
                    targets: '_all',
                    className: 'dt-head-left dt-body-left'
                },{
                    "targets": [3,4,5],
                    "orderable": false
                }],
                "stateSave": true,
                "responsive": true,
                "scrollX": true,
                "processing": true,
                "serverSide": true,
                "ajax": "ajax/get_live_trackings.php?id_map="+window.id_map,
                "language": {
                    "decimal":        "",
                    "emptyTable":     "<?php echo _("No data available in table"); ?>",
                    "info":           "<?php echo sprintf(_("Showing %s to %s of %s entries"),'_START_','_END_','_TOTAL_'); ?>",
                    "infoEmpty":      "<?php echo _("Showing 0 to 0 of 0 entries"); ?>",
                    "infoFiltered":   "<?php echo sprintf(_("(filtered from %s total entries)"),'_MAX_'); ?>",
                    "infoPostFix":    "",
                    "thousands":      ",",
                    "lengthMenu":     "<?php echo sprintf(_("Show %s entries"),'_MENU_'); ?>",
                    "loadingRecords": "<?php echo _("Loading"); ?>...",
                    "processing":     "<?php echo _("Processing"); ?>...",
                    "search":         "<?php echo _("Search"); ?>:",
                    "zeroRecords":    "<?php echo _("No matching records found"); ?>",
                    "paginate": {
                        "first":      "<?php echo _("First"); ?>",
                        "last":       "<?php echo _("Last"); ?>",
                        "next":       "<?php echo _("Next"); ?>",
                        "previous":   "<?php echo _("Previous"); ?>"
                    },
                    "aria": {
                        "sortAscending":  ": <?php echo _("activate to sort column ascending"); ?>",
                        "sortDescending": ": <?php echo _("activate to sort column descending"); ?>"
                    }
                }
            });
            $('#live_tracking_table tbody').on('click', 'td', function () {
                var id = $(this).parent().attr("id");
                $('#live_tracking_table tbody tr').removeClass("selected");
                $(this).parent().addClass("selected");
                if($(this)[0]._DT_CellIndex.column!=5) {
                    get_live_tracking(id);
                }
            });
            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;
                }
            }
            source = new ol.source.Vector({
                features: [],
            });
            var vectorLayer = new ol.layer.Vector( {
                source: source,
                updateWhileAnimating: true,
                updateWhileInteracting: true,
            })
            map = new ol.Map ({
                renderer: 'webgl',
                target: 'map',
                controls : ol.control.defaults.defaults({
                    attribution : false,
                    zoom : true,
                }),
                view: new ol.View ({
                    zoom: 1,
                    center: [0, 0]
                }),
                layers: [initial_layer, vectorLayer],
                loadTilesWhileAnimating: true,
                loadTilesWhileInteracting: true,
                moveTolerance: 5
            });
        });
        $(window).resize(function () {
            var container_h = $('#content-wrapper').height() - 155;
            $('#map').css('height',container_h+'px');
        });
        window.get_live_tracking = function(id) {
            source.clear();
            $.ajax({
                url: 'ajax/get_live_tracking.php',
                type: 'POST',
                data: {
                    id: id
                },
                async: true,
                success: function(json) {
                    var coords = JSON.parse(json);
                    const transformedCoords = coords.map(c => ol.proj.fromLonLat(c));
                    const line = new ol.geom.LineString(transformedCoords);
                    const lineFeature = new ol.Feature({
                        geometry: line
                    });
                    lineFeature.setStyle(new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'blue',
                            width: 3
                        })
                    }));
                    const startPoint = new ol.Feature({
                        geometry: new ol.geom.Point(transformedCoords[0])
                    });
                    const endPoint = new ol.Feature({
                        geometry: new ol.geom.Point(transformedCoords[transformedCoords.length - 1])
                    });
                    const startStyle = new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 9,
                            fill: new ol.style.Fill({ color: 'green' }),
                            stroke: new ol.style.Stroke({ color: 'white', width: 2 })
                        })
                    });
                    const endStyle = new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 9,
                            fill: new ol.style.Fill({ color: 'red' }),
                            stroke: new ol.style.Stroke({ color: 'white', width: 2 })
                        })
                    });
                    startPoint.setStyle(startStyle);
                    endPoint.setStyle(endStyle);
                    source.addFeatures([startPoint, endPoint, lineFeature]);
                    map.getView().fit(line.getExtent(), {
                        padding: [50, 50, 50, 50],
                        duration: 1000,
                        maxZoom: window.street_maxzoom-1
                    });
                }
            });
        };
    })(jQuery);
</script>