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

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

<div class="page-title">

    <div class="container">
        <nav class="breadcrumbs">
            <ol>
                <li><a href="<?= base_url('user/dashboard') ?>">Beranda</a></li>
                <li class="current">Strategi Mitigasi</li>
            </ol>
        </nav>


        <h1>PETA KERAWANAN BANJIR BANDANG</h1>

    </div>

</div>

<section class="section">

    <div class="container">

        <div class="row">

            <div class="col-lg-12">

                <div id="map" style="height:700px; position:relative;">

                    <div id="infoMitigasi" class="info-mitigasi">

                        <h5>Informasi Mitigasi</h5>

                        <hr>

                        <div class="text-muted">
                            Klik marker atau label lokasi untuk melihat informasi mitigasi.
                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>

</section>


<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>
    var map = L.map('map').setView([-3.3556, 120.2349], 11);

    //=====================================
    // LAYER MANAGEMENT
    //=====================================

    const layerKerawanan = L.layerGroup().addTo(map);
    const layerMitigasi = L.layerGroup().addTo(map);
    const layerBatas = L.layerGroup().addTo(map);
    const layerMarker = L.layerGroup().addTo(map);


    //=====================================
    // DRAW POLYGON
    //=====================================

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

    var drawControl = new L.Control.Draw({

        position: 'topleft',

        draw: {

            polygon: true,
            rectangle: true,
            polyline: true,
            marker: true,

            circle: false,
            circlemarker: false

        },

        edit: {
            featureGroup: drawnItems
        }

    });

    map.addControl(drawControl);

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

        drawnItems.addLayer(e.layer);

    });



    //=====================================
    // SIMPAN GEOJSON
    //=====================================

    function simpanGeoJSON() {

        const geojson = drawnItems.toGeoJSON();

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

                method: "POST",

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

                body: JSON.stringify(geojson)

            })

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

            .then(res => {

                if (res.status) {

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

                } else {

                    alert("Gagal menyimpan");

                }

            });

    }


    //=====================================
    // TOMBOL SAVE
    //=====================================

    var saveControl = L.control({

        position: 'topleft'

    });

    saveControl.onAdd = function() {

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

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

        L.DomEvent.disableClickPropagation(div);

        div.onclick = function(e) {

            e.preventDefault();

            simpanGeoJSON();

        }

        return div;

    }

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

    // ==========================================
    // ICON STRUKTURAL
    // ==========================================
    var iconStruktural = L.icon({

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

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

    });

    // ==========================================
    // ICON NON STRUKTURAL
    // ==========================================
    var iconNonStruktural = L.icon({

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

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

    });


    // =====================================
    // TAMPILKAN POLYGON MITIGASI
    // =====================================

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

        <?php if (!empty($w['polygon'])): ?>

            var geo = <?= json_encode(json_decode($w['polygon'])) ?>;

            L.geoJSON(geo, {

                style: {
                    color: "#f8f8f8",
                    weight: 5,
                    opacity: 1,
                    lineCap: "round",
                    lineJoin: "round",
                    dashArray: "10 8",
                    fillColor: "#37abf8",
                    fillOpacity: 100
                },

                onEachFeature: function(feature, layer) {

                    layer.bindPopup(`
                    <b><?= addslashes($w['judul']) ?></b><br>
                    Lokasi : <?= addslashes($w['lokasi']) ?><br>
                    Jenis : <?= ucfirst($w['jenis']) ?>
                `);

                }

            }).addTo(layerMitigasi);

        <?php endif; ?>

    <?php endforeach; ?>

    //=====================================
    // PETA KERAWANAN (ID = 19)
    //=====================================

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

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

        .then(data => {

            var batas = L.geoJSON(data, {

                style: function(feature) {

                    let warna = "#cccccc";

                    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: "#555",

                        weight: 0.5,

                        opacity: 0.4,

                        fillColor: warna,

                        fillOpacity: 0.80

                    };

                }

            }).addTo(layerKerawanan);

            map.fitBounds(batas.getBounds());


            map.fitBounds(batas.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(layerBatas);

                });

        });

    let markerAktif = null;

    const infoAwal = `
    <h5>Informasi Mitigasi</h5>

    <hr>

    <div class="text-muted">
        Klik marker atau label lokasi untuk melihat informasi mitigasi.
    </div>
`;

    //=====================================
    // MARKER MITIGASI
    //=====================================

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

        L.marker(

                [
                    <?= $w['latitude'] ?>,
                    <?= $w['longitude'] ?>
                ],

                {

                    icon: <?= $w['jenis'] == 'struktural'
                                ? 'iconStruktural'
                                : 'iconNonStruktural' ?>

                }

            )

            .addTo(layerMarker)

            .bindTooltip(

                `<div class="text-center">
<b><?= addslashes($w['lokasi']) ?></b>
</div>`,

                {

                    permanent: true,
                    direction: "bottom",
                    offset: [0, 28],
                    className: "label-lokasi"

                }

            )

            .on("click", function() {

                const info = document.getElementById("infoMitigasi");

                if (markerAktif === this) {

                    info.innerHTML = infoAwal;

                    markerAktif = null;

                    this.closePopup();

                    return;

                }

                markerAktif = this;

                info.innerHTML = `

        <h5 class="mb-2"><?= addslashes($w['judul']) ?></h5>

        <table class="table table-sm table-borderless mb-2">

            <tr>
                <td width="90"><b>Jenis</b></td>
                <td>: <?= ucfirst(str_replace('_', ' ', $w['jenis'])) ?></td>
            </tr>

            <tr>
                <td><b>Lokasi</b></td>
                <td>: <?= addslashes($w['lokasi']) ?></td>
            </tr>

        </table>

        <hr>

        <b>Deskripsi</b>

        <div class="mb-3 text-justify">

            <?= nl2br(addslashes($w['deskripsi'])) ?>

        </div>

        <b>Rekomendasi</b>

        <div class="text-justify">

            <?= nl2br(addslashes($w['rekomendasi'])) ?>

        </div>

    `;

            });




    <?php endforeach; ?>
</script>

<style>
    .label-lokasi {

        background: transparent;
        border: none;
        box-shadow: none;
        color: #000;

        font-size: 11px;
        font-weight: bold;
        text-align: center;
        line-height: 1.2;

        text-shadow:
            1px 1px 2px #fff,
            -1px -1px 2px #fff,
            1px -1px 2px #fff,
            -1px 1px 2px #fff;

    }

    .label-lokasi small {

        display: block;
        font-size: 10px;
        font-weight: 600;
    }

    .label-lokasi:before {

        display: none;

    }

    .info-mitigasi {

        position: absolute;

        top: 10px;
        right: 10px;
        /* pindah ke kanan */
        left: auto;
        /* menonaktifkan posisi kiri */

        width: 280px;
        max-height: 650px;
        overflow-y: auto;

        background: #fff;

        border-radius: 8px;

        padding: 15px;

        box-shadow: 0 3px 12px rgba(0, 0, 0, .25);

        z-index: 999;

        border-left: none;
        border-right: 5px solid #198754;
        /* garis hijau pindah ke kanan */

    }

    .info-mitigasi h5 {

        margin: 0;
        font-weight: bold;

    }

    .info-mitigasi hr {

        margin: 8px 0;

    }
</style>

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