@extends('layouts.appmin')

@section('tajuk')
Permohonan Lesen Penjaja
@endsection

@section('css')

    <!-- Select2 -->
    <link rel="stylesheet" href="{{ asset('plugins/select2/css/select2.min.css') }}">
    <link rel="stylesheet" href="{{ asset('plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css') }}">
<link href="{{ asset('css/jsapi-template-main.css') }}" rel="stylesheet" type="text/css"/>
<link href="https://js.arcgis.com/4.25/esri/css/main.css" rel="stylesheet" type="text/css" />
<style>
#viewDiv {
  padding: 0;
  margin: 0;
  height: 500px;
  width: 100%;
}
</style>
@endsection


@section('breadcrumb')
<ul class="breadcrumbs mb-3">
    <li class="nav-home">
        <a href="#">
        <i class="icon-home"></i>
        </a>
    </li>
    <li class="separator">
        <i class="icon-arrow-right"></i>
    </li>
    <li class="nav-item">
        <a href="#">Penjaja</a>
    </li>
    <li class="separator">
        <i class="icon-arrow-right"></i>
    </li>
    <li class="nav-item">
        <a href="#">Pemeriksaan Tapak</a>
    </li>
    <li class="separator">
        <i class="icon-arrow-right"></i>
    </li>
    <li class="nav-item">
        <a href="#">Papar Permohonan</a>
    </li>
</ul>
@endsection

@section('content')

    @if (session('success'))
        <div class="alert alert-success" role="alert">
            {{ session('success') }}
        </div>
    @endif  
    <div class="row mb-3">
        <div class="col-md-12">
            <a href="" class="btn btn-primary mx-2">Permohonan</a>
            <a href="{{route('ik.papar-pemeriksaan-map', [$permohonan->id])}}" class="btn btn-primary mx-2">Peta Lokasi</a>
            <a href="{{route('ik.papar-pemeriksaan-ulasan', [$permohonan->id])}}" class="btn btn-primary mx-2">Ulasan PPK</a>
            <a href="{{route('ik.papar-pemeriksaan-ulasan', [$permohonan->id])}}" class="btn btn-primary mx-2">Ulasan Pegawai</a>
            <a href="{{route('ik.papar-pemeriksaan-ulasan', [$permohonan->id])}}" class="btn btn-primary mx-2">Ulasan Pengarah</a>
        </div>
    </div>
    <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">Peta Lokasi</h4>
              </div>
            </div> <!-- /.card-header -->
            <div class="card-body">
                <form action="{{route('ik.simpan-lokasi', [$permohonan->id])}}" method="post">
                  @csrf
                  <input type="hidden" name="permohonan_id" value="{{$permohonan->id}}">
                  <div class="row">
                      <div class="col-md-5">
                          <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-5">
                          <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 class="col-md-2">
                          <div class="mb-3">
                              <br />
                              <input id="simpan" class="btn btn-secondary" type="submit" name="simpan" value="Kemaskini" autofocus autocomplete="latitude"/>
                          </div>
                      </div>
                  </div> 
                </form>
                <div id="viewDiv"></div>
            </div>
        </div> <!-- /.col -->               
    </div> <!--end::Row-->
@endsection

@section('js')
  <!-- Select2 -->
    <script src="{{ asset('plugins/select2/js/select2.full.min.js') }}"></script>
    <script type="text/javascript" src="https://js.arcgis.com/4.25/"></script>

    <script type="text/javascript">
	

