<?= $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">

        <?php if (session()->getFlashdata('success')) : ?>
            <div class="alert alert-success">
                <?= session()->getFlashdata('success') ?>
            </div>
        <?php endif; ?>

        <div class="card">

            <div class="card-header">

                <h5>Peta Wilayah Mitigasi</h5>



                <button
                    class="btn btn-primary float-right"
                    data-toggle="modal"
                    data-target="#modalTambah">

                    Tambah Lokasi Mitigasi

                </button>

            </div>

            <div class="card-body">

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

                <hr>

                <table class="table table-bordered table-striped">

                    <thead>

                        <tr>

                            <th width="60">No</th>

                            <th>Jenis Mitigasi</th>

                            <th>Judul Strategi</th>

                            <th>Lokasi</th>

                            <th>Koordinat</th>

                            <th width="150">Aksi</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php $no = 1; ?>

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

                            <tr>

                                <td><?= $no++ ?></td>

                                <td>

                                    <span class="badge badge-<?= $w['jenis'] == 'struktural' ? 'primary' : 'success' ?>">

                                        <?= ucfirst($w['jenis']) ?>

                                    </span>

                                </td>

                                <td><?= $w['judul'] ?></td>

                                <td><?= $w['lokasi'] ?></td>

                                <td>

                                    Latitude :
                                    <?= $w['latitude'] ?>

                                    <br>

                                    Longitude :
                                    <?= $w['longitude'] ?>

                                </td>

                                <td>

                                    <button
                                        class="btn btn-warning btn-sm"
                                        data-toggle="modal"
                                        data-target="#edit<?= $w['id_wilayah_mitigasi'] ?>">

                                        Edit

                                    </button>

                                    <button
                                        class="btn btn-danger btn-sm"
                                        data-toggle="modal"
                                        data-target="#hapus<?= $w['id_wilayah_mitigasi'] ?>">

                                        Hapus

                                    </button>

                                </td>

                            </tr>

                            <div class="modal fade" id="edit<?= $w['id_wilayah_mitigasi'] ?>">

                                <div class="modal-dialog modal-lg">

                                    <div class="modal-content">

                                        <form
                                            action="<?= base_url('admin/wilayahmitigasi/update/' . $w['id_wilayah_mitigasi']) ?>"
                                            method="post">

                                            <div class="modal-header">

                                                <h5>Edit Lokasi Mitigasi</h5>

                                            </div>

                                            <div class="modal-body">

                                                <div class="row">

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

                                                        <label>Strategi Mitigasi</label>

                                                        <select
                                                            name="id_mitigasi"
                                                            class="form-control mb-2">

                                                            <?php foreach ($strategi as $s) : ?>

                                                                <option
                                                                    value="<?= $s['id_mitigasi'] ?>"

                                                                    <?= $s['id_mitigasi'] == $w['id_mitigasi'] ? 'selected' : '' ?>>

                                                                    <?= ucfirst($s['jenis']) ?>

                                                                    -

                                                                    <?= $s['judul'] ?>

                                                                </option>

                                                            <?php endforeach; ?>

                                                        </select>

                                                        <input
                                                            type="hidden"
                                                            name="polygon"
                                                            id="polygon<?= $w['id_wilayah_mitigasi'] ?>"
                                                            value="<?= esc($w['polygon']) ?>">

                                                        <label>Lokasi</label>

                                                        <input
                                                            type="text"
                                                            name="lokasi"
                                                            value="<?= $w['lokasi'] ?>"
                                                            class="form-control mb-2">

                                                        <label>Keterangan</label>

                                                        <textarea
                                                            name="keterangan"
                                                            class="form-control"><?= $w['keterangan'] ?></textarea>

                                                    </div>

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

                                                        <label>Latitude</label>

                                                        <input
                                                            type="text"
                                                            name="latitude"
                                                            value="<?= $w['latitude'] ?>"
                                                            class="form-control mb-2">

                                                        <label>Longitude</label>

                                                        <input
                                                            type="text"
                                                            name="longitude"
                                                            value="<?= $w['longitude'] ?>"
                                                            class="form-control mb-2">

                                                    </div>

                                                </div>

                                            </div>

                                            <div class="modal-footer">

                                                <button class="btn btn-success">

                                                    Update

                                                </button>

                                            </div>

                                        </form>

                                    </div>

                                </div>

                            </div>


                            <div class="modal fade" id="hapus<?= $w['id_wilayah_mitigasi'] ?>">

                                <div class="modal-dialog">

                                    <div class="modal-content">

                                        <div class="modal-body text-center">

                                            <h5>Hapus lokasi mitigasi ini?</h5>

                                            <p>

                                                <strong><?= $w['lokasi'] ?></strong>

                                            </p>

                                            <a
                                                href="<?= base_url('admin/wilayahmitigasi/delete/' . $w['id_wilayah_mitigasi']) ?>"
                                                class="btn btn-danger">

                                                Ya, Hapus

                                            </a>

                                        </div>

                                    </div>

                                </div>

                            </div>



                        <?php endforeach; ?>

                    </tbody>

                </table>





                <!-- nanti -->

            </div>

        </div>

    </div>
