<form action="{{route('pt.kemaskini-petak')}}" method="POST">
    @csrf  
    <input type="hidden" name="permohonan_id" value="{{$permohonan?->id}}">
    <div class="row">
      <div class="col-md-12">
        <div class="card card-round">
          <div class="card-header">
            <div class="card-head-row card-tools-still-right">
              <h4 class="card-title">Maklumat Permohonan Lesen Penjaja</h4>
            </div>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                    <label for="jenis_penjaja">Jenis Penjaja</label>
                    <input type="text" class="form-control" id="jenis_penjaja" disabled
                    value="{{ old('jenis_penjaja', $permohonan?->jenis_penjaja->jenis) }}" />
                </div> 
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="jenis_kenderaan">Jenis Kenderaan</label>
                            <input type="text" class="form-control" id="jenis_kenderaan" disabled
                            value="{{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) }}" />
                        </div> 
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="no_pendaftaran">No Pendaftaran Kenderaan</label>
                            <input type="text" class="form-control" id="no_pendaftaran" disabled
                            value="{{ old('no_pendaftaran', $permohonan?->no_pendaftaran) }}" />
                        </div> 
                    </div>
                </div>
                <div class="form-group">
                    <label for="status_tanah">Status Tanah</label>
                    <input type="text" class="form-control" id="status_tanah" disabled
                    value="{{ old('status_tanah', $permohonan?->status_tanah) }}" />
                </div> 
                <div class="row">
                    <div class="col-sm-12 col-md-6">
                        <div class="form-group">
                            <label for="penempatan">Pusat Penempatan(jika ada)</label>
                            <input type="text" id="penempatan" class="form-control" readonly name="penempatan" value="{{$permohonan?->penempatan?->nama}}" >                            
                        </div>
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <div class="form-group">
                            <label for="kawasan">Kawasan Penjajaan</label>
                            <input type="text" id="kawasan" class="form-control" readonly name="kawasan" value="{{$permohonan?->kawasan->nama}}" >      
                        </div>
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <div class="form-group">
                            <label for="taman">Taman</label>
                            <input type="text" id="taman" class="form-control" readonly name="taman" value="{{$permohonan?->taman?->nama}}" >     
                        </div>
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <div class="form-group">
                            <label for="jalan">Jalan</label>
                            <input type="text" id="jalan" class="form-control" readonly name="jalan" value="{{$permohonan?->jalan?->nama}}" >     
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="masa_jualan_mula">Masa Mula Jualan</label>
                            <input type="text" class="form-control" id="masa_jualan_mula" disabled
                            value="{{ old('masa_jualan_mula', $permohonan?->masa_jualan_mula) }}" />
                        </div> 
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="masa_jualan_tamat">Masa Tamat Jualan</label>
                            <input type="text" class="form-control" id="masa_jualan_tamat" disabled
                            value="{{ old('masa_jualan_tamat', $permohonan?->masa_jualan_tamat) }}" />
                        </div> 
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="makanan">Makanan</label>
                            <textarea class="form-control" id="makanan" rows="4" disabled>{{ old('makanan', $permohonan?->makanan) }}</textarea>
                        </div> 
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="minuman">Minuman</label>
                            <textarea class="form-control" id="minuman" rows="4" disabled>{{ old('minuman', $permohonan?->minuman) }}</textarea>
                        </div> 
                    </div>
                </div>
                <div class="form-group">
                    <label for="lain">Lain-lain</label>
                    <input type="text" class="form-control" id="lain" disabled
                    value="{{ old('lain', $permohonan?->lain) }}" />
                </div>
              </div>    
              <div class="col-md-6">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="longitude">Longitud</label>
                                <input id="longitude" class="form-control" type="text" name="longitude" value="{{ old('longitude', $permohonan?->longitude) }}" autofocus autocomplete="longitude"/>
                            </div>
                        </div> 
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="latitude">Latitud</label>
                                <input id="latitude" class="form-control" type="text" name="latitude" value="{{ old('latitude', $permohonan?->latitude) }}" autofocus autocomplete="latitude"/>
                            </div>
                        </div>
                    </div> 

                    <div class="mt-3">
                        <label>Cari Lokasi (Nominatim)</label>
                        <input type="text" id="searchBox" class="form-control" placeholder="Taip nama tempat… (contoh: Taman Sutera)">
                        <button id="searchBtn" type="button" class="btn btn-primary mt-2"><i class="fa-solid fa-magnifying-glass-location"></i> Cari</button>
                    </div>
                    <div id="viewDiv" style="height: 450px;" class="mt-4"></div>
              </div> 
            </div>  
            <div class="row mt-4">
              <div class="col-md-12 d-flex justify-content-center">
                <input id="hantar" class="btn btn-primary" type="submit" value="Simpan"/>
              </div> 
            </div>  
          </div> 
        </div>   
      </div> 
    </div> 
</form>  

@section('js')

<!-- LEAFLET JS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>

    /* ============================================================
     * 2. LEAFLET MAP + NOMINATIM SEARCH
     * ============================================================ */

    let defaultLat  = {{ $permohonan?->latitude ?? 1.494314512652013 }};
    let defaultLng  = {{ $permohonan?->longitude ?? 103.63506317138673 }};
    let defaultZoom = {{ isset($permohonan?->latitude) ? 16 : 12 }};
    let marker;

    // Init map
    let map = L.map('viewDiv').setView([defaultLat, defaultLng], defaultZoom);

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

    // Letak marker awal jika edit
    if ("{{ $permohonan?->latitude ?? '' }}") {
        marker = L.marker([defaultLat, defaultLng], { draggable: true }).addTo(map);
        marker.on('dragend', updateInputByMarker);
    }

    // Click = create / move marker
    map.on('click', function(e) {
        placeMarker(e.latlng);
        updateInputFromLatLng(e.latlng);
    });

    function placeMarker(latlng) {
        if (!marker) {
            marker = L.marker(latlng, { draggable: true }).addTo(map);
            marker.on('dragend', updateInputByMarker);
        } else {
            marker.setLatLng(latlng);
        }
    }

    function updateInputByMarker(e) {
        updateInputFromLatLng(e.target.getLatLng());
    }

    function updateInputFromLatLng(latlng) {
        $("#latitude").val(latlng.lat);
        $("#longitude").val(latlng.lng);
    }


    /* ============================================================
     * 3. FUNGSI CARI KOORDINAT (NOMINATIM API)
     * ============================================================ */

    function cariKoordinat() {
        let query = $("#searchBox").val();

        if (query.length < 3) {
            alert("Masukkan nama tempat yang lebih spesifik.");
            return;
        }

        fetch("https://nominatim.openstreetmap.org/search?format=json&q=" + query)
            .then(r => r.json())
            .then(data => {
                if (data.length === 0) {
                    alert("Lokasi tak dijumpai.");
                    return;
                }

                let place = data[0];
                let lat = place.lat;
                let lon = place.lon;

                map.setView([lat, lon], 17);
                placeMarker({lat, lng: lon});
                updateInputFromLatLng({lat, lng: lon});
            })
            .catch(err => console.error(err));
    }

    $("#searchBtn").on("click", cariKoordinat);
</script>
@endsection