<?= $this->extend('v_template/layout') ?>
<?= $this->section('content') ?>

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

<div class="row mb-4 align-items-center">
    <div class="col-md-8">
        <h4 class="fw-bold text-success"><i class="fa-solid fa-map-location-dot me-2"></i> Peta Spasial Dinamis</h4>
        <p class="text-muted mb-0">Pemetaan wilayah kerja dan area pemantauan.</p>
    </div>
    <div class="col-md-4 text-md-end mt-3 mt-md-0">
        <?php if(session()->get('role') == 'Admin' || session()->get('role') == 'Kepala KPH') : ?>
            <a href="<?= base_url('peta/kelola') ?>" class="btn btn-warning rounded-pill shadow-sm"><i class="fa-solid fa-gear me-2"></i> Kelola Titik Peta</a>
        <?php endif; ?>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-2">
        <div id="map" style="height: 600px; width: 100%; border-radius: 10px; z-index: 1;"></div>
    </div>
</div>

<script>
    // Set view awal di wilayah Asahan
    var map = L.map('map').setView([2.9698, 99.6309], 10);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }).addTo(map);

    // MENGAMBIL DATA DARI DATABASE SECARA OTOMATIS
    var dataTitik = <?= json_encode($titik_peta) ?>;

    dataTitik.forEach(function(titik) {
        var iconHtml = '';
        var warna = '';

        // Menyesuaikan Icon dengan Kategori di Database
        if(titik.kategori == 'Kantor') { iconHtml = '<i class="fa-solid fa-building"></i>'; warna = 'text-primary'; }
        else if(titik.kategori == 'Rawan Karhutla') { iconHtml = '<i class="fa-solid fa-fire"></i>'; warna = 'text-danger'; }
        else if(titik.kategori == 'Rehabilitasi') { iconHtml = '<i class="fa-solid fa-tree"></i>'; warna = 'text-success'; }
        else { iconHtml = '<i class="fa-solid fa-location-crosshairs"></i>'; warna = 'text-warning'; }

        var customIcon = L.divIcon({ className: warna + ' fs-3', html: iconHtml, iconAnchor: [10, 30] });

        // Memasang penanda di peta sesuai Latitude dan Longitude
        L.marker([titik.latitude, titik.longitude], {icon: customIcon}).addTo(map)
         .bindPopup('<b>' + titik.nama_lokasi + '</b><br><small class="text-muted">' + titik.kategori + '</small><hr class="my-1">' + titik.deskripsi);
    });
</script>

<?= $this->endSection() ?>