<?= $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('user/dashboard') ?>">Beranda</a></li>
                <li class="current">Data</li>
            </ol>
        </nav>

        <h1>Data Kepadatan Penduduk Dan Kejadian Banjir</h1>

    </div>
</div>
<!-- End Page Title -->


<!-- Services Section -->
<section id="services" class="services section">

    <div class="container">

        <div class="row">

            <!-- PETA -->
            <div class="col-md-4">

                <div class="card shadow-sm h-100">

                    <div class="card-header">
                        <b>Peta Wilayah Kecamatan Bajo Barat</b>
                    </div>

                    <div class="card-body p-0">

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

                    </div>

                </div>

            </div>

            <!-- KEPADATAN PENDUDUK -->
            <div class="col-md-4">

                <div class="card shadow-sm h-100">

                    <div class="card-header">
                        <b>Data Kepadatan Penduduk</b>
                    </div>

                    <div class="card-body">

                        <label><b>Pilih Desa</b></label>

                        <select id="pilihDesa" class="form-control mb-3">

                            <option value="">-- Pilih Desa --</option>

                            <?php foreach ($data_bencana as $row): ?>

                                <?php if ($row['jenis_data'] == "kepadatan_penduduk"):

                                    preg_match('/Desa:\s*(.*)/', $row['keterangan'], $desa);

                                ?>

                                    <option
                                        value="<?= strtolower(trim($desa[1])) ?>"
                                        data-keterangan="<?= htmlspecialchars($row['keterangan']) ?>"
                                        data-sumber="<?= $row['sumber'] ?>"
                                        data-tahun="<?= $row['tahun'] ?>">

                                        <?= trim($desa[1]) ?>

                                    </option>

                                <?php endif; ?>

                            <?php endforeach; ?>

                        </select>

                        <div id="detailPenduduk">

                            <div class="text-muted">
                                Pilih salah satu desa untuk melihat data kepadatan penduduk.
                            </div>

                        </div>

                    </div>

                </div>

            </div>

            <!-- KEJADIAN BANJIR -->
            <div class="col-md-4">

                <div class="card shadow-sm h-100">

                    <div class="card-header">
                        <b>Data Kejadian Banjir</b>
                    </div>

                    <div class="card-body">

                        <label><b>Pilih Kejadian</b></label>

                        <select id="pilihBanjir" class="form-control mb-3">

                            <option value="">-- Pilih Kejadian Banjir --</option>

                            <?php foreach ($data_bencana as $row): ?>

                                <?php if ($row['jenis_data'] == "kejadian_banjir"):

                                    preg_match('/Tanggal:\s*(.*)/', $row['keterangan'], $tanggal);
                                    preg_match('/Kelurahan\/Desa:\s*(.*)/', $row['keterangan'], $desa);

                                ?>

                                    <option
                                        data-desa="<?= strtolower(trim($desa[1])) ?>"
                                        data-keterangan="<?= htmlspecialchars($row['keterangan']) ?>"
                                        data-sumber="<?= $row['sumber'] ?>"
                                        data-tahun="<?= $row['tahun'] ?>">

                                        <?= trim($tanggal[1]) ?> -
                                        <?= trim($desa[1]) ?>

                                    </option>

                                <?php endif; ?>

                            <?php endforeach; ?>

                        </select>

                        <div id="detailBanjir">

                            <div class="text-muted">
                                Pilih kejadian banjir untuk melihat detail.
                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>
</section>

<style>
    .label-desa {
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
        color: #000;
        font-size: 11px;
        font-weight: bold;
        text-shadow:
            -1px -1px 0 #fff,
            1px -1px 0 #fff,
            -1px 1px 0 #fff,
            1px 1px 0 #fff;
    }
