<?php
// Ekstrak semua data sebelum heredoc agar tidak terjadi Array to string conversion
$mapLat  = MAP_DEFAULT_LAT;
$mapLng  = MAP_DEFAULT_LNG;
$appUrl  = APP_URL;

$jsonKec      = json_encode(array_column($perKecamatan ?? [], 'nama'));
$jsonTotals   = json_encode(array_column($perKecamatan ?? [], 'total'));
$jsonEkstrems = json_encode(array_column($perKecamatan ?? [], 'ekstrem'));

$jsonBulan         = json_encode(array_column($trenBantuan ?? [], 'bulan'));
$jsonJmlBantuan    = json_encode(array_column($trenBantuan ?? [], 'jumlah'));
$jsonWargaTerbantu = json_encode(array_column($trenBantuan ?? [], 'warga_terbantu'));

$extraJs = <<<JS
<script>
document.addEventListener('DOMContentLoaded', async () => {
  // Peta dengan heatmap
  const map = GISMap.init('dinsos-map', {$mapLat}, {$mapLng}, 12);

  // Load semua data
  const [heatData, petaData] = await Promise.all([
    App.fetchJSON('{$appUrl}/dinsos/api/heatmap'),
    App.fetchJSON('{$appUrl}/admin/api/peta')
  ]);

  if(petaData) {
    const riLayer = GISMap.addRILayer(petaData.rumah_ibadah||[]);
    const wLayer  = GISMap.addWargaLayer(petaData.warga||[]);
    L.control.layers(GISMap.layers, {
      '⛪ Rumah Ibadah': riLayer,
      '👥 Warga Miskin': wLayer
    }, {position:'topright', collapsed:true}).addTo(map);
  }
  if(heatData) GISMap.addHeatmap(heatData);
  // Auto zoom ke seluruh Kota Pontianak
  GISMap.autoFitBounds();

  // Chart per kecamatan
  const kec = {$jsonKec};
  const totals  = {$jsonTotals};
  const ekstrems = {$jsonEkstrems};
  Charts.bar('chart-kecamatan', kec, [
    {label:'Total Warga', data:totals},
    {label:'Miskin Ekstrem', data:ekstrems}
  ]);

  // Chart tren bantuan
  const bulan = {$jsonBulan};
  const jmlBantuan = {$jsonJmlBantuan};
  const wargaTerbantu = {$jsonWargaTerbantu};
  Charts.line('chart-tren', bulan, [
    {label:'Bantuan Disalurkan', data:jmlBantuan},
    {label:'Warga Terbantu', data:wargaTerbantu}
  ]);
});
</script>
JS; ?>

<!-- Stats -->
<div class="stats-grid">
  <div class="stat-card">
    <div class="stat-card-icon blue">👥</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['total_warga']??0) ?></div>
      <div class="stat-card-label">Total Warga Miskin</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon red">💀</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['ekstrem']??0) ?></div>
      <div class="stat-card-label">Miskin Ekstrem</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon orange">⚠</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['miskin']??0) ?></div>
      <div class="stat-card-label">Miskin</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon yellow">📊</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['rentan']??0) ?></div>
      <div class="stat-card-label">Rentan Miskin</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon purple">⚠️</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['blind_spot']??0) ?></div>
      <div class="stat-card-label">Blind Spot</div>
      <div class="stat-card-sub"><a href="<?= APP_URL ?>/dinsos/blind-spot" style="color:var(--clr-primary-l)">Detail →</a></div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon green">📦</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['total_bantuan']??0) ?></div>
      <div class="stat-card-label">Total Bantuan</div>
      <div class="stat-card-sub"><?= number_format($stats['bantuan_bulan_ini']??0) ?> bulan ini</div>
    </div>
  </div>
</div>

