<?= $this->include('user/layout/header') ?>


<!-- Page Title -->
<div class="page-title" data-aos="fade">
  <div class="container">
    <nav class="breadcrumbs">
      <ol>
        <li><a href="<?= base_url('/') ?>">Beranda</a></li>
        <li class="current">WebGIS</li>
      </ol>
    </nav>
    <h1><?= $peta['judul'] ?></h1>
  </div>
</div><!-- End Page Title -->

<section class="section">
  <div class="container">

    <div class="row">

      <!-- PETA -->
      <div class="col-lg-12">
        <div class="card shadow-sm">
          <div id="map" style="height:650px;"></div>

        </div>

      </div>

    </div>

  </div>
</section>

<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />


<style>
  /* ==========================================
   LAYER CONTROL TITIK KEJADIAN BANJIR
   ========================================== */

  .leaflet-control-layers {
    background: #fff !important;
    border: none !important;
    border-radius: 8px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, .25) !important;
    padding: 8px 10px !important;
    font-size: 13px;
  }

  /* Bagian daftar layer */
  .leaflet-control-layers-list {
    margin: 0 !important;
    padding: 0 !important;
  }

  /* Label checkbox */
  .leaflet-control-layers-overlays label {
    display: flex !important;
    align-items: center !important;
    gap: 7px !important;

    margin: 0 !important;
    padding: 5px 4px !important;

    cursor: pointer;

    color: #333;
    font-size: 13px;
    font-weight: 600;

    white-space: nowrap;
  }

  /* Checkbox */
  .leaflet-control-layers-overlays input[type="checkbox"] {
    width: 16px !important;
    height: 16px !important;

    margin: 0 !important;

    cursor: pointer;

    accent-color: #dc3545;
  }

  /* Hover */
  .leaflet-control-layers-overlays label:hover {
    background: #f5f5f5;
    border-radius: 5px;
  }

  /* Tulisan */
  .leaflet-control-layers-overlays label span {
    vertical-align: middle;
  }


  .label-desa {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    text-shadow:
      -1px -1px 0 #fff,
      1px -1px 0 #fff,
      -1px 1px 0 #fff,
      1px 1px 0 #fff;
  }

  .leaflet-control.custom-control {
    background: #fff;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, .25);
    min-width: 240px;
  }

  .leaflet-control.custom-control h6 {
    margin: 0 0 8px;
    font-weight: bold;
  }

  .leaflet-control.custom-control select {
    width: 100%;
  }

  .legend-item {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
  }

  .legend-color {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    border: 1px solid #888;
  }

  .leaflet-bar a {
    width: 34px;
    height: 34px;
    line-height: 34px;
    text-align: center;
    font-size: 18px;
  }

  .leaflet-control.custom-control {
    background: #fff;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, .25);
    font-size: 13px;
  }

  .label-banjir {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    color: #000000;
    font-size: 12px;
    font-weight: bold;
    text-align: center;
    white-space: nowrap;

    text-shadow:
      -1px -1px 0 #fff,
      1px -1px 0 #fff,
      -1px 1px 0 #fff,
      1px 1px 0 #fff;
  }
</style>

<?php
$warnaSawah = '#4CAF50';

foreach ($lahan as $l) {
  if (strtolower($l['kelas']) == 'sawah') {
    $warnaSawah = $l['warna_peta'];
    break;
  }
}
?>

