<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCU3tdTex4BWClD0vauHsj01n2pydE0_O4&v=weekly"
      defer></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Tambah Data Agen</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?=base_url()?>home">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?=base_url()?>all_agen">Data Agen</a></li>
                    <li class="breadcrumb-item active">Tambah Data Agen</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <hr/>
    <section class="content">
        <div class="container-fluid">
            <form id="f1" action="#" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-lg-6">
                    <div class="card card-outline card-success">
                        <div class="card-header">
                            <div class="card-title">
                                Data Pokok Agen
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="nomor">Nomor</label>
                                <input type="text" class="form-control form-control-border" id="nomor" placeholder="Nomor" name="nomor">
                                <span id="enomor" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="nama_perusahaan">Nama Perusahaan</label>
                                <input type="text" class="form-control form-control-border" id="nama_perusahaan" placeholder="Nama Perusahaan" name="nama_perusahaan">
                                <span id="enama_perusahaan" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="nama_pemohon">Nama Pemohon</label>
                                <input type="text" class="form-control form-control-border" id="nama_pemohon" placeholder="Nama Pemohon" name="nama_pemohon">
                                <span id="enama_pemohon" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="sold_id">Sold ID</label>
                                <input type="text" class="form-control form-control-border" id="sold_id" placeholder="Sold ID" name="sold_id">
                                <span id="esold_id" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" class="form-control form-control-border" id="email" placeholder="Email" name="email">
                                <span id="eemail" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="password">Password</label>
                                <input type="password" class="form-control form-control-border" id="password" placeholder="Password Login Agen" name="password">
                                <span id="epassword" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="no_hp">Nomor HP</label>
                                <input type="text" class="form-control form-control-border" id="no_hp" name="no_hp" data-inputmask='"mask": "(+62) 999-9999999"' data-mask>
                                <span id="eno_hp" class="error invalid-feedback"></span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="card card-outline card-primary">
                        <div class="card-header">
                            <div class="card-title">
                                Data Lokasi Agen
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="alamat">Alamat</label>
                                <textarea class="form-control form-control-border" id="alamat" placeholder="Alamat" name="alamat"></textarea>
                                <span id="ealamat" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="provinsi">Provinsi</label>
                                <select class="select2 form-control form-control-border" id="provinsi" placeholder="Pilih Provinsi" name="provinsi">
                                </select>
                                <span id="eprovinsi" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="kabupaten">Kabupaten</label>
                                <select class="select2 form-control form-control-border" id="kabupaten" placeholder="Pilih Kabupaten" name="kabupaten">
                                </select>
                                <span id="ekabupaten" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="kecamatan">Kecamatan</label>
                                <select class="select2 form-control form-control-border" id="kecamatan" placeholder="Pilih Kecamatan" name="kecamatan">
                                </select>
                                <span id="ekecamatan" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="kelurahan">Kelurahan</label>
                                <select class="select2 form-control form-control-border" id="kelurahan" placeholder="Pilih Kelurahan" name="kelurahan">
                                </select>
                                <span id="ekelurahan" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="lat">Latitude</label>
                                <input type="text" class="form-control form-control-border" id="lat" name="lat" value="<?=$calon->lat?>">
                                <span id="elat" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="lng">Longitude</label>
                                <input type="text" class="form-control form-control-border" id="lng" name="lng" value="<?=$calon->lng?>">
                                <span id="elng" class="error invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <div id="map">
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-right">
                            <a id="btn_kembali" class="btn bg-gradient-warning" href="<?=base_url()?>all_agen"><span class="fas fa-arrow-left"></span> Batal</a>
                            <button id="btn_simpan" class="btn bg-gradient-primary"><span class="fas fa-check"></span> Simpan</button>
                        </div>
                    </div>
                </div>
            </div>
            </form>
        </div>
    </section>
    <script>
        $(document).ready(function () {
            var textra_query = '';
            var textra_kab = '';
            var textra_kec = '';
            var textra_kel = '';

            $("select[name='provinsi']").select2({
                placeholder: "Pilih Provinsi",
                ajax: {
                    url: "<?= base_url() ?>select_provinsi",
                    dataType: 'json',
                    method: 'POST',
                    data: function(params) {
                        var query = {
                            search: params.term,
                            extra_query: textra_query,
                            page: params.page || 1
                        }
                        return JSON.stringify(query);
                    }
                }
            });

            $("select[name='provinsi']").on('select2:select', function (e) {
                var data = e.params.data;
                textra_kab = "kode_provinsi='"+data.id+"'";

                $("select[name='kabupaten']").val(null).trigger('change');
                $("select[name='kecamatan']").val(null).trigger('change');
                $("select[name='kelurahan']").val(null).trigger('change');
            });

            $("select[name='kabupaten']").select2({
                placeholder: "Pilih Kabupaten",
                ajax: {
                    url: "<?= base_url() ?>select_kabupaten",
                    dataType: 'json',
                    method: 'POST',
                    data: function(params) {
                        var query = {
                            search: params.term,
                            extra_query: textra_kab,
                            page: params.page || 1
                        }
                        return JSON.stringify(query);
                    }
                }
            });

            $("select[name='kabupaten']").on('select2:select', function (e) {
                var data = e.params.data;
                textra_kec = "kode_kabupaten='"+data.id+"'";
                $("select[name='kecamatan']").val(null).trigger('change');
                $("select[name='kelurahan']").val(null).trigger('change');
            });

            $("select[name='kecamatan']").select2({
                placeholder: "Pilih Kecamatan",
                ajax: {
                    url: "<?= base_url() ?>select_kecamatan",
                    dataType: 'json',
                    method: 'POST',
                    data: function(params) {
                        var query = {
                            search: params.term,
                            extra_query: textra_kec,
                            page: params.page || 1
                        }
                        return JSON.stringify(query);
                    }
                }
            });

            $("select[name='kecamatan']").on('select2:select', function (e) {
                var data = e.params.data;
                textra_kel = "kode_kecamatan='"+data.id+"'";
                $("select[name='kelurahan']").val(null).trigger('change');
            });

            $("select[name='kelurahan']").select2({
                placeholder: "Pilih Kelurahan",
                ajax: {
                    url: "<?= base_url() ?>select_kelurahan",
                    dataType: 'json',
                    method: 'POST',
                    data: function(params) {
                        var query = {
                            search: params.term,
                            extra_query: textra_kel,
                            page: params.page || 1
                        }
                        return JSON.stringify(query);
                    }
                }
            });

            $('[data-mask]').inputmask();

            $("#f1").submit(function (e) {
                e.preventDefault();
                Swal.fire({
                    text: 'Menyimpan data.. Silahkan tunggu..',
                    allowOutsideClick: false
                });
                Swal.showLoading();
                var data_kirim = $("#f1").serialize();
                
                $.post("<?=base_url()?>insert_agen",data_kirim).done(function (data) {
                    if (data.status == 'success')
                    {
                        Swal.fire({
                            text:'Agen baru berhasil disimpan!',
                            icon : 'success'
                        }).then(function () {
                            window.location.href = '<?=base_url()?>view_agen/'+data.id;
                        });
                    }
                }).fail(function (data) {
                    if(data.statusText == 'input'){
                        Object.keys(data.responseJSON.messages).forEach(function(key){
                            $("#e"+key).html(data.responseJSON.messages[key]);
                            $("#e"+key).show();
                        });
                        Swal.close();
                    }else{
                        Swal.fire({
                            text:'Terjadi kesalahan pada saat registrasi!',
                            icon : 'error'
                        });
                    }
                });
            });
        });
    </script>
    <style>
        #map {
            width: 100%;
            height: 500px;
        }
    </style>
    <script>
        var map;
        var markers = [];
        var iconBase;
        var icons;
        $(document).ready(function () {
            function initMap() {
                map = new google.maps.Map(document.getElementById("map"), {
                    zoom: 12,
                    center: { lat: 3.6424551, lng: 98.5994535 },
                });

                iconBase =
                    "<?=base_url()?>/src/img/";
                icons = {
                    info: {
                        icon: iconBase + "logistic.png",
                    },
                };

                <?php
                if (!empty($calon->lat) && !empty($calon->lng))
                {
                ?>
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(<?=$calon->lat?>, <?=$calon->lng?>),
                        icon: icons['info'].icon,
                        map: map,
                        title:'Lokasi',
                    });
                    markers.push(marker);
                    map.panTo(marker.position);
                <?php
                }
                ?>

                google.maps.event.addListener(map, "click", (event) => {
                    addMarker(event.latLng, map);
                    var LatLng1 = event.latLng.toUrlValue().split(",");
                    var koordinat = LatLng1[0]+","+LatLng1[1];
                });
            }

            initMap();
            
            function addMarker(position, emap) {
                while (markers.length>0)
                {
                    markers[markers.length-1].setMap(null);
                    markers.pop();
                }

                var marker = new google.maps.Marker({
                    position: position,
                    map: emap,
                    icon: icons['info'].icon,
                    title:'Lokasi'
                });
                
                markers.push(marker);
                marker.setAnimation(google.maps.Animation.BOUNCE);
                map.panTo(marker.position);

                var LatLng1 = markers[0].position.toUrlValue().split(",");

                $("input[name='lat']").val(LatLng1[0]);
                $("input[name='lng']").val(LatLng1[1]);
            }
        });
    </script>
</div>