</div>

<div class="modal fade" id="modalTambah">

    <div class="modal-dialog modal-lg">

        <div class="modal-content">

            <form action="<?= base_url('admin/wilayahmitigasi/store') ?>" method="post">

                <div class="modal-header">

                    <h5>Tambah Lokasi Mitigasi</h5>

                </div>

                <div class="modal-body">

                    <div class="row">

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

                            <label>Strategi Mitigasi</label>

                            <select
                                name="id_mitigasi"
                                class="form-control mb-2"
                                required>

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

                                <?php foreach ($strategi as $s) : ?>

                                    <option value="<?= $s['id_mitigasi'] ?>">

                                        <?= ucfirst($s['jenis']) ?>

                                        -

                                        <?= $s['judul'] ?>

                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <input type="hidden" id="polygon" name="polygon">

                            <div class="form-group mt-2">
                                <label>Polygon yang telah digambar</label>
                                <textarea
                                    id="polygonPreview"
                                    class="form-control"
                                    rows="8"
                                    readonly></textarea>
                            </div>
                            <label>Lokasi</label>

                            <input
                                type="text"
                                name="lokasi"
                                class="form-control mb-2"
                                required>

                            <label>Keterangan</label>

                            <textarea
                                name="keterangan"
                                class="form-control"></textarea>

                        </div>

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

                            <label>Latitude</label>

                            <input
                                id="latitude"
                                type="text"
                                name="latitude"
                                class="form-control mb-2"
                                readonly>

                            <label>Longitude</label>

                            <input
                                id="longitude"
                                type="text"
                                name="longitude"
                                class="form-control mb-2"
                                readonly>




                            <div class="mb-2">
                                <button
                                    type="button"
                                    id="btnLokasiSaya"
                                    class="btn btn-primary btn-sm">

                                    <i class="feather icon-crosshair"></i>
                                    Ambil Lokasi Saat Ini

                                </button>
                            </div>

                        </div>

                    </div>

                </div>

                <div class="modal-footer">

                    <button class="btn btn-primary">

                        Simpan

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>