<script>
  const legendData = {

    rawan: [

      {
        warna: "#0cbe12",
        nama: "Aman"
      },

      {
        warna: "#4fc751",
        nama: "Risiko Rendah"
      },

      {
        warna: "#FFD600",
        nama: "Risiko Sedang"
      },

      {
        warna: "#ff8800",
        nama: "Risiko Tinggi"
      },

      {
        warna: "#ff1100",
        nama: "Sangat Rawan"
      },

      {
        marker: true,
        nama: "Titik Kejadian Banjir"
      }

    ],

    kemiringan: [

      <?php foreach ($kemiringan as $k): ?>

        {

          warna: "<?= $k['warna_peta'] ?>",

          nama: "<?= $k['kategori'] ?>"

        },

      <?php endforeach; ?>

    ],

    lahan: [

      <?php foreach ($lahan as $l): ?>

        {

          warna: "<?= $l['warna_peta'] ?>",

          nama: "<?= $l['kelas'] ?>"

        },

      <?php endforeach; ?>

    ],

    tanah: [

      <?php foreach ($jenis_tanah as $t): ?>

        {

          warna: "<?= $t['warna_peta'] ?>",

          nama: "<?= $t['jenis_tanah'] ?>"

        },

      <?php endforeach; ?>

    ],

    geologi: [

      <?php foreach ($geologi as $g): ?>

        {

          warna: "<?= $g['warna_peta'] ?>",

          nama: "<?= $g['jenis_geologi'] ?>"

        },

      <?php endforeach; ?>

    ],

    curah: [

      {

        warna: "#1975ff",

        nama: ">3000 mm/tahun"

      }

    ]

  };


  function tampilkanLegend(mode) {

    let html = "";

    if (!legendData[mode]) return;

    legendData[mode].forEach(function(item) {

      // LEGEND MARKER KEJADIAN BANJIR
      if (item.marker) {

        html += `
        <div style="
          margin-bottom:6px;
          display:flex;
          align-items:center;
        ">

          <img
            src="<?= base_url('uploads/banjir/banjir.png') ?>"
            style="
              width:25px;
              height:25px;
              object-fit:contain;
              margin-right:6px;
            "
          >

          <span>${item.nama}</span>

        </div>
      `;

      } else {

        html += `
        <div style="
          margin-bottom:6px;
          display:flex;
          align-items:center;
        ">

          <span style="
            display:inline-block;
            width:20px;
            height:20px;
            background:${item.warna};
            border:1px solid #999;
            margin-right:8px;
          "></span>

          <span>${item.nama}</span>

        </div>
      `;

      }

    });

    document.getElementById("legendContainer").innerHTML = html;

  }
</script>


<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw/dist/leaflet.draw.css">
<script src="https://unpkg.com/leaflet-draw/dist/leaflet.draw.js"></script>

<script>
  const dataKejadian = <?= json_encode($kejadian) ?>;
</script>

<script>
  const lokasiBanjir = <?= json_encode($lokasiBanjir ?? []) ?>;
</script>


