



<?php $__env->startSection('styles'); ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo e(asset('css/admin.css')); ?>">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.Default.css" />
<?php $__env->stopSection(); ?>



<?php $__env->startSection('content'); ?>


    
    <?php
        $totalSemua  = \App\Models\Lapor::count();
        $top1        = $laporan->first();
        $stMenunggu  = \App\Models\Lapor::where('status', 'menunggu')->count();
        $stProses    = \App\Models\Lapor::where('status', 'diproses')->count();
        $stSelesai   = \App\Models\Lapor::where('status', 'selesai')->count();
        $stTolak     = \App\Models\Lapor::where('status', 'ditolak')->count();

        $hamaDominan = \App\Models\Lapor::selectRaw('jenis_hama, count(*) as total')
                            ->groupBy('jenis_hama')
                            ->orderByDesc('total')
                            ->first();

        $luasKecil  = \App\Models\Lapor::where('luas_lahan', 'luas_kecil')->count();
        $luasSedang = \App\Models\Lapor::where('luas_lahan', 'luas_sedang')->count();
        $luasBesar  = \App\Models\Lapor::where('luas_lahan', 'luas_besar')->count();

        $mingguIni  = \App\Models\Lapor::where('created_at', '>=', now()->startOfWeek())->count();
        $hamaGroups = \App\Models\Lapor::selectRaw('jenis_hama, count(*) as total')
                            ->groupBy('jenis_hama')
                            ->orderByDesc('total')
                            ->get();

        $tglTerbaru = \App\Models\Lapor::max('created_at');
        $pctRingan  = $totalSemua > 0 ? number_format($statistik['Ringan'] / $totalSemua * 100, 1) : 0;
        $pctSedang  = $totalSemua > 0 ? number_format($statistik['Sedang'] / $totalSemua * 100, 1) : 0;
        $total      = $laporan->count();

        // Hitung AHP dari DecisionService (nilai REAL dari sistem)
        $decisionService = app(\App\Services\DecisionService::class);
        $ahpResult       = $decisionService->hitungAHP();
        $bobotAHP        = $ahpResult['bobot'];   // [0]=Tingkat, [1]=Luas, [2]=Lama, [3]=Hama
        $crValue         = $ahpResult['CR'];
        $crKonsisten     = $crValue < 0.1;

        // Nama kriteria sesuai urutan di DecisionService
        $kriteriaAHP = [
            ['nama' => 'Tingkat Serangan', 'bobot' => $bobotAHP[0], 'warna' => '#1b5e20'],
            ['nama' => 'Luas Lahan',       'bobot' => $bobotAHP[1], 'warna' => '#388e3c'],
            ['nama' => 'Lama Serangan',    'bobot' => $bobotAHP[2], 'warna' => '#66bb6a'],
            ['nama' => 'Jenis Hama',       'bobot' => $bobotAHP[3], 'warna' => '#a5d6a7'],
        ];
    ?>


    
    <div class="rt-bar">
        <div class="rt-bar-left">
            <span class="rt-dot-wrap">
                <span class="rt-dot"></span>
            </span>
            <span class="rt-label">Data Realtime</span>
            <span class="rt-badge">Diperbarui otomatis setiap 30 detik</span>
        </div>

        <div class="rt-bar-right">
            <span class="rt-countdown">
                Refresh dalam: <b id="rtTimer">30</b>s
            </span>
            <button onclick="manualRefresh()" class="rt-btn-refresh">
                🔃 Refresh Sekarang
            </button>
            <button onclick="exportPDF()" class="rt-btn-export" id="btnExport">
                📄 Export PDF
            </button>
        </div>
    </div>


    
    <div id="rt-toast" class="rt-toast"></div>


    
    <div id="rt-alert"
         class="dash-alert-berat"
         style="<?php echo e($statistik['Berat'] > 0 ? '' : 'display:none;'); ?>">

        <span class="dash-alert-ico">🚨</span>

        <div>
            <div class="dash-alert-title">
                <span id="rt-alert-count"><?php echo e($statistik['Berat']); ?></span>
                Laporan Memerlukan Penanganan Segera!
            </div>
            <div class="dash-alert-desc">
                Terdapat laporan dengan tingkat serangan <strong>Berat</strong>
                yang harus segera mendapat kunjungan lapangan dari penyuluh pertanian.
            </div>
        </div>
    </div>


    
    <div class="dash-metric-grid">

        
        <div class="dash-metric mc-total">
            <div class="dash-metric-top">
                <div class="dash-metric-ico" style="background:#e8f5e9;">📋</div>
                <span class="dash-chip chip-up" id="rt-minggu">+<?php echo e($mingguIni); ?> minggu ini</span>
            </div>
            <div class="dash-metric-val" id="rt-total"><?php echo e($totalSemua); ?></div>
            <div class="dash-metric-label">Total Laporan Masuk</div>
            <div class="dash-metric-sub"><?php echo e(count($perKecamatan)); ?> kecamatan terdampak</div>
        </div>

        
        <div class="dash-metric mc-ringan">
            <div class="dash-metric-top">
                <div class="dash-metric-ico" style="background:#e8f5e9;">🟢</div>
                <span class="dash-chip chip-neu" id="rt-pct-ringan"><?php echo e($pctRingan); ?>%</span>
            </div>
            <div class="dash-metric-val" id="rt-ringan"><?php echo e($statistik['Ringan']); ?></div>
            <div class="dash-metric-label">Serangan Ringan</div>
            <div class="dash-metric-sub">Status: Pantau berkala</div>
        </div>

        
        <div class="dash-metric mc-sedang">
            <div class="dash-metric-top">
                <div class="dash-metric-ico" style="background:#fff3e0;">🟡</div>
                <span class="dash-chip chip-neu" id="rt-pct-sedang"><?php echo e($pctSedang); ?>%</span>
            </div>
            <div class="dash-metric-val" id="rt-sedang"><?php echo e($statistik['Sedang']); ?></div>
            <div class="dash-metric-label">Serangan Sedang</div>
            <div class="dash-metric-sub">Status: Waspada eskalasi</div>
        </div>

        
        <div class="dash-metric mc-berat">
            <div class="dash-metric-top">
                <div class="dash-metric-ico" style="background:#ffebee;">🔴</div>
                <span class="dash-chip chip-up">Prioritas</span>
            </div>
            <div class="dash-metric-val" id="rt-berat"><?php echo e($statistik['Berat']); ?></div>
            <div class="dash-metric-label">Serangan Berat</div>
            <div class="dash-metric-sub">Status: Segera tangani</div>
        </div>

    </div>


    
    <div class="dash-status-strip">

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#fff3e0;">⏳</div>
            <div>
                <div class="dash-status-val" id="rt-menunggu"><?php echo e($stMenunggu); ?></div>
                <div class="dash-status-lbl">Menunggu</div>
            </div>
        </div>

        <div class="dash-status-div"></div>

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#e3f2fd;">🔄</div>
            <div>
                <div class="dash-status-val" id="rt-proses"><?php echo e($stProses); ?></div>
                <div class="dash-status-lbl">Diproses</div>
            </div>
        </div>

        <div class="dash-status-div"></div>

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#e8f5e9;">✅</div>
            <div>
                <div class="dash-status-val" id="rt-selesai"><?php echo e($stSelesai); ?></div>
                <div class="dash-status-lbl">Selesai</div>
            </div>
        </div>

        <div class="dash-status-div"></div>

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#ffebee;">❌</div>
            <div>
                <div class="dash-status-val" id="rt-tolak"><?php echo e($stTolak); ?></div>
                <div class="dash-status-lbl">Ditolak</div>
            </div>
        </div>

        <div class="dash-status-div"></div>

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#f3e5f5;">🐛</div>
            <div>
                <div class="dash-status-val" id="rt-hama-dom" style="font-size:13px;">
                    <?php echo e($hamaDominan->jenis_hama ?? '-'); ?>

                </div>
                <div class="dash-status-lbl">Hama Dominan</div>
            </div>
        </div>

        <div class="dash-status-div"></div>

        <div class="dash-status-item">
            <div class="dash-status-ico" style="background:#e8f5e9;">📅</div>
            <div>
                <div class="dash-status-val" style="font-size:13px;">
                    <?php echo e($tglTerbaru ? \Carbon\Carbon::parse($tglTerbaru)->format('d M Y') : '-'); ?>

                </div>
                <div class="dash-status-lbl">Laporan Terakhir</div>
            </div>
        </div>

    </div>


    
    <?php if($top1): ?>
        <div class="dash-top-priority">
            <div class="dash-tp-left">
                <div class="dash-tp-trophy">🏆</div>
                <div>
                    <div class="dash-tp-eyebrow">PRIORITAS #1 — SEGERA TANGANI</div>
                    <div class="dash-tp-name" id="rt-tp-name">
                        <?php echo e($top1->nama_petani); ?> — <?php echo e($top1->jenis_hama); ?>

                    </div>
                    <div class="dash-tp-meta">
                        <span>📍 <?php echo e(Str::limit($top1->lokasi, 45)); ?></span>
                        <span>🌾 <?php echo e(ucwords(str_replace('_', ' ', $top1->luas_lahan))); ?></span>
                        <span>⏱️ <?php echo e(ucwords(str_replace('_', ' ', $top1->lama_kejadian))); ?></span>
                        <span class="dash-tp-badge"><?php echo e($top1->tingkat_serangan); ?></span>
                    </div>
                </div>
            </div>

            <div class="dash-tp-right">
                <div class="dash-tp-score" id="rt-tp-score">
                    <?php echo e(number_format($top1->nilai_preferensi ?? 0, 4)); ?>

                </div>
                <div class="dash-tp-score-lbl">Nilai TOPSIS</div>
                <div class="dash-tp-chip" id="rt-tp-count">
                    Tertinggi dari <?php echo e($total); ?> laporan terranking
                </div>
            </div>
        </div>
    <?php endif; ?>


    
    <div class="dash-chart-grid">

        
        <div class="dash-panel">
            <div class="dash-panel-hdr">
                <div class="dash-panel-title">📊 Distribusi Tingkat Serangan</div>
            </div>
            <div class="dash-panel-body">
                <div class="dash-legend-row">
                    <span class="dash-legend-dot" style="background:#43a047;"></span>
                    Ringan (<?php echo e($statistik['Ringan']); ?>)
                    <span class="dash-legend-dot" style="background:#fb8c00; margin-left:10px;"></span>
                    Sedang (<?php echo e($statistik['Sedang']); ?>)
                    <span class="dash-legend-dot" style="background:#e53935; margin-left:10px;"></span>
                    Berat (<?php echo e($statistik['Berat']); ?>)
                </div>
                <div class="dash-chart-wrap">
                    <canvas id="chartTingkat"></canvas>
                </div>
            </div>
        </div>

        
        <div class="dash-panel">
            <div class="dash-panel-hdr">
                <div class="dash-panel-title">🐛 Distribusi Jenis Hama</div>
            </div>
            <div class="dash-panel-body">
                <?php
                    $hamaColors = ['#1b5e20', '#388e3c', '#66bb6a', '#ffa726', '#ef5350'];
                ?>

                <div class="dash-hbar-list">
                    <?php $__currentLoopData = $hamaGroups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $hg): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php
                            $pct = $totalSemua > 0 ? round($hg->total / $totalSemua * 100, 1) : 0;
                            $col = $hamaColors[$loop->index % count($hamaColors)];
                        ?>
                        <div class="dash-hbar-row">
                            <span class="dash-hbar-name"><?php echo e($hg->jenis_hama); ?></span>
                            <div class="dash-hbar-bg">
                                <div class="dash-hbar-fill"
                                     style="width:<?php echo e($pct); ?>%; background:<?php echo e($col); ?>;"></div>
                            </div>
                            <span class="dash-hbar-cnt"><?php echo e($hg->total); ?></span>
                            <span class="dash-hbar-pct"><?php echo e($pct); ?>%</span>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>

                <div class="dash-chart-wrap" style="height:140px; margin-top:12px;">
                    <canvas id="chartHama"></canvas>
                </div>
            </div>
        </div>

    </div>


    
    <div class="dash-bottom-grid">

        
        <div class="dash-panel">
            <div class="dash-panel-hdr">
                <div class="dash-panel-title">⚖️ Bobot Kriteria AHP</div>
            </div>
            <div class="dash-panel-body">

                
                <div class="dash-ahp-list">
                    <?php $__currentLoopData = $kriteriaAHP; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="dash-ahp-row">
                            <span class="dash-ahp-name"><?php echo e($k['nama']); ?></span>
                            <div class="dash-ahp-bar-bg">
                                <div class="dash-ahp-bar-fill"
                                     style="width:<?php echo e(number_format($k['bobot'] * 100, 1)); ?>%;
                                            background:<?php echo e($k['warna']); ?>;"></div>
                            </div>
                            <span class="dash-ahp-pct" style="color:<?php echo e($k['warna']); ?>;">
                                <?php echo e(number_format($k['bobot'] * 100, 2)); ?>%
                            </span>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>

                
                <div class="dash-cr-box"
                     style="<?php echo e($crKonsisten ? '' : 'background:#fff3e0; border-color:#fde68a;'); ?>">
                    <div>
                        <div class="dash-cr-label">Consistency Ratio (CR)</div>
                        <div class="dash-cr-ok"
                             style="color:<?php echo e($crKonsisten ? '#388e3c' : '#b45309'); ?>;">
                            <?php echo e($crKonsisten
                                ? '✅ Konsisten — CR < 0.1'
                                : '⚠️ Tidak Konsisten — CR ≥ 0.1'); ?>

                        </div>
                    </div>
                    <div class="dash-cr-val"
                         style="color:<?php echo e($crKonsisten ? '#1b5e20' : '#b45309'); ?>;">
                        <?php echo e(number_format($crValue, 4)); ?>

                    </div>
                </div>

                
                <div style="margin-top:16px;">
                    <div class="dash-panel-title" style="font-size:12px; margin-bottom:10px;">
                        🌾 Distribusi Luas Lahan
                    </div>
                    <div class="dash-luas-cards">
                        <div class="dash-luas-card" style="border-color:#66bb6a;">
                            <div class="dash-luas-val" style="color:#2e7d32;"><?php echo e($luasKecil); ?></div>
                            <div class="dash-luas-label">Kecil</div>
                        </div>
                        <div class="dash-luas-card" style="border-color:#ffa726;">
                            <div class="dash-luas-val" style="color:#e65100;"><?php echo e($luasSedang); ?></div>
                            <div class="dash-luas-label">Sedang</div>
                        </div>
                        <div class="dash-luas-card" style="border-color:#ef5350;">
                            <div class="dash-luas-val" style="color:#b71c1c;"><?php echo e($luasBesar); ?></div>
                            <div class="dash-luas-label">Besar</div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        
        <div class="dash-panel">
            <div class="dash-panel-hdr">
                <div class="dash-panel-title">📍 Sebaran per Kecamatan — Kab. Gowa</div>
                <span class="dash-panel-badge"><?php echo e(count($perKecamatan)); ?> aktif dari 18</span>
            </div>
            <div class="dash-panel-body" style="padding:0;">

                <?php if(count($perKecamatan) === 0): ?>
                    <div style="text-align:center; padding:30px; color:#9ca3af; font-size:13px;">
                        📭 Belum ada data laporan per kecamatan
                    </div>
                    <?php else: ?>
               <?php endif; ?>
                    <div class="dash-kec-table-wrap">
                        <table class="dash-kec-table">
                            <thead>
                                <tr>
                                    <th>Kecamatan</th>
                                    <th style="text-align:center;">Total</th>
                                    <th style="text-align:center;">Berat</th>
                                    <th style="text-align:center;">Sedang</th>
                                    <th style="text-align:center;">Ringan</th>
                                    <th>Proporsi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    $maxJml = collect($perKecamatan)->max('jumlah');
                                ?>

                                <?php $__currentLoopData = $perKecamatan; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kec): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php
                                        $barW   = $maxJml > 0 ? round($kec['jumlah'] / $maxJml * 100) : 0;
                                        $ringan = $kec['ringan'] ?? ($kec['jumlah'] - $kec['berat'] - $kec['sedang']);
                                        $pctB   = $kec['jumlah'] > 0 ? round($kec['berat']  / $kec['jumlah'] * 100) : 0;
                                        $pctS   = $kec['jumlah'] > 0 ? round($kec['sedang'] / $kec['jumlah'] * 100) : 0;
                                        $pctR   = 100 - $pctB - $pctS;
                                    ?>
                                    <tr>
                                        <td class="dash-kec-name"><?php echo e($kec['nama']); ?></td>

                                        <td style="text-align:center; font-weight:700; font-family:'DM Mono',monospace;">
                                            <?php echo e($kec['jumlah']); ?>

                                        </td>

                                        <td style="text-align:center;">
                                            <?php if($kec['berat'] > 0): ?>
                                                <span class="dash-kec-badge"
                                                      style="background:#ffebee; color:#c53030;">
                                                    <?php echo e($kec['berat']); ?>

                                                </span>
                                            <?php else: ?>
                                                <span style="color:#d1d5db;">—</span>
                                            <?php endif; ?>
                                        </td>

                                        <td style="text-align:center;">
                                            <?php if($kec['sedang'] > 0): ?>
                                                <span class="dash-kec-badge"
                                                      style="background:#fff3e0; color:#b45309;">
                                                    <?php echo e($kec['sedang']); ?>

                                                </span>
                                            <?php else: ?>
                                                <span style="color:#d1d5db;">—</span>
                                            <?php endif; ?>
                                        </td>

                                        <td style="text-align:center;">
                                            <?php if($ringan > 0): ?>
                                                <span class="dash-kec-badge"
                                                      style="background:#e8f5e9; color:#2e7d32;">
                                                    <?php echo e($ringan); ?>

                                                </span>
                                            <?php else: ?>
                                                <span style="color:#d1d5db;">—</span>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <div class="dash-kec-bar-wrap">
                                                <?php if($pctB > 0): ?>
                                                    <div class="dash-kec-bar-seg"
                                                         style="width:<?php echo e($pctB); ?>%; background:#e53935;"
                                                         title="Berat <?php echo e($pctB); ?>%"></div>
                                                <?php endif; ?>
                                                <?php if($pctS > 0): ?>
                                                    <div class="dash-kec-bar-seg"
                                                         style="width:<?php echo e($pctS); ?>%; background:#fb8c00;"
                                                         title="Sedang <?php echo e($pctS); ?>%"></div>
                                                <?php endif; ?>
                                                <?php if($pctR > 0): ?>
                                                    <div class="dash-kec-bar-seg"
                                                         style="width:<?php echo e($pctR); ?>%; background:#43a047;"
                                                         title="Ringan <?php echo e($pctR); ?>%"></div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
            <?php
                $aktifNama = collect($perKecamatan)
                    ->pluck('nama')
                    ->toArray();

                $semuaKecamatan = \App\Models\Lapor::select('kecamatan')
                    ->distinct()
                    ->pluck('kecamatan')
                    ->toArray();

                $belumTerdampak = array_filter(
                    $semuaKecamatan,
                    fn ($k) => !in_array($k, $aktifNama)
                );
            ?>
            </div>
        </div>

    </div>


    
    <div class="dash-table-section">

        <div class="dash-tbl-toolbar">
            <div class="dash-panel-title" style="margin:0;">
                🏆 Tabel Prioritas Penanganan (TOPSIS)
                <span class="dash-tbl-pill"><?php echo e($total); ?> terranking</span>
            </div>
            <div class="dash-filter-pills">
                <button class="dash-fpill active" onclick="filterTbl('all', this)">Semua</button>
                <button class="dash-fpill"        onclick="filterTbl('Ringan', this)">🟢 Ringan</button>
                <button class="dash-fpill"        onclick="filterTbl('Sedang', this)">🟡 Sedang</button>
                <button class="dash-fpill"        onclick="filterTbl('Berat', this)">🔴 Berat</button>
            </div>
        </div>

        <div class="dash-tbl-wrap">
            <table class="dash-tbl" id="tblPrioritas">
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Nama Petani</th>
                        <th>Hama</th>
                        <th>Tingkat</th>
                        <th>Luas</th>
                        <th>Lama</th>
                        <th>Status</th>
                        <th>Nilai TOPSIS</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $__currentLoopData = $laporan; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr data-tingkat="<?php echo e($item->tingkat_serangan); ?>">

                            <td>
                                <span class="dash-rank rank-<?php echo e($item->ranking <= 3 ? $item->ranking : 'n'); ?>">
                                    <?php echo e($item->ranking); ?>

                                </span>
                            </td>

                            <td>
                                <div class="dash-tbl-name"><?php echo e($item->nama_petani); ?></div>
                                <div class="dash-tbl-sub">📍 <?php echo e(Str::limit($item->lokasi, 35)); ?></div>
                            </td>

                            <td><?php echo e($item->jenis_hama); ?></td>

                            <td>
                                <span class="badge <?php echo e(strtolower($item->tingkat_serangan)); ?>">
                                    <?php echo e($item->tingkat_serangan); ?>

                                </span>
                            </td>

                            <td>
                                <span class="dash-luas-chip luas-<?php echo e($item->luas_lahan); ?>">
                                    <?php echo e(ucwords(str_replace('luas_', '', $item->luas_lahan))); ?>

                                </span>
                            </td>

                            <td><?php echo e(ucwords(str_replace('_', ' ', $item->lama_kejadian))); ?></td>

                            <td>
                                <span class="dash-status-chip status-<?php echo e($item->status); ?>">
                                    <?php echo e(ucfirst($item->status)); ?>

                                </span>
                            </td>

                            <td>
                                <div class="dash-nilai-wrap">
                                    <div class="dash-nilai-bg">
                                        <div class="dash-nilai-fill"
                                             style="width:<?php echo e(($item->nilai_preferensi ?? 0) * 100); ?>%;"></div>
                                    </div>
                                    <span class="dash-nilai-num">
                                        <?php echo e(number_format($item->nilai_preferensi ?? 0, 4)); ?>

                                    </span>
                                </div>
                            </td>

                            <td>
                                <a href="/lapor/<?php echo e($item->id); ?>">
                                    <button class="dash-btn-detail">Detail →</button>
                                </a>
                            </td>

                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </tbody>
            </table>
        </div>
    </div>


    
    <div class="dash-map-section">
        <div class="dash-panel-title" style="margin-bottom:12px;">
            🗺️ Peta Persebaran Serangan Hama — Kabupaten Gowa
        </div>
        <div class="dash-map-wrap">
            <div id="map"></div>
        </div>
    </div>


    
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://unpkg.com/leaflet.markercluster/dist/leaflet.markercluster.js"></script>
    <script src="https://unpkg.com/leaflet.heat/dist/leaflet-heat.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script>


    
    <script>
    // ── STATE ───────────────────────────────────────────────────────
    var laporan       = <?php echo json_encode($laporan, 15, 512) ?>;
    var chartTingkat, chartHama, mapInstance, clusterLayer, heatLayer;
    var rtCountdown   = 30;


    // ── FILTER TABEL ────────────────────────────────────────────────
    function filterTbl(t, btn) {
        document.querySelectorAll('.dash-fpill').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');

        document.querySelectorAll('#tblPrioritas tbody tr').forEach(row => {
            row.style.display = (t === 'all' || row.dataset.tingkat === t) ? '' : 'none';
        });
    }

    function renderTable(data) {
        const tbody = document.querySelector('#tblPrioritas tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        data.forEach(item => {
            const rk   = item.ranking <= 3 ? item.ranking : 'n';
            const sev  = (item.tingkat_serangan || '').toLowerCase();
            const luas = (item.luas_lahan       || '').replace('luas_', '').replace('_', ' ');
            const lama = (item.lama_kejadian    || '').replace(/_/g, ' ');
            const val  = parseFloat(item.nilai_preferensi || 0);

            tbody.insertAdjacentHTML('beforeend', `
                <tr data-tingkat="${item.tingkat_serangan || ''}">
                    <td>
                        <span class="dash-rank rank-${rk}">${item.ranking || '-'}</span>
                    </td>
                    <td>
                        <div class="dash-tbl-name">${item.nama_petani || '-'}</div>
                        <div class="dash-tbl-sub">📍 ${(item.lokasi || '').substring(0, 40)}</div>
                    </td>
                    <td>${item.jenis_hama || '-'}</td>
                    <td><span class="badge ${sev}">${item.tingkat_serangan || '-'}</span></td>
                    <td><span class="dash-luas-chip luas-${item.luas_lahan}">${luas}</span></td>
                    <td>${lama}</td>
                    <td><span class="dash-status-chip status-${item.status}">${item.status || '-'}</span></td>
                    <td>
                        <div class="dash-nilai-wrap">
                            <div class="dash-nilai-bg">
                                <div class="dash-nilai-fill"
                                     style="width:${Math.min(val * 100, 100).toFixed(1)}%;"></div>
                            </div>
                            <span class="dash-nilai-num">${val.toFixed(4)}</span>
                        </div>
                    </td>
                    <td>
                        <a href="/lapor/${item.id}">
                            <button class="dash-btn-detail">Detail →</button>
                        </a>
                    </td>
                </tr>
            `);
        });
    }


    // ── MAP ─────────────────────────────────────────────────────────
    function initMap() {
        mapInstance  = L.map('map').setView([-5.2, 119.45], 11);
        clusterLayer = L.markerClusterGroup();

        L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 })
            .addTo(mapInstance);

        mapInstance.addLayer(clusterLayer);
        renderMarkers(laporan);

        // Legenda
        const leg = L.control({ position: 'bottomright' });
        leg.onAdd = function () {
            const d = L.DomUtil.create('div', 'map-legend');
            d.innerHTML = `
                <div class="legend-title">🗺️ Keterangan</div>
                <div class="legend-item"><span class="legend-dot ringan"></span> Ringan</div>
                <div class="legend-item"><span class="legend-dot sedang"></span> Sedang</div>
                <div class="legend-item"><span class="legend-dot berat"></span> Berat</div>
                <hr>
                <div class="legend-item">🔥 Heatmap Intensitas</div>
            `;
            return d;
        };
        leg.addTo(mapInstance);
    }

    function renderMarkers(data) {
        if (!clusterLayer || !mapInstance) return;

        clusterLayer.clearLayers();
        if (heatLayer) mapInstance.removeLayer(heatLayer);

        const heatData = [];

        data.forEach(function (item) {
            if (!item.lat || !item.lng) return;

            const color = item.tingkat_serangan === 'Berat'  ? '#e53935'
                        : item.tingkat_serangan === 'Sedang' ? '#fb8c00'
                        : '#43a047';

            const marker = L.circleMarker(
                [parseFloat(item.lat), parseFloat(item.lng)],
                { color, radius: 10, fillColor: color, fillOpacity: 0.85, weight: 2 }
            );

            marker.bindPopup(`
                <div style="font-family:'Plus Jakarta Sans',sans-serif; min-width:190px;">
                    <div style="font-weight:700; font-size:14px;
                                border-bottom:1px solid #eee;
                                padding-bottom:6px; margin-bottom:8px;">
                        🏆 Rank #${item.ranking ?? '-'} — ${item.nama_petani}
                    </div>
                    <div style="font-size:12px; color:#374151;
                                display:flex; flex-direction:column; gap:4px;">
                        <div>🐛 Hama: <b>${item.jenis_hama}</b></div>
                        <div>⚠️ Tingkat: <b style="color:${color};">${item.tingkat_serangan}</b></div>
                        <div>🌾 Luas: <b>${(item.luas_lahan || '').replace('luas_', '').replace('_', ' ')}</b></div>
                        <div>⏱️ Lama: <b>${(item.lama_kejadian || '').replace(/_/g, ' ')}</b></div>
                        <div>📊 Status: <b>${item.status ?? '-'}</b></div>
                        <div>📈 TOPSIS: <b>${item.nilai_preferensi ? parseFloat(item.nilai_preferensi).toFixed(4) : '-'}</b></div>
                        <div>📍 Lokasi: <b>${(item.lokasi || '-').substring(0, 50)}</b></div>
                    </div>
                </div>
            `, { maxWidth: 260 });

            clusterLayer.addLayer(marker);
            heatData.push([parseFloat(item.lat), parseFloat(item.lng), 0.7]);
        });

        heatLayer = L.heatLayer(heatData, { radius: 30, blur: 20, maxZoom: 17 });
        mapInstance.addLayer(heatLayer);
    }


    // ── CHARTS ──────────────────────────────────────────────────────
    function initCharts() {
        // Bar chart: Tingkat Serangan
        chartTingkat = new Chart(document.getElementById('chartTingkat'), {
            type: 'bar',
            data: {
                labels: ['Ringan', 'Sedang', 'Berat'],
                datasets: [{
                    label: 'Jumlah',
                    data: [<?php echo e($statistik['Ringan']); ?>, <?php echo e($statistik['Sedang']); ?>, <?php echo e($statistik['Berat']); ?>],
                    backgroundColor: ['#43a047', '#fb8c00', '#e53935'],
                    borderRadius: 8,
                    borderSkipped: false,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: { duration: 600 },
                plugins: { legend: { display: false } },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { stepSize: 1, font: { size: 11 } },
                        grid: { color: 'rgba(0,0,0,0.04)' },
                    },
                    x: {
                        ticks: { font: { size: 12, weight: '600' } },
                        grid: { display: false },
                    },
                },
            },
        });

        // Doughnut chart: Jenis Hama
        const hCount = {};
        laporan.forEach(i => { hCount[i.jenis_hama] = (hCount[i.jenis_hama] || 0) + 1; });

        chartHama = new Chart(document.getElementById('chartHama'), {
            type: 'doughnut',
            data: {
                labels: Object.keys(hCount),
                datasets: [{
                    data: Object.values(hCount),
                    backgroundColor: ['#1b5e20', '#388e3c', '#66bb6a', '#ffa726', '#ef5350'],
                    borderWidth: 3,
                    borderColor: '#fff',
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '60%',
                animation: { duration: 600 },
                plugins: { legend: { display: false } },
            },
        });
    }


    // ── REALTIME REFRESH ─────────────────────────────────────────────
    function startRealtime() {
        setInterval(function () {
            rtCountdown--;

            const el = document.getElementById('rtTimer');
            if (el) el.textContent = rtCountdown;

            if (rtCountdown <= 0) {
                rtCountdown = 30;
                refreshData();
            }
        }, 1000);
    }

    function refreshData() {
        fetch('/admin/dashboard/data', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
        })
        .then(r => r.json())
        .then(data => {
            laporan = data.laporan;

            // Metric cards
            document.getElementById('rt-total').textContent      = data.totalSemua;
            document.getElementById('rt-ringan').textContent     = data.statistik.Ringan;
            document.getElementById('rt-sedang').textContent     = data.statistik.Sedang;
            document.getElementById('rt-berat').textContent      = data.statistik.Berat;
            document.getElementById('rt-pct-ringan').textContent = data.pctRingan + '%';
            document.getElementById('rt-pct-sedang').textContent = data.pctSedang + '%';
            document.getElementById('rt-minggu').textContent     = '+' + data.mingguIni + ' minggu ini';

            // Status strip
            document.getElementById('rt-menunggu').textContent = data.stMenunggu;
            document.getElementById('rt-proses').textContent   = data.stProses;
            document.getElementById('rt-selesai').textContent  = data.stSelesai;
            document.getElementById('rt-tolak').textContent    = data.stTolak;
            document.getElementById('rt-hama-dom').textContent = data.hamaDominan ?? '-';

            // Alert berat
            const alertEl = document.getElementById('rt-alert');
            if (alertEl) {
                alertEl.style.display = data.statistik.Berat > 0 ? 'flex' : 'none';
                const cnt = document.getElementById('rt-alert-count');
                if (cnt) cnt.textContent = data.statistik.Berat;
            }

            // Update charts
            if (chartTingkat) {
                chartTingkat.data.datasets[0].data = [
                    data.statistik.Ringan,
                    data.statistik.Sedang,
                    data.statistik.Berat,
                ];
                chartTingkat.update('active');
            }

            if (chartHama) {
                const hc = {};
                laporan.forEach(i => { hc[i.jenis_hama] = (hc[i.jenis_hama] || 0) + 1; });
                chartHama.data.labels             = Object.keys(hc);
                chartHama.data.datasets[0].data   = Object.values(hc);
                chartHama.update('active');
            }

            renderMarkers(laporan);
            renderTable(laporan);

            // Top priority
            if (laporan.length > 0) {
                const t  = laporan[0];
                const tn = document.getElementById('rt-tp-name');
                const ts = document.getElementById('rt-tp-score');
                const tc = document.getElementById('rt-tp-count');

                if (tn) tn.textContent = (t.nama_petani || '-') + ' — ' + (t.jenis_hama || '-');
                if (ts) ts.textContent = parseFloat(t.nilai_preferensi || 0).toFixed(4);
                if (tc) tc.textContent = 'Tertinggi dari ' + laporan.length + ' laporan terranking';
            }

            showToast('✅ Data diperbarui — ' + new Date().toLocaleTimeString('id-ID'));
            rtCountdown = 30;
        })
        .catch(() => showToast('⚠️ Gagal memperbarui data'));
    }

    function manualRefresh() {
        rtCountdown = 30;
        document.getElementById('rtTimer').textContent = 30;
        refreshData();
    }

    function showToast(msg) {
        const t = document.getElementById('rt-toast');
        if (!t) return;
        t.textContent = msg;
        t.classList.add('rt-toast-show');
        setTimeout(() => t.classList.remove('rt-toast-show'), 3000);
    }


    // ── INIT ─────────────────────────────────────────────────────────
    document.addEventListener('DOMContentLoaded', function () {
        initCharts();
        initMap();
        startRealtime();
    });


    // ── PDF EXPORT ───────────────────────────────────────────────────

    // Helper: load image as promise
    function loadImage(url) {
        return new Promise((res, rej) => {
            const img = new Image();
            img.crossOrigin = 'Anonymous';
            img.onload  = () => res(img);
            img.onerror = () => rej(new Error('Gagal: ' + url));
            img.src = url;
        });
    }

    // Colour palette helpers
    function hex(r, g, b) { return [r, g, b]; }

    const COLORS = {
        hijauTua:  hex(27,  94,  32),
        hijauMuda: hex(46,  125, 50),
        hijauAksen:hex(102, 187, 106),
        putih:     hex(255, 255, 255),
        abuMuda:   hex(245, 247, 245),
        abuGaris:  hex(220, 230, 220),
        teks:      hex(33,  33,  33),
        subTeks:   hex(100, 116, 100),
        kuning:    hex(255, 193, 7),
        merah:     hex(229, 57,  53),
        oranye:    hex(251, 140, 0),
    };

    // ── PDF: Drawing helpers ─────────────────────────────────────────

    function drawKop(doc, logo) {
        const W = 210;
        doc.setFillColor(...COLORS.hijauTua);
        doc.rect(0, 0, W, 32, 'F');

        if (logo) doc.addImage(logo, 'JPEG', 10, 5, 22, 22);

        doc.setTextColor(...COLORS.putih);
        doc.setFont('helvetica', 'bold');
        doc.setFontSize(11);
        doc.text('PEMERINTAH KABUPATEN GOWA', W / 2, 12, { align: 'center' });
        doc.setFontSize(9.5);
        doc.text('DINAS TANAMAN PANGAN DAN HORTIKULTURA', W / 2, 19, { align: 'center' });
        doc.setFont('helvetica', 'normal');
        doc.setFontSize(8);
        doc.text(
            'Jln. Tumanurung No. 17, Sungguminasa, Somba Opu, Kabupaten Gowa, Sulawesi Selatan | Telp: (0411) 860019',
            W / 2, 25.5, { align: 'center' }
        );

        doc.setDrawColor(...COLORS.hijauAksen);
        doc.setLineWidth(1.5);
        doc.line(0, 32, W, 32);
        doc.setTextColor(...COLORS.teks);
    }

    function drawFooter(doc, n, total) {
        const W = 210, yF = 287;
        doc.setDrawColor(...COLORS.abuGaris);
        doc.setLineWidth(0.4);
        doc.line(15, yF - 3, W - 15, yF - 3);
        doc.setFont('helvetica', 'italic');
        doc.setFontSize(7.5);
        doc.setTextColor(...COLORS.subTeks);
        doc.text('Sistem Pendukung Keputusan Hama — Kabupaten Gowa', 15, yF + 1);
        doc.text(`Halaman ${n} / ${total}`, W - 15, yF + 1, { align: 'right' });
        doc.setTextColor(...COLORS.teks);
    }

    function drawSectionTitle(doc, text, y) {
        doc.setFillColor(...COLORS.hijauMuda);
        doc.roundedRect(15, y, 180, 9, 2, 2, 'F');
        doc.setFont('helvetica', 'bold');
        doc.setFontSize(10);
        doc.setTextColor(...COLORS.putih);
        doc.text(text, 20, y + 6.2);
        doc.setTextColor(...COLORS.teks);
        return y + 14;
    }

    function drawInfoBox(doc, x, y, w, h, label, value, color) {
        doc.setFillColor(...(color || COLORS.abuMuda));
        doc.roundedRect(x, y, w, h, 3, 3, 'F');
        doc.setDrawColor(...COLORS.abuGaris);
        doc.setLineWidth(0.3);
        doc.roundedRect(x, y, w, h, 3, 3, 'S');

        doc.setFont('helvetica', 'normal');
        doc.setFontSize(8);
        doc.setTextColor(...COLORS.subTeks);
        doc.text(label, x + w / 2, y + 6, { align: 'center' });

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(18);
        doc.setTextColor(...COLORS.hijauTua);
        doc.text(String(value), x + w / 2, y + 16, { align: 'center' });
        doc.setTextColor(...COLORS.teks);
    }

    // ── PDF: Main export function ────────────────────────────────────
    async function exportPDF() {
        const btn = document.getElementById('btnExport');
        btn.disabled   = true;
        btn.textContent = '⏳ Membuat PDF...';

        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('p', 'mm', 'a4');
        const W   = 210;
        const now = new Date();

        let logo = null;
        try { logo = await loadImage("<?php echo e(asset('logo.jpg')); ?>"); } catch (e) {}

        // Ringkasan data
        const sorted = [...laporan].sort((a, b) => a.ranking - b.ranking);
        const total  = laporan.length;
        const ringan = laporan.filter(l => l.tingkat_serangan === 'Ringan').length;
        const sedang = laporan.filter(l => l.tingkat_serangan === 'Sedang').length;
        const berat  = laporan.filter(l => l.tingkat_serangan === 'Berat').length;
        const top    = sorted[0];

        const hCount = {};
        laporan.forEach(l => { hCount[l.jenis_hama] = (hCount[l.jenis_hama] || 0) + 1; });
        const hEnt = Object.entries(hCount).sort((a, b) => b[1] - a[1]);

        // ── Halaman 1: COVER ─────────────────────────────────────────
        doc.setFillColor(...COLORS.hijauTua);
        doc.rect(0, 0, W, 297, 'F');
        doc.setFillColor(...COLORS.hijauMuda);
        doc.rect(0, 100, W, 90, 'F');

        doc.setDrawColor(...COLORS.hijauAksen);
        doc.setLineWidth(2);
        doc.line(0, 100, W, 100);
        doc.line(0, 190, W, 190);

        if (logo) doc.addImage(logo, 'JPEG', W / 2 - 18, 30, 36, 36);

        doc.setTextColor(...COLORS.putih);
        doc.setFont('helvetica', 'bold');
        doc.setFontSize(14);
        doc.text('PEMERINTAH KABUPATEN GOWA', W / 2, 78, { align: 'center' });
        doc.setFontSize(11);
        doc.text('DINAS TANAMAN PANGAN DAN HORTIKULTURA', W / 2, 86, { align: 'center' });

        doc.setTextColor(...COLORS.hijauTua);
        doc.setFontSize(16);
        doc.text('LAPORAN PRIORITAS', W / 2, 125, { align: 'center' });
        doc.text('PENANGANAN SERANGAN HAMA', W / 2, 137, { align: 'center' });
        doc.setFont('helvetica', 'normal');
        doc.setFontSize(10);
        doc.text('Berdasarkan Metode AHP & TOPSIS', W / 2, 148, { align: 'center' });

        doc.setFillColor(...COLORS.putih);
        doc.roundedRect(30, 200, 150, 40, 4, 4, 'F');
        doc.setTextColor(...COLORS.hijauTua);
        doc.setFont('helvetica', 'bold');
        doc.setFontSize(9);
        doc.text('Nomor Dokumen', 55,  210, { align: 'center' });
        doc.text('Tanggal Cetak',  105, 210, { align: 'center' });
        doc.text('Total Laporan',  155, 210, { align: 'center' });

        doc.setFont('helvetica', 'normal');
        doc.setFontSize(11);
        doc.text(
            'SPK-' + now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0'),
            55, 220, { align: 'center' }
        );
        doc.text(
            now.toLocaleDateString('id-ID', { day: '2-digit', month: 'long', year: 'numeric' }),
            105, 220, { align: 'center' }
        );
        doc.text(String(total), 155, 220, { align: 'center' });

        doc.setTextColor(150, 200, 150);
        doc.setFont('helvetica', 'italic');
        doc.setFontSize(8);
        doc.text(
            'Dicetak: ' + now.toLocaleString('id-ID') + ' | Data Realtime',
            W / 2, 280, { align: 'center' }
        );

        // ── Halaman 2: RINGKASAN ─────────────────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        let y = 42;

        y = drawSectionTitle(doc, 'RINGKASAN EKSEKUTIF', y);

        const bW = 40, bH = 24, gap = 5;
        const sX = (W - (bW * 4 + gap * 3)) / 2;
        drawInfoBox(doc, sX,                    y, bW, bH, 'Total Laporan', total,  COLORS.abuMuda);
        drawInfoBox(doc, sX + (bW + gap),       y, bW, bH, 'Ringan',        ringan, [232, 245, 233]);
        drawInfoBox(doc, sX + (bW + gap) * 2,   y, bW, bH, 'Sedang',        sedang, [255, 243, 224]);
        drawInfoBox(doc, sX + (bW + gap) * 3,   y, bW, bH, 'Berat',         berat,  [255, 235, 238]);
        y += bH + 10;

        if (top) {
            doc.setFillColor(...COLORS.hijauTua);
            doc.roundedRect(15, y, 180, 22, 3, 3, 'F');
            doc.setFont('helvetica', 'bold');
            doc.setFontSize(9);
            doc.setTextColor(...COLORS.hijauAksen);
            doc.text('PRIORITAS UTAMA PENANGANAN', 20, y + 7);
            doc.setFontSize(11);
            doc.setTextColor(...COLORS.putih);
            doc.text((top.nama_petani || '-') + '  —  ' + (top.jenis_hama || '-'), 20, y + 15);
            doc.setFontSize(8);
            doc.setTextColor(180, 230, 180);
            doc.text(
                'Ranking #1  |  TOPSIS: ' + parseFloat(top.nilai_preferensi || 0).toFixed(4) +
                '  |  Tingkat: ' + top.tingkat_serangan,
                20, y + 21
            );
            doc.setTextColor(...COLORS.teks);
            y += 30;
        }

        y = drawSectionTitle(doc, 'INFORMASI LAPORAN', y);

        const infoRows = [
            ['Tanggal Cetak',   now.toLocaleDateString('id-ID', { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' })],
            ['Waktu Cetak',     now.toLocaleTimeString('id-ID') + ' (Realtime)'],
            ['Hama Dominan',    hEnt.length > 0 ? hEnt[0][0] + ' (' + hEnt[0][1] + ' kasus)' : '-'],
            ['Metode Analisis', 'AHP (pembobotan) + TOPSIS (perangkingan)'],
        ];

        infoRows.forEach((row, i) => {
            doc.setFillColor(...(i % 2 === 0 ? COLORS.abuMuda : COLORS.putih));
            doc.rect(15, y, 180, 9, 'F');
            doc.setFont('helvetica', 'bold');
            doc.setTextColor(...COLORS.subTeks);
            doc.text(row[0], 20, y + 6.2);
            doc.setFont('helvetica', 'normal');
            doc.setTextColor(...COLORS.teks);
            doc.text(row[1], 90, y + 6.2);
            y += 9;
        });

        y += 8;
        y  = drawSectionTitle(doc, 'BOBOT KRITERIA AHP', y);

        const kriteriaRows = [
            { n: 'Tingkat Serangan', b: <?php echo e($bobotAHP[0]); ?> },
            { n: 'Luas Lahan',       b: <?php echo e($bobotAHP[1]); ?> },
            { n: 'Lama Serangan',    b: <?php echo e($bobotAHP[2]); ?> },
            { n: 'Jenis Hama',       b: <?php echo e($bobotAHP[3]); ?> },
        ];

        kriteriaRows.forEach((k, i) => {
            doc.setFillColor(...(i % 2 === 0 ? COLORS.abuMuda : COLORS.putih));
            doc.rect(15, y, 180, 11, 'F');
            doc.setFont('helvetica', 'normal');
            doc.setFontSize(9);
            doc.setTextColor(...COLORS.teks);
            doc.text(k.n, 20, y + 7.5);

            doc.setFillColor(...COLORS.abuGaris);
            doc.roundedRect(80, y + 3, 100, 5, 1, 1, 'F');
            doc.setFillColor(...COLORS.hijauMuda);
            doc.roundedRect(80, y + 3, k.b * 100, 5, 1, 1, 'F');

            doc.setFont('helvetica', 'bold');
            doc.setFontSize(9);
            doc.setTextColor(...COLORS.hijauTua);
            doc.text((k.b * 100).toFixed(1) + '%', 185, y + 7.5);
            y += 11;
        });

        drawFooter(doc, 2, '?');

        // ── Halaman 3: CHART TINGKAT ──────────────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        y = 42;
        y = drawSectionTitle(doc, 'DISTRIBUSI TINGKAT SERANGAN', y);

        const c1 = document.getElementById('chartTingkat');
        if (c1) {
            doc.addImage(c1.toDataURL('image/png'), 'PNG', 20, y, 170, 80);
            y += 90;
        }

        doc.autoTable({
            startY: y,
            head: [['Tingkat', 'Jumlah', 'Persentase', 'Status']],
            body: [
                ['Ringan', ringan, ((ringan / total) * 100).toFixed(1) + '%', 'Pantau'],
                ['Sedang', sedang, ((sedang / total) * 100).toFixed(1) + '%', 'Waspada'],
                ['Berat',  berat,  ((berat  / total) * 100).toFixed(1) + '%', 'Segera Tangani'],
                ['TOTAL',  total,  '100%', '—'],
            ],
            theme: 'grid',
            headStyles: { fillColor: COLORS.hijauTua, textColor: 255, fontStyle: 'bold', fontSize: 9 },
            styles: { fontSize: 9, cellPadding: 3.5, halign: 'center' },
            columnStyles: { 0: { halign: 'left', fontStyle: 'bold' } },
            alternateRowStyles: { fillColor: [245, 250, 245] },
            didParseCell: function (d) {
                if (d.section === 'body') {
                    const v = d.row.raw[0];
                    if (v === 'Ringan') d.cell.styles.textColor = COLORS.hijauMuda;
                    if (v === 'Sedang') d.cell.styles.textColor = COLORS.oranye;
                    if (v === 'Berat')  d.cell.styles.textColor = COLORS.merah;
                    if (v === 'TOTAL')  d.cell.styles.fillColor = [240, 248, 240];
                }
            },
        });

        drawFooter(doc, 3, '?');

        // ── Halaman 4: CHART HAMA ─────────────────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        y = 42;
        y = drawSectionTitle(doc, 'DISTRIBUSI JENIS HAMA', y);

        const c2 = document.getElementById('chartHama');
        if (c2) {
            doc.addImage(c2.toDataURL('image/png'), 'PNG', 30, y, 150, 80);
            y += 90;
        }

        doc.autoTable({
            startY: y,
            head: [['#', 'Jenis Hama', 'Jumlah', 'Persentase', 'Ket']],
            body: hEnt.map(([h, j], i) => [
                i + 1,
                h,
                j,
                ((j / total) * 100).toFixed(1) + '%',
                i === 0 ? '★ Terbanyak' : '',
            ]),
            theme: 'grid',
            headStyles: { fillColor: COLORS.hijauTua, textColor: 255, fontStyle: 'bold', fontSize: 9 },
            styles: { fontSize: 9, cellPadding: 3.5 },
            columnStyles: {
                0: { halign: 'center', cellWidth: 12 },
                2: { halign: 'center' },
                3: { halign: 'center' },
                4: { halign: 'center', textColor: COLORS.kuning, fontStyle: 'bold' },
            },
            alternateRowStyles: { fillColor: [245, 250, 245] },
        });

        drawFooter(doc, 4, '?');

        // ── Halaman 5: PETA ───────────────────────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        y = 42;
        y = drawSectionTitle(doc, 'PETA PERSEBARAN SERANGAN HAMA — KAB. GOWA', y);

        try {
            const mc = await html2canvas(document.getElementById('map'), { useCORS: true, scale: 1.5 });
            doc.addImage(mc.toDataURL('image/png'), 'PNG', 15, y, 180, 110);
            y += 118;
        } catch (e) {
            doc.setFont('helvetica', 'italic');
            doc.setFontSize(9);
            doc.setTextColor(...COLORS.subTeks);
            doc.text('[Peta tidak dapat dimuat]', W / 2, y + 10, { align: 'center' });
            y += 20;
        }

        doc.setFont('helvetica', 'bold');
        doc.setFontSize(9);
        doc.setTextColor(...COLORS.teks);
        doc.text('Keterangan:', 15, y + 5);

        [
            { label: 'Ringan', color: COLORS.hijauMuda },
            { label: 'Sedang', color: COLORS.oranye },
            { label: 'Berat',  color: COLORS.merah },
        ].forEach((l, i) => {
            const lx = 40 + i * 50;
            doc.setFillColor(...l.color);
            doc.circle(lx, y + 4, 3, 'F');
            doc.setFont('helvetica', 'normal');
            doc.setFontSize(8.5);
            doc.setTextColor(...COLORS.teks);
            doc.text(l.label, lx + 5, y + 6);
        });

        drawFooter(doc, 5, '?');

        // ── Halaman 6: TABEL PRIORITAS ────────────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        y = 42;
        y = drawSectionTitle(doc, 'TABEL PRIORITAS PENANGANAN (TOPSIS) — REALTIME', y);

        doc.autoTable({
            startY: y,
            head: [['Rank', 'Petani', 'Hama', 'Tingkat', 'Luas', 'Lama', 'Status', 'Nilai TOPSIS']],
            body: sorted.map(item => [
                '#' + (item.ranking || '-'),
                item.nama_petani   || '-',
                item.jenis_hama    || '-',
                item.tingkat_serangan || '-',
                (item.luas_lahan   || '-').replace('luas_', '').replace('_', ' '),
                (item.lama_kejadian || '-').replace(/_/g, ' '),
                item.status        || '-',
                parseFloat(item.nilai_preferensi || 0).toFixed(4),
            ]),
            theme: 'grid',
            headStyles: { fillColor: COLORS.hijauTua, textColor: 255, fontStyle: 'bold', fontSize: 8, halign: 'center' },
            styles: { fontSize: 8, cellPadding: 2.5, overflow: 'linebreak' },
            columnStyles: {
                0: { halign: 'center', cellWidth: 12, fontStyle: 'bold' },
                3: { halign: 'center', cellWidth: 18 },
                4: { halign: 'center', cellWidth: 16 },
                5: { halign: 'center', cellWidth: 18 },
                6: { halign: 'center', cellWidth: 18 },
                7: { halign: 'center', cellWidth: 22, fontStyle: 'bold', textColor: COLORS.hijauTua },
            },
            alternateRowStyles: { fillColor: [245, 250, 245] },
            didParseCell: function (d) {
                if (d.section === 'body') {
                    if (d.column.index === 3) {
                        const v = d.cell.raw;
                        if (v === 'Ringan') d.cell.styles.textColor = COLORS.hijauMuda;
                        if (v === 'Sedang') d.cell.styles.textColor = COLORS.oranye;
                        if (v === 'Berat')  d.cell.styles.textColor = COLORS.merah;
                        d.cell.styles.fontStyle = 'bold';
                    }
                    if (d.row.index < 3) d.cell.styles.fillColor = [235, 248, 235];
                }
            },
        });

        drawFooter(doc, 6, '?');

        // ── Halaman 7: ANALISIS & REKOMENDASI ────────────────────────
        doc.addPage();
        drawKop(doc, logo);
        y = 42;
        y = drawSectionTitle(doc, 'ANALISIS HASIL', y);

        const analisis = [
            'Berdasarkan hasil perhitungan TOPSIS, alternatif dengan nilai preferensi tertinggi merupakan kasus paling mendesak untuk segera ditangani oleh penyuluh pertanian.',
            'Nilai preferensi TOPSIS berkisar antara 0 hingga 1. Semakin mendekati 1, semakin dekat alternatif dengan solusi ideal positif.',
            'Bobot kriteria AHP: tingkat serangan (55,8%), luas lahan (26,3%), lama serangan (12,2%), dan jenis hama (5,7%).',
        ];

        analisis.forEach(p => {
            const lines = doc.splitTextToSize('• ' + p, 175);
            doc.setFont('helvetica', 'normal');
            doc.setFontSize(9.5);
            doc.setTextColor(...COLORS.teks);
            doc.text(lines, 18, y);
            y += lines.length * 5.5 + 3;
        });

        y += 5;
        y  = drawSectionTitle(doc, 'REKOMENDASI', y);

        const rekomendasi = [
            'Laporan ranking tertinggi agar segera mendapat kunjungan lapangan dan penanganan teknis.',
            'Kasus tingkat "Berat" diprioritaskan untuk penyaluran bantuan pestisida dan bimbingan penyuluh.',
            'Pemantauan berkala pada laporan "Sedang" untuk mencegah eskalasi menjadi Berat.',
            'Data laporan diperbarui secara rutin agar perangkingan selalu mencerminkan kondisi terkini.',
        ];

        rekomendasi.forEach((rek, i) => {
            doc.setFillColor(...COLORS.hijauTua);
            doc.circle(21, y + 3.5, 3.5, 'F');
            doc.setFont('helvetica', 'bold');
            doc.setFontSize(8);
            doc.setTextColor(...COLORS.putih);
            doc.text(String(i + 1), 21, y + 5.3, { align: 'center' });

            const lines = doc.splitTextToSize(rek, 165);
            doc.setFont('helvetica', 'normal');
            doc.setFontSize(9.5);
            doc.setTextColor(...COLORS.teks);
            doc.text(lines, 28, y + 4.5);
            y += lines.length * 5.5 + 5;
        });

        // Footer info box
        y += 10;
        doc.setFillColor(...COLORS.abuMuda);
        doc.roundedRect(15, y, 180, 16, 3, 3, 'F');
        doc.setFont('helvetica', 'italic');
        doc.setFontSize(9);
        doc.setTextColor(...COLORS.subTeks);
        doc.text(
            'Laporan otomatis SPK Hama | Dicetak: ' + now.toLocaleString('id-ID'),
            W / 2, y + 10, { align: 'center', maxWidth: 170 }
        );

        // Tanda tangan
        y += 26;
        const tglGowa = now.toLocaleDateString('id-ID', { day: '2-digit', month: 'long', year: 'numeric' });
        doc.setFont('helvetica', 'normal');
        doc.setFontSize(9.5);
        doc.setTextColor(...COLORS.teks);
        doc.text('Gowa, ' + tglGowa, 135, y, { align: 'center' });
        doc.setFont('helvetica', 'bold');
        doc.text('Kepala Dinas Tanaman Pangan',     135, y + 7,  { align: 'center' });
        doc.text('dan Hortikultura Kabupaten Gowa', 135, y + 13, { align: 'center' });

        doc.setDrawColor(...COLORS.abuGaris);
        doc.setLineWidth(0.4);
        doc.rect(110, y + 16, 50, 28);
        doc.setFont('helvetica', 'normal');
        doc.setFontSize(9);
        doc.text('(                              )',   135, y + 46, { align: 'center' });
        doc.text('NIP. ________________________',     135, y + 52, { align: 'center' });

        drawFooter(doc, 7, '?');

        // ── Perbaiki nomor halaman di semua halaman ───────────────────
        const totalPages = doc.internal.getNumberOfPages();
        for (let i = 1; i <= totalPages; i++) {
            doc.setPage(i);
            doc.setFillColor(255, 255, 255);
            doc.rect(0, 283, W, 14, 'F');
            drawFooter(doc, i, totalPages);
        }

        // Simpan file
        const fname = 'Laporan-Hama-Gowa-'
                    + now.getFullYear()
                    + String(now.getMonth() + 1).padStart(2, '0')
                    + String(now.getDate()).padStart(2, '0')
                    + '.pdf';

        doc.save(fname);

        btn.disabled    = false;
        btn.textContent = '📄 Export PDF';
    }
    </script>


<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Maylha\pelaporanpertanian\resources\views/admin/dashboard.blade.php ENDPATH**/ ?>