<?php
session_start();
$id_map_sel = $_SESSION['id_map_sel'];
$id_user = $_SESSION['id_user'];
session_write_close();
$can_create = true;
$can_edit = 1;
$can_delete = true;
if($user_info['role']=='editor') {
    $editor_permissions = get_editor_permissions($id_user,$id_map_sel);
    if($editor_permissions['create_markers']==0) {
        $can_create=false;
    }
    if($editor_permissions['edit_markers']==0) {
        $can_edit=0;
    }
    if($editor_permissions['delete_markers']==0) {
        $can_delete=false;
    }
}
$markers_missing_coordinates = get_missing_coordinates_markers($id_map_sel);
$markers_missing_address = get_missing_address_markers($id_map_sel);
$count_missing_coordinates = count($markers_missing_coordinates);
$count_missing_address = count($markers_missing_address);
$count_markers = count_markers($id_map_sel);
$settings = get_settings();
$map = get_map($id_map_sel,$id_user);
?>

<div class="row marker_add_bar">
    <div class="col-md-3">
        <?php if($can_create) : ?>
            <button id="btn_add_marker" data-toggle="modal" data-target="#modal_add_marker" class="btn btn-block btn-success mb-1"><i class="fa fa-plus"></i> <?php echo _("ADD MARKER"); ?></button>
        <?php endif; ?>
    </div>
    <div class="col-md-3">
        <button data-toggle="modal" data-target="#modal_find_duplicates" class="btn btn-block btn-info mb-1"><i class="fas fa-search-location"></i> <?php echo _("FIND DUPLICATES"); ?></button>
    </div>
    <div class="col-md-3">
        <button data-toggle="modal" data-target="#modal_batch_geocode" class="btn btn-block btn-primary <?php echo ($count_missing_coordinates==0 && $count_missing_address==0) ? 'disabled' : ''; ?> mb-1"><i class="fas fa-map-pin"></i> <?php echo _("BATCH GEOCODE"); ?></button>
    </div>
    <div class="col-md-3">
        <button onclick="bulk_select();" class="btn btn-block btn-secondary mb-1 <?php echo ($demo) ? 'disabled':''; ?>"><i class="fas fa-tasks"></i> <?php echo _("BULK SELECT"); ?></button>
    </div>
</div>

<div style="display: none;" class="row marker_bulk_select_bar">
    <div id="div_bulk_info" class="col-md-6">
        <div style="pointer-events:none;" class="btn btn-block text-left mb-1"><?php echo _("SELECTED MARKERS"); ?> <b id="markers_selected">0</b>&nbsp;&nbsp;&nbsp;<span onclick="select_all_markers();" style="cursor:pointer;pointer-events:initial;" class="badge badge-secondary"><?php echo _("select all"); ?></span>&nbsp;<span onclick="deselect_all_markers();" style="cursor:pointer;pointer-events:initial;" class="badge badge-secondary"><?php echo _("deselect all"); ?></span></div>
    </div>
    <div class="col-md-2">
        <select id="bulk_action" onchange="change_bulk_action();" class="form-control">
            <option id="0"><?php echo _("Select Bulk Action"); ?></option>
            <?php if($can_delete) : ?>
                <option id="delete"><?php echo _("Delete"); ?></option>
            <?php endif; ?>
            <option id="activate"><?php echo _("Activate"); ?></option>
            <option id="disable"><?php echo _("Disable"); ?></option>
            <option id="validate"><?php echo _("Validate"); ?></option>
            <option id="categories"><?php echo _("Assign to Category"); ?></option>
            <option id="add_featured"><?php echo _("Add to Featured"); ?></option>
            <option id="remove_featured"><?php echo _("Remove to Featured"); ?></option>
            <option id="visible_map"><?php echo _("Visible into Map"); ?></option>
            <option id="hide_map"><?php echo _("Hide from Map"); ?></option>
            <option id="visible_search"><?php echo _("Visible into Search"); ?></option>
            <option id="hide_search"><?php echo _("Hide from Search"); ?></option>
        </select>
    </div>
    <div id="div_bulk_cat" style="display:none;" class="col-md-2">
        <select multiple id="category" data-live-search="true" data-actions-box="true" data-selected-text-format="count > 2" class="form-control selectpicker">
            <?php echo get_categories($id_map_sel,null); ?>
        </select>
    </div>
    <div class="col-md-2">
        <button id="btn_execute_bulk" onclick="execute_bulk_action();" class="btn btn_bulk_action btn-block btn-primary mb-1 disabled"><i class="far fa-check"></i> <?php echo _("EXECUTE"); ?></button>
    </div>
    <div class="col-md-2">
        <button onclick="exit_bulk_select();" class="btn btn-block btn-dark mb-1"><i class="far fa-times"></i> <?php echo _("CANCEL"); ?></button>
    </div>
