<?= $this->include('admin/layout/header') ?>
<?= $this->include('admin/layout/navbar') ?>
<?= $this->include('admin/layout/topbar') ?>

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

<div class="pcoded-main-container">
    <div class="pcoded-content">

        <div class="card">

            <div class="card-header">

                <h5><?= $peta['judul'] ?></h5>

                <a href="<?= base_url('admin/peta-kerawanan') ?>"
                    class="btn btn-secondary float-right">
                    Kembali
                </a>

            </div>

            <div class="card-body">

                <table class="table table-bordered">

                    <tr>
                        <th width="200">Judul</th>
                        <td><?= $peta['judul'] ?></td>
                    </tr>

                    <tr>
                        <th>Tanggal Update</th>
                        <td><?= $peta['tanggal_update'] ?></td>
                    </tr>

                    <tr>
                        <th>Deskripsi</th>
                        <td><?= $peta['deskripsi'] ?></td>
                    </tr>

                    <tr>
                        <th>File GeoJSON</th>
                        <td><?= $peta['file_geojson'] ?></td>
                    </tr>

                </table>

                <div class="card mb-3 shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <i class="fa fa-layer-group mr-2"></i>
                        <b>Pilih Tampilan Peta</b>
                    </div>

                    <div class="card-body">

                        <div class="row">

                            <div class="col-md-6">

                                <div class="custom-control custom-radio mb-3">
                                    <input type="radio"
                                        id="rbRawan"
                                        name="modePeta"
                                        value="rawan"
                                        class="custom-control-input">

                                    <label class="custom-control-label" for="rbRawan">
                                        <b>Peta Zonasi Rawan Banjir</b>
                                    </label>
                                </div>

                                <div class="custom-control custom-radio mb-3">
                                    <input type="radio"
                                        id="rbKemiringan"
                                        name="modePeta"
                                        value="kemiringan"
                                        class="custom-control-input"
                                        checked>

                                    <label class="custom-control-label" for="rbKemiringan">
                                        Peta Kemiringan Lereng
                                    </label>
                                </div>

                                <div class="custom-control custom-radio">
                                    <input type="radio"
                                        id="rbLahan"
                                        name="modePeta"
                                        value="lahan"
                                        class="custom-control-input">

                                    <label class="custom-control-label" for="rbLahan">
                                        Peta Penggunaan Lahan
                                    </label>
                                </div>

                            </div>

                            <div class="col-md-6">

                                <div class="custom-control custom-radio mb-3">
                                    <input type="radio"
                                        id="rbTanah"
                                        name="modePeta"
                                        value="tanah"
                                        class="custom-control-input">

                                    <label class="custom-control-label" for="rbTanah">
                                        Peta Jenis Tanah
                                    </label>
                                </div>

                                <div class="custom-control custom-radio mb-3">
                                    <input type="radio"
                                        id="rbGeologi"
                                        name="modePeta"
                                        value="geologi"
                                        class="custom-control-input">

                                    <label class="custom-control-label" for="rbGeologi">
                                        Peta Geologi
                                    </label>
                                </div>

                                <div class="custom-control custom-radio">
                                    <input type="radio"
                                        id="rbCurah"
                                        name="modePeta"
                                        value="curah"
                                        class="custom-control-input">

                                    <label class="custom-control-label" for="rbCurah">
                                        Peta Curah Hujan
                                    </label>
                                </div>

                            </div>

                        </div>

                    </div>
                </div>

                <div id="map" style="height:600px;"></div>

            </div>

        </div>

    </div>
</div>


<style>
    .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;
    }
</style>

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

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

<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script>
    var map = L.map('map').setView([-3.3556, 120.2349], 11);

    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);



    // ==========================================
    // ICON MARKER WILAYAH
    // ==========================================
    var iconWilayah = L.icon({

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

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

    });


    // ==========================================
    // MODE PETA
    // ==========================================
    let modePeta = "kemiringan";

    // layer dibuat global
    let geojsonLayer;

    // ==========================================
    // 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") {

            // Ada GeoJSON yang memakai NAME
            let nama = (feature.properties.NAME ?? "").toLowerCase();

            // Ada juga yang memakai FORMATION
            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();

            // Curah Hujan >3000 mm/tahun
            if (curah.includes(">3000")) {

                warna = "#1975ff";

            }

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

            // Mendukung GeoJSON lama (KELAS) maupun baru (KELAS_RAWA)
            let kelas = (
                feature.properties.KELAS_RAWA ??
                feature.properties.KELAS ??
                ""
            ).toLowerCase();

            if (kelas == "aman") {

                warna = "#0a920e"; // Hijau

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

                warna = "#FFD600"; // Biru

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

                warna = "#ff8800"; // Kuning

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

                warna = "#ff1100"; // Merah

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

                // Tetap didukung untuk GeoJSON lama
                warna = "#0a920e"; // Hijau

                // ==========================================
                // TAMBAHAN KELAS BARU
                // ==========================================

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

                warna = "#09d10c"; // Hijau muda

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

                warna = "#FFD600"; // Kuning

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

                warna = "#ff8800"; // Oranye

            }
        }


        return {
            color: warna,
            weight: 1.5,
            opacity: 1,
            fillColor: warna,
            fillOpacity: 0.9,
            lineJoin: "round",
            lineCap: "round",
            smoothFactor: 2
        };
    }

    // ==========================================
    // EVENT RADIO BUTTON
    // ==========================================
    document.querySelectorAll('input[name="modePeta"]').forEach(function(radio) {

        radio.addEventListener('change', function() {

            modePeta = this.value;

            if (geojsonLayer) {
                geojsonLayer.setStyle(stylePeta);
            }

        });

    });

    // ==========================================
    // LOAD GEOJSON
    // ==========================================
    fetch('<?= base_url('uploads/peta_kerawanan/' . $peta['file_geojson']) ?>')
        .then(response => response.json())
        .then(data => {

            geojsonLayer = L.geoJSON(data, {

                style: stylePeta,

                onEachFeature: function(feature, layer) {

                    let isi = '';

                    if (feature.properties) {

                        for (let key in feature.properties) {
                            isi += '<b>' + key + '</b>: ' + feature.properties[key] + '<br>';
                        }

                    }

                    layer.bindPopup(isi);

                }

            }).addTo(map);

            map.fitBounds(geojsonLayer.getBounds());

            // ==========================================
            // MARKER WILAYAH
            // ==========================================
            <?php foreach ($wilayah as $w): ?>

                L.marker(
                        [
                            <?= $w['latitude'] ?>,
                            <?= $w['longitude'] ?>
                        ], {
                            icon: iconWilayah
                        }
                    )
                    .addTo(map)
                    .bindPopup(`
    <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'] ?> %
`)
                    .bindTooltip(
                        "<?= addslashes($w['nama_desa']) ?>", {
                            permanent: true,
                            direction: "bottom",
                            offset: [0, 18],
                            className: "label-desa"
                        }
                    );

            <?php endforeach; ?>


        })
        .catch(error => {

            console.log(error);

            alert('GeoJSON gagal dimuat');

        });
</script>

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