

<?php $__env->startSection('title', 'Peta Spasial GIS Global Jateng | PRADIPA'); ?>

<?php $__env->startSection('styles'); ?>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<style>
    /* Mengunci tinggi halaman agar pas dengan viewport */
    .gis-container {
        height: calc(100vh - 11rem);
    }
    
    /* Memaksa hardware acceleration GPU */
    .leaflet-tile-container {
        will-change: transform;
        transform: translateZ(0);
        -webkit-transform: translateZ(0);
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="flex flex-col gap-4 h-full">
    
    <!-- HEADER INTERAKTIF -->
    <div class="bg-white px-6 py-4 rounded-xl border border-slate-200 shadow-sm flex flex-col sm:flex-row justify-between sm:items-center gap-3">
        <div>
            <h2 class="text-xl font-bold text-slate-800">Peta Spasial GIS Global Jawa Tengah</h2>
            <p class="text-xs text-slate-500 mt-0.5 font-medium">Monitoring sebaran se-Jateng batas lahan pertanian sawah kelompok tani penerima bantuan saprodi secara real-time.</p>
        </div>
        <div class="flex items-center gap-2 text-xs font-mono font-bold text-slate-400">
            <span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span>
            <span>GOOGLE HYBRID SATELIT ACTIVE</span>
        </div>
    </div>

    <!-- MAIN GIS PANEL (Peta & Sidebar Filter Bersebelahan) -->
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-4 flex-1 gis-container">
        
        <!-- SIDEBAR FILTER INTERAKTIF (Kiri - 3/12) -->
        <div class="lg:col-span-3 bg-white p-5 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between h-full overflow-y-auto">
            <div class="flex flex-col gap-4 font-sans text-xs">
                <h3 class="font-extrabold text-slate-700 uppercase tracking-wider text-[11px] border-b border-slate-100 pb-2">Filter Geospasial</h3>

                <!-- Filter Kabupaten (Hanya muncul untuk Provinsi) -->
                <?php if($role !== 'kabupaten_user'): ?>
                    <div class="flex flex-col gap-1.5">
                        <label class="font-bold text-slate-500">Pilih Wilayah Kabupaten:</label>
                        <select id="filterKabupaten" onchange="muatPetaGisGlobal()" class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 font-semibold cursor-pointer">
                            <option value="">Semua Kabupaten</option>
                            <?php $__currentLoopData = $kabupatens; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kab): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($kab->id); ?>">Kab. <?php echo e($kab->nama_kabupaten); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                <?php else: ?>
                    <div class="p-3 bg-emerald-50 border border-emerald-100 rounded-lg text-emerald-800 leading-normal font-semibold">
                        🤖 Akun Anda dikunci otomatis ke wilayah kabupaten penugasan Sandbox aktif.
                    </div>
                <?php endif; ?>

                <!-- Filter Program Kegiatan -->
                <div class="flex flex-col gap-1.5">
                    <label class="font-bold text-slate-500">Program Kegiatan:</label>
                    <select id="filterKegiatan" onchange="muatPetaGisGlobal()" class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 font-semibold cursor-pointer">
                        <option value="">Semua Program Bantuan</option>
                        <?php $__currentLoopData = $kegiatans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($k->id); ?>"><?php echo e($k->nama_kegiatan); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <!-- Filter Status Berkas -->
                <div class="flex flex-col gap-1.5">
                    <label class="font-bold text-slate-500">Status Berkas Usulan:</label>
                    <select id="filterStatus" onchange="muatPetaGisGlobal()" class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 font-semibold cursor-pointer">
                        <option value="">Semua Status Berkas</option>
                        <option value="diajukan">Diajukan (Review)</option>
                        <option value="perbaikan">Butuh Perbaikan</option>
                        <option value="diverifikasi">Diverifikasi Admin</option>
                        <option value="final">Final SK Terbit</option>
                    </select>
                </div>

                <!-- BOX RINGKASAN WARNA LEGENDA STATUS -->
                <div class="border-t border-slate-100 pt-4 flex flex-col gap-2">
                    <h4 class="font-bold text-slate-700 uppercase text-[10px] tracking-widest mb-1">Legenda Status Usulan</h4>
                    <div class="flex items-center gap-2.5 font-semibold text-slate-500">
                        <span class="w-3.5 h-3.5 rounded bg-blue-500/25 border border-blue-600 shrink-0"></span>
                        <span>Diajukan (Review)</span>
                    </div>
                    <div class="flex items-center gap-2.5 font-semibold text-slate-500">
                        <span class="w-3.5 h-3.5 rounded bg-amber-500/25 border border-amber-600 shrink-0"></span>
                        <span>Butuh Perbaikan</span>
                    </div>
                    <div class="flex items-center gap-2.5 font-semibold text-slate-500">
                        <span class="w-3.5 h-3.5 rounded bg-emerald-500/25 border border-emerald-600 shrink-0"></span>
                        <span>Terverifikasi</span>
                    </div>
                    <div class="flex items-center gap-2.5 font-semibold text-slate-500">
                        <span class="w-3.5 h-3.5 rounded bg-purple-500/25 border border-purple-600 shrink-0"></span>
                        <span>Final SK Terbit</span>
                    </div>
                </div>
            </div>

            <!-- Panel Statistik Spasial -->
            <div class="p-3.5 bg-slate-50 border border-slate-200 rounded-xl text-center text-xs mt-4">
                <span class="text-slate-400 font-semibold block">Total Lahan Tergambar:</span>
                <b id="statsTotalPolygons" class="text-2xl font-black text-slate-800 block mt-1 leading-none">0</b>
                <span class="text-[10px] text-emerald-600 font-bold block mt-1 font-sans">Batas Bidang Sawah</span>
            </div>
        </div>

        <!-- AREA MAPS UTAMA LEAFLET CANVAS (Kanan - 9/12) -->
        <div class="lg:col-span-9 bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden h-full relative">
            <div id="globalGisMap" class="w-full h-full z-10"></div>
            
            <!-- Panduan Melayang GIS -->
            <div class="absolute z-20 top-4 right-4 bg-slate-950/85 text-white p-3.5 rounded-xl shadow-lg border border-slate-800 text-[10px] space-y-1.5 font-sans max-w-xs leading-normal">
                <span class="font-extrabold text-emerald-400 block uppercase tracking-wider">Akurasi Visual Spasial:</span>
                Peta global Jawa Tengah ini merender semua data batas bidang tanah langsung dari WKT (Well-Known Text) di database yang telah diinput operator menggunakan Citra Satelit Google Hybrid.
            </div>
        </div>

    </div>