<!-- Grid: Peta Besar + Info -->
<div class="dashboard-grid" style="margin-bottom:20px">
  <div class="card">
    <div class="card-header">
      <span class="card-icon">🌡</span><h3>Heatmap Kemiskinan Kota Pontianak</h3>
      <div class="card-actions">
        <a href="<?= APP_URL ?>/dinsos/kemiskinan" class="btn btn-ghost btn-sm">Detail Peta</a>
        <a href="<?= APP_URL ?>/dinsos/blind-spot" class="btn btn-danger btn-sm">⚠ Blind Spot</a>
      </div>
    </div>
    <div class="card-body no-pad" style="position:relative">
      <div id="dinsos-map" style="height:460px"></div>
      <div class="map-legend">
        <h4>Intensitas Kemiskinan</h4>
        <div style="height:12px;border-radius:6px;background:linear-gradient(to right,#fef9c3,#fb923c,#ef4444,#7f1d1d);margin-bottom:6px"></div>
        <div style="display:flex;justify-content:space-between;font-size:0.65rem;color:var(--clr-text-muted)">
          <span>Rendah</span><span>Tinggi</span>
        </div>
      </div>
    </div>
  </div>

  <!-- Sidebar: Per kec + Top RI -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <!-- Peringkat Kecamatan -->
    <div class="card">
      <div class="card-header"><span class="card-icon">🗾</span><h3>Kemiskinan per Kecamatan</h3></div>
      <div class="card-body no-pad">
        <?php foreach($perKecamatan as $i=>$k): ?>
        <div style="padding:10px 16px;border-bottom:1px solid #f1f5f9">
          <div style="display:flex;justify-content:space-between;margin-bottom:4px">
            <span style="font-weight:600;font-size:0.82rem"><?= $i+1 ?>. <?= e($k['nama']) ?></span>
            <span style="font-weight:700;color:var(--clr-primary)"><?= number_format($k['total']) ?></span>
          </div>
          <div style="height:5px;background:#f1f5f9;border-radius:3px;overflow:hidden">
            <?php $maxTotal = max(array_column($perKecamatan,'total')?:[1]); ?>
            <div style="height:100%;background:var(--clr-danger);width:<?= $maxTotal>0?round($k['total']/$maxTotal*100):0 ?>%;border-radius:3px"></div>
          </div>
          <div style="font-size:0.7rem;color:var(--clr-text-muted);margin-top:2px">
            Ekstrem: <?= $k['ekstrem'] ?> · Blind: <?= $k['blind_spot']??0 ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Top Rumah Ibadah Aktif -->
    <div class="card">
      <div class="card-header"><span class="card-icon">🏆</span><h3>Rumah Ibadah Paling Aktif</h3></div>
      <div class="card-body no-pad">
        <?php foreach($topRi as $i=>$r): ?>
        <div style="padding:10px 16px;border-bottom:1px solid #f1f5f9;display:flex;gap:12px;align-items:center">
          <div style="width:28px;height:28px;border-radius:50%;background:var(--clr-accent);color:var(--clr-primary-d);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:0.85rem;flex-shrink:0"><?= $i+1 ?></div>
          <div style="flex:1;min-width:0">
            <div style="font-weight:600;font-size:0.82rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= e($r['nama']) ?></div>
            <div style="font-size:0.72rem;color:var(--clr-text-muted)"><?= number_format($r['jml_bantuan']) ?> bantuan · <?= number_format($r['jml_warga']) ?> warga</div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<!-- Charts Row -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
  <div class="card">
    <div class="card-header"><span class="card-icon">📊</span><h3>Perbandingan per Kecamatan</h3></div>
    <div class="card-body"><div class="chart-wrap"><canvas id="chart-kecamatan"></canvas></div></div>
  </div>
  <div class="card">
    <div class="card-header"><span class="card-icon">📈</span><h3>Tren Bantuan 6 Bulan</h3></div>
    <div class="card-body"><div class="chart-wrap"><canvas id="chart-tren"></canvas></div></div>
  </div>
</div>