require([
"esri/Map",
"esri/views/MapView",
"esri/widgets/Home",
"esri/widgets/ScaleBar",
"esri/widgets/LayerList",
"esri/widgets/Legend",
"esri/widgets/Expand",
"esri/widgets/Compass",
"esri/layers/Layer",
  "esri/layers/GraphicsLayer", 
  "esri/Graphic",
      "esri/geometry/support/webMercatorUtils"
], (
Map, MapView, Home, ScaleBar, LayerList, Legend,
Expand, Compass, Layer, GraphicsLayer, Graphic, webMercatorUtils
) => {
  const layerUrl = "https://onemap.mbip.gov.my/arcgis/rest/services/Hosted/Maklumat_Lot/FeatureServer";
  const map = new Map({basemap: "topo-vector"});
  const view = new MapView({
    container: "viewDiv",
    map: map,    
    center: [<?php if(!is_null($permohonan->longitude)){ echo $permohonan->longitude; } else{ echo '103.576'; } ?>, <?php if(!is_null($permohonan->latitude)){ echo $permohonan->latitude; } else{ echo '1.555'; } ?>] ,
    zoom: 16  
  });


      //Construct a SimpleMarkerSymbol object
      var markerSymbol = {
        type: "simple-marker",
        color:[226,15,5],
        outline:{
            color:[255,255,255],
            width:2
        }
      };  

    
      <?php
      if(!is_null($permohonan->longitude)){
      ?>
      //Construct a point object
      var point1 = {
          type:"point",
          longitude:<?php if(!is_null($permohonan->longitude)){ echo $permohonan->longitude; } else{ echo '103.576'; } ?>,
          latitude:<?php if(!is_null($permohonan->latitude)){ echo $permohonan->latitude; } else{ echo '1.555'; } ?>
      };

      //Construct a Graphic object
      var graphic1 = new Graphic({
          geometry:point1,
          symbol: markerSymbol
      });
      

      makeGraphicDraggable(graphic1);
      // Construct a GraphicsLayer with Graphic objects
      var layer = new GraphicsLayer({
          graphics: [graphic1]
      });
      <?php
      }
      else{
        ?>
        // Construct a GraphicsLayer with Graphic objects
        var layer = new GraphicsLayer({
            graphics: []
        });
        <?php
      }
      ?>    

      layer.title = "Kedudukan Projek";

  createFeatureLayers(layerUrl);

  async function createFeatureLayers(url) {
    const featureService = await Layer.fromArcGISServerUrl(url);

    map.add(featureService);    
    map.add(layer);
  }


      // Function to make graphics draggable
      function makeGraphicDraggable(graphic) {
        let moveGraphic = false;

        view.on("drag", (event) => {
            
          if (moveGraphic) {
            event.stopPropagation();
            const point = view.toMap({ x: event.x, y: event.y });
            graphic.geometry = point;
          }
        });

        view.on("pointer-down", (event) => {
          const screenPoint = { x: event.x, y: event.y };
          view.hitTest(screenPoint).then((response) => {
            if (response.results.length > 0 && response.results[0].graphic === graphic) {
              moveGraphic = true;
            }
          });
        });

        view.on("pointer-up", () => {
          if (moveGraphic) {
            const { longitude, latitude } = webMercatorUtils.webMercatorToGeographic(graphic.geometry);
            console.log(`New position - Longitude: ${longitude}, Latitude: ${latitude}`);

            $("#latitude").val(latitude);
            $("#longitude").val(longitude);
            moveGraphic = false;
          }
        });
      }

      
      // Add a new marker on map click if no marker exists
      view.on("click", (event) => {
        if (layer.graphics.length === 0) {
          const point = view.toMap({ x: event.x, y: event.y });
          const newGraphic = new Graphic({
            geometry: point,
            symbol: markerSymbol
          });
          layer.add(newGraphic);
          makeGraphicDraggable(newGraphic);
          const { longitude, latitude } = webMercatorUtils.webMercatorToGeographic(newGraphic.geometry);
          console.log(`Added marker at - Longitude: ${longitude}, Latitude: ${latitude}`);

          $("#latitude").val(latitude);
          $("#longitude").val(longitude);

            $("#waze").attr('href', 'https://waze.com/ul?ll='+latitude+','+longitude+'&z=10');
        } else {
          console.log('Marker already exists.');
        }
      });


  const homeBtn = new Home({
    view: view
  });
  const scaleBar = new ScaleBar({
    view: view,
    unit: "dual"
  });
  const layerList = new LayerList({
    view: view
  });
  const legend = new Legend({
    view: view
  });
  const layerListExpand = new Expand({
    view: view,
    content: layerList,
    expanded: false,
    expandTooltip: "Expand LayerList"
  });
  const legendExpand = new Expand({
    view: view,
    content: legend,
    expandTooltip: "Expand Legend",
    expanded: false
  });
  const compass = new Compass({
    view: view,
    visible: false
  });
  view.ui.add(homeBtn, "top-left");
  view.ui.add(scaleBar, "bottom-right");
  view.ui.add(layerListExpand, "top-right");
  view.ui.add(legendExpand, "bottom-left");
  view.ui.add(compass, "top-left");
  // load the Compass only when the view is rotated
  view.watch('rotation', function (rotation) {
    if (rotation && !compass.visible) {
      compass.visible = true;
    }
  });
});
</script>
@endsection