

<?php $__env->startSection('title', 'Pemantauan Usulan Bantuan | 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=""/>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="flex flex-col gap-5">
    <!-- Header Halaman -->
    <div class="bg-white p-5 rounded-xl border border-slate-200 shadow-sm flex flex-col md:flex-row justify-between md:items-center gap-4">
        <div>
            <h2 class="text-xl font-bold text-slate-800">Daftar Usulan Bantuan Masuk</h2>
            <p class="text-xs text-slate-500 mt-1 font-medium font-sans">Pantau, verifikasi kelengkapan berkas syarat spasial, hitung prioritas, dan finalisasikan usulan bantuan.</p>
        </div>
        <!-- Tombol Tambah Usulan (Simulasi Cepat) -->
        <?php if($role === 'kabupaten_user'): ?>
            <a href="<?php echo e(route('kabupaten.usulan.create')); ?>" class="px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-semibold shadow-sm transition-all flex items-center gap-1.5 self-start md:self-auto font-sans">
                <i data-lucide="plus" class="w-4 h-4"></i>
                Tambah Usulan Baru (Kab)
            </a>
        <?php endif; ?>
    </div>

    <!-- SPANDUK INDIKATOR FILTER PROGRAM AKTIF -->
    <?php if(request()->anyFilled(['search', 'kabupaten', 'kegiatan', 'status'])): ?>
        <div class="bg-slate-100 border border-slate-200 px-4 py-2 rounded-xl text-xs flex justify-between items-center gap-4 flex-wrap animate-fade-in font-sans">
            <div class="flex items-center gap-1.5 text-slate-600 font-medium">
                <i data-lucide="filter" class="w-3.5 h-3.5 text-emerald-600 shrink-0"></i>
                <span>Statistik ringkasan di bawah telah disaring mengikuti kriteria filter yang aktif saat ini.</span>
            </div>
            <a href="<?php echo e(route('shared.usulan.index')); ?>" class="text-emerald-700 hover:text-emerald-800 font-bold hover:underline shrink-0">Bersihkan Filter</a>
        </div>
    <?php endif; ?>

    <!-- KARTU RINGKASAN STATUS USULAN (MINIMALIS & REAKTIF) -->
    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 font-sans text-xs">
        <!-- Card Draft -->
        <div class="bg-white p-3 rounded-xl border border-slate-200/80 border-l-4 border-l-slate-400 shadow-sm flex flex-col justify-between">
            <span class="text-slate-400 font-bold uppercase tracking-wider text-[8px] block">Draft Konsep</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-slate-700"><?php echo e($summary['draft']); ?></span>
                <span class="text-[9px] text-slate-400">berkas</span>
            </div>
        </div>

        <!-- Card Diajukan -->
        <div class="bg-white p-3 rounded-xl border border-blue-100 border-l-4 border-l-blue-500 shadow-sm flex flex-col justify-between">
            <span class="text-blue-500 font-bold uppercase tracking-wider text-[8px] block">Diajukan (Review)</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-blue-700"><?php echo e($summary['diajukan']); ?></span>
                <span class="text-[9px] text-blue-400">berkas</span>
            </div>
        </div>

        <!-- Card Butuh Perbaikan -->
        <div class="bg-white p-3 rounded-xl border border-amber-100 border-l-4 border-l-amber-500 shadow-sm flex flex-col justify-between">
            <span class="text-amber-600 font-bold uppercase tracking-wider text-[8px] block">Butuh Revisi</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-amber-700"><?php echo e($summary['perbaikan']); ?></span>
                <span class="text-[9px] text-amber-400">berkas</span>
            </div>
        </div>

        <!-- Card Terverifikasi -->
        <div class="bg-white p-3 rounded-xl border border-emerald-100 border-l-4 border-l-emerald-500 shadow-sm flex flex-col justify-between">
            <span class="text-emerald-600 font-bold uppercase tracking-wider text-[8px] block">Terverifikasi</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-emerald-700"><?php echo e($summary['diverifikasi']); ?></span>
                <span class="text-[9px] text-emerald-400">berkas</span>
            </div>
        </div>

        <!-- Card Final -->
        <div class="bg-white p-3 rounded-xl border border-purple-100 border-l-4 border-l-purple-500 shadow-sm flex flex-col justify-between">
            <span class="text-purple-600 font-bold uppercase tracking-wider text-[8px] block">SK Terbit (Final)</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-purple-700"><?php echo e($summary['final']); ?></span>
                <span class="text-[9px] text-purple-400">berkas</span>
            </div>
        </div>

        <!-- Card Total Kumulatif -->
        <div class="bg-slate-900 p-3 rounded-xl border border-slate-800 border-l-4 border-l-emerald-500 shadow-md text-white flex flex-col justify-between">
            <span class="text-emerald-400 font-extrabold uppercase tracking-wider text-[8px] block">Total Berkas</span>
            <div class="flex items-baseline gap-1 mt-1">
                <span class="text-base font-black text-white"><?php echo e($summary['total']); ?></span>
                <span class="text-[9px] text-slate-400">aktif</span>
            </div>
        </div>
    </div>

    <!-- Tampilan Error Validasi Server -->
    <?php if($errors->any()): ?>
        <div class="bg-rose-100 border-l-4 border-rose-600 text-rose-800 p-4 rounded-xl shadow-sm text-sm flex gap-3 items-start animate-fade-in">
            <i data-lucide="alert-triangle" class="w-5 h-5 text-rose-600 shrink-0 mt-0.5"></i>
            <div>
                <span class="font-extrabold block mb-1">Gagal Memproses Transisi Berkas:</span>
                <p class="font-medium text-xs text-rose-950 font-sans font-sans"><?php echo e($errors->first()); ?></p>
            </div>
        </div>
    <?php endif; ?>

    <!-- Tampilan Toast Flash Message Sukses -->
    <?php if(session('success')): ?>
        <div class="bg-emerald-100 border-l-4 border-emerald-600 text-emerald-800 p-4 rounded-xl shadow-sm text-sm flex items-center gap-2 font-sans">
            <i data-lucide="check-circle" class="text-emerald-600"></i>
            <span class="font-medium"><?php echo e(session('success')); ?></span>
        </div>
    <?php endif; ?>

    <!-- PANEL FILTER PENCARIAN & SORTING TERINTEGRASI -->
    <form action="<?php echo e(route('shared.usulan.index')); ?>" method="GET" class="bg-white p-4 rounded-xl border border-slate-200 shadow-sm grid grid-cols-1 md:grid-cols-12 gap-3.5">
        <!-- Input Cari (Nama Kelompok) -->
        <div class="md:col-span-4 relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-slate-400">
                <i data-lucide="search" class="w-4 h-4"></i>
            </span>
            <input type="text" name="search" value="<?php echo e(request('search')); ?>" placeholder="Cari kelompok tani..." class="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500 transition-all font-medium text-slate-700">
        </div>
        
        <!-- Filter Kabupaten (Hanya Provinsi) -->
        <?php if($role !== 'kabupaten_user'): ?>
            <div class="md:col-span-2">
                <select name="kabupaten" class="w-full px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer font-sans text-slate-600 font-semibold">
                    <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); ?>" <?php echo e(request('kabupaten') == $kab->id ? 'selected' : ''); ?>><?php echo e($kab->nama_kabupaten); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>
        <?php endif; ?>

        <!-- Filter Kegiatan -->
        <div class="<?php echo e($role === 'kabupaten_user' ? 'md:col-span-3' : 'md:col-span-2'); ?>">
            <select name="kegiatan" class="w-full px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer font-sans text-slate-600 font-semibold">
                <option value="">Semua Kegiatan</option>
                <?php $__currentLoopData = $kegiatans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $keg): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($keg->id); ?>" <?php echo e(request('kegiatan') == $keg->id ? 'selected' : ''); ?>><?php echo e($keg->nama_kegiatan); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>

        <!-- Filter Status -->
        <div class="<?php echo e($role === 'kabupaten_user' ? 'md:col-span-3' : 'md:col-span-2'); ?>">
            <select name="status" class="w-full px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer font-sans text-slate-600 font-semibold">
                <option value="">Semua Status</option>
                <option value="draft" <?php echo e(request('status') === 'draft' ? 'selected' : ''); ?>>Draft (Konsep)</option>
                <option value="diajukan" <?php echo e(request('status') === 'diajukan' ? 'selected' : ''); ?>>Diajukan (Review)</option>
                <option value="perbaikan" <?php echo e(request('status') === 'perbaikan' ? 'selected' : ''); ?>>Butuh Perbaikan</option>
                <option value="diverifikasi" <?php echo e(request('status') === 'diverifikasi' ? 'selected' : ''); ?>>Diverifikasi Admin</option>
                <option value="final" <?php echo e(request('status') === 'final' ? 'selected' : ''); ?>>Final (SK Terbit)</option>
            </select>
        </div>

        <!-- Dropdown Pengurutan (Sorting) -->
        <div class="<?php echo e($role === 'kabupaten_user' ? 'md:col-span-3' : 'md:col-span-2'); ?>">
            <select name="sort_by" class="w-full px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer font-sans text-slate-600 font-bold">
                <option value="">Urutkan: Terbaru</option>
                <option value="skor_desc" <?php echo e(request('sort_by') === 'skor_desc' ? 'selected' : ''); ?>>Skor: Tertinggi</option>
                <option value="skor_asc" <?php echo e(request('sort_by') === 'skor_asc' ? 'selected' : ''); ?>>Skor: Terendah</option>
                <option value="luas_desc" <?php echo e(request('sort_by') === 'luas_desc' ? 'selected' : ''); ?>>Luas: Terbesar</option>
                <option value="luas_asc" <?php echo e(request('sort_by') === 'luas_asc' ? 'selected' : ''); ?>>Luas: Terkecil</option>
            </select>
        </div>

        <!-- Tombol Filter Aksi -->
        <div class="md:col-span-2 flex gap-2">
            <button type="submit" class="flex-1 py-2 bg-slate-800 hover:bg-slate-900 text-white rounded-lg text-xs font-semibold transition-all font-sans text-center">
                Filter
            </button>
            <?php if(request()->anyFilled(['search', 'kabupaten', 'kegiatan', 'status', 'sort_by'])): ?>
                <a href="<?php echo e(route('shared.usulan.index')); ?>" class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-lg text-sm font-bold flex items-center justify-center transition-all animate-fade-in" title="Reset Filter">
                    <i data-lucide="rotate-ccw" class="w-4 h-4"></i>
                </a>
            <?php endif; ?>
        </div>
    </form>

    <!-- TABEL MONITORING UTAMA -->
    <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm divide-y divide-slate-100">
                <thead class="bg-slate-50">
                    <tr class="text-slate-500 uppercase text-[11px] font-bold tracking-wider">
                        <th class="py-4 px-6">Poktan / Kabupaten</th>
                        <th class="py-4 px-6">Kegiatan Bantuan</th>
                        <th class="py-4 px-6">Luas Pengajuan</th>
                        <th class="py-4 px-6 text-center">Skor Prioritas</th>
                        <th class="py-4 px-6">Status Berkas</th>
                        <th class="py-4 px-6 text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php $__empty_1 = true; $__currentLoopData = $usulans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $u): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr class="hover:bg-slate-50/50 transition-all">
                            <td class="py-4 px-6">
                                <div class="font-bold text-slate-800 text-sm"><?php echo e($u->nama_kelompok); ?></div>
                                <div class="text-[10px] text-slate-400 mt-0.5 font-sans">Kab: <?php echo e($u->nama_kabupaten); ?> | No Induk: <?php echo e($u->nomor_induk); ?></div>
                            </td>
                            <td class="py-4 px-6">
                                <div class="text-xs font-bold text-slate-700"><?php echo e($u->nama_kegiatan); ?></div>
                                <div class="text-[10px] text-slate-400 mt-0.5 font-sans">Tahun Anggaran <?php echo e($u->tahun_anggaran); ?></div>
                            </td>
                            <td class="py-4 px-6 font-semibold text-slate-700 text-xs font-sans">
                                <?php echo e($u->luas_pemanfaatan ?? 0); ?> Ha
                            </td>
                            <td class="py-4 px-6 text-center bg-emerald-50/30">
                                <span class="font-extrabold text-sm text-emerald-800" id="rowSkor-<?php echo e($u->id); ?>"><?php echo e($u->akumulasi_skor); ?></span>
                                <span class="text-[10px] text-emerald-600 block font-semibold">pts</span>
                            </td>
                            <td class="py-4 px-6">
                                <span id="rowBadge-<?php echo e($u->id); ?>">
                                    <?php if($u->status === 'draft'): ?>
                                        <span class="bg-slate-100 text-slate-800 text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase border border-slate-200">Draft</span>
                                    <?php elseif($u->status === 'diajukan'): ?>
                                        <span class="bg-blue-100 text-blue-800 text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase">Diajukan</span>
                                    <?php elseif($u->status === 'perbaikan'): ?>
                                        <span class="bg-amber-100 text-amber-800 text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase">Perbaikan</span>
                                    <?php elseif($u->status === 'diverifikasi'): ?>
                                        <span class="bg-emerald-100 text-emerald-800 text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase">Terverifikasi</span>
                                    <?php elseif($u->status === 'final'): ?>
                                        <span class="bg-purple-100 text-purple-800 text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase">Final SK</span>
                                    <?php endif; ?>
                                </span>
                            </td>
                            <td class="py-4 px-6 text-center">
                                <div class="flex items-center justify-center gap-1.5">
                                    <!-- Tombol Detail Usulan -->
                                    <button data-id="<?php echo e($u->id); ?>" class="btn-detail-usulan p-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg transition-all hover:scale-105 flex items-center justify-center" title="Proses / Detail Usulan">
                                        <i data-lucide="eye" class="w-4 h-4"></i>
                                    </button>

                                    <!-- AKSES SIMULASI OPERATOR KABUPATEN -->
                                    <?php if($role === 'kabupaten_user'): ?>
                                        <?php if($u->status === 'draft'): ?>
                                            <!-- Tombol Edit Draft -->
                                            <a href="<?php echo e(route('kabupaten.usulan.edit', $u->id)); ?>" class="p-2 bg-amber-50 hover:bg-amber-100 text-amber-700 border border-amber-200 rounded-lg transition-all hover:scale-105 flex items-center justify-center" title="Edit Draf">
                                                <i data-lucide="edit-3" class="w-4 h-4"></i>
                                            </a>
                                            <!-- Tombol Hapus Draft -->
                                            <form action="<?php echo e(route('kabupaten.usulan.destroy', $u->id)); ?>" method="POST" onsubmit="return confirm('Apakah Anda yakin ingin menghapus draf usulan ini secara permanen?');" class="inline">
                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>
                                                <button type="submit" class="p-2 bg-rose-50 hover:bg-rose-100 text-rose-600 border border-rose-200 rounded-lg transition-all hover:scale-105 flex items-center justify-center" title="Hapus Draft Permanen">
                                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                                </button>
                                            </form>
                                        <?php elseif($u->status === 'perbaikan'): ?>
                                            <!-- Tombol Revisi Berkas -->
                                            <a href="<?php echo e(route('kabupaten.usulan.edit', $u->id)); ?>" class="p-2 bg-amber-50 hover:bg-amber-100 text-amber-700 border border-amber-200 rounded-lg transition-all hover:scale-105 flex items-center justify-center" title="Revisi Berkas">
                                                <i data-lucide="edit-3" class="w-4 h-4"></i>
                                            </a>
                                            <!-- Tombol Batalkan Usulan -->
                                            <form action="<?php echo e(route('kabupaten.usulan.destroy', $u->id)); ?>" method="POST" onsubmit="return confirm('Apakah Anda yakin ingin mematalkan pengusulan berkas resmi ini dari Provinsi?');" class="inline">
                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>
                                                <button type="submit" class="p-2 bg-slate-100 hover:bg-slate-200 text-slate-600 border border-slate-300 rounded-lg transition-all hover:scale-105 flex items-center justify-center" title="Batalkan Pengusulan">
                                                    <i data-lucide="ban" class="w-4 h-4"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="6" class="py-8 text-center text-slate-400 text-xs font-medium font-sans">Belum ada usulan masuk untuk kriteria filter pencarian ini.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ================= MODAL DETIL & VERIFIKASI USULAN ================= -->