</div>

<div class="row mt-2">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-body">
                <table class="table table-bordered table-hover" id="markers_table" width="100%" cellspacing="0">
                    <thead>
                    <tr>
                        <th><?php echo _("Name"); ?></th>
                        <th><?php echo _("Category"); ?></th>
                        <th><?php echo _("Address"); ?></th>
                        <th><?php echo _("Active"); ?></th>
                        <th><?php echo _("Visible"); ?></th>
                        <th><?php echo _("Validated"); ?></th>
                        <th><?php echo _("Centered"); ?></th>
                        <th><?php echo _("Featured"); ?></th>
                        <th><?php echo _("Last update"); ?></th>
                        <th><?php echo _("Order"); ?></th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>

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

<div class="row mb-3">
    <div class="col-md-12 text-center">
        <?php if($can_create) : ?>
            <a id="btn_import_marker" href="index.php?p=import" class="badge badge-primary p-1 px-2"><i class="far fa-file-excel"></i> <?php echo _("import excel"); ?></a>
        <?php endif; ?>
        <a class="badge badge-primary p-1 px-2" target="_blank" href="ajax/export_markers.php?id_map=<?php echo $id_map_sel; ?>&code=<?php echo $map['code']; ?>"><i class="fas fa-file-download"></i> <?php echo _("export markers"); ?></a>
    </div>
</div>

