<script>
    $(function() {
        table = $('#list_data').DataTable({
            "processing": true, //Feature control the processing indicator.
            "serverSide": true, //Feature control DataTables' server-side processing mode.
            "order": [], //Initial no order.
            "searching": true,
            'ordering': true,
            'paging': true,
            'lengthChange': true,
            'info': true,
            'language': {
                <?php if ($this->code_lang == 'id') : ?> 'url': '<?= base_url("assets/plugins/datatables/dataTables-language-id.json") ?>',
                    'sEmptyTable': 'Tidak ada data untuk ditampilkan',
                    'searchPlaceholder': 'Nama Lokasi'
                <?php else : ?> 'searchPlaceholder': 'Location'
                <?php endif; ?>
            },
            // Load data for the table's content from an Ajax source
            "ajax": {
                "url": "<?php echo site_url('master/lokasi/list_data') ?>",
                "type": "GET",
                "data": {
                    id_cabang: function() {
                        return $(".filter #id_cabang").val()
                    },
                },
                "complete": function(data) {
                    reconfigure(data);
                }
            },
            //Set column definition initialisation properties.
            "columnDefs": [{
                    "targets": [-1], //last column
                    "orderable": false //set not orderable
                },
                {
                    "targets": [0], //2 last column (photo)
                    "orderable": false //set not orderable
                }
            ],
            "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                $('td:eq(0)', nRow).css({
                    'text-align': 'center'
                });
                $('td:eq(1)', nRow).css({
                    'text-align': 'left'
                });
                $('td:eq(2)', nRow).css({
                    'text-align': 'left'
                });
                $('td:eq(3)', nRow).css({
                    'text-align': 'left'
                });
                $('td:eq(5)', nRow).css({
                    'text-align': 'center'
                });
                $('td:eq(6)', nRow).css({
                    'text-align': 'center'
                });
            }
        });

        $('.filter #id_cabang').select2({
            placeholder: '<?= $this->lang->line('semua_cabang') ?>',
            allowClear: true,
            ajax: {
                // type: 'POST',
                url: '<?= route("dropdown.cabang") ?>',
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: true
            },
            minLength: 3,
        });

        $(document).on('click', '.filter #btn_filter', function() {
            var loading = Ladda.create(this);
            loading.start();
            table.ajax.reload(function() {
                id_cabang = $('.filter #id_cabang').val();
                reloadMarkers(id_cabang);
                loading.stop();
            });
        });


        //btn_hapus
        $(document).on('click', '.btn_delete', function() {
            var id_lokasi = $(this).attr('id');
            $('#modal_lokasi #id_lokasi').val(id_lokasi);
            $('#modal_lokasi').modal('show');
            $(".title").text("<?= $this->lang->line('title_form_hapus_data') ?>");
            $(".btn_hapus").removeClass("btn_hapus").addClass("btn_hapus btn btn-danger");
            $("#modal_lokasi .card-body").show();
            $("#modal_lokasi .card-footer").show();
        });

        //btn_delete
        $(document).on('click', '.btn_hapus', function() {
            var loading = Ladda.create(this);
            loading.start();
            id_lokasi = $('#modal_lokasi #id_lokasi').val();
            $.ajax({
                type: 'POST',
                url: "<?php echo site_url('master/lokasi/delete') ?>",
                data: 'id_lokasi=' + id_lokasi,
                dataType: 'JSON',
                success: function(result) {
                    $("#modal_lokasi .card-body").hide();
                    $("#modal_lokasi .card-footer").hide();
                    $("#modal_lokasi .title").html(result.message.replace("009900", "FFFFFF"));
                    if (result.success == true) {
                        location.reload();
                    }

                    loading.stop();
                },
                error: function() {
                    loading.stop();
                    $("#modal_lokasi .card-body").hide();
                    $("#modal_lokasi .card-footer").hide();
                    $("#modal_lokasi .title").html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong><?= $this->lang->line('error') ?></strong></font>');
                }
            });
        });
        //btn_delete

    });
</script>
<style type="text/css">
    th {
        text-align: center;
    }
</style>