<div id="modalVerifikasi" class="hidden fixed inset-0 z-50 bg-slate-900/60 flex items-center justify-center p-4">
    <div class="bg-white w-full max-w-5xl rounded-2xl shadow-2xl border border-slate-200 flex flex-col max-h-[92vh] overflow-hidden animate-fade-in">
        
        <!-- Modal Header -->
        <div class="bg-slate-50 border-b border-slate-100 px-6 py-4 flex justify-between items-center">
            <div>
                <h3 class="font-extrabold text-slate-800 text-lg">Lembar Verifikasi Berkas Usulan</h3>
                <p class="text-xs text-slate-500 mt-0.5 font-sans" id="mvSubTitle">Kabupaten ... | Kelompok Tani ...</p>
            </div>
            <button onclick="tutupModalVerifikasi()" class="text-slate-400 hover:text-slate-600 bg-slate-100 hover:bg-slate-200 p-1.5 rounded-full transition-all">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        
        <!-- Modal Body (Scrollable) -->
        <div class="p-6 overflow-y-auto flex flex-col gap-6 custom-scrollbar">
            <!-- Informasi Poktan (🆕 DIKONSOLIDASIKAN UNTUK MEMECAH INFO HP KETUA DAN PENGIRIM SECARA PRESISI) -->
            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 p-4 bg-slate-50 border border-slate-100 rounded-xl text-xs font-sans">
                <div><span class="text-slate-400 block mb-0.5">Nomor Induk Poktan</span><b class="text-slate-800 font-mono" id="infoNomorInduk">-</b></div>
                <div><span class="text-slate-400 block mb-0.5">Ketua & NIK</span><b class="text-slate-800" id="infoKetua">-</b></div>
                <div><span class="text-slate-400 block mb-0.5">Hubungi Ketua (HP)</span><b class="text-emerald-700" id="infoHpKetua">-</b></div>
                <div><span class="text-slate-400 block mb-0.5">Luas Lahan Usulan</span><b class="text-slate-800" id="infoLuas">-</b></div>
                <!-- 🆕 ID 'infoPengirim' yang sempat terhapus dikembalikan dengan struktur yang minimalis -->
                <div><span class="text-slate-400 block mb-0.5">Pengirim Berkas</span><b class="text-slate-800" id="infoPengirim">-</b></div>
            </div>

            <!-- LAYOUT DUA KOLOM: Syarat vs Peta Spasial -->
            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
                
                <!-- KOLOM KIRI (7/12): List Persyaratan Berkas -->
                <div class="lg:col-span-7 flex flex-col gap-3 font-sans">
                    <h4 class="font-bold text-slate-700 text-xs uppercase tracking-wider">Berkas Persyaratan & Nilai Bobot</h4>
                    <div class="flex flex-col gap-3" id="syaratListContainer">
                        <!-- Dinamis terisi via Javascript -->
                    </div>
                </div>

                <!-- KOLOM KANAN (5/12): Visualisasi Peta Spasial -->
                <div class="lg:col-span-5 flex flex-col gap-3 font-sans">
                    <h4 class="font-bold text-slate-700 text-xs uppercase tracking-wider flex items-center gap-1.5">
                        <i data-lucide="map-pin" class="text-rose-500"></i>
                        Visualisasi Spasial Batas Lahan
                    </h4>
                    
                    <!-- KOTAK PREVIEW MINI MAP LEAFLET GOOGLE HYBRID NYATA -->
                    <div onclick="bukaMapModalDariDetail()" class="group relative w-full h-48 bg-slate-900 rounded-xl overflow-hidden shadow-inner cursor-pointer border border-slate-200 flex flex-col items-center justify-center font-sans">
                        <!-- Kontainer Peta Mini Leaflet -->
                        <div id="miniMapDetail" class="absolute inset-0 w-full h-full z-10 font-sans text-xs"></div>
                        <div class="absolute inset-0 bg-gradient-to-t from-slate-950/40 to-transparent z-20 pointer-events-none"></div>
                        
                        <!-- Tombol Maksimal Melayang di Atas Peta Mini -->
                        <div class="absolute top-3 right-3 z-30 bg-white/95 hover:bg-white text-emerald-800 p-2 rounded-lg shadow-md transition-all scale-95 hover:scale-100">
                            <i data-lucide="maximize-2" class="w-4 h-4 font-sans text-xs"></i>
                        </div>
                        <span id="detailMapStatusBadge" class="absolute bottom-3 left-3 z-30 text-[9px] bg-emerald-600 text-white font-extrabold px-2 py-0.5 rounded uppercase tracking-wider shadow">Sawah Tergambar</span>
                    </div>

                    <!-- Keterangan Spasial Geo-info -->
                    <div class="bg-slate-50 border border-slate-100 p-3 rounded-xl text-[10px] font-mono leading-relaxed text-slate-500">
                        <span class="font-bold block text-slate-600 mb-1">DATA GEOLOKASI (WKT):</span>
                        <div id="wktViewDisplay" class="truncate max-w-sm font-bold text-emerald-800 font-sans">Menunggu koordinat...</div>
                    </div>
                </div>

            </div>

            <!-- Skor Akumulasi Akhir -->
            <div class="flex justify-between items-center p-4 bg-emerald-50 border border-emerald-100 rounded-xl font-sans">
                <div>
                    <span class="text-xs text-emerald-800 font-bold block">Akumulasi Nilai Kesesuaian Syarat:</span>
                    <p class="text-[10px] text-emerald-600 font-medium">Bantuan diprioritaskan bagi pengusul yang melengkapi syarat dengan nilai >70 pts.</p>
                </div>
                <div class="text-2xl font-extrabold text-emerald-800 font-sans"><span id="mvSkorTotal">0</span> <span class="text-xs font-normal text-emerald-600 font-sans font-sans font-sans">dari 100</span></div>
            </div>

            <!-- Alur WhatsApp Redirect -->
            <div class="hidden p-4 bg-amber-50 border border-amber-100 rounded-xl flex items-center justify-between gap-4 font-sans" id="waRedirectPanel">
                <div class="flex gap-2.5 items-start">
                    <div class="bg-amber-100 text-amber-800 p-1.5 rounded-lg shrink-0 mt-0.5">
                        <i data-lucide="info" class="w-4 h-4 text-amber-700 font-sans text-xs"></i>
                    </div>
                    <div>
                        <span class="text-xs text-amber-900 font-bold block font-sans">Butuh koordinasi cepat?</span>
                        <p class="text-[10px] text-amber-700 leading-relaxed mt-0.5 font-sans font-sans font-sans">Gunakan tombol kirim template pesan WhatsApp di samping untuk menginstruksikan perbaikan berkas kepada operator kabupaten terkait.</p>
                    </div>
                </div>
                <a href="#" id="btnWhatsAppRedirect" target="_blank" class="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-lg transition-colors flex items-center gap-1.5 shrink-0 shadow-sm font-sans">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2H2v20l4-4h16V2z"/></svg>
                    Kirim WA
                </a>
            </div>

            <!-- ================= TIMELINE RIWAYAT PROSES (AUDIT TRAIL) ================= -->
            <div class="border-t border-slate-100 pt-6 font-sans">
                <h4 class="font-bold text-slate-800 text-sm mb-4 flex items-center gap-2 font-sans">
                    <i data-lucide="history" class="text-slate-500 font-sans text-xs"></i>
                    Timeline Perjalanan Berkas (Audit Trail Sistem)
                </h4>
                
                <div class="relative border-l-2 border-slate-100 ml-3 space-y-6" id="timelineContainer">
                    <!-- Dinamis terisi dari JavaScript -->
                </div>
            </div>

        </div>

        <!-- Modal Footer -->
        <div class="bg-slate-50 border-t border-slate-100 px-6 py-4 flex justify-between items-center font-sans" id="mvActions">
            <!-- Dinamis terisi via Javascript -->
        </div>
    </div>