</style>
<!-- /Services Section -->
<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
    //=============================

    var iconWilayah = L.icon({

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

        iconSize: [35, 35],

        iconAnchor: [17, 35]

    });

    //=============================
    // VARIABEL GLOBAL
    //=============================

    var batas;

    //=============================
    // BATAS DESA
    //=============================

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

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

        .then(data => {

            batas = L.geoJSON(data, {

                style: function(feature) {

                    let desa = (feature.properties.NAMOBJ || "").toLowerCase();

                    let warna = "#dddddd";

                    switch (desa) {

                        case "bonelemo":
                            warna = "#3949AB";
                            break;

                        case "bonelemo barat":
                            warna = "#4A5CC5";
                            break;

                        case "bonelemo utara":
                            warna = "#5C6FD9";
                            break;

                        case "kadong-kadong":
                            warna = "#6F82E8";
                            break;

                        case "marinding":
                            warna = "#8193F2";
                            break;

                        case "sampeang":
                            warna = "#96A8FF";
                            break;

                        case "saronda":
                            warna = "#B3BEFF";
                            break;

                        case "tettekang":
                            warna = "#CCD4FF";
                            break;

                        case "tumbubara":
                            warna = "#E3E7FF";
                            break;

                        default:
                            warna = "#3949AB";
                    }

                    return {
                        color: "#4d4d4d",
                        weight: 2,
                        fillColor: warna,
                        fillOpacity: 0.7
                    };
                },

                onEachFeature: function(feature, layer) {

                    layer.bindPopup(`
                        <b>Desa :</b> ${feature.properties.NAMOBJ}
                    `);

                }

            }).addTo(map);

            map.fitBounds(batas.getBounds());

            //=================================
            // EVENT DROPDOWN DESA
            //=================================

            document.getElementById("pilihDesa").addEventListener("change", function() {

                let desaDipilih = this.value;

                let option = this.options[this.selectedIndex];

                if (desaDipilih == "") {

                    document.getElementById("detailPenduduk").innerHTML =
                        '<div class="text-muted">Pilih salah satu desa untuk melihat data kepadatan penduduk.</div>';

                } else {

                    document.getElementById("detailPenduduk").innerHTML = `
                        <div class="alert alert-success mb-0">

                            <b>Tahun</b><br>
                            ${option.dataset.tahun}

                            <hr>

                            <b>Sumber</b><br>
                            ${option.dataset.sumber}

                            <hr>

                            ${option.dataset.keterangan.replace(/\r\n/g,"<br>")}

                        </div>
                    `;

                }

                batas.eachLayer(function(layer) {

                    let nama = (layer.feature.properties.NAMOBJ || "").toLowerCase();

                    if (nama == desaDipilih) {

                        layer.setStyle({

                            fillColor: "#4CAF50",
                            color: "#2E7D32",
                            weight: 3,
                            fillOpacity: 0.9

                        });

                        map.fitBounds(layer.getBounds());

                    } else {

                        layer.setStyle({

                            fillColor: warnaDefault(nama),
                            color: "#4d4d4d",
                            weight: 2,
                            fillOpacity: 0.7

                        });

                    }

                });

            });

            document.getElementById("pilihBanjir").addEventListener("change", function() {

                let option = this.options[this.selectedIndex];

                if (this.value == "") {

                    document.getElementById("detailBanjir").innerHTML =
                        '<div class="text-muted">Pilih kejadian banjir untuk melihat detail.</div>';

                    batas.eachLayer(function(layer) {

                        let nama = (layer.feature.properties.NAMOBJ || "").toLowerCase();

                        layer.setStyle({

                            fillColor: warnaDefault(nama),
                            color: "#4d4d4d",
                            weight: 2,
                            fillOpacity: 0.7

                        });

                    });

                    return;
                }

                document.getElementById("detailBanjir").innerHTML = `

        <div class="alert alert-danger mb-0">

            <b>Tahun</b><br>
            ${option.dataset.tahun}

            <hr>

            <b>Sumber</b><br>
            ${option.dataset.sumber}

            <hr>

            ${option.dataset.keterangan.replace(/\r\n/g,"<br>")}

        </div>

    `;

                let daftarDesa = option.dataset.desa
                    .split(",")
                    .map(x => x.trim());

                batas.eachLayer(function(layer) {

                    let nama = (layer.feature.properties.NAMOBJ || "").toLowerCase();

                    if (daftarDesa.includes(nama)) {

                        layer.setStyle({

                            fillColor: "#E53935",
                            color: "#B71C1C",
                            weight: 3,
                            fillOpacity: 0.9

                        });

                    } else {

                        layer.setStyle({

                            fillColor: warnaDefault(nama),
                            color: "#4d4d4d",
                            weight: 2,
                            fillOpacity: 0.7

                        });

                    }

                });

            });


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

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

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

                .then(data => {

                    L.geoJSON(data, {

                        interactive: false,

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

                    }).addTo(map);

                });

        });

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

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

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

            .addTo(map)

            .bindPopup(`
    <b><?= addslashes($w['nama_desa']) ?></b><br>

    Penduduk :
    <?= number_format($w['total_penduduk']) ?> Jiwa<br>

    Luas :
    <?= $w['luas_daerah'] ?> Km²<br>

    Persentase : <?= $w['persentase_luas'] ?> %`)

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

    <?php endforeach; ?>
</script>

<script>
    function warnaDefault(desa) {

        switch (desa) {

            case "bonelemo":
                return "#3949AB";

            case "bonelemo barat":
                return "#4A5CC5";

            case "bonelemo utara":
                return "#5C6FD9";

            case "kadong-kadong":
                return "#6F82E8";

            case "marinding":
                return "#8193F2";

            case "sampeang":
                return "#96A8FF";

            case "saronda":
                return "#B3BEFF";

            case "tettekang":
                return "#CCD4FF";

            case "tumbubara":
                return "#E3E7FF";

            default:
                return "#3949AB";

        }

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