@extends('layouts.main')
@section('css')
  <link href="https://cdn.jsdelivr.net/npm/ol@v9.0.0/ol.css" rel="stylesheet" >
  <style>
  .modal-fullscreen {
    width: 100vw;
    max-width: none;
    height: 100vh;
    margin: 0;
  }
  .modal-fullscreen .modal-content {
    height: 100%;
    border: 0;
    border-radius: 0;
  }
  #marker {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background:url('{{ asset('assets/images/location.png') }}') no-repeat top center;
    background-size:100%;
    opacity: 1;
    cursor: move;
    z-index: 9000
  }
  </style>
@endsection
@section('content')
  <form action="{{ route('proses_penerima_manfaat') }}" method="post" enctype="multipart/form-data" data-parsley-validate >
    {{ csrf_field() }}
    <div class="card rounded-20">
      <div class="card-body pd-30">
        <div class="row">
          <div class="col-md-3">
            <div style="position:sticky;top:30px;z-index:0">
              <div class="image-wrapper rounded-20" id="logo"  data-tippy-placement="bottom" style="aspect-ratio:1/1;padding:5px" title="Change Image">
                <img src="{{ (!empty($data['penerima-manfaat']->logo) ? asset('storage/'.$data['penerima-manfaat']->logo) : asset('assets/images/image-default.jpg') ) }}" class="rounded-20" alt="" />
                <div class="upload-button" onclick="changeImage('logo')"></div>
                <input class="file-upload" type="file" name="logo" accept="image/*"/>
              </div>
            </div>
          </div>
          <div class="col-md-9">
            <h5 class="mg-b-30">Informasi Sekolah</h5>
            <div class="row row-sm">
              <div class="col-md-4">
                <div class="form-group">
                  <label>NPSN</label>
                  <input type="text" class="form-control numeric" name="npsn" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->npsn : null ) }}" required data-parsley-required-message="NPSN tidak boleh kosong" >
                </div>
              </div>
              <div class="col-md-8">
                <div class="form-group">
                  <label>Nama Sekolah</label>
                  <input type="text" class="form-control" name="nama_sekolah" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->nama_sekolah : null ) }}" required data-parsley-required-message="Nama Sekolah tidak boleh kosong" >
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Status Sekolah</label>
                  <select class="select2" style="width:100%" name="status">
                    @foreach ($data['status'] as $key => $status)
                    <option value="{{ $status }}" {{ (!empty($data['penerima-manfaat']) ? ($data['penerima-manfaat']->status == $status ? 'selected' : '' ) : '' ) }} >{{ $status }}</option>
                    @endforeach
                  </select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Status Kepemilikan</label>
                  <select class="select2" style="width:100%"  name="kepemilikan">
                    @foreach ($data['kepemilikan'] as $label => $kepemilikan)
                    <option value="{{ $label }}" {{ (!empty($data['penerima-manfaat']) ? ($data['penerima-manfaat']->kepemilikan == $label ? 'selected' : '' ) : '' ) }}>{{ $kepemilikan }}</option>
                    @endforeach
                  </select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Bentuk Sekolah</label>
                  <select class="select2" style="width:100%" name="bentuk">
                    @foreach ($data['bentuk'] as $label => $bentuk)
                    <option value="{{ $label }}" {{ (!empty($data['penerima-manfaat']) ? ($data['penerima-manfaat']->bentuk == $label ? 'selected' : '' ) : '' ) }} >{{ $bentuk }}</option>
                    @endforeach
                  </select>
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-md-8">
                <div class="form-group">
                  <label>No. SK Pendirian</label>
                  <input type="text" class="form-control" name="sk_pendirian" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->sk_pendirian : null ) }}" required data-parsley-required-message="SK Pendirian tidak boleh kosong" >
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Tanggal SK Pendirian</label>
                  <input
                    type="text" class="form-control datepicker"
                    autocomplete="off" id="tanggal" name="tanggal_pendirian"
                    value="{{ (!empty($data['penerima-manfaat']) ? GlobalHelper::dateFormat($data['penerima-manfaat']->tanggal_pendirian,'d-m-Y') : null ) }}"
                    required data-parsley-required-message="Tanggal tidak boleh kosong"
                    data-parsley-dateformat data-parsley-dateformat-message="Tanggal harus dalam format dd-mm-yyyy."
                  >
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-md-8">
                <div class="form-group">
                  <label>No. SK Izin Operasional</label>
                  <input type="text" class="form-control" name="sk_izin_operasional" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->sk_izin_operasional : null ) }}" required data-parsley-required-message="SK Izin Operasional tidak boleh kosong">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Tanggal SK Izin Operasional</label>
                  <input
                    type="text" class="form-control datepicker"
                    autocomplete="off" id="tanggal" name="tanggal_izin_operasional"
                    value="{{ (!empty($data['penerima-manfaat']) ? GlobalHelper::dateFormat($data['penerima-manfaat']->tanggal_izin_operasional,'d-m-Y') : null ) }}"
                    required data-parsley-required-message="Tanggal tidak boleh kosong"
                    data-parsley-dateformat data-parsley-dateformat-message="Tanggal harus dalam format dd-mm-yyyy."
                  >
                </div>
              </div>
            </div>

            <hr>

            <h5 class="mg-b-30 mg-t-30">Informasi Alamat dan Kontak</h5>
            <div class="form-group" id="info_alamat">
              <label>Titik Kordinat</label>
              <div class="row row-sm">
                <div class="col-md-4">
                  <input type="text" class="form-control" name="latitude" placeholder="Latitude" id="latitude" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->latitude : null ) }}" required data-parsley-required-message="Latitude tidak boleh kosong" >
                </div>
                <div class="col-md-4">
                  <input type="text" class="form-control" name="longitude" placeholder="Longitude" id="longitude" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->longitude : null ) }}" required data-parsley-required-message="Longitude tidak boleh kosong">
                </div>
                <div class="col-md-4">
                  <button type="button" class="btn btn-block btn-dark" onclick="open_modal_map()">Tentukan Titik Kordinat</button>
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-md-12">
                <div class="form-group">
                  <label>Alamat Lengkap</label>
                  <input type="text" class="form-control" name="alamat" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->alamat : null ) }}" required data-parsley-required-message="Alamat tidak boleh kosong">
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Provinsi</label>
                  <select class="form-control select2" name="provinsi" id="provinsi"></select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Kabupaten/Kota</label>
                  <select class="form-control select2" name="kabupaten" id="kabupaten"></select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Kecamatan</label>
                  <select class="form-control select2" name="kecamatan" id="kecamatan"></select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Desa/Kelurahan</label>
                  <select class="form-control select2" name="desa" id="desa"></select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Kode POS</label>
                  <input type="text" class="form-control numeric" name="kode_pos" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->kode_pos : null ) }}" required data-parsley-required-message="Kode POS tidak boleh kosong" >
                </div>
              </div>
              <div class="col-md-2">
                <div class="form-group">
                  <label>RT</label>
                  <input type="text" class="form-control numeric" name="rt" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->rt : null ) }}" required data-parsley-required-message="No RT tidak boleh kosong">
                </div>
              </div>
              <div class="col-md-2">
                <div class="form-group">
                  <label>RW</label>
                  <input type="text" class="form-control numeric" name="rw" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->rw : null ) }}" required data-parsley-required-message="No RW tidak boleh kosong">
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Nama PIC</label>
                  <input type="text" class="form-control" name="nama_pic" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->nama_pic : null ) }}" required data-parsley-required-message="Nama PIC tidak boleh kosong">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>No. Telephone</label>
                  <input type="text" class="form-control numeric" name="no_telephone" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->no_telephone : null ) }}" required data-parsley-required-message="No. Telephone tidak boleh kosong">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Email</label>
                  <input type="email" class="form-control" id="email" name="email" required data-parsley-required-message="Email tidak boleh kosong" data-parsley-type="email" data-parsley-type-message="Masukkan email yang valid, contoh: user@example.com." >
                </div>
              </div>
            </div>

            @if(empty($data['penerima-manfaat']))
            <hr>

            <h5 class="mg-b-30 mg-t-30">Informasi Peserta Didik</h5>

            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <label>Pilih Semester</label>
                  <select class="form-control select2" name="semester" >
                    @foreach ($data['semester'] as $key => $value)
                    <option value="{{ $value->id }}">Semester {{ $value->semester }} {{ $value->tahun_pelajaran }}</option>
                    @endforeach
                  </select>
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group">
                  <label>Jumlah Laki-Laki</label>
                  <input type="text" class="form-control numeric" name="jumlah_laki_laki" required data-parsley-required-message="Jumlah Siswa Laki-Laki tidak boleh kosong">
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group">
                  <label>Jumlah Perempuan</label>
                  <input type="text" class="form-control numeric" name="jumlah_perempuan" required data-parsley-required-message="Jumlah Siswa Perempuan tidak boleh kosong">
                </div>
              </div>
            </div>
            @endif
            <hr>
            <div class="pull-right">
              <input type="hidden" name="id" value="{{ (!empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->id : 0) }}">
              <a class="btn btn-dark" href="{{ route('penerima_manfaat') }}">Kembali</a>
              <button class="btn btn-primary" name="action" value="{{ (!empty($data['penerima-manfaat']) ? 'edit' : 'add') }}" >Simpan</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>

  <div class="modal fade" id="get_position" role="dialog">
    <div class="modal-dialog modal-fullscreen">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Tentukan Titik Koordinat</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div id="map" style="width:100%;height:100%"></div>
          <div id="marker"></div>
        </div>
        <div class="modal-footer">
          <div class="input-group w-400px">
            <input type="text" class="form-control" name="latitude" id="latitude" placeholder="Latitude" value="{{ (!empty($data['penerima-manfaat']->latitude) ? $data['penerima-manfaat']->latitude : '-7.2080393' ) }}" />
            <input type="text" class="form-control" name="longitude" id="longitude" placeholder="Longitude" value="{{ (!empty($data['penerima-manfaat']->longitude) ? $data['penerima-manfaat']->longitude : '113.0312995' ) }}" />
          </div>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Kembali</button>
          <button type="button" class="btn btn-success" onclick="add_coordinate()">Simpan</button>
        </div>
      </div>
    </div>
  </div>