</div>

<!--             PGIM TERPADU PENERIMA (VIEW MODE ONLY)                        -->
<?php echo $__env->make('components.map-geospatial', [
    'mode' => 'view'
], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
    let activeUsulanId = null;
    let currentActiveWkt = null;
    
    const activeUserRole = "<?php echo e($role); ?>";

    let miniMapDetail = null;
    let miniMapPolygonLayer = null;

    document.addEventListener('DOMContentLoaded', function() {
        document.addEventListener('click', function(e) {
            const btn = e.target.closest('.btn-detail-usulan');
            if (btn) {
                const id = btn.getAttribute('data-id');
                bukaModalVerifikasi(id);
            }
        });
    });

    function bukaMapModalDariDetail() {
        if (currentActiveWkt) {
            window.bukaModalPetaDetail(currentActiveWkt);
        } else {
            alert("Kelompok tani ini belum memetakan polygon koordinat batas sawah!");
        }
    }

    function inisialisasiPetaMiniDetail(wktString) {
        const mapContainer = document.getElementById('miniMapDetail');
        if (!mapContainer) return;

        if (!miniMapDetail) {
            miniMapDetail = L.map('miniMapDetail', {
                center: [-7.0522, 110.4325],
                zoom: 12,
                zoomControl: false,
                dragging: false,
                scrollWheelZoom: false,
                doubleClickZoom: false,
                boxZoom: false,
                keyboard: false,
                attributionControl: false
            });

            L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
            }).addTo(miniMapDetail);

            miniMapPolygonLayer = L.polygon([], {
                color: '#10b981',
                fillColor: '#10b981',
                fillOpacity: 0.35,
                weight: 2
            }).addTo(miniMapDetail);
        }

        if (wktString) {
            try {
                const cleanWkt = wktString.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])];
                });

                miniMapPolygonLayer.setLatLngs(latLngs);

                setTimeout(() => {
                    miniMapDetail.invalidateSize();
                    const bounds = miniMapPolygonLayer.getBounds();
                    miniMapDetail.fitBounds(bounds, { padding: [10, 10] });
                }, 200);

            } catch (e) {
                console.error("Gagal menggambar polygon di peta mini:", e);
            }
        } else {
            miniMapPolygonLayer.setLatLngs([]);
        }
    }

    function bukaModalVerifikasi(id) {
        activeUsulanId = id;
        
        fetch(`<?php echo e(url('shared/usulan')); ?>/${id}/detail`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Gagal memuat data (HTTP ${response.status}).`);
                }
                return response.json();
            })
            .then(data => {
                const u = data.usulan;
                const sList = data.syarat;
                const rList = data.riwayat || [];
                
                document.getElementById('mvSubTitle').innerText = `${u.nama_kabupaten} | Kelompok Tani ${u.nama_kelompok}`;
                document.getElementById('infoNomorInduk').innerText = u.nomor_induk;
                
                // Tampilkan info Nama Ketua & NIK
                document.getElementById('infoKetua').innerText = `${u.nama_ketua} (${u.nik_ketua})`;
                
                // Tampilkan Nomor HP Ketua Kelompok Tani dengan Tautan WhatsApp langsung!
                const noHpKetua = u.no_hp_ketua ? u.no_hp_ketua : '-';
                if (u.no_hp_ketua) {
                    let formattedWaKetua = u.no_hp_ketua.replace(/[^0-9]/g, '');
                    if (formattedWaKetua.startsWith('0')) {
                        formattedWaKetua = '62' + formattedWaKetua.substring(1);
                    }
                    document.getElementById('infoHpKetua').innerHTML = `
                        <a href="https://wa.me/${formattedWaKetua}" target="_blank" class="text-emerald-600 hover:text-emerald-800 hover:underline flex items-center gap-1 font-bold">
                            ${noHpKetua}
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M22 2H2v20l4-4h16V2z"/></svg>
                        </a>`;
                } else {
                    document.getElementById('infoHpKetua').innerText = '-';
                }

                document.getElementById('infoLuas').innerText = `${data.barang[0]?.luas_pemanfaatan || 0} Ha`;
                
                // 🟢 SINKRONISASI DIPERBAIKI: Mengembalikan penulisan text ke container 'infoPengirim' secara aman
                document.getElementById('infoPengirim').innerText = `${u.nama_pengirim} (${u.no_hp_pengirim || '-'})`;
                
                document.getElementById('mvSkorTotal').innerText = u.akumulasi_skor;

                const waPanel = document.getElementById('waRedirectPanel');
                if (u.no_hp_pengirim) {
                    waPanel.classList.remove('hidden');
                    let noHp = u.no_hp_pengirim.replace(/[^0-9]/g, '');
                    if (noHp.startsWith('0')) {
                        noHp = '62' + noHp.substring(1);
                    }
                    const textMsg = `Halo ${u.nama_pengirim},\r\n\r\nKami dari Admin Dinas Pertanian Provinsi Jateng ingin mengonfirmasi bahwa berkas pengajuan usulan bantuan "${u.nama_kegiatan}" untuk kelompok tani *"${u.nama_kelompok}"* pada aplikasi *PRADIPA* berstatus *BUTUH PERBAIKAN*.\r\n\r\nCatatan Evaluasi: \r\n_${u.catatan_terakhir || 'Mohon lengkapi file persyaratan sesuai petunjuk.'}_\r\n\r\nHarap segera login ke aplikasi Pradipa untuk memperbaiki berkas. Terima kasih.`;
                    document.getElementById('btnWhatsAppRedirect').href = `https://wa.me/${noHp}?text=${encodeURIComponent(textMsg)}`;
                } else {
                    waPanel.classList.add('hidden');
                }

                let spatialWkt = null;
                sList.forEach(s => {
                    if (s.tipe_file === 'polygon' && s.koordinat_wkt) {
                        spatialWkt = s.koordinat_wkt;
                    }
                });

                currentActiveWkt = spatialWkt;

                if (spatialWkt) {
                    document.getElementById('wktViewDisplay').innerText = spatialWkt;
                    document.getElementById('detailMapStatusBadge').innerText = "Sawah Tergambar";
                    document.getElementById('detailMapStatusBadge').className = "absolute bottom-3 left-3 z-30 text-[9px] bg-emerald-600 text-white font-extrabold px-2 py-0.5 rounded uppercase tracking-wider shadow";
                } else {
                    document.getElementById('wktViewDisplay').innerText = "[tidak ada data koordinat]";
                    document.getElementById('detailMapStatusBadge').innerText = "Belum Tergambar";
                    document.getElementById('detailMapStatusBadge').className = "absolute bottom-3 left-3 z-30 text-[9px] bg-slate-600 text-white font-extrabold px-2 py-0.5 rounded uppercase tracking-wider shadow";
                }

                inisialisasiPetaMiniDetail(spatialWkt);

                const listContainer = document.getElementById('syaratListContainer');
                listContainer.innerHTML = '';

                sList.forEach(s => {
                    let statusColor = "bg-slate-100 text-slate-600";
                    if (s.status_verifikasi === 'valid') statusColor = "bg-emerald-100 text-emerald-800 font-bold";
                    if (s.status_verifikasi === 'ditolak') statusColor = "bg-rose-100 text-rose-800 font-bold";

                    let buttonActions = '';
                    
                    if (u.status === 'diajukan' && activeUserRole === 'provinsi_admin') {
                        buttonActions = `
                            <div class="flex items-center gap-2 mt-2 self-end sm:self-auto font-sans">
                                <button onclick="verifikasikanItem(${s.id}, 'valid')" class="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-[10px] font-bold transition-colors">Setujui Valid</button>
                                <button onclick="verifikasikanItem(${s.id}, 'ditolak')" class="px-2.5 py-1 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-[10px] font-bold transition-colors">Tolak Berkas</button>
                            </div>
                        `;
                    }

                    let fileDownloadLink = '';
                    if (s.file_path) {
                        const fileUrl = `<?php echo e(asset('')); ?>${s.file_path}`;
                        fileDownloadLink = `
                            <div class="mt-2 flex items-center gap-1.5 text-xs text-emerald-700 font-extrabold font-sans">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-emerald-600 shrink-0" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>
                                <a href="${fileUrl}" target="_blank" class="hover:underline flex items-center gap-1">Pratinjau / Unduh Berkas Persyaratan</a>
                            </div>
                        `;
                    }

                    listContainer.innerHTML += `
                        <div class="p-4 border border-slate-200 rounded-xl flex flex-col gap-2 bg-white shadow-sm">
                            <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-2">
                                <div>
                                    <div class="flex items-center gap-2 flex-wrap">
                                        <span class="px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 font-mono text-[9px] uppercase font-bold">${s.tipe_file}</span>
                                        <h5 class="font-bold text-slate-800 text-sm">${s.nama_syarat}</h5>
                                        <span class="bg-amber-100 text-amber-800 text-[9px] font-bold px-1.5 py-0.5 rounded font-sans">Bobot: ${Math.round(s.bobot_nilai)} pts</span>
                                    </div>
                                    <p class="text-[10px] text-slate-400 mt-1 font-mono leading-none truncate max-w-sm font-sans">
                                        ${s.file_path ? `Terunggah: ${s.file_path}` : `WKT: ${s.koordinat_wkt}`}
                                    </p>
                                    
                                    ${fileDownloadLink}
                                </div>
                                <span class="text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider self-start sm:self-auto ${statusColor}">${s.status_verifikasi}</span>
                            </div>
                            
                            ${s.catatan_perbaikan ? `
                                <div class="p-2 bg-rose-50 border border-rose-100 text-[10px] text-rose-800 rounded-lg flex gap-1.5 mt-1 leading-relaxed">
                                    <i data-lucide="info" class="w-3.5 h-3.5 text-rose-600 shrink-0"></i>
                                    <span><b>Alasan Penolakan:</b> ${s.catatan_perbaikan}</span>
                                </div>
                            ` : ''}

                            ${buttonActions}
                        </div>
                    `;
                });

                const timelineContainer = document.getElementById('timelineContainer');
                timelineContainer.innerHTML = '';

                if (rList.length > 0) {
                    rList.forEach(r => {
                        const tgl = new Date(r.created_at);
                        const tglString = tgl.toLocaleString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute:'2-digit' });

                        let statusSesudahBadge = '';
                        if (r.status_sesudah === 'diajukan') statusSesudahBadge = '<span class="bg-blue-100 text-blue-800 px-2 py-0.5 rounded text-[9px] font-extrabold uppercase ml-2">Diajukan</span>';
                        if (r.status_sesudah === 'perbaikan') statusSesudahBadge = '<span class="bg-amber-100 text-amber-800 px-2 py-0.5 rounded text-[9px] font-extrabold uppercase ml-2">Revisis</span>';
                        if (r.status_sesudah === 'diverifikasi') statusSesudahBadge = '<span class="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded text-[9px] font-extrabold uppercase ml-2">Terverifikasi</span>';
                        if (r.status_sesudah === 'final') statusSesudahBadge = '<span class="bg-purple-100 text-purple-800 px-2 py-0.5 rounded text-[9px] font-extrabold uppercase ml-2">Final SK</span>';

                        timelineContainer.innerHTML += `
                            <div class="relative pl-6">
                                <div class="absolute -left-[7px] top-1 w-3.5 h-3.5 rounded-full border-2 border-white bg-slate-400 shadow-sm"></div>
                                <div class="bg-slate-50 border border-slate-100 p-3.5 rounded-xl">
                                    <div class="flex items-center justify-between gap-4 flex-wrap">
                                        <div class="flex items-center gap-1.5 flex-wrap">
                                            <span class="font-extrabold text-slate-800 text-xs">${r.nama_petugas}</span>
                                            <span class="text-[9px] text-slate-400 uppercase font-bold font-mono">(${r.peran_petugas.replace('_', ' ')})</span>
                                            ${statusSesudahBadge}
                                        </div>
                                        <span class="text-[10px] text-slate-400 font-semibold">${tglString} WIB</span>
                                    </div>
                                    <p class="text-xs text-slate-500 mt-1.5 leading-relaxed font-sans">${r.catatan || 'Perubahan status dokumen diproses oleh sistem.'}</p>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    timelineContainer.innerHTML = `
                        <div class="relative pl-6">
                            <div class="absolute -left-[7px] top-1 w-3.5 h-3.5 rounded-full border-2 border-white bg-emerald-500 shadow-sm animate-pulse"></div>
                            <div class="bg-slate-50 border border-slate-100 p-3 rounded-xl">
                                <span class="text-[10px] text-slate-400 font-bold block uppercase tracking-wider">Berkas Awal Terdaftar</span>
                                <span class="font-extrabold text-slate-800 text-xs block mt-1">Operator Kabupaten</span>
                                <p class="text-xs text-slate-500 mt-1 font-sans">Berkas usulan sukses dikirim dari draf kabupaten ke sistem Pradipa Provinsi.</p>
                            </div>
                        </div>
                    `;
                }

                const footerActions = document.getElementById('mvActions');
                footerActions.innerHTML = '';

                if (u.status === 'diajukan' && activeUserRole === 'provinsi_admin') {
                    footerActions.innerHTML = `
                        <button onclick="mintaPerbaikanKab(${u.id})" class="px-4 py-2.5 bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs rounded-lg transition-colors shadow-sm">Kembalikan ke Kabupaten (Butuh Revisi)</button>
                        <form action="<?php echo e(url('shared/usulan')); ?>/${u.id}/proses-verifikasi" method="POST">
                            <?php echo csrf_field(); ?>
                            <button type="submit" class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-lg transition-colors shadow-sm font-sans">Kirim Hasil Verifikasi ke Pejabat</button>
                        </form>
                    `;
                } else if (u.status === 'diverifikasi' && activeUserRole === 'provinsi_pejabat') {
                    footerActions.innerHTML = `
                        <button onclick="tutupModalVerifikasi()" class="px-4 py-2.5 bg-slate-100 text-slate-600 font-bold text-xs rounded-lg font-sans">Batal</button>
                        <form action="<?php echo e(url('shared/usulan')); ?>/${u.id}/finalisasi" method="POST">
                            <?php echo csrf_field(); ?>
                            <button type="submit" class="px-4 py-2.5 bg-purple-600 hover:bg-purple-700 text-white font-bold text-xs rounded-lg transition-colors shadow-sm font-sans">Finalisasi & Terbitkan Status SK</button>
                        </form>
                    `;
                } else {
                    let textIndicator = "Tampilan Pratinjau Berkas (Sesuai Hak Otoritas Akun Anda)";
                    if (u.status === 'diajukan' && activeUserRole === 'provinsi_pejabat') {
                        textIndicator = "Menunggu Sidang Verifikasi Teknis oleh Admin Provinsi";
                    } else if (u.status === 'diverifikasi' && activeUserRole === 'provinsi_admin') {
                        textIndicator = "Menunggu Persetujuan Final & Penerbitan SK Kepala Dinas";
                    }

                    footerActions.innerHTML = `
                        <div class="text-[11px] text-slate-400 italic font-bold font-sans">${textIndicator}</div>
                        <button onclick="tutupModalVerifikasi()" class="px-4 py-2.5 bg-slate-100 text-slate-600 font-bold text-xs rounded-lg font-sans">Tutup</button>
                    `;
                }

                document.getElementById('modalVerifikasi').classList.remove('hidden');
                if (typeof lucide !== 'undefined') {
                    lucide.createIcons();
                }
            })
            .catch(error => {
                console.error('Error AJAX:', error);
                alert(`Gagal memuat detail usulan!\n\nAlasan: ${error.message}`);
            });
    }

    function verifikasikanItem(syaratId, action) {
        let catatan = '';
        if (action === 'ditolak') {
            catatan = prompt("Tuliskan alasan spesifik mengapa berkas ditolak:");
            if (catatan === null) return;
        }

        fetch(`<?php echo e(route('shared.usulan.verify_syarat')); ?>`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                usulan_syarat_id: syaratId,
                action: action,
                catatan: catatan
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(json => { throw new Error(json.error || 'Gagal mengubah status verifikasi.') });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                document.getElementById('mvSkorTotal').innerText = data.new_skor;
                document.getElementById(`rowSkor-${activeUsulanId}`).innerText = data.new_skor;
                bukaModalVerifikasi(activeUsulanId);
            }
        })
        .catch(err => {
            alert('Kesalahan Otoritas: ' + err.message);
        });
    }

    function mintaPerbaikanKab(id) {
        let catatan = prompt("Tuliskan memo catatan perbaikan berkas untuk Operator Kabupaten:");
        if (!catatan) {
            alert("Sistem membutuhkan catatan alasan pengembalian berkas!");
            return;
        }

        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `<?php echo e(url('shared/usulan')); ?>/${id}/kembalikan`;
        
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '_token';
        csrfInput.value = '<?php echo e(csrf_token()); ?>';
        form.appendChild(csrfInput);

        const catatanInput = document.createElement('input');
        catatanInput.type = 'hidden';
        catatanInput.name = 'catatan_terakhir';
        catatanInput.value = catatan;
        form.appendChild(catatanInput);

        document.body.appendChild(form);
        form.submit();
    }

    function tutupModalVerifikasi() {
        document.getElementById('modalVerifikasi').classList.add('hidden');
        activeUsulanId = null;
    }
</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/monitoring.blade.php ENDPATH**/ ?>