<?php
/* ════ Daftar kelas terpusat ════ */
$daftarJurusan = [
    'X'   => ['1','2','3','4'],
    'XI'  => ['A-1','A-2','B-1','B-2'],
    'XII' => ['IPA 1','IPA 2','IPS 1','IPS 2'],
];

require_once 'layout/header.php';

$bulan   = (int)($_GET['bulan']   ?? 0);
$tahun   = (int)($_GET['tahun']   ?? date('Y'));
$metode  = $_GET['metode']        ?? '';
$search  = trim($_GET['q']        ?? '');
$kelas   = trim($_GET['kelas']    ?? '');
$jurusan = trim(str_replace('+', ' ', $_GET['jurusan'] ?? ''));

$perPage     = (int)($_GET['per_page'] ?? 20);
$allowedPP   = [10, 20, 50, 100];
if (!in_array($perPage, $allowedPP)) $perPage = 20;
$currentPage = max(1, (int)($_GET['p'] ?? 1));
$offset      = ($currentPage - 1) * $perPage;

$whereSQL = " WHERE YEAR(COALESCE(p.tanggal_bayar,p.created_at)) = ?";
$params   = [$tahun];
if ($bulan)   { $whereSQL .= " AND MONTH(COALESCE(p.tanggal_bayar,p.created_at)) = ?"; $params[] = $bulan; }
if ($metode)  { $whereSQL .= " AND p.metode_bayar = ?";              $params[] = $metode; }
if ($kelas)   { $whereSQL .= " AND s.kelas = ?";                     $params[] = $kelas; }
if ($jurusan) { $whereSQL .= " AND s.jurusan = ?";                   $params[] = $jurusan; }
if ($search)  { $whereSQL .= " AND (s.nama LIKE ? OR s.nis LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }

$baseJoin = " FROM pembayaran p
              JOIN siswa s       ON p.siswa_id  = s.id
              JOIN tagihan_spp t ON p.tagihan_id = t.id
              JOIN admin a       ON p.admin_id  = a.id";

$stmtC = $pdo->prepare("SELECT COUNT(*)" . $baseJoin . $whereSQL);
$stmtC->execute($params);
$totalRows  = (int)$stmtC->fetchColumn();
$stmtC->closeCursor();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($currentPage > $totalPages) $currentPage = $totalPages;
$offset = ($currentPage - 1) * $perPage;

$stmtS = $pdo->prepare("SELECT COALESCE(SUM(p.jumlah_bayar),0)" . $baseJoin . $whereSQL);
$stmtS->execute($params);
$totalBayar = (int)$stmtS->fetchColumn();
$stmtS->closeCursor();

$whereBase  = " WHERE YEAR(COALESCE(p.tanggal_bayar,p.created_at)) = ?";
$paramsBase = [$tahun];
if ($bulan)  { $whereBase  .= " AND MONTH(COALESCE(p.tanggal_bayar,p.created_at)) = ?"; $paramsBase[] = $bulan; }
if ($metode) { $whereBase  .= " AND p.metode_bayar = ?";              $paramsBase[] = $metode; }
if ($search) { $whereBase  .= " AND (s.nama LIKE ? OR s.nis LIKE ?)"; $paramsBase[] = "%$search%"; $paramsBase[] = "%$search%"; }

$kelasCounts = []; $jurusanCounts = [];
try {
    $stBadge = $pdo->prepare("SELECT s.kelas, s.jurusan, COUNT(DISTINCT p.id) as total" . $baseJoin . $whereBase . " GROUP BY s.kelas, s.jurusan");
    $stBadge->execute($paramsBase);
    foreach ($stBadge->fetchAll() as $row) {
        $k = $row['kelas']; $j = $row['jurusan'];
        $kelasCounts[$k]          = ($kelasCounts[$k] ?? 0) + $row['total'];
        $jurusanCounts[$k.'|'.$j] = $row['total'];
    }
} catch(Exception $e){}

/* Fetch data + foto siswa */
$rootDir      = str_replace('\\', '/', dirname(__DIR__));
$fotoSiswaUrl = 'uploads/foto_siswa/';
$fotoSiswaAbs = $rootDir . '/uploads/foto_siswa/';

$stmtD = $pdo->prepare(
    "SELECT p.*,
            COALESCE(p.tanggal_bayar,p.created_at) AS tgl_bayar,
            s.nama, s.nis, s.kelas, s.jurusan, s.foto AS foto_siswa,
            t.bulan AS t_bulan, t.tahun AS t_tahun,
            a.nama_lengkap AS admin_nama"
    . $baseJoin . $whereSQL
    . " ORDER BY COALESCE(p.tanggal_bayar,p.created_at) DESC LIMIT ? OFFSET ?"
);
foreach ($params as $pi => $pv) { $stmtD->bindValue($pi + 1, $pv, PDO::PARAM_STR); }
$stmtD->bindValue(count($params) + 1, (int)$perPage, PDO::PARAM_INT);
$stmtD->bindValue(count($params) + 2, (int)$offset,  PDO::PARAM_INT);
$stmtD->execute();
$rows = $stmtD->fetchAll();

$avatarColors = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];