@endsection
@section('js')
<script src="https://cdn.jsdelivr.net/npm/ol@v9.0.0/dist/ol.js"></script>
<script>

  Parsley.addValidator('dateformat', {
    validateString: function (value) {
      // Regex untuk format tanggal d-m-Y
      const dateRegex = /^([0-2][0-9]|(3)[0-1])-((0)[0-9]|(1)[0-2])-\d{4}$/;
      return dateRegex.test(value); // Valid jika regex cocok
    },
    messages: {
      en: "The date must be in the format dd-mm-yyyy.",
      id: "Tanggal harus dalam format dd-mm-yyyy."
    }
  });

  //basic config map
  var pos = ol.proj.fromLonLat([{{ (!empty($data['penerima-manfaat']->longitude) ? $data['penerima-manfaat']->longitude : '113.0312995' ) }},{{ (!empty($data['penerima-manfaat']->latitude) ? $data['penerima-manfaat']->latitude : '-7.2080393' ) }}]);
  var layer = new ol.layer.Tile({
    source: new ol.source.OSM()
  });
  var map = new ol.Map({
    layers: [layer],
    target: 'map',
    view: new ol.View({
      center: pos,
      zoom: 15
    })
  });
  var marker_el = document.getElementById('marker');
  var marker = new ol.Overlay({
    position: pos,
    positioning: 'center-center',
    element: marker_el,
    stopEvent: false,
    dragging: false
  });
  map.addOverlay(marker);

  // drag action
  var dragPan;
  map.getInteractions().forEach(function(interaction){
    if (interaction instanceof ol.interaction.DragPan) {
      dragPan = interaction;
    }
  });

  // drag pin
  marker_el.addEventListener('mousedown', function(evt) {
    dragPan.setActive(false);
    marker.set('dragging', true);
    console.info('start dragging');
  });

  map.on('pointermove', function(evt) {
    if (marker.get('dragging') === true) {
      marker.setPosition(evt.coordinate);
      var coordinate = evt.coordinate;
      var lonLat = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326');
      $('#get_position #latitude').val(lonLat[1]);
      $('#get_position #longitude').val(lonLat[0]);
    }
  });

  map.on('pointerup', function(evt) {
    if (marker.get('dragging') === true) {
      dragPan.setActive(true);
      marker.set('dragging', false);
      var coordinate = evt.coordinate;
      var lonLat = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326');
      $('#get_position #latitude').val(lonLat[1]);
      $('#get_position #longitude').val(lonLat[0]);
    }
  });

  // onclick marker
  map.on('click', function(evt,popup){
    marker.setPosition(evt.coordinate);
    marker.set('dragging', false);
    var coordinate = evt.coordinate;
    var lonLat = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326');
    $('#get_position #latitude').val(lonLat[1]);
    $('#get_position #longitude').val(lonLat[0]);
  });

  function add_coordinate(){
    $('#info_alamat #latitude').val($('#get_position #latitude').val());
    $('#info_alamat #longitude').val($('#get_position #longitude').val());
    $('#get_position').modal('hide');
  }

  function open_modal_map(){
    $('#get_position').modal('show');
  }



  function getLocation(select_target, level, parent_id, selected ){
      $.get("{{ url('api/get_wilayah') }}/"+level+"/"+parent_id+"/"+selected, function (result) {
        $selectElement = $('#'+select_target);
        $selectElement.empty();
        $.each(result.data, function (i, value) {
          $selectElement.append('<option data-id="'+value.id+'" value="'+value.id+'">'+value.nama_wilayah+'</option>');
        });
        if(result.selected != null ){
          $selectElement.val(selected);
          $selectElement.select2();
        }
        $selectElement.trigger('change');
      });
    }

    getLocation('provinsi','1', '0', {{ ( !empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->fid_provinsi : 0 ) }});
    $('#provinsi').change(function () {
      let id = $(this).find('option:selected').attr('data-id');
      getLocation('kabupaten', '2', id, {{ ( !empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->fid_kabupaten : 0 ) }} );
    });
    $('#kabupaten').change(function () {
      let id = $(this).find('option:selected').attr('data-id');
      getLocation('kecamatan', '3', id, {{ ( !empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->fid_kecamatan : 0 ) }} );
    });
    $('#kecamatan').change(function () {
      let id = $(this).find('option:selected').attr('data-id');
      getLocation('desa', '4', id, {{ ( !empty($data['penerima-manfaat']) ? $data['penerima-manfaat']->fid_desa : 0 ) }} );
    });
</script>
@endsection
