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

<?= $this->section('title') ?>Edit 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">Edit 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 Edit</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">
                                        <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_kanwil"></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">
                                            <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">
                                            <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">
                                        <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">
                                        <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"><?= $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">
                                        <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">
                                        <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">
                                        <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>
                                    <?= form_submit('btn_pdksatker', $button, 'waves-effect waves-themed float-right') ?>
                                </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>
                                    <small class="text-muted mt-2 d-block">Geser marker untuk mengubah koordinat</small>
                                </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);

    $('#prov').on('change', function() {  
        $('#kako').empty().append('<option value="">Pilih Kabupaten/Kota...</option>');              
        $.ajax({
            type: "POST",
            url: "<?= base_url('referensi/pdksatker/get_prov') ?>",
            dataType: 'json',
            data: { 'id_prov': this.value },
            success: function(data){
                $.each(data, function(i, d) {
                   $('#kako').append('<option value="' + d.id + '">' + d.nama_kako + '</option>');
                });
            }
        });
        
        // Fokus peta ke provinsi yang dipilih
        if (this.value && geocoder) {
            const selectedOption = this.options[this.selectedIndex];
            const provinceName = selectedOption.text;
            if (provinceName && provinceName !== 'Pilih Provinsi...') {
                focusToProvince(provinceName);
            }
        }
    });
    
    // Event untuk kabupaten/kota
    $('#kako').on('change', function() {
        if (this.value && geocoder) {
            const selectedOption = this.options[this.selectedIndex];
            const cityName = selectedOption.text;
            const provinceOption = document.getElementById('prov').options[document.getElementById('prov').selectedIndex];
            const provinceName = provinceOption ? provinceOption.text : '';
            
            if (cityName && cityName !== 'Pilih Kabupaten/Kota...' && provinceName) {
                focusToCity(cityName, provinceName);
            }
        }
    });
    
    // Event untuk input alamat dengan debounce
    let addressTimeout;
    $('#alamat').on('input', function() {
        clearTimeout(addressTimeout);
        const address = this.value;
        
        addressTimeout = setTimeout(function() {
            if (address.length > 10 && geocoder) { // Minimal 10 karakter untuk pencarian
                focusToAddress(address);
            }
        }, 1000); // Delay 1 detik setelah user berhenti mengetik
    });

    $("#pdksatker_form").submit(function(e) {
        e.preventDefault();
        var url = '<?= $action ?>';
        var formData = $(this).serialize();
        
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            data: formData,
            beforeSend: function() {
                // Clear previous validation errors
                $(".form-control").removeClass("is-invalid");
                $(".invalid-feedback").html('').hide();
                $("#em_message").html('').hide();
                
                // Show loading button
                BtnLoading($("#btn_pdksatker"));
            },
            error: function(xhr, status, message) {
                try {
                    var res = JSON.parse(xhr.responseText);
                    
                    // Handle validation errors
                    if (res.messages) {
                        $(res.messages).each(function(i, val) {
                            var inputname = Object.keys(val)[0];
                            $.each(val, function(k, v) {
                                $("#" + k).addClass("is-invalid");
                                $("#em_" + k).html(v).fadeIn();
                                $("#" + inputname).focus();
                            });
                        });
                    }
                    
                    // Handle general error message
                    if (res.message) {
                        $("#em_message").html(res.message).fadeIn();
                    }
                    
                } catch (e) {
                    console.error('Error parsing response:', e);
                    $("#em_message").html('Terjadi kesalahan sistem').fadeIn();
                }
            },
            success: function(res) {
                // Show success message and redirect back to list
                toastr.success(res.message, 'Berhasil!', {
                    timeOut: 2000,
                    onHidden: function() {
                        // Redirect ke halaman list
                        window.location.href = '<?= base_url('referensi/pdksatker') ?>';
                    }
                });
            },
            complete: function() {
                // Reset button state
                BtnReset($("#btn_pdksatker"));
            }
        });
    });
</script>

<script>
    // Variabel global untuk marker dan map
    let map, marker, geocoder;
    
    // Fungsi untuk fokus ke provinsi
    function focusToProvince(provinceName) {
        if (geocoder && provinceName) {
            geocoder.geocode({
                'address': provinceName + ', Indonesia'
            }, function(results, status) {
                if (status === 'OK') {
                    const bounds = results[0].geometry.viewport;
                    map.fitBounds(bounds);
                    map.setZoom(Math.min(map.getZoom(), 8));
                }
            });
        }
    }
    
    // Fungsi untuk fokus ke kabupaten/kota
    function focusToCity(cityName, provinceName) {
        if (geocoder && cityName) {
            const address = cityName + ', ' + provinceName + ', Indonesia';
            geocoder.geocode({
                'address': address
            }, function(results, status) {
                if (status === 'OK') {
                    const bounds = results[0].geometry.viewport;
                    map.fitBounds(bounds);
                    map.setZoom(Math.min(map.getZoom(), 11));
                }
            });
        }
    }
    
    // Fungsi untuk fokus ke alamat
    function focusToAddress(address) {
        if (geocoder && address.trim() !== '') {
            geocoder.geocode({
                'address': address + ', Indonesia'
            }, function(results, status) {
                if (status === 'OK') {
                    const location = results[0].geometry.location;
                    map.setCenter(location);
                    map.setZoom(16);
                    marker.setPosition(location);
                    document.getElementById("lati").value = location.lat();
                    document.getElementById("longi").value = location.lng();
                }
            });
        }
    }
    
    // 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: true,
            title: 'Drag saya untuk menentukan lokasi'
        });
        
        // Event saat marker dipindahkan
        marker.addListener('dragend', function() {
            const newPosition = marker.getPosition();
            document.getElementById("lati").value = newPosition.lat();
            document.getElementById("longi").value = newPosition.lng();
        });
        
        // Event saat marker diklik
        marker.addListener('click', function() {
            const position = marker.getPosition();
            document.getElementById("lati").value = position.lat();
            document.getElementById("longi").value = position.lng();
        });
        
        // Event saat peta diklik
        map.addListener('click', function(event) {
            const clickPosition = event.latLng;
            marker.setPosition(clickPosition);
            document.getElementById("lati").value = clickPosition.lat();
            document.getElementById("longi").value = clickPosition.lng();
        });
        
        // 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-->
