@extends('layouts.blank')
@section('css')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<style>
    .bg-login{
        background-image: url("{{asset('assets/bg-login.png')}}");
        background-repeat: no-repeat;
        background-size: cover;
    }
    #map { height: 60vh; min-height: 400px; }
</style>
@endsection
@section('content')
<div class="d-flex align-items-center justify-content-center min-vh-100">
            <div class="container py-4 py-lg-5 px-4 px-sm-0">
                <div class="row justify-content-center">
                    <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12">
                        <div class="card pr-4 rounded-plus bg-faded" style="border:none;">
                            @include('include.alert')
                            <div class="row">
                                <div class="col-md-12 p-4 d-flex flex-column justify-content-center align-items-center gap-3">
                                     <div class="d-flex flex-column gap-3 align-items-center justify-content-center mb-5">
                                        <div>
                                            <img src="{{asset('assets/logo-dinas.ico')}}" width="50">
                                            <img src="{{asset('assets/dinaspendidikan.png')}}" width="75">
                                        </div>
                                        <div>
                                            <h5 class="fw-700">Form Kelengkapan Data Profile Sekolah</h5>
                                        </div>
                                    </div>
                                    <div>
                                    <div class="col-12 row mx-auto mt-3">
                                        <div class="col-md-6">
                                            <div class="alert alert-danger">
                                                <h5><b><x-lucide-info width="20"/> Info:</b></h5>
                                                <ul>
                                                    <li>Pastikan <b>NPSN</b> yang diisi benar</li>
                                                    <li>Pastikan kembali untuk Wilayah,Provinsi,Kecamatan,Kabupaten sesuai dengan data sekolah</li>
                                                </ul>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="alert alert-info">
                                                <h5><b><x-lucide-user width="20"/> Data User Pendaftar:</b></h5>
                                                <ul>
                                                    <li>Nama Lengkap : <b>  {{session('kontak_person')}}</b></li>
                                                    <li>Telp : <b>  {{session('telp')}}</b></li>
                                                    <li>Email : <b>  {{$user->email}}</b></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                        <form method="POST" action="{{route($route.'.updateLengkapi')}}">
                                            {{csrf_field()}}
                                            <div class="row">
                                                <div id="loading-spinner" style="display: none; text-align: center;">
                                                    <img src="{{ asset('assets/spinner.gif') }}" alt="Loading..." width="20">
                                                </div>

                                                <div class="col-md-6">
                                                    <div class="card row mx-auto">
                                                        <div class="card-header">
                                                            <h5 class="mb-0"><b>Profile Sekolah</b></h5>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Nama Sekolah</label>
                                                                    <div class="col-12 pr-1">
                                                                        <input type="text" value="{{$user->name ? $user->name : old('name')}}" name="name"  class="form-control nama_sekolah @error('name') is-invalid @enderror" placeholder="Masukan Nama Sekolah">
                                                                        @error('name')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">NPSN</label>
                                                                    <div class="col-12 pr-1">
                                                                        <input maxlength="8" autocomplete="off" type="text" value="{{ $user->username ? $user->username : old('npsn')}}" name="npsn" class="form-control @error('npsn') is-invalid @enderror numberInput npsn" placeholder="Masukan NPSN">
                                                                        <ul id="result"></ul>
                                                                        @error('npsn')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div> 
                                                            </div> 
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label">Tingkat Sekolah</label>
                                                                    <div class="col-12 pr-1">
                                                                        <select name="tingkat_sekolah" class="form-control tingkat_sekolah select2 @error('tingkat_sekolah') is-invalid @enderror">
                                                                            <option value="">-Pilih Tingkat Sekolah-</option>
                                                                            <option value="1">SD</option>
                                                                            <option value="2">SMP</option>
                                                                            <option value="3">SMA</option>
                                                                            <option value="4">SMK</option>
                                                                            <option value="5">MI</option>
                                                                            <option value="6">MTs</option>
                                                                            <option value="7">MA</option>
                                                                            <option value="8">SD LB</option>
                                                                            <option value="9">SMP LB</option>
                                                                            <option value="10">SMA LM</option>
                                                                            <option value="11">SLB Khusus</option>
                                                                        </select>
                                                                        @error('tingkat_sekolah')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Status Sekolah</label>
                                                                    <div class="col-12 pr-1">
                                                                        <select name="status_sekolah" class="form-control select2 @error('status_sekolah') is-invalid @enderror">
                                                                            <option value="" data-select2-id="3">-Pilih Status Sekolah-</option>
                                                                            <option value="Negeri">Negeri</option>
                                                                            <option value="Swasta">Swasta</option>
                                                                        </select>
                                                                        @error('status_sekolah')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Provinsi</label>
                                                                    <div class="col-12 pr-1">
                                                                        <select name="provinsi" class="form-control select2 @error('provinsi') provinsi is-invalid @enderror" id="provinsi">
                                                                            <option value="0">- PILIH PROVINSI -</option>
                                                                            @foreach($provinsi as $datProv)
                                                                            <option value="{{encode_id($datProv->MsProvinsiId)}}">{{$datProv->name}}</option>
                                                                            @endforeach
                                                                        </select>
                                                                        @error('provinsi')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Kabupaten</label>
                                                                    <div class="col-12 pr-1">
                                                                        <select name="kabupaten" class="form-control select2 @error('kabupaten') kabupaten is-invalid @enderror" id="kabupaten" required>
                                                                            <option value="0">- PILIH KABUPATEN/KOTA -</option>
                                                                        </select>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Kecamatan</label>
                                                                    <div class="col-12 pr-1">
                                                                        <select name="kecamatan" class="form-control select2 @error('kecamatan') kecamatan is-invalid @enderror" id="kecamatan" required>
                                                                            <option value="0">- PILIH KECAMATAN -</option>
                                                                        </select>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label" for="fname">Alamat Sekolah</label>
                                                                    <div class="col-12 pr-1">
                                                                        <textarea cols="10" rows="5" name="alamat_sekolah" class="form-control @error('alamat_sekolah') is-invalid @enderror" placeholder="Masukan Alamat Sekolah, Nama Jalan / Dusun / RT-RW" required>{{session('alamat_sekolah')}}</textarea>
                                                                        @error('alamat_sekolah')
                                                                            <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                        </div>
                                                    </div> 
                                                    
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="card row mx-auto">
                                                        <div class="card-header">
                                                            <h5 class="mb-0"><b>Lokasi Sekolah</b></h5>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label">Latitude</label>
                                                                    <div class="col-12 pr-1">
                                                                        <input type="text" id="latInput" value="{{ @$user->profile->lat ? @$user->profile->lat : old('lat')}}" name="lat" class="form-control @error('lat') is-invalid @enderror" placeholder="Masukan Latitude">
                                                                        <ul id="result"></ul>
                                                                        @error('lat')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div> 
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <div class="form-group row">
                                                                    <label class="col-xl-12 form-label">Longitude</label>
                                                                    <div class="col-12 pr-1">
                                                                        <input id="lngInput" type="text" value="{{ @$user->profile->long ? @$user->profile->long : old('long')}}" name="long" class="form-control @error('long') is-invalid @enderror" placeholder="Masukan Longitude">
                                                                        <ul id="result"></ul>
                                                                        @error('long')
                                                                        <span class="invalid-feedback" style="display: block!important;"><strong>{{$message}}</strong></span>
                                                                        @enderror
                                                                    </div>
                                                                </div> 
                                                            </div>
                                                            <div class="col-md-12 mt-3">
                                                                <button type="button" id="btnUseLocation" class="px-3 btn-primary border-0 mb-2 py-2 bg-blue-600 text-white rounded">Gunakan Lokasi Saya</button>
                                                                <button type="button" id="btnClear" class="px-3 btn-warning py-2 border-0 mb-2 rounded">Reset</button>
                                                                <div id="map" class="rounded-md border"></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="col-md-12 mt-3">
                                                    <div class="row no-gutters">
                                                        <div class="col-md-12 ml-auto text-right">
                                                            <button id="js-login-btn" type="submit" class="btn btn-block btn-primary btn-lg mt-3">Simpan Data Sekolah</button>
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                        </form>
                                        <p class="text-muted mt-auto text-center mb-0 pt-3">
                                            {{date('Y')}} © Dinas Lingkungan Hidup DKI Jakarta
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
@endsection
@section('js')
<script src="{{asset('assets/js/vendors.bundle.js')}}"></script>
        <script src="{{asset('assets/js/app.bundle.js')}}"></script>
        <script src="{{asset('assets/js/formplugins/select2/select2.bundle.js')}}"></script>
         <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
        <script>
            // ===== Inisialisasi peta =====
            const defaultLat = -6.200000;
            const defaultLng = 106.816666;
            const defaultZoom = 12;

            const map = L.map('map').setView([defaultLat, defaultLng], defaultZoom);

            // Tile layer (OpenStreetMap)
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors'
            }).addTo(map);

            // Marker (dapat digerakkan)
            let marker = L.marker([defaultLat, defaultLng], { draggable: true }).addTo(map);

            // Element input
            const latInput = document.getElementById('latInput');
            const lngInput = document.getElementById('lngInput');
            const btnUseLocation = document.getElementById('btnUseLocation');
            const btnClear = document.getElementById('btnClear');

            // Fungsi format untuk menampilkan lat/lng (6 desimal)
            function fmt(n) {
            return Number(n).toFixed(6);
            }

            // Set input berdasarkan koordinat
            function setInputs(lat, lng) {
            latInput.value = fmt(lat);
            lngInput.value = fmt(lng);
            }

            // Ketika klik di map => pindah marker & isi input
            map.addEventListener('click', function(e) {
            const { lat, lng } = e.latlng;
            marker.setLatLng([lat, lng]);
            setInputs(lat, lng);
            });

            // Ketika marker di-drag selesai => update input
            marker.addEventListener('moveend', function(e) {
                const pos = e.target.getLatLng();
                setInputs(pos.lat, pos.lng);
            });


            // Tombol: gunakan lokasi (geolocation)
            btnUseLocation.addEventListener('click', function() {
            if (!navigator.geolocation) {
                alert('Geolocation tidak didukung oleh browser ini.');
                return;
            }

            btnUseLocation.disabled = true;
            btnUseLocation.textContent = 'Mencari lokasi...';

            navigator.geolocation.getCurrentPosition(function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                map.setView([lat, lng], 15);
                marker.setLatLng([lat, lng]);
                setInputs(lat, lng);
                btnUseLocation.disabled = false;
                btnUseLocation.textContent = 'Gunakan Lokasi Saya';
            }, function(err) {
                alert('Gagal mendapatkan lokasi: ' + err.message);
                btnUseLocation.disabled = false;
                btnUseLocation.textContent = 'Gunakan Lokasi Saya';
            }, {
                enableHighAccuracy: true,
                timeout: 10000
            });
            });

            // Tombol reset: pindah kembali ke default dan clear input
            btnClear.addEventListener('click', function() {
                map.setView([defaultLat, defaultLng], defaultZoom);
                marker.setLatLng([defaultLat, defaultLng]);
                latInput.value = '';
                lngInput.value = '';
            });

            // Inisialisasi input awal (kosong)
            latInput.value = '';
            lngInput.value = '';

            // Opsional: jika mau isi input dengan koordinat awal marker:
            // setInputs(defaultLat, defaultLng);
        </script>
        <script>
            $(document).ready(function() {
                $('.select2').select2();
                $('.numberInput').on('input', function() {
                    this.value = this.value.replace(/[^0-9]/g, ''); // Hanya angka 0-9
                });
                $('#togglePassword').on('click', function() {
                    let passwordField = $('#password');
                    let icon = $(this).find('i');

                    // Cek apakah input saat ini bertipe password
                    if (passwordField.attr('type') === 'password') {
                        passwordField.attr('type', 'text'); // Ubah ke teks
                        icon.removeClass('fa-eye').addClass('fa-eye-slash'); // Ganti ikon
                    } else {
                        passwordField.attr('type', 'password'); // Ubah ke password
                        icon.removeClass('fa-eye-slash').addClass('fa-eye'); // Kembalikan ikon
                    }
                });

                $('.npsn').on('keyup', function(){
                    var query = $(this).val();
                    var tingkat_sekolah = $('.tingkat_sekolah').find(':selected').val();
                    if(query.length > 0) {
                        $.ajax({
                            url: "{{ url('sekolahNpsn') }}",
                            type: "POST",
                            xhrFields: {
                                withCredentials: true
                            },
                            data: {
                                query: query,
                                _token: '{{csrf_token()}}',
                                tingkat_sekolah:tingkat_sekolah
                            },
                            success: function(data) {
                                $('#result').html('');
                                if(data.length > 0) {
                                    $('#result').show();
                                    $.each(data, function(index, data){
                                        $('#result').append('<li data-npsn="'+data.npsn+'">' + data.nama_sekolah + '</li>');
                                    });
                                    
                                } else {
                                    $('.nama_sekolah').removeAttr('readonly');
                                    $('#result').hide();
                                }
                            }
                        });
                    } else {
                        $('#result').hide();
                    }
                });

                // Saat klik pada hasil pencarian, isi input dan sembunyikan daftar
                $(document).on('click', '#result li', function(){
                    var npsn = $(this).attr('data-npsn');

                    $('.npsn').val(npsn);
                    $('.nama_sekolah').attr('readonly',true);
                    $('.nama_sekolah').val($(this).text());
                    $('#result').hide();
                });

                // Klik di luar input atau hasil pencarian untuk menyembunyikan daftar
                $(document).on('click', function(e) {
                    if (!$(e.target).closest('.npsn, #result').length) {
                        $('#result').hide();
                    }
                });
            });
            $("#js-login-btn").click(function(event)
            {

                // Fetch form to apply custom Bootstrap validation
                var form = $("#js-login")

                if (form[0].checkValidity() === false)
                {
                    event.preventDefault()
                    event.stopPropagation()
                }

                form.addClass('was-validated');
                // Perform ajax submit here...
            });

            function clear(elementId) {
              $('#' + elementId).empty();
              $('#' + elementId).select2();
            }

            $('#sekolah').on('select2:select', function(e) {
                let npsn = $(this).find(':selected').attr('data-npsn');
                $('.npsn').val(npsn);
            });


            $('select').on("select2:selecting", function(e) {
              var selectorOrigin = this.id;
              var id = e.params.args.data.id;
              
              
              if(selectorOrigin=='provinsi'){
                $('#loading-spinner').show();
                clear('kabupaten');
                selector = 'kabupaten';
                url_to = 'kabupaten';
                getSelect(id, selector, url_to);
              }

              if(selectorOrigin=='kabupaten'){
                $('#loading-spinner').show();
                clear('kecamatan');
                selector = 'kecamatan';
                url_to = 'kecamatan';
                getSelect(id, selector, url_to);
              }
              if(selectorOrigin=='kecamatan'){
                $('#loading-spinner').show();
                clear('sekolah');
                selector = 'sekolah';
                url_to = 'sekolah';
                getSelect(id, selector, url_to);
              }
            });

          function getSelect(id, selectTo, urlTo, selected = "") {
              id = id;
              var base_url = "{{url('/')}}";
              //alert(id);
              destino = "#" + selectTo;
              valor = $('#' + id).find(":selected").val();

              $.ajax({
                  method: "POST",
                  url: base_url + "/get/" + urlTo,
                  data: {
                    _token: '{{csrf_token()}}',
                    id: id
                  }
                })
                .done(function(msg) {
                  obj = msg.data;

                  if (obj.length > 0) {
                    //Clear the current options
                    $(destino).empty();
                    
                    if(selectTo=='kabupaten'){
                      $(destino).append('<option value="">-PILIH KABUPATEN/KOTA-</option>').select2("val", "0");


                      
                      $.each(obj, function(index) {
                        value = obj[index].id;
                        text = obj[index].name;
                        $(destino).append('<option value=' + value + '>' + text + '</option>');
                      });
                      console.log(selected)
                      if (selected) {
                        $(destino).val(selected).trigger('change');
                        selected = "";
                      }
                    }

                    if(selectTo=='kecamatan'){
                      $(destino).append('<option value="">-PILIH KECAMATAN-</option>').select2("val", "0");
                      
                      $.each(obj, function(index) {
                        value = obj[index].id;
                        text = obj[index].name;
                        $(destino).append('<option value=' + value + '>' + text + '</option>');
                      });
                      console.log(selected)
                      if (selected) {
                        $(destino).val(selected).trigger('change');
                        selected = "";
                      }
                    }

                    if(selectTo=='sekolah'){
                      $(destino).append('<option value="">-PILIH SEKOLAH-</option>').select2("val", "0");
                      
                      $.each(obj, function(index) {
                        value = obj[index].id;
                        text = obj[index].name;
                        npsn = obj[index].npsn;
                        $(destino).append('<option data-npsn="'+npsn+'" value=' + value + '>' + text + '</option>');
                      });
                      console.log(selected)
                      if (selected) {
                        $(destino).val(selected).trigger('change');
                        selected = "";
                      }
                    }

                    
                  } else {

                    if(selectTo=='provinsi'){
                      $(destino).empty().append('<option value="0">-PILIH PROVINSI-</option>').select2("val", "0");
                    }
                    if(selectTo=='kabupaten'){
                      $(destino).empty().append('<option value="0">-PILIH KABUPATEN/KOTA-</option>').select2("val", "0");
                    }
                    if(selectTo=='kecamatan'){
                      $(destino).empty().append('<option value="0">-PILIH KECAMATAN-</option>').select2("val", "0");
                    }
                    if(selectTo=='sekolah'){
                      $(destino).empty().append('<option value="0">-PILIH SEKOLAH-</option>').select2("val", "0");
                    }

                    
                  }
                  $('#loading-spinner').hide();
                });
              return false;
            }

        </script>
@endsection