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

<?php if(!$geodata): ?>
    <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 border-left-success">
            <div class="card-body">
                <form id="frm" action="ajax/upload_geodata.php" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group mb-0 mb-sm-2">
                                <label for="file_url"><?php echo _("File URL"); ?></label>
                                <input oninput="check_add_geodata();" type="text" class="form-control" id="file_url" value="" />
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label><?php echo _("File Upload"); ?></label><br>
                            <div class="input-group mb-0 mb-sm-2">
                                <div class="custom-file">
                                    <input type="file" class="custom-file-input" id="txtFile" name="txtFile" />
                                    <label class="custom-file-label" for="txtFile"><?php echo _("Choose file"); ?></label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label style="opacity:0">.</label><br>
                            <div class="form-group mb-0">
                                <input <?php echo ($demo) ? 'disabled':''; ?> type="submit" class="btn btn-block btn-success" id="btnUpload" value="<?php echo _("Upload File"); ?>" />
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label style="opacity:0">.</label><br>
                            <div class="preview text-center">
                                <div class="progress mb-0" style="height: 2.35rem;display: none">
                                    <div class="progress-bar" id="progressBar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width:0%;">
                                        0%
                                    </div>
                                </div>
                                <div style="display: none;padding: .38rem;" class="alert alert-danger" id="error"></div>
                            </div>
                        </div>
                        <div class="col-md-1 text-right">
                            <label style="opacity:0">.</label><br>
                            <div class="form-group mb-0">
                                <button id="btn_add_geodata" class="btn btn-success disabled <?php echo ($demo) ? 'disabled_d':''; ?>"><i class="fas fa-plus"></i> <?php echo _("Add"); ?></button>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-1 mb-0">
                        <div class="col-md-12">
                            <div class="alert alert-success mb-0" role="alert">
                                <?php echo _("Supported file formats"); ?>: <b>geojson</b>, <b>json</b>, <b>kml</b>, <b>kmz</b>, <b>gpx</b>, <b>shapefile (zip)</b>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row mt-3">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-body">
                <table class="table table-bordered table-hover" id="geodata_table" width="100%" cellspacing="0">
                    <thead>
                    <tr>
                        <th><?php echo _("File"); ?></th>
                        <th><?php echo _("Type"); ?></th>
                        <th><?php echo _("Categories"); ?></th>
                        <th><?php echo _("Style"); ?></th>
                        <th><?php echo _("Content"); ?></th>
                        <th style="width: 30px;"></th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div id="modal_geodata_categories" class="modal" tabindex="-1" role="dialog" data-backdrop="static">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo _("Categories"); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <select multiple id="category" data-live-search="true" data-actions-box="true" data-selected-text-format="count > 3" class="form-control selectpicker">
                                <?php echo get_categories($id_map_sel,''); ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_save_geodata_category" onclick="" type="button" class="btn btn-success"><?php echo _("Save"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_geodata_content" class="modal" tabindex="-1" role="dialog" data-backdrop="static">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo _("Geodata Content"); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="geodata_content"><?php echo _("Content"); ?></label><?php echo print_language_input_selector($array_languages,$default_language,'geodata_content'); ?><br>
                            <div><div id="geodata_content"></div></div>
                            <?php foreach ($array_languages as $lang) {
                                if($lang!=$default_language) : ?>
                                    <div style="display:none;"><div id="geodata_content_<?php echo $lang; ?>" type="text" class="input_lang" data-target-id="geodata_content" data-lang="<?php echo $lang; ?>"></div></div>
                                <?php endif;
                            } ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_save_geodata_content" onclick="" type="button" class="btn btn-success"><?php echo _("Save"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_geodata_style" class="modal" tabindex="-1" role="dialog" data-backdrop="static">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo _("Customize Geodata Styles"); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div style="display:none;" class="col-md-12 mb-3">
                        <label for="use_kml_style" class="form-label"><?php echo _("Use KML Style"); ?></label><br>
                        <input type="checkbox" id="use_kml_style">
                    </div>
                    <div class="col-12">
                        <label for="geometryType" class="form-label"><?php echo _("Geometry Type"); ?></label>
                        <select class="form-control" id="geometryType">
                            <option selected value="Point">Point</option>
                            <option value="LineString">LineString</option>
                            <option value="MultiLineString">MultiLineString</option>
                            <option value="Polygon">Polygon</option>
                            <option value="MultiPolygon">MultiPolygon</option>
                        </select>
                    </div>
                </div>
                <div id="pointStyles">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="pointFillColor" class="form-label"><?php echo _("Fill Color"); ?></label>
                            <input type="text" class="form-control" id="pointFillColor">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="pointRadius" class="form-label"><?php echo _("Radius"); ?></label>
                            <input type="number" class="form-control" id="pointRadius">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="pointStrokeColor" class="form-label"><?php echo _("Stroke Color"); ?></label>
                            <input type="text" class="form-control" id="pointStrokeColor">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="pointStrokeWidth" class="form-label"><?php echo _("Stroke Width"); ?></label>
                            <input type="number" class="form-control" id="pointStrokeWidth">
                        </div>
                    </div>
                </div>
                <div id="lineStringStyles" class="d-none">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="lineStringStrokeColor" class="form-label"><?php echo _("Stroke Color"); ?></label>
                            <input type="text" class="form-control" id="lineStringStrokeColor">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="lineStringStrokeWidth" class="form-label"><?php echo _("Stroke Width"); ?></label>
                            <input type="number" class="form-control" id="lineStringStrokeWidth">
                        </div>
                    </div>
                </div>
                <div id="multiLineStringStyles" class="d-none">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="multiLineStringStrokeColor" class="form-label"><?php echo _("Stroke Color"); ?></label>
                            <input type="text" class="form-control" id="multiLineStringStrokeColor" value="#00FF00">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="multiLineStringStrokeWidth" class="form-label"><?php echo _("Stroke Width"); ?></label>
                            <input type="number" class="form-control" id="multiLineStringStrokeWidth" value="3">
                        </div>
                    </div>
                </div>
                <div id="polygonStyles" class="d-none">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="polygonStrokeColor" class="form-label"><?php echo _("Stroke Color"); ?></label>
                            <input type="text" class="form-control" id="polygonStrokeColor">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="polygonStrokeWidth" class="form-label"><?php echo _("Stroke Width"); ?></label>
                            <input type="number" class="form-control" id="polygonStrokeWidth">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="polygonFillColor" class="form-label"><?php echo _("Fill Color"); ?></label>
                            <input type="text" class="form-control" id="polygonFillColor">
                        </div>
                    </div>
                </div>
                <div id="multiPolygonStyles" class="d-none">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="multiPolygonStrokeColor" class="form-label"><?php echo _("Stroke Color"); ?></label>
                            <input type="text" class="form-control" id="multiPolygonStrokeColor">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="multiPolygonStrokeWidth" class="form-label"><?php echo _("Stroke Width"); ?></label>
                            <input type="number" class="form-control" id="multiPolygonStrokeWidth">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="multiPolygonFillColor" class="form-label"><?php echo _("Fill Color"); ?></label>
                            <input type="text" class="form-control" id="multiPolygonFillColor">
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_save_geodata_style" onclick="" type="button" class="btn btn-success"><?php echo _("Save"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
    (function($) {
        "use strict";
        window.id_user = '<?php echo $id_user; ?>';
        window.id_map = '<?php echo $id_map_sel; ?>';
        var DirectionAttribute = Quill.import('attributors/attribute/direction');
        Quill.register(DirectionAttribute,true);
        var AlignClass = Quill.import('attributors/class/align');
        Quill.register(AlignClass,true);
        var BackgroundClass = Quill.import('attributors/class/background');
        Quill.register(BackgroundClass,true);
        var ColorClass = Quill.import('attributors/class/color');
        Quill.register(ColorClass,true);
        var DirectionClass = Quill.import('attributors/class/direction');
        Quill.register(DirectionClass,true);
        var FontClass = Quill.import('attributors/class/font');
        Quill.register(FontClass,true);
        var SizeClass = Quill.import('attributors/class/size');
        Quill.register(SizeClass,true);
        var AlignStyle = Quill.import('attributors/style/align');
        Quill.register(AlignStyle,true);
        var BackgroundStyle = Quill.import('attributors/style/background');
        Quill.register(BackgroundStyle,true);
        var ColorStyle = Quill.import('attributors/style/color');
        Quill.register(ColorStyle,true);
        var DirectionStyle = Quill.import('attributors/style/direction');
        Quill.register(DirectionStyle,true);
        var FontStyle = Quill.import('attributors/style/font');
        Quill.register(FontStyle,true);
        var SizeStyle = Quill.import('attributors/style/size');
        SizeStyle.whitelist = ['12px','14px','16px','18px','20px','22px'];
        Quill.register(SizeStyle,true);
        var LinkFormats = Quill.import("formats/link");
        Quill.register(LinkFormats,true);
        window.geodata_content_editor = null;
        window.geodata_content_editor_lang = [];
        $(document).ready(function () {
            bsCustomFileInput.init();
            $('#geodata_table').DataTable({
                "columnDefs": [{
                    targets: '_all',
                    className: 'dt-head-left dt-body-left'
                }],
                "pageLength": 10,
                "responsive": true,
                "scrollX": true,
                "processing": true,
                "serverSide": true,
                "ajax": "ajax/get_geodata.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"); ?>"
                    }
                },
            });
            var toolbarOptions = [
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'size': ['12px','14px','16px','18px','20px','22px'] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'align': [] }],['link'],['image'],
                ['clean']
            ];
            geodata_content_editor = new Quill('#geodata_content', {
                modules: {
                    toolbar: toolbarOptions
                },
                theme: 'snow'
            });
            $('.input_lang[data-target-id="geodata_content"]').each(function() {
                var lang = $(this).attr('data-lang');
                var id = $(this).attr('id');
                geodata_content_editor_lang[lang] = new Quill('#'+id, {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow'
                });
            });
        });
    })(jQuery);

    document.getElementById('geometryType').addEventListener('change', function () {
        const styles = [
            'pointStyles',
            'lineStringStyles',
            'multiLineStringStyles',
            'polygonStyles',
            'multiPolygonStyles',
        ];
        styles.forEach((id) => document.getElementById(id).classList.add('d-none'));
        const selectedType = this.value;
        if (selectedType === 'Point') {
            document.getElementById('pointStyles').classList.remove('d-none');
        } else if (selectedType === 'LineString') {
            document.getElementById('lineStringStyles').classList.remove('d-none');
        } else if (selectedType === 'MultiLineString') {
            document.getElementById('multiLineStringStyles').classList.remove('d-none');
        } else if (selectedType === 'Polygon') {
            document.getElementById('polygonStyles').classList.remove('d-none');
        } else if (selectedType === 'MultiPolygon') {
            document.getElementById('multiPolygonStyles').classList.remove('d-none');
        }
    });

    $('body').on('submit','#frm',function(e){
        e.preventDefault();
        $('#error').hide();
        var url = $(this).attr('action');
        var frm = $(this);
        var data = new FormData();
        if(frm.find('#txtFile[type="file"]').length === 1 ){
            data.append('file', frm.find( '#txtFile' )[0].files[0]);
        }
        var ajax  = new XMLHttpRequest();
        ajax.upload.addEventListener('progress',function(evt){
            var percentage = (evt.loaded/evt.total)*100;
            upadte_progressbar(Math.round(percentage));
        },false);
        ajax.addEventListener('load',function(evt){
            upadte_progressbar(0);
            frm[0].reset();
            if(evt.target.responseText.toLowerCase().indexOf('error')>=0){
                show_error(evt.target.responseText);
            } else {
                if(evt.target.responseText!='') {
                    var file = evt.target.responseText;
                    $('#file_url').val(file);
                    check_add_geodata();
                    add_geodata();
                }
            }
        },false);
        ajax.addEventListener('error',function(evt){
            show_error('upload failed');
            upadte_progressbar(0);
        },false);
        ajax.addEventListener('abort',function(evt){
            show_error('upload aborted');
            upadte_progressbar(0);
        },false);
        ajax.open('POST',url);
        ajax.send(data);
        return false;
    });

    function upadte_progressbar(value){
        $('#progressBar').css('width',value+'%').html(value+'%');
        if(value==0){
            $('.progress').hide();
        }else{
            $('.progress').show();
        }
    }

    function show_error(error){
        $('.progress').hide();
        $('#error').show();
        $('#error').html(error);
    }

    function check_add_geodata() {
        var file = $('#file_url').val().toLowerCase();
        if(file=='') {
            $('#btn_add_geodata').addClass('disabled');
        } else {
            if(hasSupportedExtension(file)) {
                $('#btn_add_geodata').removeClass('disabled');
            } else {
                $('#btn_add_geodata').addClass('disabled');
            }
        }
    }

    function hasSupportedExtension(str) {
        const regex = /\.(geojson|json|kml|kmz|gpx)$/i;
        return regex.test(str);
    }
</script>