<div id="modal_delete_marker" 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 _("Delete Marker"); ?></h5>
            </div>
            <div class="modal-body">
                <p><?php echo _("Are you sure you want to delete the marker?"); ?></p>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_delete_marker" onclick="" type="button" class="btn btn-danger"><?php echo _("Yes, Delete"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_clone_marker" 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 _("Duplicate Marker"); ?></h5>
            </div>
            <div class="modal-body">
                <p><?php echo _("Are you sure you want to duplicate the marker?"); ?></p>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="duplicate_target_map"><?php echo _("Map"); ?></label><br>
                            <select class="form-control" id="duplicate_target_map">
                                <option id="0"><?php echo _("On the same map"); ?></option>
                                <?php
                                $maps_d = get_maps($id_user);
                                foreach ($maps_d as $map_d) {
                                    $id_map_d = $map_d['id'];
                                    if($id_map_d!=$id_map_sel) {
                                        $name_map_d = $map_d['name'];
                                        echo "<option id='$id_map_d'>$name_map_d</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_clone_marker" onclick="" type="button" class="btn btn-success"><?php echo _("Yes, Duplicate"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_batch_geocode" 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 _("Batch Geocode"); ?></h5>
            </div>
            <div class="modal-body">
                <p><?php echo _("This procedure will try to associate the coordinates to all those markers that are missing, converting them from the addresses and viceversa."); ?></p>
                <label><input onchange="change_checkbox_geolocate();" id="checkbox_address_position" type="checkbox" <?php echo ($count_missing_coordinates>0) ? 'checked' : 'disabled'; ?>>&nbsp;&nbsp;<?php echo _("Address")." → "._("Position"); ?></label>
                <div id="batch_geocode_progress" class="progress" style="height: 20px;">
                    <div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0 / <?php echo $count_missing_coordinates; ?></div>
                </div>
                <br>
                <label><input onchange="change_checkbox_geolocate();" id="checkbox_position_address" type="checkbox" <?php echo ($count_missing_address>0) ? 'checked' : 'disabled'; ?>>&nbsp;&nbsp;<?php echo _("Position")." → "._("Address"); ?></label>
                <div id="batch_geocode_progress_reverse" class="progress" style="height: 20px;">
                    <div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0 / <?php echo $count_missing_address; ?></div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_batch_geocode" onclick="start_batch_geocode();" type="button" class="btn btn-success"><i class="fas fa-play"></i>&nbsp;&nbsp;<?php echo _("Start"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-close"></i>&nbsp;&nbsp;<?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_add_marker" 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 _("Add Marker"); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="name"><?php echo _("Name"); ?></label>
                            <input type="text" class="form-control" id="name" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button <?php echo ($demo) ? 'disabled':''; ?> id="btn_add_marker" onclick="add_marker();" type="button" class="btn btn-success"><i class="fas fa-plus"></i>&nbsp;&nbsp;<?php echo _("Add"); ?></button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-close"></i>&nbsp;&nbsp;<?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_find_duplicates" 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 _("Find Duplicates"); ?></h5>
            </div>
            <div class="modal-body">
                <p><?php echo _("Find markers that are close to each other based on a distance threshold."); ?></p>
                <div class="form-group">
                    <label for="duplicate_distance"><?php echo ($map['unit_map']=='miles') ? _("Distance (feet)") : _("Distance (meters)"); ?></label>
                    <input type="number" class="form-control" id="duplicate_distance" value="10" min="0">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
                <button type="button" class="btn btn-primary" onclick="find_duplicates()"><?php echo _("Search"); ?></button>
            </div>
        </div>
    </div>
</div>

<div id="modal_duplicate_results" 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 _("Duplicate Results"); ?></h5>
            </div>
            <div class="modal-body">
                <div id="duplicate_loading" class="text-center" style="display:none; padding: 20px;">
                    <i class="fas fa-circle-notch fa-spin fa-3x text-primary"></i><br><br><?php echo _("Searching for duplicates..."); ?>
                </div>
                <div id="duplicate_results_container" style="max-height:600px; overflow-y:auto; display:none;">
                    <table class="table table-hover table-sm">
                        <thead>
                        <tr>
                            <th class="text-right"><?php echo _("Marker 1"); ?></th>
                            <th class="text-center"><?php echo _("Distance"); ?></th>
                            <th><?php echo _("Marker 2"); ?></th>
                        </tr>
                        </thead>
                        <tbody id="duplicate_results_tbody">
                        </tbody>
                    </table>
                </div>
                <p id="no_duplicates_msg" style="display:none;"><?php echo _("No duplicates found within the specified distance."); ?></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo _("Close"); ?></button>
            </div>
        </div>
    </div>
</div>

<style>
    <?php if(!$can_delete) : ?>
    .btn-danger {
        display: none !important;
        opacity: 0 !important;
        pointer-events: none !important;
    }
    <?php endif; ?>
    <?php if($can_edit==0) : ?>
    #markers_table tbody tr {
        pointer-events: none !important;
    }
    <?php endif; ?>
</style>

<script>
    (function($) {
        "use strict";
        window.id_user = '<?php echo $id_user; ?>';
        window.id_map = '<?php echo $id_map_sel; ?>';
        window.can_edit = <?php echo $can_edit; ?>;
        window.unit_map = '<?php echo $map['unit_map']; ?>';
        window.bulk_select_mode = false;
        window.missing_markers_coord_json = `<?php echo json_encode($markers_missing_coordinates); ?>`;
        window.missing_markers_address_json = `<?php echo json_encode($markers_missing_address); ?>`;
        window.geocoding_provider = '<?php echo $settings['geocoding_provider']; ?>';
        window.xhr_duplicate_search = null;
        $(document).ready(function () {
            $('#markers_table').DataTable({
                "columnDefs": [{
                    targets: '_all',
                    className: 'dt-head-left dt-body-left'
                },{
                    targets: [8,9,10],
                    className: 'nowrap'
                }],
                "order": [[ 9, "desc" ]],
                "responsive": true,
                "scrollX": true,
                "lengthMenu": [ [10, 25, 50, 100, 1000], [10, 25, 50, 100, 1000] ],
                "pageLength": 100,
                "processing": true,
                "serverSide": true,
                "ajax": "ajax/get_markers.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"); ?>"
                    }
                },
                "drawCallback": function( settings ) {
                    if(window.bulk_select_mode) {
                        $('.btn_delete_marker').hide();
                        $('.btn_duplicate_marker').hide();
                        $('.btn_link_marker').hide();
                        $('.btn_review_marker').hide();
                        $('.check_bulk_marker').show();
                        $('.order_icon').addClass('disabled');
                        $('#markers_selected').html(0);
                        $('.btn_bulk_action').addClass('disabled');
                        $('.check_bulk_marker').change(function(){
                            var num = 0;
                            $('.check_bulk_marker').each(function() {
                                if ($(this).is(':checked')) {
                                    num++;
                                }
                            });
                            $('#markers_selected').html(num);
                            var bulk_action = $('#bulk_action option:selected').attr('id');
                            if(num!=0 && bulk_action!='0') {
                                $('.btn_bulk_action').removeClass('disabled');
                            } else {
                                $('.btn_bulk_action').addClass('disabled');
                            }
                        });
                    }
                }
            });
            if(window.can_edit==1) {
                $('#markers_table tbody').on('click', 'td', function () {
                    if(!window.bulk_select_mode) {
                        if($(this)[0]._DT_CellIndex.column!=9 && $(this)[0]._DT_CellIndex.column!=10) {
                            var marker_id = $(this).parent().attr("id");
                            location.href = 'index.php?p=edit_marker&id='+marker_id;
                        }
                    } else {
                        if($(this)[0]._DT_CellIndex.column!=9 && $(this)[0]._DT_CellIndex.column!=10) {
                            var marker_id = $(this).parent().attr("id");
                            $('#marker_'+marker_id).trigger('click');
                        }
                    }
                });
            }
            $('#modal_add_marker').on('shown.bs.modal', function () {
                $('#name').trigger('focus');
            });
            $('#name').on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    add_marker();
                }
            });

            $('#modal_duplicate_results').on('hide.bs.modal', function () {
                if(window.xhr_duplicate_search) {
                    window.xhr_duplicate_search.abort();
                    window.xhr_duplicate_search = null;
                }
            });
        });
    })(jQuery);

    function find_duplicates() {
        var distance = $('#duplicate_distance').val();
        if(distance == "") distance = 10;
        if (window.unit_map === 'miles') {
            distance = distance * 0.3048;
        }
        $('#modal_find_duplicates').modal('hide');
        $('#duplicate_results_tbody').html('');
        $('#duplicate_results_container').hide();
        $('#no_duplicates_msg').hide();
        $('#duplicate_loading').show();
        $('#modal_duplicate_results').modal('show');
        if(window.xhr_duplicate_search) {
            window.xhr_duplicate_search.abort();
        }
        window.xhr_duplicate_search = $.ajax({
            url: 'ajax/get_duplicate_markers.php',
            type: 'GET',
            data: {
                id_map: window.id_map,
                distance: distance
            },
            dataType: 'json',
            success: function(data) {
                window.xhr_duplicate_search = null;
                $('#duplicate_loading').hide();
                if(data.length > 0) {
                    var html = '';
                    $.each(data, function(i, item) {
                        var lengthInMeters = parseFloat(item.distance);
                        var is_exact = (String(item.lat1) === String(item.lat2) && String(item.lon1) === String(item.lon2)) || lengthInMeters.toFixed(2) === "0.00";
                        var dist_label;

                        if(is_exact) {
                            dist_label = '<?php echo _("equal"); ?>';
                        } else {
                            if (window.unit_map === 'km') {
                                if (lengthInMeters > 1000) {
                                    dist_label = Math.round((lengthInMeters / 1000) * 100) / 100 + ' km';
                                } else {
                                    dist_label = Math.round(lengthInMeters * 100) / 100 + ' m';
                                }
                            } else {
                                const lengthInFeet = lengthInMeters * 3.28084;
                                if (lengthInFeet > 5280) {
                                    dist_label = (Math.round((lengthInFeet / 5280) * 100) / 100) + ' mi';
                                } else {
                                    dist_label = (Math.round(lengthInFeet * 100) / 100) + ' ft';
                                }
                            }
                        }
                        var address1_html = '';
                        if(item.address1 && item.address1.trim() !== '') {
                            address1_html = '<div style="font-size:12px;" class="mb-1">'+item.address1+'</div>';
                        }
                        var address2_html = '';
                        if(item.address2 && item.address2.trim() !== '') {
                            address2_html = '<div style="font-size:12px;">'+item.address2+'</div>';
                        }
                        html += '<tr>';
                        html += '<td style="vertical-align:middle;text-align:right;">';
                        html += '<div class="mb-1"><b>'+item.name1+'</b> <a target="_blank" href="index.php?p=edit_marker&id='+item.id1+'" class="text-primary ml-2" title="<?php echo _("Edit"); ?>"><i class="fas fa-edit"></i></a></div>';
                        html += '<div style="font-size:12px;" class="mb-1">'+item.lat1+', '+item.lon1+' <i class="fas fa-map-pin"></i></div>';
                        html += address1_html;
                        html += '</td>';
                        html += '<td class="text-center" style="vertical-align:middle;">'+dist_label+'</td>';
                        html += '<td style="vertical-align:middle;">';
                        html += '<div class="mb-1"><a target="_blank" href="index.php?p=edit_marker&id='+item.id2+'" class="text-primary mr-2" title="<?php echo _("Edit"); ?>"><i class="fas fa-edit"></i></a> <b>'+item.name2+'</b></div>';
                        html += '<div style="font-size:12px;" class="mb-1"><i class="fas fa-map-pin"></i> '+item.lat2+', '+item.lon2+'</div>';
                        html += address2_html;
                        html += '</td>';
                        html += '</tr>';
                    });
                    $('#duplicate_results_tbody').html(html);
                    $('#duplicate_results_container').show();
                } else {
                    $('#duplicate_results_container').hide();
                    $('#no_duplicates_msg').show();
                }
            },
            error: function(jqXHR) {
                window.xhr_duplicate_search = null;
                if(jqXHR.statusText !== 'abort') {
                    $('#duplicate_loading').hide();
                }
            }
        });
    }
</script>