<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<style>
/* ─── DESIGN TOKENS ── */
:root {
  --teal-800: #0b5a52;
  --teal-700: #0b7a6e;
  --teal-600: #0d9488;
  --teal-500: #14b8a6;
  --teal-50:  #f0fdfa;
  --slate-50: #f8fafc;
  --slate-100:#f1f5f9;
  --slate-200:#e2e8f0;
  --slate-400:#94a3b8;
  --slate-500:#64748b;
  --slate-900:#0f172a;
  --shadow: 0 1px 5px rgba(0,0,0,.07);
  --shadow-md: 0 4px 16px rgba(0,0,0,.09);
}

/* ─── PAGE HEADER ── */
.ar-page-header {
  display: flex; justify-content: space-between; align-items: flex-start;
  flex-wrap: wrap; gap: 14px; margin-bottom: 24px;
}
.ar-header-left h4 {
  font-size: 1.25rem; font-weight: 800; color: var(--teal-800);
  margin: 0 0 5px; display: flex; align-items: center; gap: 11px; letter-spacing: -.3px;
}
.ar-header-left h4 .hi {
  width: 40px; height: 40px; border-radius: 11px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1.05rem;
  box-shadow: 0 4px 12px rgba(13,148,136,0.32); flex-shrink: 0;
}
.ar-breadcrumb {
  display: flex; align-items: center; gap: 6px;
  font-size: 0.77rem; color: var(--slate-400); padding-left: 51px;
}
.ar-breadcrumb a { color: var(--teal-600); text-decoration: none; font-weight: 600; }
.ar-breadcrumb a:hover { text-decoration: underline; }
.ar-breadcrumb .sep { color: var(--slate-200); }
.btn-back {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 10px 20px; border-radius: 50px;
  border: 2px solid var(--teal-600); background: transparent;
  color: var(--teal-600); font-size: 0.85rem; font-weight: 700;
  text-decoration: none; transition: all .2s; white-space: nowrap;
}
.btn-back:hover { background: var(--teal-600); color: #fff; transform: translateY(-1px); }

/* ─── FILTER CARD ── */
.filter-card {
  background: #fff; border-radius: 14px;
  border: 1px solid var(--slate-100);
  box-shadow: var(--shadow); margin-bottom: 24px; overflow: hidden;
}
.filter-card-header {
  background: linear-gradient(135deg, #0d9488 0%, #14b8a6 100%);
  padding: 13px 20px; display: flex; align-items: center; gap: 9px;
  font-size: .85rem; font-weight: 700; color: #fff;
  cursor: pointer; user-select: none;
}
.filter-card-header i { font-size: 1rem; }
.filter-card-header .toggle-icon { margin-left: auto; transition: transform .25s; }
.filter-card-header.collapsed .toggle-icon { transform: rotate(-90deg); }
.filter-card-body { padding: 18px 20px; }
.filter-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; }
.filter-group { display: flex; flex-direction: column; gap: 5px; flex: 1 1 160px; min-width: 130px; }
.filter-group label { font-size: .72rem; font-weight: 700; color: var(--slate-500); text-transform: uppercase; letter-spacing: .05em; }
.filter-group select,
.filter-group input {
  padding: 9px 12px; border-radius: 8px;
  border: 1.5px solid var(--slate-200); font-size: .85rem;
  background: var(--slate-50); color: var(--slate-900);
  transition: border-color .2s, box-shadow .2s; outline: none;
  appearance: none; -webkit-appearance: none;
}
.filter-group select:focus,
.filter-group input:focus {
  border-color: var(--teal-500);
  box-shadow: 0 0 0 3px rgba(20,184,166,.15);
  background: #fff;
}
.filter-group select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%2394a3b8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 30px; }
.filter-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; padding-top: 18px; border-top: 1px solid var(--slate-100); margin-top: 14px; }
.btn-filter {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 9px 20px; border-radius: 50px; font-size: .83rem; font-weight: 700;
  cursor: pointer; border: none; transition: all .2s; text-decoration: none;
}
.btn-filter.primary { background: linear-gradient(135deg, #0d9488, #14b8a6); color: #fff; box-shadow: 0 4px 12px rgba(13,148,136,.25); }
.btn-filter.primary:hover { transform: translateY(-1px); box-shadow: 0 6px 18px rgba(13,148,136,.35); }
.btn-filter.secondary { background: var(--slate-100); color: var(--slate-500); }
.btn-filter.secondary:hover { background: var(--slate-200); }

/* ─── STAT SUMMARY ── */
.stat-summary {
  display: grid; grid-template-columns: repeat(5, 1fr);
  gap: 14px; margin-bottom: 24px;
}
.stat-mini {
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  border-radius: 12px; padding: 16px 18px;
  display: flex; justify-content: space-between; align-items: center;
  box-shadow: 0 4px 16px rgba(13,148,136,0.22); position: relative;
}
.stat-mini.orange { background: linear-gradient(135deg, #f59e0b, #fbbf24); box-shadow: 0 4px 16px rgba(245,158,11,.22); }
.stat-mini.rose   { background: linear-gradient(135deg, #e11d48, #fb7185); box-shadow: 0 4px 16px rgba(225,29,72,.22); }
.stat-mini.blue   { background: linear-gradient(135deg, #1d4ed8, #60a5fa); box-shadow: 0 4px 16px rgba(29,78,216,.22); }
.stat-mini.purple { background: linear-gradient(135deg, #7c3aed, #a78bfa); box-shadow: 0 4px 16px rgba(124,58,237,.22); }
.stat-mini-label { font-size: .72rem; font-weight: 600; color: rgba(255,255,255,.82); margin-bottom: 4px; }
.stat-mini-value { font-size: 1.3rem; font-weight: 800; color: #fff; line-height: 1; }
.stat-mini-sub   { font-size: .68rem; color: rgba(255,255,255,.65); margin-top: 3px; }
.stat-mini-icon  { width: 38px; height: 38px; border-radius: 8px; background: rgba(255,255,255,.2); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.stat-mini-icon i { font-size: 1.1rem; color: #fff; }

/* ─── SECTION LABEL ── */
.section-label {
  font-size: .72rem; font-weight: 700; letter-spacing: .08em;
  text-transform: uppercase; color: var(--slate-400);
  margin-bottom: 10px; padding-left: 2px;
}

/* ─── CHART CARD ── */
.chart-card {
  background: #fff; border-radius: 12px;
  box-shadow: var(--shadow); overflow: hidden; border: 1px solid var(--slate-100);
}
.chart-card-header {
  padding: 12px 18px; display: flex; align-items: center; gap: 8px;
  border-bottom: 1px solid #f1f3f5; background: #fff;
  font-size: .84rem; font-weight: 700; color: #374151;
}
.chart-card-header i { color: var(--teal-600); }
.chart-card-body { padding: 16px; }

/* ─── TABEL RINGKASAN ── */
.tbl-card {
  background: #fff; border-radius: 12px;
  box-shadow: var(--shadow); border: 1px solid var(--slate-100); overflow: hidden;
}
.tbl-card-header {
  padding: 12px 18px; display: flex; align-items: center; gap: 8px;
  border-bottom: 1px solid #f1f5f9;
  font-size: .84rem; font-weight: 700; color: #374151;
}
.tbl-card-header i { color: var(--teal-600); }
.tbl-iuran { width: 100%; border-collapse: collapse; font-size: .82rem; }
.tbl-iuran thead th {
  background: var(--slate-50); padding: 9px 14px;
  font-size: .7rem; font-weight: 700; text-transform: uppercase;
  letter-spacing: .05em; color: var(--slate-500);
  border-bottom: 1px solid var(--slate-100); white-space: nowrap;
}
.tbl-iuran tbody td { padding: 9px 14px; border-bottom: 1px solid var(--slate-50); vertical-align: middle; }
.tbl-iuran tbody tr:last-child td { border-bottom: none; }
.tbl-iuran tbody tr:hover td { background: var(--teal-50); }
.badge-status {
  display: inline-block; padding: 3px 9px; border-radius: 50px;
  font-size: .68rem; font-weight: 700;
}
.badge-status.lunas     { background: #d1fae5; color: #065f46; }
.badge-status.pending   { background: #fef3c7; color: #92400e; }
.badge-status.cicil     { background: #dbeafe; color: #1e40af; }
.badge-status.menunggu  { background: #ede9fe; color: #5b21b6; }

/* ─── FILTER AKTIF BADGE ── */
.filter-active-bar {
  display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
  margin-bottom: 16px; font-size: .78rem;
}
.filter-badge {
  display: inline-flex; align-items: center; gap: 5px;
  background: var(--teal-50); border: 1px solid var(--teal-500);
  color: var(--teal-700); padding: 3px 10px; border-radius: 50px;
  font-size: .73rem; font-weight: 700;
}

/* ─── MOBILE ── */
@media (max-width: 991px) {
  .stat-summary { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 767px) {
  .stat-summary { grid-template-columns: 1fr 1fr; }
  .chart-row > [class*='col-'] { flex: 0 0 100% !important; max-width: 100% !important; }
  .ar-page-header { flex-direction: column; align-items: flex-start; }
  .btn-back { width: 100%; justify-content: center; }
}
</style>

<script src="<?php echo base_url('assets/js/chart.js'); ?>"></script>

<?php
/* ════════════════════════════════════════════════
   DATA AWAL — ambil dari $iuran_list yang sudah
   di-filter oleh controller sebelum dikirim ke view.
   Variabel yang WAJIB disiapkan controller:
     $iuran_list      — hasil get_all($filter) atau get_by_user()
     $jenis_iuran_list — dropdown jenis iuran
     $filter          — array filter aktif (status, bulan, tahun, jenis_iuran_id, nama)
   ════════════════════════════════════════════════ */

$filter          = $filter          ?? [];
$iuran_list      = $iuran_list      ?? [];
$jenis_iuran_list= $jenis_iuran_list ?? [];

/* ── Hitung statistik dari $iuran_list ── */
$total_tagihan   = count($iuran_list);
$total_nominal   = 0;
$total_terbayar  = 0;
$total_tunggakan = 0;
$total_cicil     = 0;

$cnt_lunas   = 0; $cnt_pending = 0; $cnt_cicil   = 0; $cnt_menunggu = 0;

/* Untuk chart per bulan */
$per_bulan_nominal   = array_fill(1, 12, 0);
$per_bulan_terbayar  = array_fill(1, 12, 0);

/* Untuk chart per jenis */
$per_jenis = [];

/* Untuk chart per status */
$per_status = ['lunas' => 0, 'pending' => 0, 'cicil' => 0, 'menunggu_verifikasi' => 0];

/* Untuk tabel ringkasan per jenis */
$ringkasan_jenis = [];

$bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
               'Juli','Agustus','September','Oktober','November','Desember'];

foreach($iuran_list as $row) {
    $nominal    = (float)($row->nominal ?? 0);
    $terbayar   = (float)($row->total_terbayar ?? 0);
    $sisa       = (float)($row->sisa_tagihan ?? ($nominal - $terbayar));
    $status     = $row->status ?? 'pending';
    $bln        = (int)($row->periode_bulan ?? 0);
    $jns        = $row->nama_iuran ?? 'Unknown';

    $total_nominal  += $nominal;
    $total_terbayar += $terbayar;

    if($status !== 'lunas') $total_tunggakan += max(0, $sisa);

    if(isset($per_bulan_nominal[$bln])) {
        $per_bulan_nominal[$bln]  += $nominal;
        $per_bulan_terbayar[$bln] += $terbayar;
    }

    /* Per jenis */
    if(!isset($per_jenis[$jns])) $per_jenis[$jns] = ['nominal'=>0,'terbayar'=>0,'lunas'=>0,'pending'=>0,'cicil'=>0,'menunggu'=>0,'total'=>0];
    $per_jenis[$jns]['nominal']   += $nominal;
    $per_jenis[$jns]['terbayar']  += $terbayar;
    $per_jenis[$jns]['total']++;

    /* Per status */
    $cnt_key = $status;
    if($cnt_key === 'cicil' || ($status === 'pending' && $terbayar > 0)) $cnt_key = 'cicil';
    switch($status) {
        case 'lunas':               $cnt_lunas++;    $per_status['lunas']++;              $per_jenis[$jns]['lunas']++;   break;
        case 'pending':             $cnt_pending++;  $per_status['pending']++;            $per_jenis[$jns]['pending']++; break;
        case 'cicil':               $cnt_cicil++;    $per_status['cicil']++;              $per_jenis[$jns]['cicil']++;   break;
        case 'menunggu_verifikasi': $cnt_menunggu++; $per_status['menunggu_verifikasi']++;$per_jenis[$jns]['menunggu']++; break;
    }

    /* Ringkasan per jenis untuk tabel */
    if(!isset($ringkasan_jenis[$jns])) {
        $ringkasan_jenis[$jns] = ['nama'=>$jns,'total'=>0,'nominal'=>0,'terbayar'=>0,'tunggakan'=>0,'lunas'=>0,'pending'=>0,'cicil'=>0];
    }
    $ringkasan_jenis[$jns]['total']++;
    $ringkasan_jenis[$jns]['nominal']   += $nominal;
    $ringkasan_jenis[$jns]['terbayar']  += $terbayar;
    $ringkasan_jenis[$jns]['tunggakan'] += ($status !== 'lunas') ? max(0,$sisa) : 0;
    if($status === 'lunas')   $ringkasan_jenis[$jns]['lunas']++;
    if($status === 'pending') $ringkasan_jenis[$jns]['pending']++;
    if($status === 'cicil')   $ringkasan_jenis[$jns]['cicil']++;
}

$pct_lunas = $total_tagihan > 0 ? round(($cnt_lunas / $total_tagihan) * 100, 1) : 0;

/* ── Filter aktif sebagai teks badge ── */
$filter_aktif = [];
if(!empty($filter['status']))         $filter_aktif[] = 'Status: ' . strtoupper($filter['status']);
if(!empty($filter['bulan']))          $filter_aktif[] = 'Bulan: ' . $bulan_nama[(int)$filter['bulan']];
if(!empty($filter['tahun']))          $filter_aktif[] = 'Tahun: ' . $filter['tahun'];
if(!empty($filter['jenis_iuran_id'])){
    foreach($jenis_iuran_list as $ji) {
        if($ji->id == $filter['jenis_iuran_id']) { $filter_aktif[] = 'Jenis: '.$ji->nama_iuran; break; }
    }
}
if(!empty($filter['nama'])) $filter_aktif[] = 'Nama: ' . $filter['nama'];

/* ── Tahun yang tersedia untuk dropdown ── */
$tahun_sekarang = (int)date('Y');
$tahun_options  = range($tahun_sekarang - 4, $tahun_sekarang + 1);
?>

<!-- ── PAGE HEADER ── -->
<div class="ar-page-header">
    <div class="ar-header-left">
        <h4>
            <span class="hi"><i class="bi bi-bar-chart-line-fill"></i></span>
            Statistik Iuran
        </h4>
        <div class="ar-breadcrumb">
            <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
            <span class="sep">/</span>
            <a href="<?php echo base_url('iuran'); ?>">Iuran</a>
            <span class="sep">/</span>
            <span>Statistik</span>
        </div>
    </div>
    <a href="<?php echo base_url('iuran'); ?>" class="btn-back">
        <i class="bi bi-arrow-left"></i> Kembali
    </a>
</div>

<!-- ── FILTER CARD ── -->
<div class="filter-card">
    <div class="filter-card-header" id="filterToggle">
        <i class="bi bi-funnel-fill"></i>
        Filter Statistik
        <span id="filterBadge" style="background:rgba(255,255,255,.25);padding:2px 9px;border-radius:50px;font-size:.7rem;margin-left:6px;display:<?php echo count($filter_aktif) ? 'inline' : 'none'; ?>">
            <?php echo count($filter_aktif); ?> aktif
        </span>
        <i class="bi bi-chevron-down toggle-icon" id="filterChevron"></i>
    </div>
    <div class="filter-card-body" id="filterBody">
        <form method="GET" action="<?php echo base_url('iuran/statistik'); ?>" id="filterForm">
            <div class="filter-row">

                <!-- Status -->
                <div class="filter-group">
                    <label><i class="bi bi-circle-fill" style="font-size:.5rem;"></i> Status</label>
                    <select name="status">
                        <option value="">Semua Status</option>
                        <option value="lunas"               <?php echo ($filter['status']??'')==='lunas'               ?'selected':''; ?>>Lunas</option>
                        <option value="pending"             <?php echo ($filter['status']??'')==='pending'             ?'selected':''; ?>>Pending</option>
                        <option value="cicil"               <?php echo ($filter['status']??'')==='cicil'               ?'selected':''; ?>>Cicil</option>
                        <option value="menunggu_verifikasi" <?php echo ($filter['status']??'')==='menunggu_verifikasi' ?'selected':''; ?>>Menunggu Verifikasi</option>
                    </select>
                </div>

                <!-- Bulan -->
                <div class="filter-group">
                    <label><i class="bi bi-calendar-month"></i> Bulan</label>
                    <select name="bulan">
                        <option value="">Semua Bulan</option>
                        <?php for($m=1; $m<=12; $m++): ?>
                        <option value="<?php echo $m; ?>" <?php echo ($filter['bulan']??'')==$m?'selected':''; ?>>
                            <?php echo $bulan_nama[$m]; ?>
                        </option>
                        <?php endfor; ?>
                    </select>
                </div>

                <!-- Tahun -->
                <div class="filter-group">
                    <label><i class="bi bi-calendar-year"></i> Tahun</label>
                    <select name="tahun">
                        <option value="">Semua Tahun</option>
                        <?php foreach($tahun_options as $ty): ?>
                        <option value="<?php echo $ty; ?>" <?php echo ($filter['tahun']??'')==$ty?'selected':''; ?>>
                            <?php echo $ty; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Jenis Iuran -->
                <div class="filter-group">
                    <label><i class="bi bi-tag"></i> Jenis Iuran</label>
                    <select name="jenis_iuran_id">
                        <option value="">Semua Jenis</option>
                        <?php foreach($jenis_iuran_list as $ji): ?>
                        <option value="<?php echo $ji->id; ?>" <?php echo ($filter['jenis_iuran_id']??'')==$ji->id?'selected':''; ?>>
                            <?php echo htmlspecialchars($ji->nama_iuran); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <?php if(!is_warga()): ?>
                <!-- Nama Warga (admin only) -->
                <div class="filter-group">
                    <label><i class="bi bi-person"></i> Nama Warga</label>
                    <input type="text" name="nama" placeholder="Cari nama..."
                           value="<?php echo htmlspecialchars($filter['nama']??''); ?>">
                </div>
                <?php endif; ?>

            </div><!-- /.filter-row -->
            <div class="filter-actions">
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-search"></i> Terapkan Filter
                </button>
                <a href="<?php echo base_url('iuran/statistik'); ?>" class="btn-filter secondary">
                    <i class="bi bi-x-circle"></i> Reset
                </a>
                <?php if(count($filter_aktif)): ?>
                <div style="margin-left:8px;font-size:.78rem;color:var(--slate-400);">
                    <?php echo count($filter_aktif); ?> filter aktif
                </div>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- ── FILTER AKTIF BADGE ── -->
<?php if(count($filter_aktif)): ?>
<div class="filter-active-bar mb-3">
    <span style="font-size:.75rem;color:var(--slate-400);font-weight:600;">Filter aktif:</span>
    <?php foreach($filter_aktif as $fa): ?>
    <span class="filter-badge"><i class="bi bi-check2"></i> <?php echo htmlspecialchars($fa); ?></span>
    <?php endforeach; ?>
    <a href="<?php echo base_url('iuran/statistik'); ?>" style="font-size:.73rem;color:#e11d48;font-weight:700;text-decoration:none;margin-left:4px;">
        <i class="bi bi-x"></i> Hapus semua
    </a>
</div>
<?php endif; ?>

<!-- ── STAT SUMMARY ── -->
<div class="section-label">Ringkasan
    <?php if(count($filter_aktif)) echo '<small style="text-transform:none;letter-spacing:0;font-weight:400;color:#cbd5e1;"> — berdasarkan filter aktif</small>'; ?>
</div>
<div class="stat-summary mb-4">

    <div class="stat-mini">
        <div>
            <div class="stat-mini-label">Total Tagihan</div>
            <div class="stat-mini-value"><?php echo number_format($total_tagihan,0,',','.'); ?></div>
            <div class="stat-mini-sub">tagihan</div>
        </div>
        <div class="stat-mini-icon"><i class="bi bi-receipt"></i></div>
    </div>

    <div class="stat-mini blue">
        <div>
            <div class="stat-mini-label">Total Nominal</div>
            <div class="stat-mini-value" style="font-size:1.1rem;">Rp <?php echo number_format($total_nominal,0,',','.'); ?></div>
            <div class="stat-mini-sub">seluruh tagihan</div>
        </div>
        <div class="stat-mini-icon"><i class="bi bi-cash-stack"></i></div>
    </div>

    <div class="stat-mini">
        <div>
            <div class="stat-mini-label">Terkumpul</div>
            <div class="stat-mini-value" style="font-size:1.1rem;">Rp <?php echo number_format($total_terbayar,0,',','.'); ?></div>
            <div class="stat-mini-sub"><?php echo $pct_lunas; ?>% dari total</div>
        </div>
        <div class="stat-mini-icon"><i class="bi bi-check-circle-fill"></i></div>
    </div>

    <div class="stat-mini rose">
        <div>
            <div class="stat-mini-label">Tunggakan</div>
            <div class="stat-mini-value" style="font-size:1.1rem;">Rp <?php echo number_format($total_tunggakan,0,',','.'); ?></div>
            <div class="stat-mini-sub">belum terbayar</div>
        </div>
        <div class="stat-mini-icon"><i class="bi bi-exclamation-triangle-fill"></i></div>
    </div>

    <div class="stat-mini orange">
        <div>
            <div class="stat-mini-label">Lunas</div>
            <div class="stat-mini-value"><?php echo number_format($cnt_lunas,0,',','.'); ?></div>
            <div class="stat-mini-sub"><?php echo $pct_lunas; ?>% dari tagihan</div>
        </div>
        <div class="stat-mini-icon"><i class="bi bi-patch-check-fill"></i></div>
    </div>

</div>

<!-- ── STATUS BADGES MINI ── -->
<div class="d-flex flex-wrap gap-2 mb-4">
    <?php
    $statuses = [
        'lunas'               => ['label'=>'Lunas',             'count'=>$cnt_lunas,    'bg'=>'#d1fae5','color'=>'#065f46'],
        'pending'             => ['label'=>'Pending',           'count'=>$cnt_pending,  'bg'=>'#fef3c7','color'=>'#92400e'],
        'cicil'               => ['label'=>'Cicil',             'count'=>$cnt_cicil,    'bg'=>'#dbeafe','color'=>'#1e40af'],
        'menunggu_verifikasi' => ['label'=>'Menunggu Verif.',   'count'=>$cnt_menunggu, 'bg'=>'#ede9fe','color'=>'#5b21b6'],
    ];
    foreach($statuses as $s): ?>
    <a href="<?php echo base_url('iuran/statistik?status='.$s['label']); ?>"
       style="display:inline-flex;align-items:center;gap:6px;
              background:<?php echo $s['bg']; ?>;color:<?php echo $s['color']; ?>;
              padding:7px 14px;border-radius:50px;font-size:.78rem;font-weight:700;
              text-decoration:none;border:1.5px solid <?php echo $s['color'].'33'; ?>;
              transition:all .15s;"
       onmouseover="this.style.transform='translateY(-1px)'"
       onmouseout="this.style.transform='translateY(0)'">
        <span style="width:8px;height:8px;border-radius:50%;background:<?php echo $s['color']; ?>;flex-shrink:0;"></span>
        <?php echo $s['label']; ?>: <strong><?php echo number_format($s['count'],0,',','.'); ?></strong>
    </a>
    <?php endforeach; ?>
</div>

<!-- ── GRAFIK ROW 1: Status Donut + Per Bulan ── -->
<div class="section-label">Grafik Pembayaran</div>
<div class="row g-3 mb-3 chart-row">
    <div class="col-lg-4">
        <div class="chart-card">
            <div class="chart-card-header"><i class="bi bi-pie-chart-fill"></i> Komposisi Status</div>
            <div class="chart-card-body"><canvas id="statusChart" height="260"></canvas></div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="chart-card">
            <div class="chart-card-header"><i class="bi bi-bar-chart-fill"></i> Nominal per Bulan (Tagihan vs Terbayar)</div>
            <div class="chart-card-body"><canvas id="perBulanChart" height="260"></canvas></div>
        </div>
    </div>
</div>

<!-- ── GRAFIK ROW 2: Per Jenis + Progress Lunas ── -->
<div class="row g-3 mb-4 chart-row">
    <div class="col-lg-7">
        <div class="chart-card">
            <div class="chart-card-header"><i class="bi bi-tags-fill"></i> Nominal per Jenis Iuran</div>
            <div class="chart-card-body"><canvas id="perJenisChart" height="260"></canvas></div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="chart-card">
            <div class="chart-card-header"><i class="bi bi-activity"></i> Rasio Lunas vs Belum (per Jenis)</div>
            <div class="chart-card-body" style="padding-bottom:10px;">
                <?php if(empty($ringkasan_jenis)): ?>
                <div style="text-align:center;color:var(--slate-400);padding:40px 0;font-size:.85rem;">Tidak ada data</div>
                <?php else: ?>
                <?php foreach($ringkasan_jenis as $jns => $rj):
                    $pct = $rj['total'] > 0 ? round(($rj['lunas']/$rj['total'])*100) : 0;
                    $color = $pct >= 80 ? '#10b981' : ($pct >= 50 ? '#f59e0b' : '#e11d48');
                ?>
                <div style="margin-bottom:14px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                        <span style="font-size:.78rem;font-weight:700;color:var(--slate-900);"><?php echo htmlspecialchars($jns); ?></span>
                        <span style="font-size:.72rem;font-weight:800;color:<?php echo $color; ?>;"><?php echo $pct; ?>%</span>
                    </div>
                    <div style="height:8px;background:var(--slate-100);border-radius:50px;overflow:hidden;">
                        <div style="height:100%;width:<?php echo $pct; ?>%;background:<?php echo $color; ?>;border-radius:50px;transition:width .6s ease;"></div>
                    </div>
                    <div style="font-size:.68rem;color:var(--slate-400);margin-top:3px;">
                        <?php echo $rj['lunas']; ?> lunas / <?php echo $rj['total']; ?> tagihan
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ── TABEL RINGKASAN PER JENIS IURAN ── -->
<div class="section-label">Ringkasan Per Jenis Iuran</div>
<div class="tbl-card mb-4">
    <div class="tbl-card-header">
        <i class="bi bi-table"></i>
        Detail Ringkasan per Jenis Iuran
        <span style="margin-left:auto;font-size:.72rem;color:var(--slate-400);font-weight:400;">
            <?php echo $total_tagihan; ?> total tagihan
        </span>
    </div>
    <div style="overflow-x:auto;">
        <table class="tbl-iuran">
            <thead>
                <tr>
                    <th>Jenis Iuran</th>
                    <th style="text-align:right;">Total Tagihan</th>
                    <th style="text-align:right;">Nominal</th>
                    <th style="text-align:right;">Terbayar</th>
                    <th style="text-align:right;">Tunggakan</th>
                    <th style="text-align:center;">Lunas</th>
                    <th style="text-align:center;">Pending</th>
                    <th style="text-align:center;">Cicil</th>
                    <th style="text-align:right;">Progress</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($ringkasan_jenis)): ?>
                <tr><td colspan="9" style="text-align:center;color:var(--slate-400);padding:30px;">Tidak ada data untuk filter ini.</td></tr>
                <?php else: ?>
                <?php foreach($ringkasan_jenis as $r):
                    $pct2 = $r['total'] > 0 ? round(($r['lunas']/$r['total'])*100) : 0;
                    $clr  = $pct2 >= 80 ? '#10b981' : ($pct2 >= 50 ? '#f59e0b' : '#e11d48');
                ?>
                <tr>
                    <td style="font-weight:700;color:var(--teal-700);"><?php echo htmlspecialchars($r['nama']); ?></td>
                    <td style="text-align:right;font-weight:600;"><?php echo number_format($r['total'],0,',','.'); ?></td>
                    <td style="text-align:right;font-weight:600;">Rp <?php echo number_format($r['nominal'],0,',','.'); ?></td>
                    <td style="text-align:right;color:#065f46;font-weight:700;">Rp <?php echo number_format($r['terbayar'],0,',','.'); ?></td>
                    <td style="text-align:right;color:#b91c1c;font-weight:700;">Rp <?php echo number_format($r['tunggakan'],0,',','.'); ?></td>
                    <td style="text-align:center;"><span class="badge-status lunas"><?php echo $r['lunas']; ?></span></td>
                    <td style="text-align:center;"><span class="badge-status pending"><?php echo $r['pending']; ?></span></td>
                    <td style="text-align:center;"><span class="badge-status cicil"><?php echo $r['cicil']; ?></span></td>
                    <td style="text-align:right;min-width:100px;">
                        <div style="display:flex;align-items:center;gap:6px;justify-content:flex-end;">
                            <div style="flex:1;height:6px;background:var(--slate-100);border-radius:50px;overflow:hidden;min-width:60px;">
                                <div style="height:100%;width:<?php echo $pct2; ?>%;background:<?php echo $clr; ?>;border-radius:50px;"></div>
                            </div>
                            <span style="font-size:.72rem;font-weight:800;color:<?php echo $clr; ?>;white-space:nowrap;"><?php echo $pct2; ?>%</span>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <!-- TOTAL ROW -->
                <tr style="background:var(--teal-50);font-weight:800;">
                    <td style="color:var(--teal-800);">TOTAL</td>
                    <td style="text-align:right;color:var(--teal-800);"><?php echo number_format($total_tagihan,0,',','.'); ?></td>
                    <td style="text-align:right;color:var(--teal-800);">Rp <?php echo number_format($total_nominal,0,',','.'); ?></td>
                    <td style="text-align:right;color:#065f46;">Rp <?php echo number_format($total_terbayar,0,',','.'); ?></td>
                    <td style="text-align:right;color:#b91c1c;">Rp <?php echo number_format($total_tunggakan,0,',','.'); ?></td>
                    <td style="text-align:center;"><span class="badge-status lunas"><?php echo $cnt_lunas; ?></span></td>
                    <td style="text-align:center;"><span class="badge-status pending"><?php echo $cnt_pending; ?></span></td>
                    <td style="text-align:center;"><span class="badge-status cicil"><?php echo $cnt_cicil; ?></span></td>
                    <td style="text-align:right;">
                        <span style="font-size:.78rem;font-weight:800;color:var(--teal-700);"><?php echo $pct_lunas; ?>%</span>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ── SCRIPTS ── -->
<script>
(function() {
    var COLORS_PIE = ['#1abc9c','#f59e0b','#3b82f6','#8b5cf6','#ef4444'];
    var opts_donut = {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'bottom', labels: { usePointStyle: true, padding: 14, font: { size: 11 } } } },
        cutout: '58%'
    };

    /* ── 1. Chart Status ── */
    new Chart(document.getElementById('statusChart').getContext('2d'), {
        type: 'doughnut',
        data: {
            labels: ['Lunas', 'Pending', 'Cicil', 'Menunggu Verif.'],
            datasets: [{
                data: [<?php echo $cnt_lunas.','.$cnt_pending.','.$cnt_cicil.','.$cnt_menunggu; ?>],
                backgroundColor: ['#1abc9c','#f59e0b','#3b82f6','#8b5cf6'],
                borderWidth: 2
            }]
        },
        options: opts_donut
    });

    /* ── 2. Chart per Bulan ── */
    var bln_labels = <?php echo json_encode(array_values($bulan_nama)); ?>.slice(1); // jan-des
    var bln_nominal  = <?php echo json_encode(array_values($per_bulan_nominal)); ?>;
    var bln_terbayar = <?php echo json_encode(array_values($per_bulan_terbayar)); ?>;

    new Chart(document.getElementById('perBulanChart').getContext('2d'), {
        type: 'bar',
        data: {
            labels: bln_labels,
            datasets: [
                {
                    label: 'Total Nominal',
                    data: bln_nominal,
                    backgroundColor: 'rgba(13,148,136,.25)',
                    borderColor: '#0d9488',
                    borderWidth: 1.5,
                    borderRadius: 4,
                    order: 2,
                },
                {
                    label: 'Terbayar',
                    data: bln_terbayar,
                    backgroundColor: '#14b8a6',
                    borderColor: '#0b7a6e',
                    borderWidth: 1,
                    borderRadius: 4,
                    order: 1,
                }
            ]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            plugins: { legend: { position: 'bottom', labels: { usePointStyle:true, font:{size:11} } } },
            scales: {
                y: { beginAtZero: true, ticks: { precision:0, font:{size:10},
                    callback: function(v){ return v>=1000000 ? 'Rp '+(v/1000000).toFixed(1)+'jt' : 'Rp '+v.toLocaleString('id-ID'); }
                }},
                x: { ticks: { font:{size:10} } }
            }
        }
    });

    /* ── 3. Chart per Jenis ── */
    var jenis_labels  = <?php echo json_encode(array_keys($per_jenis)); ?>;
    var jenis_nominal = <?php echo json_encode(array_column(array_values($per_jenis), 'nominal')); ?>;
    var jenis_bayar   = <?php echo json_encode(array_column(array_values($per_jenis), 'terbayar')); ?>;

    new Chart(document.getElementById('perJenisChart').getContext('2d'), {
        type: 'bar',
        data: {
            labels: jenis_labels,
            datasets: [
                { label: 'Total Nominal',  data: jenis_nominal, backgroundColor: 'rgba(13,148,136,.25)', borderColor:'#0d9488', borderWidth:1.5, borderRadius:5 },
                { label: 'Terbayar',       data: jenis_bayar,   backgroundColor: '#14b8a6',              borderColor:'#0b7a6e', borderWidth:1,   borderRadius:5 }
            ]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            plugins: { legend: { position:'bottom', labels:{ usePointStyle:true, font:{size:11} } } },
            scales: {
                y: { beginAtZero:true, ticks:{ precision:0, font:{size:10},
                    callback: function(v){ return v>=1000000 ? 'Rp '+(v/1000000).toFixed(1)+'jt' : 'Rp '+v.toLocaleString('id-ID'); }
                }},
                x: { ticks:{ font:{size:10} } }
            }
        }
    });

    /* ── Toggle Filter ── */
    var filterToggle = document.getElementById('filterToggle');
    var filterBody   = document.getElementById('filterBody');
    var filterChevron= document.getElementById('filterChevron');

    // Default: buka jika ada filter aktif, tutup jika tidak
    var hasFilter = <?php echo count($filter_aktif) ? 'true' : 'false'; ?>;
    if(!hasFilter) {
        filterBody.style.display = 'none';
        filterToggle.classList.add('collapsed');
    }

    filterToggle.addEventListener('click', function() {
        var isOpen = filterBody.style.display !== 'none';
        filterBody.style.display = isOpen ? 'none' : 'block';
        filterChevron.style.transform = isOpen ? 'rotate(-90deg)' : 'rotate(0deg)';
        filterToggle.classList.toggle('collapsed', isOpen);
    });
})();
</script>