$icoSearch   = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>';
$icoFilter   = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>';
$icoCalendar = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
$icoUser     = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>';
$icoMoney    = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>';
$icoList     = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>';
$icoGrid     = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></svg>';
$icoCheck    = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
$icoChevL    = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';
$icoChevR    = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';
$icoChevsL   = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="11 17 6 12 11 7"/><polyline points="18 17 13 12 18 7"/></svg>';
$icoChevsR   = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';

$metodeConfig = [
    'tunai'         => ['label'=>'Tunai',        'pill'=>'pill-orange', 'icon'=>$icoMoney, 'bar'=>'#F59E0B', 'bg'=>'#FEF3C7', 'color'=>'#92400E'],
    'transfer'      => ['label'=>'Transfer',     'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#3B82F6', 'bg'=>'#DBEAFE', 'color'=>'#1E40AF'],
    'qris'          => ['label'=>'QRIS',         'pill'=>'pill-purple', 'icon'=>$icoMoney, 'bar'=>'#8B5CF6', 'bg'=>'#EDE9FE', 'color'=>'#5B21B6'],
    'dana'          => ['label'=>'DANA',         'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#118EEA', 'bg'=>'#DBEAFE', 'color'=>'#1251B5'],
    'gopay'         => ['label'=>'GoPay',        'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#00AED6', 'bg'=>'#CCFBF1', 'color'=>'#0369A1'],
    'ovo'           => ['label'=>'OVO',          'pill'=>'pill-purple', 'icon'=>$icoMoney, 'bar'=>'#4C3494', 'bg'=>'#EDE9FE', 'color'=>'#4C3494'],
    'shopeepay'     => ['label'=>'ShopeePay',    'pill'=>'pill-orange', 'icon'=>$icoMoney, 'bar'=>'#EE4D2D', 'bg'=>'#FFE4E4', 'color'=>'#C0392B'],
    'linkaja'       => ['label'=>'LinkAja',      'pill'=>'pill-orange', 'icon'=>$icoMoney, 'bar'=>'#E02020', 'bg'=>'#FFE4E4', 'color'=>'#B91C1C'],
    'credit_card'   => ['label'=>'Kartu Kredit', 'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#1D4ED8', 'bg'=>'#DBEAFE', 'color'=>'#1E40AF'],
    'bank_transfer' => ['label'=>'Transfer Bank','pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#3B82F6', 'bg'=>'#DBEAFE', 'color'=>'#1E40AF'],
    'echannel'      => ['label'=>'Mandiri VA',   'pill'=>'pill-orange', 'icon'=>$icoMoney, 'bar'=>'#F59E0B', 'bg'=>'#FEF3C7', 'color'=>'#92400E'],
    'permata'       => ['label'=>'Permata VA',   'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#1E40AF', 'bg'=>'#DBEAFE', 'color'=>'#1E40AF'],
    'bca'           => ['label'=>'BCA VA',       'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#006CB7', 'bg'=>'#DBEAFE', 'color'=>'#006CB7'],
    'bni'           => ['label'=>'BNI VA',       'pill'=>'pill-orange', 'icon'=>$icoMoney, 'bar'=>'#F59E0B', 'bg'=>'#FEF3C7', 'color'=>'#92400E'],
    'bri'           => ['label'=>'BRI VA',       'pill'=>'pill-blue',   'icon'=>$icoMoney, 'bar'=>'#00529C', 'bg'=>'#DBEAFE', 'color'=>'#00529C'],
    'cstore'        => ['label'=>'Minimarket',   'pill'=>'pill-green',  'icon'=>$icoMoney, 'bar'=>'#10B981', 'bg'=>'#D1FAE5', 'color'=>'#065F46'],
    'midtrans'      => ['label'=>'Midtrans',     'pill'=>'pill-purple', 'icon'=>$icoMoney, 'bar'=>'#8B5CF6', 'bg'=>'#EDE9FE', 'color'=>'#5B21B6'],
];

