<?= $this->extend('template/layout') ?>

<?= $this->section('title') ?>Detail Data Kantor - <?= env('app.name') ?><?= $this->endSection() ?>

<!-- main section start-->
<?= $this->section('main') ?>
<?php
    $uri      = current_url(true);
    $segment1 = $uri->setSilent()->getSegment(1);
    $segment2 = $uri->setSilent()->getSegment(2);
    $segment3 = $uri->setSilent()->getSegment(3);
?>
<!-- Breadcumb -->
<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);"><?= env('app.name') ?></a></li>
    <li class="breadcrumb-item"><?= ucfirst($segment1) ?></li>
    <li class="breadcrumb-item">Data Kantor</li>
    <li class="breadcrumb-item">Detail Data Kantor</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>
<div class="row">
    <div class="col-xl-12">
        <div id="panel-1" class="panel">
            <div class="panel-hdr border-faded border-top-1 border-right-0 border-left-0 shadow-0">
                <h2>Form</h2>
                <div class="panel-toolbar pr-3">
                    
                </div>
            </div>

            <div class="panel-container show">
                <div class="panel-content">
                    <div class="row">
                        <div class="col-12 col-sm-6">
                            
                            <?= form_open("", 'id="pdksatker_form"', ['id' => $id]) ?>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Nama Kantor:</label>
                                    <div class="col-9 col-sm-10">
                                        <input type="text" id="satker" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent ginputx" name="satker" value="<?= $satker ?>" placeholder="Nama Kantor" maxlength="100" disabled>
                                        <div class="invalid-feedback" id="em_satker"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Tipe:</label>
                                    <div class="col-9 col-sm-10">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="tipe" name="tipe">
                                            <option value="">Pilih Tipe Kantor...</option>
                                            <option value="Pusat" <?= ($tipe == 'Pusat') ? 'selected' : '' ?>>Pusat</option>
                                            <option value="Wilayah" <?= ($tipe == 'Wilayah') ? 'selected' : '' ?>>Wilayah</option>
                                            <option value="Area" <?= ($tipe == 'Area') ? 'selected' : '' ?>>Area</option>
                                            <option value="Cabang/ UPC/ UPS" <?= ($tipe == 'Cabang/ UPC/ UPS') ? 'selected' : '' ?>>Cabang/ UPC/ UPS</option>
                                        </select>
                                        <div class="invalid-feedback" id="em_tipe"></div>
                                    </div>
                                </div>

                                <div class="row mb-3" id="kol-wil">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Wilayah:</label>
                                    <div class="col-9 col-sm-10">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="id_kanwil" name="id_kanwil" disabled>
                                            <option value="">Pilih Kantor Wilayah...</option>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_wilayah"></div>
                                    </div>
                                </div>

                                <div class="row mb-3" id="kol-area">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Area:</label>
                                    <div class="col-9 col-sm-10">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="id_area" name="id_area" disabled>
                                            <option value="">Pilih Kantor Area...</option>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_area"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Provinsi:</label>
                                    <div class="col-9 col-sm-10">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="prov" name="prov" disabled>
                                            <option value="">Pilih Provinsi...</option>
                                            <?php foreach ($dt_prov as $k) { ?>
                                            <option value="<?= $k->id ?>" <?= ($prov == $k->id) ? 'selected' : '' ?>><?= $k->nama_prov ?></option>
                                            <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_prov"></div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Kab/Kota:</label>
                                    <div class="col-9 col-sm-10">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="kako" name="kako" disabled>
                                            <option value="">Pilih Kabupaten/Kota...</option>
                                            <?php if (isset($dd_kako)) { ?>
                                                <?php foreach ($dd_kako as $k) { ?>
                                                <option value="<?= $k->id ?>" <?= ($kako == $k->id) ? 'selected' : '' ?>><?= $k->nama_kako ?></option>
                                                <?php } ?>
                                            <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_kako"></div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Koordinat:</label>
                                    <div class="col-5 col-sm-5">
                                        <input type="text" id="lati" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent angkax" name="lati" value="<?= $lati ?>" placeholder="Latitude" maxlength="50" disabled>
                                        <div class="invalid-feedback" id="em_lati"></div>
                                    </div>
                                    <div class="col-4 col-sm-5">
                                        <input type="text" id="longi" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent angkax" name="longi" value="<?= $longi ?>" placeholder="Longitude" maxlength="50" disabled>
                                        <div class="invalid-feedback" id="em_longi"></div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Alamat:</label>
                                    <div class="col-9 col-sm-10">
                                        <textarea class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent ginputx" rows="3" id="alamat" name="alamat" placeholder="Alamat" disabled><?= $alamat ?></textarea>
                                        <div class="invalid-feedback" id="em_alamat"></div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Kode Pos:</label>
                                    <div class="col-9 col-sm-10">
                                        <input type="text" id="kodepos" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent angkax" name="kodepos" value="<?= $kodepos ?>" placeholder="Kode Pos" maxlength="10" disabled>
                                        <div class="invalid-feedback" id="em_kodepos"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-2 col-form-label text-right">Kontak:</label>
                                    <div class="col-5 col-sm-5">
                                        <input type="text" id="tel1" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent angkax" name="tel1" value="<?= $tel1 ?>" placeholder="Telepon" maxlength="25" disabled>
                                        <div class="invalid-feedback" id="em_tel1"></div>
                                    </div>
                                    <div class="col-4 col-sm-5">
                                        <input type="text" id="mail1" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent ginputx" name="mail1" value="<?= $mail1 ?>" placeholder="Email" maxlength="50" disabled>
                                        <div class="invalid-feedback" id="em_mail1"></div>
                                    </div>
                                </div>
   
                                <hr>
                                <div class="invalid-feedback text-center" id="em_message"></div>
                                <div class="clearfix">
                                    <a href="<?= $back ?>" class="btn btn-secondary">
                                        <i class="fal fa-arrow-left"></i> KEMBALI
                                    </a>
                                </div>
                            </form>
                        </div>
                        <div class="col-12 col-sm-6">
                            <div class="card">
                                <div class="card-header">Lokasi Peta</div>
                                <div class="card-body">
                                    <div id="map"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- end panel 1 -->
    </div><!-- end col-xl-6 -->
</div><!-- end row -->
<?= $this->endSection() ?>
<!-- main section end-->

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script type="text/javascript">
    $('.ginputx').inputmask({
        regex: "^[a-zA-Z0-9\\s.,@-]*$"
    });

    $('.angkax').numeric();

    $('.select2').select2({
        dropdownCssClass:'increasezindex'
    });

    // Fungsi untuk mengatur enable/disable wilayah dan area berdasarkan tipe
    function toggleWilayahArea() {
        const tipe = $('#tipe').val();
        
        // Reset select values
        $('#id_kanwil').val('').trigger('change');
        $('#id_area').val('').trigger('change');
        
        switch(tipe) {
            case 'Pusat':
            case 'Wilayah':
                $('#id_kanwil').prop('disabled', true).trigger('change');
                $('#id_area').prop('disabled', true).trigger('change');
                break;
            case 'Area':
                $('#id_kanwil').prop('disabled', false);
                $('#id_area').prop('disabled', true).trigger('change');
                loadWilayahData();
                break;
            case 'Cabang/ UPC/ UPS':
                $('#id_kanwil').prop('disabled', false);
                $('#id_area').prop('disabled', false);
                loadWilayahData();
                break;
            default:
                $('#id_kanwil').prop('disabled', true).trigger('change');
                $('#id_area').prop('disabled', true).trigger('change');
                break;
        }
    }

    // Fungsi untuk load data wilayah
    function loadWilayahData() {
        $('#id_kanwil').empty().append('<option value="">Pilih Kantor Wilayah...</option>');
        
        $.ajax({
            type: "POST",
            url: "<?= base_url('referensi/pdksatker/get_wilayah') ?>",
            dataType: 'json',
            success: function(data) {
                $.each(data, function(i, d) {
                    $('#id_kanwil').append('<option value="' + d.id + '">' + d.satker + '</option>');
                });
            },
            error: function() {
                console.log('Error loading wilayah data');
            }
        });
    }

    // Fungsi untuk load data area berdasarkan wilayah
    function loadAreaData(idWilayah) {
        $('#id_area').empty().append('<option value="">Pilih Kantor Area...</option>');
        
        if (idWilayah) {
            $.ajax({
                type: "POST",
                url: "<?= base_url('referensi/pdksatker/get_area') ?>",
                dataType: 'json',
                data: { 'id_kanwil': idWilayah },
                success: function(data) {
                    $.each(data, function(i, d) {
                        $('#id_area').append('<option value="' + d.id + '">' + d.satker + '</option>');
                    });
                    $('#id_area').trigger('change'); // Update Select2
                },
                error: function() {
                    console.log('Error loading area data');
                }
            });
        }
    }

    // Event handler untuk perubahan tipe
    $('#tipe').on('change', function() {
        toggleWilayahArea();
    });

    // Event handler untuk perubahan wilayah (load area)
    $('#id_kanwil').on('change', function() {
        if ($('#tipe').val() === 'Cabang/ UPC/ UPS') {
            loadAreaData(this.value);
        }
    });

    // Jalankan pada load awal
    toggleWilayahArea();
    
    // Set nilai awal untuk mode edit
    function setEditValues() {
        const editTipe = '<?= $tipe ?>';
        const editIdKanwil = '<?= $id_kanwil ?>';
        const editIdArea = '<?= $id_area ?>';
        
        // Set tipe
        if (editTipe) {
            $('#tipe').val(editTipe).trigger('change');
        }
        
        // Set wilayah dan area setelah tipe diatur
        setTimeout(function() {
            if (editTipe === 'Area' || editTipe === 'Cabang/ UPC/ UPS') {
                if (editIdKanwil) {
                    $('#id_kanwil').val(editIdKanwil).trigger('change');
                    
                    // Set area setelah wilayah dipilih
                    if (editTipe === 'Cabang/ UPC/ UPS' && editIdArea) {
                        setTimeout(function() {
                            $('#id_area').val(editIdArea).trigger('change');
                        }, 500);
                    }
                }
            }
        }, 700);
    }
    
    // Jalankan set edit values setelah semua init selesai
    setTimeout(setEditValues, 1000);
</script>

<script>
    // Variabel global untuk marker dan map
    let map, marker, geocoder;
    
    // Fungsi inisialisasi peta
    function initMap() {
        // Inisialisasi peta
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: { lat: -2.5489, lng: 118.0149 } // Pusat Indonesia
        });
        
        // Inisialisasi geocoder
        geocoder = new google.maps.Geocoder();
        
        // Membuat posisi awal marker
        let position = { lat: -2.5489, lng: 118.0149 };
        
        // Membuat marker standar (lebih kompatibel)
        marker = new google.maps.Marker({
            position: position,
            map: map,
            draggable: false,
            title: 'Lokasi'
        });
        
        // Jika ini mode edit dan ada data latitude/longitude, set marker ke posisi tersebut
        const editLat = parseFloat('<?= $lati ?>');
        const editLng = parseFloat('<?= $longi ?>');
        
        if (!isNaN(editLat) && !isNaN(editLng) && editLat !== 0 && editLng !== 0) {
            const editPosition = { lat: editLat, lng: editLng };
            map.setCenter(editPosition);
            map.setZoom(16);
            marker.setPosition(editPosition);
            document.getElementById("lati").value = editLat;
            document.getElementById("longi").value = editLng;
        } else {
            // Coba dapatkan lokasi user saat ini jika tidak ada data koordinat
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        const userLocation = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude
                        };
                        map.setCenter(userLocation);
                        map.setZoom(15);
                        marker.setPosition(userLocation);
                        document.getElementById("lati").value = userLocation.lat;
                        document.getElementById("longi").value = userLocation.lng;
                    },
                    function() {
                        console.log('Tidak bisa mendapatkan lokasi user');
                        // Inisialisasi nilai form dengan posisi awal default
                        document.getElementById("lati").value = position.lat;
                        document.getElementById("longi").value = position.lng;
                    }
                );
            } else {
                // Inisialisasi nilai form dengan posisi awal default
                document.getElementById("lati").value = position.lat;
                document.getElementById("longi").value = position.lng;
            }
        }
    }
</script>

<!-- Load Google Maps API dengan API Key Anda -->
<script src="https://maps.googleapis.com/maps/api/js?key=<?= $map_api ?>&callback=initMap&libraries=geometry,places" async defer></script>

<style>
    #map {
        height: 400px;
        width: 100%;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
</style>
<?= $this->endSection() ?>
<!-- pageScripts section end-->