<div class="content-header">
    <div class="row align-items-center">
        <div class="content-header-left col-md-6 col-12 mb-md-0 mb-1">
            <h3 class="content-header-title"><?= $judul ?></h3>
            <div class="row breadcrumbs-top">
                <div class="breadcrumb-wrapper col-12">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#"><?= $this->lang->line('menu_master_data') ?></a>
                        </li>
                        <li class="breadcrumb-item active"><?= $judul ?>
                        </li>
                    </ol>
                </div>
            </div>
        </div>
        <div class="content-header-right col-md-6 col-12">
            <div class="float-md-right">
                <?php
                if (in_array($this->session->userdata('level_user'), array("1", "5")) and $kode_paket != 15) {
                ?>
                    <div class="text-right">
                        <a href="<?= site_url("master/lokasi/tambah")  ?>" title="Tambah Lokasi">
                            <button id="new" type="button" class="btn waves-effect waves-light btn-biru">
                                <i class="fa fa-plus"></i> <?= $this->lang->line('button_tambah_data') ?>
                            </button>
                        </a>
                    </div>
                <?php
                }
                ?>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div class="card-body">
            <div class="row">
                <div id="show_maps" class="col-md-12">
                    <div id="map_canvas" style="height:580px"></div>
                </div>
            </div>

            <div class="row mt-3 filter">
                <div class="col-md-4">
                    <select id="id_cabang" class="form-control select2"></select>
                </div>
                <div class="col-md-1">
                    <button id="btn_filter" class="btn btn-primary ladda-button" data-style="expand-left">FILTER</button>
                </div>
            </div>

            <div class="row mt-2">
                <div class="col-md-12 table-responsive">
                    <table id="list_data" class="table table-striped">
                        <thead>
                            <tr>
                                <th class="text-center">NO</th>
                                <th class="text-left"><?= strtoupper($this->lang->line('lokasi')) ?></th>
                                <th class="text-left text-uppercase"><?= $this->lang->line('cabang') ?></th>
                                <th class="text-left">LATITUDE</th>
                                <th class="text-left">LONGITUDE</th>
                                <th class="text-center">RADIUS (METER)</th>
                                <?php
                                if (in_array($this->session->userdata('level_user'), array("1", "5")) || in_array($this->session->userdata('level_khusus'), array("1"))) {
                                ?>
                                    <th><?= $this->lang->line('aksi') ?></th>
                                <?php
                                }
                                ?>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div> <!-- card-body -->
    </div><!-- card-content -->
</div><!-- card-rounded -->


<!-- START TAMPIL MODAL -->
<div id="modal_lokasi" class="modal fade in">
    <div class="modal-dialog modal-md">
        <div id="tampil_form" class="modal-content">
            <input type="hidden" id="id_lokasi">
            <div class="card-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h3 class="title modal-title"></h3>
            </div>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-7 text-left">
                        <div id="message"></div>
                    </div>
                    <div class="col-md-5 text-right">
                        <button class="btn_hapus ladda-button" id="btn_hapus" data-style="expand-left"><?= $this->lang->line('button_form_hapus') ?></button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- END TAMPIL MODAL -->

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<?= $this->config->item('api_map_key') ?>&sensor=false"></script>
<script type="text/javascript">
    var map;
    var lat_longs_map = new Array();
    var markers = []; // Create a marker array to hold your markers
    var beaches = [];
    $.get("<?= route("master.lokasi.maps.json") ?>", function(data) {
        $.each(data, function(index, element) {
            var arr = [];
            arr.push(element.lat);
            arr.push(element.long);
            arr.push(element.title);
            arr.push(element.index);
            beaches.push(arr);
        });

        setMarkers(beaches);
        fitMapToBounds_map();
    }, "json");

    var mapCentre;

    function reloadMarkers(id_cabang) {

        // Loop through markers and set map to null for each
        for (var i = 0; i < markers.length; i++) {

            markers[i].setMap(null);
        }

        // Reset the markers array
        markers = [];

        // Reset the lat_longs_map array
        lat_longs_map = [];
        beaches = [];
        $.get("<?= route("master.lokasi.maps.json") ?>" + "/" + id_cabang, function(data) {
            $.each(data, function(index, element) {
                var arr = [];
                arr.push(element.lat);
                arr.push(element.long);
                arr.push(element.title);
                arr.push(element.index);
                beaches.push(arr);
            });

            setMarkers(beaches);
            fitMapToBounds_map();
        }, "json");
    }

    function setMarkers(locations) {
        for (var i = 0; i < locations.length; i++) {
            var beach = locations[i];
            console.log(beach[0]);
            var myLatLng = new google.maps.LatLng(beach[0], beach[1]);
            // var myLatLng = new google.maps.LatLng(beach[0]);
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                animation: google.maps.Animation.DROP,
                title: beach[2],
                zIndex: beach[3]
            });

            // Push marker to markers array
            markers.push(marker);

            // Push marker to lat_longs_map array
            lat_longs_map.push(marker.getPosition());

        }
    }

    function initialize() {
        var varcenter = new google.maps.LatLng(-0.4183772, 117.4237542);
        var varZoom = 5.4;
        var mapOptions = {
            zoom: varZoom,
            center: varcenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

        setMarkers(beaches);
        fitMapToBounds_map();
    }

    function fitMapToBounds_map() {
        var bounds = new google.maps.LatLngBounds();

        if (lat_longs_map.length > 0) {
            for (var i = 0; i < lat_longs_map.length; i++) {
                bounds.extend(lat_longs_map[i]);
            }
            map.fitBounds(bounds);
        }
    }

    initialize();
</script>