function pageUrl($p, $bulan, $tahun, $metode, $search, $perPage, $kelas = '', $jurusan = '') {
    return '?page=riwayat'
        . '&bulan='    . rawurlencode($bulan)
        . '&tahun='    . rawurlencode($tahun)
        . '&metode='   . rawurlencode($metode)
        . '&q='        . rawurlencode($search)
        . '&kelas='    . rawurlencode($kelas)
        . '&jurusan='  . rawurlencode($jurusan)
        . '&per_page=' . $perPage
        . '&p='        . $p;
}
function pageWindow($current, $total, $window = 2) {
    $start = max(1, $current - $window);
    $end   = min($total, $current + $window);
    if ($end - $start < $window * 2) {
        if ($start === 1) $end = min($total, $start + $window * 2);
        else              $start = max(1, $end - $window * 2);
    }
    return range($start, $end);
}

$baseKelasUrl = '?page=riwayat'
    . '&bulan='    . rawurlencode($bulan)
    . '&tahun='    . rawurlencode($tahun)
    . '&metode='   . rawurlencode($metode)
    . '&q='        . rawurlencode($search)
    . '&per_page=' . $perPage
    . '&p=1';
?>

<style>
.rw-view-toggle {
  display:flex;gap:3px;background:var(--surface2,#f1f5f9);border-radius:10px;padding:3px;
}
.rw-view-toggle button {
  display:flex;align-items:center;justify-content:center;gap:5px;padding:6px 12px;
  border:none;border-radius:8px;background:transparent;color:var(--text3);
  font-size:12px;font-weight:500;cursor:pointer;transition:all .18s ease;font-family:inherit;white-space:nowrap;
}
.rw-view-toggle button.active { background:var(--surface,#fff);color:var(--indigo,#4F6EF7);box-shadow:0 1px 4px rgba(0,0,0,.09); }
.rw-view-toggle button:hover:not(.active) { color:var(--text); }
.rw-toggle-label { display:inline; }
@media (max-width:480px) { .rw-toggle-label { display:none; } }

.kelas-filter-wrap {
  display:flex;align-items:center;flex-wrap:wrap;gap:4px;
  background:var(--surface2,#f1f5f9);border:1.5px solid var(--border);
  border-radius:12px;padding:5px 8px;width:100%;box-sizing:border-box;
}
.kelas-btn {
  display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:8px;
  font-size:12px;font-weight:600;text-decoration:none;color:var(--text2);
  transition:background .15s,color .15s,box-shadow .15s;white-space:nowrap;line-height:1.5;
}
.kelas-btn:hover { background:var(--surface,#fff);color:var(--indigo,#4F6EF7);box-shadow:0 1px 4px rgba(0,0,0,.07); }
.kelas-btn.active { background:var(--indigo,#4F6EF7);color:#fff;box-shadow:0 2px 8px rgba(79,110,247,.28); }
.kelas-btn.active .kelas-btn-count { background:rgba(255,255,255,.28);color:#fff; }
.kelas-btn-count {
  background:var(--surface,#fff);color:var(--indigo,#4F6EF7);
  border-radius:99px;font-size:10px;font-weight:700;padding:0 5px;min-width:16px;text-align:center;line-height:1.6;
}

/* Card grid */
#viewCards {
  display:none;
  grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:12px;
}
@media (max-width:640px) { #viewCards { grid-template-columns:1fr; } }

.txn-card {
  background:var(--surface,#fff);border:1.5px solid var(--border);border-radius:16px;
  overflow:hidden;display:flex;flex-direction:column;
  transition:box-shadow .2s,transform .2s;animation:txnIn .22s ease both;
}
.txn-card:hover { box-shadow:0 6px 22px rgba(0,0,0,.09);transform:translateY(-2px); }
@keyframes txnIn { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
.txn-card-bar  { height:4px;flex-shrink:0; }
.txn-card-body { padding:14px 15px;display:flex;flex-direction:column;gap:11px;flex:1; }
.txn-card-top  { display:flex;align-items:center;gap:10px; }
.txn-card-ava  {
  width:40px;height:40px;border-radius:12px;flex-shrink:0;
  display:flex;align-items:center;justify-content:center;
  font-weight:700;font-size:15px;color:#fff;overflow:hidden;
}
.txn-card-ava img { width:100%;height:100%;object-fit:cover;border-radius:12px; }
.txn-card-name   { font-size:13.5px;font-weight:700;color:var(--text);line-height:1.3; }
.txn-card-sub    { font-size:11px;color:var(--text3);margin-top:2px; }
.txn-card-amount { margin-left:auto;font-family:'DM Mono',monospace;font-weight:700;font-size:14px;color:var(--green,#059669);white-space:nowrap; }
.txn-card-hr     { border:none;border-top:1px solid var(--border);margin:0; }
.txn-card-rows   { display:flex;flex-direction:column;gap:7px; }
.txn-card-row    { display:flex;align-items:center;justify-content:space-between;font-size:12px;gap:6px; }
.txn-card-row-label { display:flex;align-items:center;gap:5px;color:var(--text3);flex-shrink:0; }
.txn-card-row-val   { color:var(--text2);text-align:right; }
.txn-metode-pill    { display:inline-flex;align-items:center;gap:5px;padding:2px 9px;border-radius:99px;font-size:11px;font-weight:600; }
.txn-num { width:22px;height:22px;border-radius:6px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;color:var(--text3);flex-shrink:0; }

/* Table avatar */
.tbl-ava {
  width:34px;height:34px;border-radius:9px;flex-shrink:0;
  display:flex;align-items:center;justify-content:center;
  font-size:13px;font-weight:700;color:#fff;overflow:hidden;
}
.tbl-ava img { width:100%;height:100%;object-fit:cover;border-radius:9px; }

.summary-bar {
  display:flex;align-items:center;justify-content:space-between;
  background:var(--indigo-light,#EEF2FF);border:1.5px solid var(--indigo-border,#C7D2FE);
  border-radius:12px;padding:11px 16px;flex-wrap:wrap;gap:8px;
}
.summary-bar-text   { display:flex;align-items:center;gap:7px;font-size:13px;color:var(--indigo,#4F6EF7);font-weight:600; }
.summary-bar-amount { font-family:'DM Mono',monospace;font-weight:700;font-size:15px;color:var(--indigo,#4F6EF7); }

.pgn-info { font-size:12.5px;color:var(--text3);white-space:nowrap; }
.pgn-info strong { color:var(--text2);font-weight:600; }
.pgn-controls { display:flex;align-items:center;gap:4px;flex-wrap:wrap; }
.pgn-btn {
  display:inline-flex;align-items:center;justify-content:center;
  min-width:32px;height:32px;padding:0 6px;
  border:1.5px solid var(--border);border-radius:8px;
  background:var(--surface,#fff);color:var(--text2);
  font-size:13px;font-weight:500;text-decoration:none;
  cursor:pointer;transition:all .15s ease;user-select:none;font-family:inherit;line-height:1;
}
.pgn-btn:hover:not(.pgn-active):not(.pgn-disabled) { background:var(--bg3);border-color:var(--border2);color:var(--text); }
.pgn-btn.pgn-active { background:var(--indigo,#4F6EF7);border-color:var(--indigo,#4F6EF7);color:#fff;box-shadow:0 2px 8px rgba(79,110,247,.3);pointer-events:none; }
.pgn-btn.pgn-disabled { opacity:.38;pointer-events:none;cursor:default; }
.pgn-dots { display:inline-flex;align-items:flex-end;justify-content:center;min-width:28px;height:32px;padding-bottom:4px;color:var(--text3);font-size:14px;letter-spacing:1px; }
.pgn-per-page { display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--text3); }
.pgn-per-page select { padding:4px 8px;font-size:12.5px;border:1.5px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text2);cursor:pointer;font-family:inherit; }

.rw-wrapper { display:flex;flex-direction:column;border:1.5px solid var(--border);border-radius:14px;overflow:hidden;background:var(--surface); }
.rw-scroll {
  overflow-y:auto;overflow-x:hidden;max-height:62vh;min-height:180px;
  scrollbar-width:thin;scrollbar-color:var(--border2,#CBD5E1) transparent;
}
.rw-scroll::-webkit-scrollbar { width:5px; }
.rw-scroll::-webkit-scrollbar-thumb { background:var(--border2,#CBD5E1);border-radius:99px; }
.rw-scroll .card { border:none!important;border-radius:0!important;box-shadow:none!important;margin-bottom:0!important; }
.rw-scroll table thead th { position:sticky;top:0;z-index:2;background:var(--surface2,#F8FAFC); }
.rw-scroll #viewCards { padding:12px; }

.rw-pgn-bar {
  flex-shrink:0;border-top:1.5px solid var(--border);background:var(--surface2,#F8FAFC);
  padding:9px 14px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;
}
@media (max-width:600px) {
  .rw-scroll { max-height:55vh; }
  .rw-pgn-bar { justify-content:center; }
  .rw-pgn-bar .pgn-info { width:100%;text-align:center; }
  .rw-pgn-bar .pgn-controls { justify-content:center; }
}
<?php for($i=0;$i<20;$i++): ?>
.txn-card:nth-child(<?= $i+1 ?>) { animation-delay:<?= $i*25 ?>ms; }
<?php endfor ?>
</style>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title" style="display:flex;align-items:center;gap:10px">
      <span style="width:32px;height:32px;background:var(--indigo-light);border-radius:9px;display:inline-flex;align-items:center;justify-content:center;color:var(--indigo);flex-shrink:0"><?= $icoList ?></span>
      Riwayat Pembayaran
    </div>
    <div class="page-header-sub">Histori semua transaksi pembayaran SPP<?php if($kelas): ?> &mdash; Kelas <?= e($kelas) ?><?= $jurusan ? ' '.$jurusan : '' ?><?php endif ?></div>
  </div>
</div>

<!-- Filter Card -->
<div class="card" style="margin-bottom:10px">
  <form method="GET" action="index.php">
    <input type="hidden" name="page"     value="riwayat">
    <input type="hidden" name="per_page" value="<?= $perPage ?>">
    <input type="hidden" name="kelas"    value="<?= e($kelas) ?>">
    <input type="hidden" name="jurusan"  value="<?= e($jurusan) ?>">
    <div class="form-row" style="margin-bottom:14px">
      <div class="form-group" style="grid-column:span 2;margin-bottom:0">
        <label>Cari Siswa</label>
        <div style="position:relative">
          <span style="position:absolute;left:11px;top:50%;transform:translateY(-50%);color:var(--text3);pointer-events:none"><?= $icoSearch ?></span>
          <input type="text" name="q" value="<?= e($search) ?>" placeholder="Nama atau NIS..." style="padding-left:34px">
        </div>
      </div>
      <div class="form-group" style="margin-bottom:0">
        <label>Bulan</label>
        <select name="bulan">
          <option value="0" <?= $bulan===0?'selected':'' ?>>Semua Bulan</option>
          <?php for($b=1;$b<=12;$b++): ?><option value="<?= $b ?>" <?= $bulan===$b?'selected':'' ?>><?= bulanIndo($b) ?></option><?php endfor ?>
        </select>
      </div>
      <div class="form-group" style="margin-bottom:0">
        <label>Tahun</label>
        <select name="tahun">
          <?php for($y=date('Y');$y>=2020;$y--): ?><option value="<?= $y ?>" <?= $tahun===$y?'selected':'' ?>><?= $y ?></option><?php endfor ?>
        </select>
      </div>
    </div>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
      <?php $metodeOpts = [''=> 'Semua','tunai'=>'Tunai','transfer'=>'Transfer','qris'=>'QRIS'];
      foreach($metodeOpts as $v => $l):
        $isAct = ($metode === $v); ?>
      <a href="<?= pageUrl(1,$bulan,$tahun,$v,$search,$perPage,$kelas,$jurusan) ?>"
         style="display:inline-flex;align-items:center;gap:5px;padding:6px 14px;border-radius:99px;font-size:12.5px;font-weight:600;text-decoration:none;transition:all .15s;
                <?= $isAct ? 'background:var(--indigo);color:#fff;box-shadow:0 2px 8px rgba(79,110,247,.3)' : 'background:var(--bg3);color:var(--text2);border:1px solid var(--border2)' ?>">
        <?php if($isAct): ?><?= $icoCheck ?><?php endif ?>
        <?= $l ?>
      </a>
      <?php endforeach ?>
      <div class="pgn-per-page" style="margin-left:auto">
        <label>Tampilkan</label>
        <select onchange="changePerPage(this.value)">
          <?php foreach($allowedPP as $pp): ?><option value="<?= $pp ?>" <?= $pp===$perPage?'selected':'' ?>><?= $pp ?></option><?php endforeach ?>
        </select>
        <span>/ hal</span>
      </div>
      <button type="submit" class="btn btn-primary" style="gap:6px"><?= $icoFilter ?> Filter</button>
    </div>
  </form>
</div>

<!-- Filter Kelas -->
<div style="display:flex;flex-direction:column;gap:6px;margin-bottom:14px">
  <div class="kelas-filter-wrap">
    <a href="<?= $baseKelasUrl ?>&kelas=&jurusan=" class="kelas-btn <?= (!$kelas&&!$jurusan)?'active':'' ?>">🏫 Semua Kelas</a>
    <?php foreach($daftarJurusan as $tkt => $jList): $jmlTkt = $kelasCounts[$tkt] ?? 0; ?>
    <a href="<?= $baseKelasUrl ?>&kelas=<?= rawurlencode($tkt) ?>&jurusan=" class="kelas-btn <?= $kelas===$tkt?'active':'' ?>">
      Kelas <?= $tkt ?>
      <?php if($jmlTkt > 0): ?><span class="kelas-btn-count"><?= number_format($jmlTkt) ?></span><?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php if($kelas && isset($daftarJurusan[$kelas])): ?>
  <div class="kelas-filter-wrap" style="background:var(--surface);border-color:var(--indigo);border-left-width:4px">
    <a href="<?= $baseKelasUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=" class="kelas-btn <?= !$jurusan?'active':'' ?>">Semua <?= e($kelas) ?></a>
    <?php foreach($daftarJurusan[$kelas] as $j): $jmlJ = $jurusanCounts[$kelas.'|'.$j] ?? 0; ?>
    <a href="<?= $baseKelasUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=<?= rawurlencode($j) ?>" class="kelas-btn <?= $jurusan===$j?'active':'' ?>">
      <?= e($kelas) ?> <?= e($j) ?>
      <?php if($jmlJ > 0): ?><span class="kelas-btn-count"><?= number_format($jmlJ) ?></span><?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php endif ?>
</div>

<!-- Summary + View Toggle -->
<?php if($totalRows > 0): ?>
<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;flex-wrap:wrap">
  <div class="summary-bar" style="flex:1;margin-bottom:0;min-width:0">
    <div class="summary-bar-text">
      <?= $icoList ?>
      <span><?= number_format($totalRows) ?> transaksi ditemukan</span>
      <?php if($kelas): ?><span style="font-weight:400;opacity:.8">&mdash; Kelas <?= e($kelas) ?><?= $jurusan ? ' '.$jurusan : '' ?></span><?php endif ?>
      <?php if($totalPages > 1): ?><span style="font-weight:400;opacity:.7">— halaman <?= $currentPage ?> dari <?= $totalPages ?></span><?php endif ?>
    </div>
    <div class="summary-bar-amount"><?= rupiah($totalBayar) ?></div>
  </div>
  <div class="rw-view-toggle">
    <button id="btnViewTable" class="active" onclick="switchView('table')" title="Tabel"><?= $icoList ?><span class="rw-toggle-label">Tabel</span></button>
    <button id="btnViewCard" onclick="switchView('card')" title="Kartu"><?= $icoGrid ?><span class="rw-toggle-label">Kartu</span></button>
  </div>
</div>
<?php endif ?>

<!-- Wrapper -->
<div class="rw-wrapper">
<div class="rw-scroll" id="rwScroll">

<!-- TABLE VIEW -->
<div id="viewTable">
  <div class="card" style="padding:0;overflow:hidden">
    <div style="overflow-x:auto">
    <table>
      <thead>
        <tr><th>#</th><th>Siswa</th><th>Periode</th><th>Jumlah</th><th>Metode</th><th>Petugas</th><th>Tanggal</th></tr>
      </thead>
      <tbody>
      <?php if(empty($rows)): ?>
        <tr><td colspan="7">
          <div class="empty-state">
            <div class="empty-state-icon"><?= $icoList ?></div>
            <h4>Belum ada riwayat</h4>
            <p>Tidak ada data pembayaran untuk filter yang dipilih</p>
          </div>
        </td></tr>
      <?php else: foreach($rows as $i => $r):
        $rowNum  = $offset + $i + 1;
        $col     = $avatarColors[$i % count($avatarColors)];
        $mKey    = strtolower($r['metode_bayar']);
        $mConf   = $metodeConfig[$mKey] ?? ['label'=>ucfirst($mKey),'pill'=>'pill-purple','icon'=>$icoMoney,'bar'=>'#94A3B8','bg'=>'#F1F5F9','color'=>'#475569'];
        $fotoF   = $r['foto_siswa'] ?? '';
        $hasFoto = $fotoF && file_exists($fotoSiswaAbs.$fotoF);
      ?>
        <tr>
          <td><div style="width:26px;height:26px;border-radius:7px;background:var(--bg3);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:var(--text3)"><?= $rowNum ?></div></td>
          <td>
            <div style="display:flex;align-items:center;gap:9px">
              <?php if($hasFoto): ?>
              <div class="tbl-ava">
                <img src="<?= e($fotoSiswaUrl.$fotoF) ?>" alt=""
                     onerror="this.style.display='none';this.parentElement.style.background='<?= $col ?>';this.parentElement.textContent='<?= mb_strtoupper(mb_substr($r['nama'],0,1)) ?>'">
              </div>
              <?php else: ?>
              <div class="tbl-ava" style="background:<?= $col ?>"><?= mb_strtoupper(mb_substr($r['nama'],0,1)) ?></div>
              <?php endif ?>
              <div>
                <div style="font-weight:600;font-size:13.5px"><?= e($r['nama']) ?></div>
                <div style="font-size:11px;color:var(--text3)">
                  <?= e($r['nis']) ?> &middot;
                  <span class="pill pill-purple" style="font-size:10px;padding:1px 6px"><?= e($r['kelas']) ?></span>
                  <?php if(!empty($r['jurusan'])): ?><span class="pill pill-blue" style="font-size:10px;padding:1px 6px"><?= e($r['jurusan']) ?></span><?php endif ?>
                </div>
              </div>
            </div>
          </td>
          <td><div style="display:flex;align-items:center;gap:5px;color:var(--text2);font-size:13px"><?= $icoCalendar ?> <?= bulanIndo((int)$r['t_bulan']).' '.$r['t_tahun'] ?></div></td>
          <td><span style="font-family:'DM Mono',monospace;font-weight:500;color:var(--green);font-size:14px;letter-spacing:-.5px"><?= rupiah((int)$r['jumlah_bayar']) ?></span></td>
          <td><span class="pill <?= $mConf['pill'] ?>" style="display:inline-flex;align-items:center;gap:5px"><?= $mConf['icon'] ?><?= $mConf['label'] ?></span></td>
          <td><div style="display:flex;align-items:center;gap:5px;font-size:12.5px;color:var(--text2)"><?= $icoUser ?><?= e($r['admin_nama']) ?></div></td>
          <td>
            <div style="font-size:12.5px;color:var(--text2);font-weight:500"><?= date('d/m/Y', strtotime($r['tgl_bayar'])) ?></div>
            <div style="font-size:11px;color:var(--text3)"><?= date('H:i', strtotime($r['tgl_bayar'])) ?> WIB</div>
          </td>
        </tr>
      <?php endforeach; endif ?>
      </tbody>
    </table>
    </div>
  </div>
</div>

<!-- CARD VIEW -->
<div id="viewCards" style="display:none;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:12px">
  <?php if(empty($rows)): ?>
  <div class="card" style="text-align:center;padding:40px;grid-column:1/-1">
    <div style="font-size:40px;margin-bottom:10px;opacity:.3"><?= $icoList ?></div>
    <p style="color:var(--text3)">Tidak ada data pembayaran</p>
  </div>
  <?php else: foreach($rows as $i => $r):
    $rowNum  = $offset + $i + 1;
    $col     = $avatarColors[$i % count($avatarColors)];
    $mKey    = strtolower($r['metode_bayar']);
    $mConf   = $metodeConfig[$mKey] ?? ['label'=>ucfirst($mKey),'pill'=>'pill-purple','icon'=>$icoMoney,'bar'=>'#94A3B8','bg'=>'#F1F5F9','color'=>'#475569'];
    $fotoF   = $r['foto_siswa'] ?? '';
    $hasFoto = $fotoF && file_exists($fotoSiswaAbs.$fotoF);
  ?>
  <div class="txn-card">
    <div class="txn-card-bar" style="background:<?= $mConf['bar'] ?>"></div>
    <div class="txn-card-body">
      <div class="txn-card-top">
        <!-- Avatar dengan foto -->
        <?php if($hasFoto): ?>
        <div class="txn-card-ava">
          <img src="<?= e($fotoSiswaUrl.$fotoF) ?>" alt="<?= e($r['nama']) ?>"
               onerror="this.parentElement.style.background='<?= $col ?>';this.parentElement.innerHTML='<?= mb_strtoupper(mb_substr($r['nama'],0,1)) ?>'">
        </div>
        <?php else: ?>
        <div class="txn-card-ava" style="background:<?= $col ?>"><?= mb_strtoupper(mb_substr($r['nama'],0,1)) ?></div>
        <?php endif ?>
        <div style="flex:1;min-width:0">
          <div class="txn-card-name" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= e($r['nama']) ?></div>
          <div class="txn-card-sub">
            <?= e($r['nis']) ?> ·
            <span style="background:var(--surface2);border-radius:4px;padding:0 4px;font-size:10px;font-weight:600"><?= e($r['kelas']) ?></span>
            <?php if(!empty($r['jurusan'])): ?><span style="background:var(--surface2);border-radius:4px;padding:0 4px;font-size:10px;font-weight:600"><?= e($r['jurusan']) ?></span><?php endif ?>
          </div>
        </div>
        <div class="txn-card-amount">+<?= rupiah((int)$r['jumlah_bayar']) ?></div>
      </div>
      <hr class="txn-card-hr">
      <div class="txn-card-rows">
        <div class="txn-card-row">
          <span class="txn-card-row-label"><?= $icoCalendar ?> Periode</span>
          <span class="txn-card-row-val"><?= bulanIndo((int)$r['t_bulan']).' '.$r['t_tahun'] ?></span>
        </div>
        <div class="txn-card-row">
          <span class="txn-card-row-label"><?= $icoMoney ?> Metode</span>
          <span class="txn-metode-pill" style="background:<?= $mConf['bg'] ?>;color:<?= $mConf['color'] ?>"><?= $mConf['label'] ?></span>
        </div>
        <div class="txn-card-row">
          <span class="txn-card-row-label"><?= $icoUser ?> Petugas</span>
          <span class="txn-card-row-val" style="font-size:12px"><?= e($r['admin_nama']) ?></span>
        </div>
        <div class="txn-card-row">
          <span class="txn-card-row-label">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            Waktu
          </span>
          <span class="txn-card-row-val">
            <?= date('d/m/Y', strtotime($r['tgl_bayar'])) ?>
            <span style="color:var(--text3);margin-left:3px"><?= date('H:i', strtotime($r['tgl_bayar'])) ?></span>
          </span>
        </div>
      </div>
    </div>
    <div style="padding:7px 15px;background:var(--surface2);border-top:1px solid var(--border);display:flex;align-items:center;gap:6px">
      <div class="txn-num"><?= $rowNum ?></div>
      <span style="font-size:11px;color:var(--text3)">Transaksi #<?= $r['id'] ?></span>
    </div>
  </div>
  <?php endforeach; endif ?>
</div>

</div><!-- /rw-scroll -->

<!-- Pagination -->
<?php if($totalPages > 1 || $totalRows > 10):
  $from = $totalRows > 0 ? $offset + 1 : 0;
  $to   = min($offset + $perPage, $totalRows);
?>
<div class="rw-pgn-bar">
  <div class="pgn-info">Menampilkan <strong><?= number_format($from) ?>–<?= number_format($to) ?></strong> dari <strong><?= number_format($totalRows) ?></strong> transaksi</div>
  <?php if($totalPages > 1): ?>
  <div class="pgn-controls">
    <a href="<?= pageUrl(1,$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn <?= $currentPage<=1?'pgn-disabled':'' ?>"><?= $icoChevsL ?></a>
    <a href="<?= pageUrl(max(1,$currentPage-1),$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn <?= $currentPage<=1?'pgn-disabled':'' ?>"><?= $icoChevL ?></a>
    <?php
    $pages     = pageWindow($currentPage, $totalPages);
    $showFirst = ($pages[0] > 1);
    $showLast  = ($pages[count($pages)-1] < $totalPages);
    if($showFirst): ?>
      <a href="<?= pageUrl(1,$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn">1</a>
      <?php if($pages[0] > 2): ?><span class="pgn-dots">···</span><?php endif ?>
    <?php endif ?>
    <?php foreach($pages as $pg): ?>
      <a href="<?= pageUrl($pg,$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn <?= $pg===$currentPage?'pgn-active':'' ?>"><?= $pg ?></a>
    <?php endforeach ?>
    <?php if($showLast): ?>
      <?php if($pages[count($pages)-1] < $totalPages-1): ?><span class="pgn-dots">···</span><?php endif ?>
      <a href="<?= pageUrl($totalPages,$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn"><?= $totalPages ?></a>
    <?php endif ?>
    <a href="<?= pageUrl(min($totalPages,$currentPage+1),$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn <?= $currentPage>=$totalPages?'pgn-disabled':'' ?>"><?= $icoChevR ?></a>
    <a href="<?= pageUrl($totalPages,$bulan,$tahun,$metode,$search,$perPage,$kelas,$jurusan) ?>" class="pgn-btn <?= $currentPage>=$totalPages?'pgn-disabled':'' ?>"><?= $icoChevsR ?></a>
  </div>
  <?php endif ?>
</div>
<?php endif ?>

</div><!-- /rw-wrapper -->

<script>
(function(){
  var STORAGE_KEY='riwayat_view_mode';
  function switchView(mode){
    var isCard=mode==='card';
    document.getElementById('viewTable').style.display=isCard?'none':'block';
    document.getElementById('viewCards').style.display=isCard?'grid':'none';
    document.getElementById('btnViewTable').classList.toggle('active',!isCard);
    document.getElementById('btnViewCard').classList.toggle('active',isCard);
    var sc=document.getElementById('rwScroll'); if(sc) sc.scrollTop=0;
    try{localStorage.setItem(STORAGE_KEY,mode);}catch(e){}
  }
  var saved=null; try{saved=localStorage.getItem(STORAGE_KEY);}catch(e){}
  if(!saved) saved=window.innerWidth<=640?'card':'table';
  switchView(saved);
  window.switchView=switchView;
  window.changePerPage=function(val){
    var url=new URL(window.location.href);
    url.searchParams.set('per_page',val);url.searchParams.set('p','1');
    window.location.href=url.toString();
  };
})();
</script>

<?php require_once 'layout/footer.php'; ?>