</div>

<!-- Masukkan Script CDN Leaflet.js -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

<script>
    let gisMap;
    let polygonFeatureGroup;

    document.addEventListener('DOMContentLoaded', () => {
        initGlobalGisMap();
    });

    function initGlobalGisMap() {
        // Koordinat tengah Jawa Tengah
        const defaultLat = -7.0522;
        const defaultLon = 110.4325;

        gisMap = L.map('globalGisMap', {
            center: [defaultLat, defaultLon],
            zoom: 9,
            zoomControl: true,
            fadeAnimation: true,
            zoomAnimation: true,
            inertia: true
        });

        // Layer Google Maps Hybrid (Satelit + Jalan + Label)
        L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
            attribution: '&copy; Google Maps Hybrid',
            updateWhenIdle: true,
            keepBuffer: 4
        }).addTo(gisMap);

        polygonFeatureGroup = L.featureGroup().addTo(gisMap);

        // Unduh dan plot data geospasial
        muatPetaGisGlobal();
    }

    function muatPetaGisGlobal() {
        // Bersihkan seluruh polygon lama
        polygonFeatureGroup.clearLayers();

        // Siapkan parameter filter
        const regencyId = document.getElementById('filterKabupaten') ? document.getElementById('filterKabupaten').value : '';
        const kegiatanId = document.getElementById('filterKegiatan').value;
        const status = document.getElementById('filterStatus').value;

        // Ambil data polygon via AJAX JSON
        fetch(`<?php echo e(route('shared.gis.data')); ?>?regency_id=${regencyId}&kegiatan_id=${kegiatanId}&status=${status}`)
            .then(res => res.json())
            .then(data => {
                document.getElementById('statsTotalPolygons').innerText = data.length;

                if (data.length === 0) {
                    return;
                }

                // Gambar masing-masing polygon berdasarkan format WKT
                data.forEach(item => {
                    const cleanWkt = item.koordinat_wkt.replace(/POLYGON\(\(/i, '').replace(/\)\)/, '');
                    const points = cleanWkt.split(',').map(pair => pair.trim().split(' '));

                    const latLngs = points.slice(0, -1).map(p => {
                        return [parseFloat(p[0]), parseFloat(p[1])];
                    });

                    // Skema warna dinamis berdasarkan status usulan
                    let borderCol = '#2563eb'; // blue
                    let fillCol = '#3b82f6';
                    
                    if (item.status === 'perbaikan') {
                        borderCol = '#d97706'; // amber
                        fillCol = '#f59e0b';
                    } else if (item.status === 'diverifikasi') {
                        borderCol = '#059669'; // emerald
                        fillCol = '#10b981';
                    } else if (item.status === 'final') {
                        borderCol = '#7c3aed'; // purple
                        fillCol = '#8b5cf6';
                    }

                    const polygon = L.polygon(latLngs, {
                        color: borderCol,
                        fillColor: fillCol,
                        fillOpacity: 0.35,
                        weight: 2
                    });

                    // Pop-up detil sawah premium
                    const popupContent = `
                        <div class="font-sans text-xs p-1 space-y-2 max-w-sm">
                            <div class="border-b border-slate-100 pb-1.5">
                                <span class="text-[9px] font-black uppercase text-emerald-800 block">Identitas Kelompok Tani:</span>
                                <h4 class="font-extrabold text-slate-800 text-sm">${item.nama_kelompok}</h4>
                                <span class="text-[9px] font-mono text-slate-400 mt-0.5 block">No Induk: ${item.nomor_induk}</span>
                            </div>
                            <div class="grid grid-cols-2 gap-2 text-[10px] leading-relaxed">
                                <div><span class="text-slate-400 block">Kecamatan:</span><b>${item.nama_kecamatan}</b></div>
                                <div><span class="text-slate-400 block">Desa:</span><b>${item.nama_desa}</b></div>
                                <div><span class="text-slate-400 block">Luas Lahan:</span><b class="text-emerald-700">${parseFloat(item.luas_lahan).toFixed(2)} Ha</b></div>
                                <div><span class="text-slate-400 block">Kabupaten:</span><b>${item.nama_kabupaten}</b></div>
                            </div>
                            <div class="border-t border-slate-100 pt-1.5 flex justify-between items-center">
                                <span class="px-2 py-0.5 rounded-full text-[9px] font-bold uppercase ${item.status === 'final' ? 'bg-purple-100 text-purple-800' : 'bg-slate-100 text-slate-600'}">${item.status}</span>
                                <span class="font-bold text-emerald-800 text-[10px] bg-emerald-50 px-2 py-0.5 rounded border border-emerald-100">${Math.round(item.akumulasi_skor)} pts</span>
                            </div>
                        </div>
                    `;

                    polygon.bindPopup(popupContent);
                    polygon.addTo(polygonFeatureGroup);
                });

                // Sesuaikan fokus kamera otomatis
                const bounds = polygonFeatureGroup.getBounds();
                gisMap.fitBounds(bounds, { padding: [30, 30] });
            })
            .catch(err => {
                console.error("Gagal memuat data GIS:", err);
            });
    }
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laragon\www\pradipa\resources\views/shared/gis/global.blade.php ENDPATH**/ ?>