<script>
  var map = L.map('map').setView([-3.3556, 120.2349], 11);

  var drawnItems = new L.FeatureGroup();
  map.addLayer(drawnItems);

  var kontrolLayer = L.control({
    position: 'topleft'
  });

  kontrolLayer.onAdd = function() {

    var div = L.DomUtil.create('div', 'leaflet-control custom-control');

    div.innerHTML = `

<h6 style="margin-bottom:10px;">
    Tampilan Peta
</h6>

<div>

<label style="display:block;margin-bottom:6px;">
<input type="radio" name="modePeta" value="kemiringan" checked>
 Kemiringan Lereng
</label>

<label style="display:block;margin-bottom:6px;">
<input type="radio" name="modePeta" value="lahan">
 Penggunaan Lahan
</label>

<label style="display:block;margin-bottom:6px;">
<input type="radio" name="modePeta" value="tanah">
 Jenis Tanah
</label>

<label style="display:block;margin-bottom:6px;">
<input type="radio" name="modePeta" value="geologi">
 Geologi
</label>

<label style="display:block;margin-bottom:6px;">
<input type="radio" name="modePeta" value="curah">
 Curah Hujan
</label>

<label style="display:block;">
<input type="radio" name="modePeta" value="rawan">
 Zonasi Kerawanan
</label>

</div>

`;

    L.DomEvent.disableClickPropagation(div);

    return div;

  };

  kontrolLayer.addTo(map);


  var drawControl = new L.Control.Draw({

    position: "topright",

    draw: {

      polygon: true,

      polyline: true,

      rectangle: true,

      circle: false,

      circlemarker: false,

      marker: true

    },

    edit: {

      featureGroup: drawnItems

    }

  });

  map.addControl(drawControl);



  map.on(L.Draw.Event.CREATED, function(e) {

    var layer = e.layer;

    drawnItems.addLayer(layer);

  });


  function simpanGeoJSON() {

    var data = drawnItems.toGeoJSON();

    fetch("<?= base_url('user/simpan_polygon') ?>", {

        method: "POST",

        headers: {
          "Content-Type": "application/json"
        },

        body: JSON.stringify(data)

      })

      .then(res => res.json())
      .then(res => {

        alert("Berhasil disimpan\n" + res.file);

      });;

  }


  var simpan = L.control({
    position: 'topright'
  });

  simpan.onAdd = function() {

    var div = L.DomUtil.create('div', 'leaflet-bar');

    div.innerHTML = '<a href="#" title="Simpan">💾</a>';

    div.onclick = function() {

      simpanGeoJSON();

    };

    return div;

  }

  simpan.addTo(map);


  var legendControl = L.control({
    position: 'topleft'
  });

  legendControl.onAdd = function() {

    var div = L.DomUtil.create('div', 'leaflet-control custom-control');

    div.innerHTML = `

        <h6>Keterangan Warna</h6>

        <div id="legendContainer"></div>

    `;

    return div;

  };

  legendControl.addTo(map);

  L.tileLayer(
    'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: '&copy; Webgis Banjir Bandang Kec. Bajo Barat'
    }
  ).addTo(map);


  //==========================================
  // KONTROL ZOOM
  //==========================================
  map.zoomControl.remove();

  L.control.zoom({
    position: 'topright'
  }).addTo(map);

  //==========================================
  // SCALE / SKALA JARAK
  //==========================================
  L.control.scale({
    imperial: false,
    position: 'bottomright'
  }).addTo(map);

  //==========================================
  // TOMBOL HOME (RESET VIEW)
  //==========================================
  var home = L.control({
    position: 'topright'
  });

  home.onAdd = function() {

    var div = L.DomUtil.create(
      'div',
      'leaflet-bar leaflet-control'
    );

    div.innerHTML =
      '<a href="#" title="Kembali ke Wilayah Awal" style="font-size:20px;font-weight:bold;">⌂</a>';

    L.DomEvent.disableClickPropagation(div);

    div.onclick = function() {

      if (geojsonLayer) {
        map.fitBounds(geojsonLayer.getBounds());
      }

    };

    return div;

  };

  home.addTo(map);

  //==========================================
  // KOORDINAT MOUSE
  //==========================================
  var koordinat = L.control({
    position: 'bottomleft'
  });

  koordinat.onAdd = function() {

    this._div = L.DomUtil.create(
      'div',
      'leaflet-control custom-control'
    );

    this.update();

    return this._div;

  };

  koordinat.update = function(lat, lng) {

    if (lat) {

      this._div.innerHTML =
        "<b>Koordinat</b><br>" +
        "Lat : " + lat.toFixed(6) +
        "<br>Lng : " + lng.toFixed(6);

    } else {

      this._div.innerHTML =
        "<b>Koordinat</b><br>Gerakkan mouse";

    }

  };

  koordinat.addTo(map);

  map.on("mousemove", function(e) {

    koordinat.update(
      e.latlng.lat,
      e.latlng.lng
    );

  });



  function cariKejadian(namaDesa) {
    let html = "";

    dataKejadian.forEach(function(item) {

      if (item.keterangan.toLowerCase().includes(namaDesa.toLowerCase())) {
        html += `
            <hr>
            <b>Tahun :</b> ${item.tahun} Kejadian Banjir<br>
            <b>Sumber :</b> ${item.sumber}<br>
            <pre style="white-space:pre-wrap;margin:0;">
${item.keterangan}
            </pre>
            `;
      }

    });

    if (html == "") {
      html = `
        <hr>
        <i>Tidak ada data kejadian banjir.</i>
        `;
    }

    return html;
  }


  //==========================================
  // ICON MARKER
  //==========================================

  var iconWilayah = L.icon({

    iconUrl: "<?= base_url('uploads/wilayah/marker.png') ?>",

    iconSize: [35, 35],
    iconAnchor: [17, 35],
    popupAnchor: [0, -35]

  });

  //==========================================
  // ICON LOKASI KEJADIAN BANJIR
  //==========================================

  var iconBanjir = L.icon({

    iconUrl: "<?= base_url('uploads/banjir/banjir.png') ?>",

    iconSize: [40, 40],

    iconAnchor: [20, 40],

    popupAnchor: [0, -40]

  });


  //==========================================
  // MODE PETA
  //==========================================

  let modePeta = "kemiringan";

  let geojsonLayer;
  tampilkanLegend(modePeta);



  //==========================================
  // LAYER LOKASI KEJADIAN BANJIR
  //==========================================

  var layerLokasiBanjir = L.layerGroup();

  //==========================================
  // LAYER CONTROL TITIK KEJADIAN BANJIR
  //==========================================

  var kontrolKejadian = L.control.layers(
    null, {
      "🌊 Titik Kejadian Banjir": layerLokasiBanjir
    }, {
      position: 'topright',
      collapsed: false
    }
  );

  //==========================================
  // TAMPILKAN MARKER BANJIR
  //==========================================

  function tampilkanLokasiBanjir() {

    // Hapus marker lama
    layerLokasiBanjir.clearLayers();

    // Marker hanya digunakan pada mode Zonasi Kerawanan
    if (modePeta !== "rawan") {
      return;
    }

    lokasiBanjir.forEach(function(item) {

      let lat = parseFloat(item.latitude);
      let lng = parseFloat(item.longitude);

      if (isNaN(lat) || isNaN(lng)) {
        return;
      }

      //======================================
      // MARKER
      //======================================

      let marker = L.marker(
        [lat, lng], {
          icon: iconBanjir
        }
      );

      //======================================
      // LABEL MARKER
      //======================================

      let labelMarker = item.marker ?
        item.marker :
        "Banjir";

      let labelDesa = item.desa ?
        item.desa :
        "-";

      let tahun = item.tahun ?
        item.tahun :
        "-";

      marker.bindTooltip(

        `
      <div>
          ${labelMarker}<br>
          ${labelDesa} (${tahun})
      </div>
      `,

        {
          permanent: true,
          direction: "bottom",
          offset: [0, 10],
          className: "label-banjir"
        }

      );

      //======================================
      // POPUP
      //======================================

      let popup = `

      <div style="min-width:250px">

        <h6>
          🌊 <b>Lokasi Kejadian Banjir</b>
        </h6>

        <hr style="margin:5px 0;">

        <b>Marker:</b>
        ${labelMarker}

        <br>

        <b>Desa:</b>
        ${labelDesa}

        <br>

        <b>Tahun:</b>
        ${tahun}

        <br>

        <b>Latitude:</b>
        ${lat}

        <br>

        <b>Longitude:</b>
        ${lng}

        ${
          item.keterangan
          ?
          `
          <hr style="margin:5px 0;">

          <b>Keterangan:</b>

          <br>

          ${item.keterangan}
          `
          :
          ''
        }

      </div>

    `;

      marker.bindPopup(popup);

      //======================================
      // MASUKKAN KE LAYER
      //======================================

      marker.addTo(layerLokasiBanjir);

    });

  }



  //==========================================
  // STYLE PETA
  //==========================================

  function stylePeta(feature) {

    let warna = "#999";

    if (modePeta == "kemiringan") {

      let raw = feature.properties.Kemiringan ?? "";
      let angka = 0;

      if (raw.includes(">")) {

        angka = parseFloat(raw.replace(/[^\d.]/g, "")) || 0;

      } else if (raw.includes("-")) {

        angka = parseFloat(raw.split("-")[0]) || 0;

      } else {

        angka = parseFloat(raw) || 0;

      }

      <?php foreach ($kemiringan as $k): ?>

        if (
          angka >= <?= $k['nilai_min'] ?> &&
          angka <= <?= $k['nilai_max'] ?>
        ) {
          warna = "<?= $k['warna_peta'] ?>";
        }

      <?php endforeach; ?>

    } else if (modePeta == "lahan") {

      let penggunaan = (feature.properties.Penggunaan ?? "").toLowerCase();

      <?php foreach ($lahan as $l): ?>

        if (
          penggunaan == "<?= strtolower($l['kelas']) ?>"
        ) {
          warna = "<?= $l['warna_peta'] ?>";
        }

      <?php endforeach; ?>

      if (penggunaan == "sawah/ladang") {
        warna = "<?= $warnaSawah ?>";
      }

    } else if (modePeta == "tanah") {

      let tanah = (feature.properties.Jenis_Tana ?? "").toLowerCase();

      <?php foreach ($jenis_tanah as $t): ?>

        if (

          tanah.includes("<?= strtolower(str_replace('Orthic ', '', str_replace('Dystric ', '', $t['jenis_tanah']))) ?>")

        ) {

          warna = "<?= $t['warna_peta'] ?>";

        }

      <?php endforeach; ?>

    } else if (modePeta == "geologi") {

      let nama = (feature.properties.NAME ?? "").toLowerCase();

      let formasi = (feature.properties.FORMATION ?? "").toLowerCase();

      <?php foreach ($geologi as $g): ?>

        if (

          nama.includes("<?= strtolower($g['jenis_geologi']) ?>") ||

          formasi.includes("<?= strtolower($g['jenis_geologi']) ?>")

        ) {

          warna = "<?= $g['warna_peta'] ?>";

        }

      <?php endforeach; ?>

    } else if (modePeta == "curah") {

      let curah = (feature.properties.Curah_Huja ?? "").toLowerCase();

      if (curah.includes(">3000")) {

        warna = "#1975ff";

      }

    } else if (modePeta == "rawan") {

      let kelas = (
        feature.properties.KELAS_RAWA ??
        feature.properties.KELAS ??
        ""
      ).toLowerCase();

      if (kelas == "aman") {

        warna = "#0cbe12"; // Hijau

      } else if (kelas == "risiko rendah") {

        warna = "#4fc751"; // Hijau muda

      } else if (kelas == "risiko sedang") {

        warna = "#FFD600"; // Kuning

      } else if (kelas == "risiko tinggi") {

        warna = "#ff8800"; // Oranye

      } else if (kelas == "sangat rawan") {

        warna = "#ff1100"; // Merah

      }

    }

    return {

      color: warna,
      weight: 1.5,
      opacity: 1,

      fillColor: warna,
      fillOpacity: 0.9,

      lineJoin: "round",
      lineCap: "round",
      smoothFactor: 2

    };

  }


  //==========================================
  // EVENT RADIO BUTTON
  //==========================================

  document.addEventListener("change", function(e) {

    if (e.target.name == "modePeta") {

      modePeta = e.target.value;

      tampilkanLegend(modePeta);

      if (geojsonLayer) {

        geojsonLayer.setStyle(stylePeta);

      }

      //==========================================
      // LAYER TITIK KEJADIAN
      // HANYA PADA ZONASI KERAWANAN
      //==========================================

      if (modePeta === "rawan") {

        tampilkanLokasiBanjir();

        if (!map.hasLayer(kontrolKejadian)) {
          kontrolKejadian.addTo(map);
        }

      } else {

        // Hapus marker ketika pindah mode
        if (map.hasLayer(layerLokasiBanjir)) {
          map.removeLayer(layerLokasiBanjir);
        }

        // Hapus kontrol layer
        if (map.hasLayer(kontrolKejadian)) {
          map.removeControl(kontrolKejadian);
        }

      }

    }

  });


  //==========================================
  // LOAD GEOJSON
  //==========================================

  fetch("<?= base_url('uploads/peta_kerawanan/' . $peta['file_geojson']) ?>")

    .then(response => response.json())

    .then(function(data) {

      geojsonLayer = L.geoJSON(data, {

        style: stylePeta,

        onEachFeature: function(feature, layer) {

          function isiPopup() {

            let p = feature.properties;
            let html = "";

            switch (modePeta) {

              case "kemiringan":

                html = `
                    <b>Kemiringan Lereng</b><hr>
                    Kemiringan : ${p.Kemiringan ?? "-"}<br>
                    Skor : ${p.Skor ?? "-"}
                `;

                break;

              case "lahan":

                html = `
                    <b>Penggunaan Lahan</b><hr>
                    Penggunaan : ${p.Penggunaan ?? "-"}<br>
                    Skor : ${p.Skor_Total ?? "-"}
                `;

                break;

              case "tanah":

                html = `
                    <b>Jenis Tanah</b><hr>
                    Jenis Tanah : ${p.Jenis_Tana ?? "-"}<br>
                    Skor : ${p.Skor_T ?? "-"}
                `;

                break;

              case "geologi":

                html = `
                    <b>Geologi</b><hr>
                    Jenis Geologi : ${p.NAME ?? "-"}<br>
                    Formasi : ${p.FORMATION ?? "-"}<br>
                    Kelas Litologi : ${p.CLASS_LITH ?? "-"}<br>
                    Skor : ${p.Skor_1 ?? "-"}
                `;

                break;

              case "curah":

                html = `
                    <b>Curah Hujan</b><hr>
                    Curah Hujan : ${p.Curah_Huja ?? "-"}<br>
                    Skor : ${p.Skor_12 ?? "-"}
                `;

                break;

              default:

                html = `
    <b>Zonasi Kerawanan</b><hr>

    Tingkat Kerawanan :
    ${p.KELAS_RAWA ?? p.KELAS ?? "-"}<br>

    Total Skor :
    ${p.N_TOTAL ?? "-"}
`;

            }

            return html;

          }

          layer.bindPopup(isiPopup());

          layer.on("click", function() {

            layer.setPopupContent(isiPopup());

          });

        }
      }).addTo(map);


      map.fitBounds(geojsonLayer.getBounds());

      //=====================================
      // OVERLAY BATAS KECAMATAN
      //=====================================

      fetch("<?= base_url('uploads/wilayah/bajo_barat.json') ?>")

        .then(res => res.json())

        .then(data => {

          L.geoJSON(data, {

            interactive: false,

            style: {
              stroke: true,
              color: "#000",
              weight: 3,
              opacity: 1,
              dashArray: "10 8",
              fill: false
            }

          }).addTo(map);

        });

      //==========================================
      // MARKER WILAYAH
      //==========================================

      <?php foreach ($wilayah as $w): ?>

        var marker = L.marker(
          [
            <?= $w['latitude'] ?>,
            <?= $w['longitude'] ?>
          ], {
            icon: iconWilayah
          }
        ).addTo(map);

        marker.bindTooltip(
          "<?= addslashes($w['nama_desa']) ?>", {
            permanent: true,
            direction: "bottom",
            offset: [0, 18],
            className: "label-desa"
          }
        );

        marker.on("click", function() {

          let html = `
        <b>Desa : <?= addslashes($w['nama_desa']) ?></b><br>
        Penduduk : <?= number_format($w['total_penduduk']) ?> Jiwa<br>
        Luas : <?= $w['luas_daerah'] ?> Km²<br>
        Persentase Luas : <?= $w['persentase_luas'] ?> %
    `;

          if (modePeta === "rawan") {
            html += cariKejadian("<?= addslashes($w['nama_desa']) ?>");
          }

          this.bindPopup(html).openPopup();

        });

      <?php endforeach; ?>

    })

    .catch(function(error) {

      console.log(error);

      alert("GeoJSON gagal dimuat.");

    });
</script>


<?= $this->include('user/layout/footer') ?>