<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>
    // ==========================================
    // INISIALISASI PETA
    // ==========================================
    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);

    // ==========================================
    // BATAS WILAYAH BAJO BARAT
    // ==========================================
    let batasWilayah;

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

            batasWilayah = L.geoJSON(data, {

                style: {
                    color: "#000",
                    weight: 2,
                    fillColor: "#4CAF50",
                    fillOpacity: 0.2
                }

            }).addTo(map);

            map.fitBounds(batasWilayah.getBounds());

        })
        .catch(error => {

            console.log(error);

        });

    // ==========================================
    // 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]

    });

    // ==========================================
    // ICON INPUT
    // ==========================================
    var iconInput = L.icon({

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

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

    });

    // ==========================================
    // MARKER SAAT KLIK
    // ==========================================
    var markerInput = null;

    map.on('click', function(e) {

        if (markerInput) {
            map.removeLayer(markerInput);
        }

        markerInput = L.marker(e.latlng, {
            icon: iconInput
        }).addTo(map);

        document.getElementById('latitude').value = e.latlng.lat.toFixed(6);

        document.getElementById('longitude').value = e.latlng.lng.toFixed(6);

    });



    // ==========================================
    // AMBIL LOKASI SAAT INI
    // ==========================================

    document.getElementById("btnLokasiSaya").addEventListener("click", function() {

        if (!navigator.geolocation) {

            alert("Browser tidak mendukung Geolocation.");

            return;
        }

        navigator.geolocation.getCurrentPosition(

            function(position) {

                let lat = position.coords.latitude;
                let lng = position.coords.longitude;

                // isi textbox
                document.getElementById("latitude").value = lat.toFixed(6);
                document.getElementById("longitude").value = lng.toFixed(6);

                // hapus marker lama
                if (markerInput) {
                    map.removeLayer(markerInput);
                }

                // buat marker baru
                markerInput = L.marker([lat, lng], {
                    icon: iconInput
                }).addTo(map);

                // pindahkan peta
                map.setView([lat, lng], 16);

                markerInput.bindPopup("Lokasi Anda Saat Ini").openPopup();

            },

            function(error) {

                switch (error.code) {

                    case error.PERMISSION_DENIED:
                        alert("Izin lokasi ditolak.");
                        break;

                    case error.POSITION_UNAVAILABLE:
                        alert("Lokasi tidak tersedia.");
                        break;

                    case error.TIMEOUT:
                        alert("Pengambilan lokasi timeout.");
                        break;

                    default:
                        alert("Terjadi kesalahan saat mengambil lokasi.");
                }

            }, {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0
            }

        );

    });


    var drawnItems = new L.FeatureGroup();

    map.addLayer(drawnItems);

    var drawControl = new L.Control.Draw({

        position: 'topleft',

        draw: {

            polygon: true,

            rectangle: true,

            polyline: false,

            marker: false,

            circle: false,

            circlemarker: false

        },

        edit: {

            featureGroup: drawnItems

        }

    });

    map.addControl(drawControl);

    map.on('draw:created', function(e) {

        alert("Polygon dibuat");

    });

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

        var layer = e.layer;

        drawnItems.addLayer(layer);

        var geojson = drawnItems.toGeoJSON();

        var json = JSON.stringify(geojson);

        document.getElementById("polygon").value = json;

        document.getElementById("polygonPreview").value = json;

        console.log(json);

    });

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

        <?php if ($w['jenis'] == "struktural"): ?>

            var icon = iconStruktural;

        <?php else: ?>

            var icon = iconNonStruktural;

        <?php endif; ?>

        L.marker(

                [

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

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

                ],

                {

                    icon: icon

                }

            )

            .addTo(map)

            .bindPopup(`

            <b><?= addslashes($w['lokasi']) ?></b>

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

            <b>Jenis :</b>

            <?= ucfirst($w['jenis']) ?>

            <br>

            <b>Strategi :</b>

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

            <br>

            <b>Latitude :</b>

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

            <br>

            <b>Longitude :</b>

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

            <br>

            <b>Keterangan :</b>

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

        `)

            .bindTooltip(

                "<?= addslashes($w['lokasi']) ?>",

                {

                    permanent: true,

                    direction: "bottom",

                    offset: [0, 10],

                    className: "labelDesa"

                }

            );

    <?php endforeach; ?>

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

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

            var geojson = <?= $w['polygon'] ?>;

            L.geoJSON(geojson, {

                style: {

                    color: "#2196F3",

                    weight: 3,

                    fillColor: "#2196F3",

                    fillOpacity: 0.25

                }

            }).addTo(map);

        <?php endif; ?>

    <?php endforeach; ?>

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

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

            var geo = <?= $w['polygon'] ?>;

            var layer = L.geoJSON(geo);

            layer.eachLayer(function(l) {

                drawnItems.addLayer(l);

            });

        <?php endif; ?>

    <?php endforeach; ?>


    map.on('draw:edited', function() {

        drawnItems.eachLayer(function(layer) {

            document.getElementById("polygon").value =
                JSON.stringify(layer.toGeoJSON());

        });

    });


    document.getElementById("modalTambah").addEventListener("shown.bs.modal", function() {
        document.getElementById("polygonPreview").value =
            document.getElementById("polygon").value;
    });
</script>


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