<script>
    function validateForm() {
        var jumlah = document.forms["form"]["jarak"].value;
        var angka = /^[0-9]+$/;

        if (!jumlah.match(angka)) {
            alert("Inputan harus angka!");
            //from.no_hp.focus();
            return false;
        }
    }
	
	$(function() {
		$('#cabang').select2({
			placeholder: 'Pilih Cabang',
			ajax: {
			  // type: 'POST',
                url: '<?= route("dropdown.cabang")  ?>',
                dataType: 'json',
                delay: 250,
                processResults: function (data) {
                return {
                        results: data
                    };
                },
                cache: false
            },
            minLength: 3
		});

        $(document).on('click','#btn_new_input', function(){
                $('#form_input input[type=text]').prop("disabled",false);
                $("#form_input input[type=text]").val('');

                $('#cabang').prop("disabled",false);
                $("#cabang").val('').trigger('change');
                
                $('.btn_save').show();
                $('#btn_new_input').hide();
                $('#message').hide();
            });
	});
</script>

<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>
                        <li class="breadcrumb-item"><a href="#">Master Data</a>
                        </li>
                        <li class="breadcrumb-item"><a href="#">Lokasi</a>
                        </li>
                        <li class="breadcrumb-item active"><?= $judul ?>
                        </li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card card-rounded">
    <div class="card-content">
        <div class="card-body">
            <div class="row">
                        <div class="col-lg-9">
                            <div id = "map" style = "width:100%; height:450px"></div>
                            <h5 style="color: red"><strong>*) Klik dua kali untuk memilih lokasi</strong></h5>
                                <script>
                                var theMarker = {};
                                var map = L.map('map').setView([-6.990581698473311, 110.42295643957527], 10);

                                    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                                        attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
                                    }).addTo(map);

                                    theMarker = L.marker([-6.990581698473311, 110.42295643957527]).addTo(map);

                                var searchControl = L.esri.Geocoding.geosearch().addTo(map);

                                var results = L.layerGroup().addTo(map);

                                searchControl.on('results', function (data) {
                                    results.clearLayers();
                                    for (var i = data.results.length - 1; i >= 0; i--) {
                                        results.addLayer(L.marker(data.results[i].latlng));
                                        map.removeLayer(results);
                                    }
                                });

                                 // get coordinate
                                map.on('dblclick',
                                    function(e){
                                    var coord = e.latlng.toString().split(',');
                                    var lat = coord[0].split('(');
                                    var lng = coord[1].split(')');
                                    //alert("You clicked the map at latitude: " + lat[1] + " and longitude:" + lng[0]);
                                    if (theMarker != undefined || results != undefined) {
                                        map.removeLayer(theMarker);
                                        map.removeLayer(results);
                                    };

                                    //Add a marker to show where you clicked.
                                    theMarker = L.marker([lat[1],lng[0]]).addTo(map);  

                                    document.getElementById("lat").value = lat[1];
                                    document.getElementById("lng").value = lng[0];
                                });
                            </script>

                        </div>

                        <div class="col-lg-3" id="form_input">
                            <div class="form-group">
                                <label class="control-label" for="nama">Nama Lokasi <span class="text-danger">*</span></label>
                                <input type="text" name='kantor' id="kantor" class="form-control input-xlarge">
                            </div>
                            <?php
                                if(in_array($this->session->userdata("level_user"),["1"]) || $this->session->userdata("multi_cabang") == true){
                            ?>
                                    <div class="form-group">
                                        <label class="control-label" for="lat">Nama Cabang <span class="text-danger">*</span></label>
                                        <select type="text" class="form-control" name="cabang" id="cabang"></select>
                                    </div>
                            <?php
                                }
                            ?>
                            
                            <div class="form-group">
                                <label class="control-label" for="lat">Latitude <span class="text-danger">*</span></label>
                                <input type="text" class="form-control gllpLatitude" name='lat' id='lat' onkeyup="this.value = this.value.replace(/[^0-9.-]/g, '')">
                            </div>
                            <div class="form-group">
                                <label class="control-label" for="lng">Longitude <span class="text-danger">*</span></label>
                                <input type="text" class="form-control gllpLongitude" name='lng' id='lng' onkeyup="this.value = this.value.replace(/[^0-9.]/g, '')">
                            </div>
                            <div class="form-group">
                                <label class="control-label" for="lat">Radius <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name='jarak' id='jarak' onkeyup="this.value = this.value.replace(/[^0-9.]/g, '')">
                                <small class="form-control-feedback">*) radius dalam meter</small>
                                <input type="hidden" name="flag" id="flag" value="1">
                            </div>
                            <div class="form-group">
                                <div class="input-control text-left">
                                    <div id="message"></div>
                                </div>
                                <div class="input-control text-left">
                                    <button id="btn_new_input" class="btn btn-light" style="display:none; color: black">TAMBAH BARU</button>
                                    <button class="btn btn-success btn_save ladda-button" name='aksi' data-style="expand-left"><i class="fa fa-save"></i> SIMPAN</button>
                                    <a href="<?= site_url('master/lokasi') ?>" class="btn btn-secondary">KEMBALI</a>
                                </div>
                            </div>
                        </div>
                    </div>
        </div>
    </div>
</div>
<script type="text/javascript">

        $(document).on("click",".btn_save",function(e){
            e.preventDefault();
            $('#message').html("");
            var loading = Ladda.create(this);
        
            if(!$("#kantor").val()){
                $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama Lokasi belum diisi</font>");
                $("#kantor").focus();
                return false;
            }

            <?php
                if(in_array($this->session->userdata("level_user"),["1"]) || $this->session->userdata("multi_cabang") == true){
            ?>
                    var id_cabang = $("#cabang").val();

                    if(!$("#cabang").val()){
                        $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama cabang belum dipilih</font>");
                        $('#cabang').focus();
                        return false;
                    }
            <?php
                }else{
            ?>
                    var id_cabang = '<?= $this->session->userdata("id_cabang") ?>';
            <?php
                }
            ?>
            if(!$("#lat").val()){
                $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Latitude belum diiisi</font>");
                $('#lat').focus();
                return false;
            }else if(!$("#lng").val()){
                $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Longitude belum diiisi</font>");
                $('#lng').focus();
                return false;
            }else if(!$("#jarak").val()){
                $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Radius belum diiisi</font>");
                $('#jarak').focus();
                return false;
            }
            
            loading.start();           
        
            var param = 'kantor='+$("#kantor").val()+
                        '&cabang='+id_cabang+
                        '&flag='+$("#flag").val()+
                        '&lat='+$("#lat").val()+
                        '&lng='+$("#lng").val()+
                        '&jarak='+$("#jarak").val();
        
            $.ajax({
                type: 'POST',
                url: "<?= site_url('master/lokasi/save') ?>",
                data: param,
                dataType:'JSON',
                success: function(result) {
                    if(result.success == true){
                        if(result.type == 'save'){
                            <?php
                                if(in_array($this->session->userdata("level_user"),["1"])){
                            ?>
                                    $("#kantor, #cabang, #lat, #lng, #jarak").prop("disabled", true);
                            <?php
                                }else{
                            ?>
                                    $("#kantor, #lat, #lng, #jarak").prop("disabled", true);
                            <?php
                                }
                            ?>
                            $('.btn_save').hide();
                            $('#btn_new_input').show();
                        }
                        
                    }
                    loading.stop();
                    $('#message').show();
                    $('#message').html(result.message);
                },
                error:function(){
                    loading.stop();
                    $('#message').show();
                    $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
                }
            });
        });
</script>

