<?php
/**
 * SisPen Snesaka - Cetak Rapor PTS (Per Tengah Semester)
 * Format: Per siswa, 1 halaman per siswa, semua mapel
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle  = 'Cetak Rapor PTS';
$activeMenu = 'cetak-rapor-pts';
$pengaturan = getPengaturan();
$formula    = getFormula();
$jsSumatif  = $formula['jumlah_sumatif'];
$isAdmin    = $_SESSION['role'] === 'admin';
$currentUser = getCurrentUser();
$guruId     = $currentUser['guru_id'] ?? null;

// ── Akses hanya untuk Admin dan Wali Kelas ───────────────────
if (!$isAdmin) {
    $cekWali = $guruId
        ? db_fetch("SELECT id FROM kelas WHERE wali_kelas_id=? LIMIT 1", [$guruId])
        : null;
    if (empty($cekWali)) {
        setFlash('danger', 'Akses ditolak. Halaman ini hanya untuk Admin dan Wali Kelas.');
        header('Location: ' . BASE_URL . '/guru.php');
        exit;
    }
}

$ta  = $pengaturan['tahun_ajaran_aktif'] ?? '2024/2025';
$sem = $pengaturan['semester_aktif'] ?? '1';

// ── Tanggal & tempat cetak ───────────────────────────────────
$namaBulan  = array(1=>'Januari',2=>'Februari',3=>'Maret',4=>'April',5=>'Mei',6=>'Juni',
                    7=>'Juli',8=>'Agustus',9=>'September',10=>'Oktober',11=>'November',12=>'Desember');
$kecamatan  = trim($pengaturan['kecamatan'] ?? '');

$tglCetakRaw = $_GET['tgl_cetak'] ?? '';
if ($tglCetakRaw && preg_match('/^\d{4}-\d{2}-\d{2}$/', $tglCetakRaw)) {
    $tglObj = date_create($tglCetakRaw);
    $tglHariIni = intval(date_format($tglObj,'j')) . ' ' . $namaBulan[intval(date_format($tglObj,'n'))] . ' ' . date_format($tglObj,'Y');
    $tglCetak = $tglCetakRaw;
} else {
    $tglHariIni = intval(date('j')) . ' ' . $namaBulan[intval(date('n'))] . ' ' . date('Y');
    $tglCetak   = date('Y-m-d');
}
$tempatCetak = trim($_GET['tempat_cetak'] ?? '');
if ($tempatCetak === '') $tempatCetak = $kecamatan !== '' ? $kecamatan : 'Sekaran';
$tempatTgl = $tempatCetak . ', ' . $tglHariIni;

// ── Filter & data ────────────────────────────────────────────
$kelasId  = intval($_GET['kelas_id'] ?? 0);
$siswaId  = intval($_GET['siswa_id'] ?? 0);
$doCetak  = isset($_GET['cetak']);

if ($isAdmin) {
    $kelasList = db_fetchAll(
        "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
        [$ta, $sem]
    );
} else {
    $kelasList = db_fetchAll(
        "SELECT DISTINCT k.* FROM pengampu p
         JOIN kelas k ON k.id=p.kelas_id
         WHERE p.guru_id=? AND p.tahun_ajaran=? AND p.semester=?
         ORDER BY k.tingkat, k.nama_kelas",
        [$guruId, $ta, $sem]
    );
}

$siswaList     = [];
$selectedKelas = null;
$selectedSiswa = null;

if ($kelasId) {
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);
    $siswaList = db_fetchAll(
        "SELECT * FROM siswa WHERE kelas_id=? AND status='aktif' ORDER BY nama",
        [$kelasId]
    );
}

// ── Ambil data rapor satu siswa ──────────────────────────────
$nilaiList  = [];
$absensi    = null;
$ekstraList = [];
$waliKelas  = null;

if ($kelasId && $siswaId) {
    $selectedSiswa = db_fetch("SELECT * FROM siswa WHERE id=?", [$siswaId]);

    // Wali kelas
    $waliKelas = db_fetch(
        "SELECT g.nama, g.nip FROM kelas k
         LEFT JOIN guru g ON g.id=k.wali_kelas_id
         WHERE k.id=?", [$kelasId]
    );

    // Nilai semua mapel
    $nilaiList = db_fetchAll(
        "SELECT m.nama_mapel, m.kode_mapel, m.kelompok, m.urutan,
                n.sumatif_1, n.sumatif_2, n.sumatif_3, n.sumatif_4, n.sumatif_5,
                n.rata_sumatif, n.sts, n.nilai_akhir, n.catatan,
                g.nama as nama_guru
         FROM mata_pelajaran m
         LEFT JOIN nilai n ON n.mapel_id = m.id
                          AND n.siswa_id = ?
                          AND n.kelas_id = ?
                          AND n.tahun_ajaran = ?
                          AND n.semester = ?
         LEFT JOIN guru g ON g.id = n.guru_id
         WHERE m.status = 'aktif'
         ORDER BY m.kelompok, m.urutan, m.nama_mapel",
        [$siswaId, $kelasId, $ta, $sem]
    );

    // Absensi
    $absensi = db_fetch(
        "SELECT COALESCE(SUM(sakit),0) as sakit,
                COALESCE(SUM(izin),0) as izin,
                COALESCE(SUM(tanpa_keterangan),0) as alpha
         FROM absensi WHERE kelas_id=? AND tahun_ajaran=? AND semester=?",
        [$kelasId, $ta, $sem]
    );

    // Ekskul
    $ekstraList = db_fetchAll(
        "SELECT e.nama, ne.predikat, ne.keterangan
         FROM nilai_ekstra ne JOIN ekstrakurikuler e ON e.id=ne.ekstra_id
         WHERE ne.siswa_id=? AND ne.tahun_ajaran=? AND ne.semester=?
         ORDER BY e.nama",
        [$siswaId, $ta, $sem]
    );
}

// ── Mode Cetak Semua Siswa ───────────────────────────────────
$cetakSemua = isset($_GET['cetak_semua']) && $kelasId;

// Jika mode cetak — output langsung tanpa layout
if ($doCetak && $siswaId && $selectedSiswa) {
    // render print-only
    include '../../templates/rapor_pts_print.php';
    exit;
}

include '../../templates/header.php';
?>

<style>
/* Preview card rapor */
.rapor-preview {
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 24px 28px;
    max-width: 760px;
    margin: 0 auto;
    font-family: Arial, sans-serif;
    font-size: 10.5pt;
    line-height: 1.4;
}
.rapor-header-sekolah {
    display: flex;
    align-items: center;
    gap: 16px;
    border-bottom: 3px double #000;
    padding-bottom: 10px;
    margin-bottom: 12px;
}
.rapor-logo {
    width: 65px; height: 65px;
    object-fit: contain; flex-shrink: 0;
}
.rapor-logo-placeholder {
    width: 65px; height: 65px;
    border: 2px solid #999;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 24px; color: #999; flex-shrink: 0;
}
.rapor-sekolah-info { flex: 1; text-align: center; }
.rapor-sekolah-info .kop-baris1 { font-size: 11pt; font-weight: 600; margin-bottom: 1px; }
.rapor-sekolah-info .kop-baris2 { font-size: 10pt; font-weight: 600; margin-bottom: 1px; }
.rapor-sekolah-info .kop-baris3 { font-size: 14pt; font-weight: 900; text-transform: uppercase; margin-bottom: 2px; }
.rapor-sekolah-info .kop-baris4 { font-size: 9pt; color: #333; margin: 1px 0; }
.rapor-sekolah-info .kop-baris5 { font-size: 9pt; color: #333; margin: 1px 0; }
.rapor-judul {
    text-align: center;
    font-size: 12pt;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 1px;
    margin: 10px 0 14px;
    border: 2px solid #000;
    padding: 5px;
    background: #bfbfbf;
}
.rapor-identitas {
    width: 100%;
    border-collapse: collapse;
    font-size: 10pt;
    margin-bottom: 14px;
}
.rapor-identitas td { padding: 3px 8px; }
.rapor-identitas td:first-child { width: 130px; font-weight: 600; }
.rapor-identitas td:nth-child(2) { width: 10px; }

/* Tabel nilai */
.rapor-tbl {
    width: 100%;
    border-collapse: collapse;
    font-size: 9.5pt;
    margin-bottom: 14px;
}
.rapor-tbl th, .rapor-tbl td {
    border: 1px solid #000;
    padding: 4px 6px;
    text-align: center;
    vertical-align: middle;
}
.rapor-tbl th { background: #bfbfbf; color: #000; font-size: 9pt; }
.rapor-tbl td.mapel { text-align: left; font-weight: 600; padding-left: 8px; }
.rapor-tbl td.kosong { color: #ccc; }
.rapor-tbl tr:nth-child(even) td { background: #f9f9f9; }
.rapor-tbl td.nilai-akhir { font-weight: bold; font-size: 11pt; }
.rapor-tbl td.predikat { font-weight: bold; }

/* Absensi & Ekskul */
.rapor-section-title {
    font-weight: bold;
    font-size: 10pt;
    border-bottom: 1px solid #000;
    margin: 12px 0 6px;
    padding-bottom: 3px;
    text-transform: uppercase;
    letter-spacing: .5px;
}
.abs-tbl {
    width: 100%;
    border-collapse: collapse;
    font-size: 9.5pt;
    margin-bottom: 12px;
}
.abs-tbl td, .abs-tbl th { border: 1px solid #000; padding: 4px 8px; }
.abs-tbl th { background: #f0f0f0; font-weight: bold; }
.ekstra-tbl { width: 100%; border-collapse: collapse; font-size: 9.5pt; margin-bottom: 12px; }
.ekstra-tbl td, .ekstra-tbl th { border: 1px solid #000; padding: 4px 8px; }
.ekstra-tbl th { background: #f0f0f0; font-weight: bold; }

/* TTD */
.ttd-wrap {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    font-size: 9.5pt;
}
.ttd-col { text-align: center; width: 44%; }
.ttd-col .ttd-nama { font-weight: bold; text-transform: uppercase; margin-top: 44px; }
.ttd-col .ttd-nip  { font-size: 9pt; }

@media print {
    .no-print { display: none !important; }
    body { background: #fff !important; }
    .sidebar, .topbar, .main-content > .page-content > .card.no-print { display: none; }
    .rapor-preview { border: none; padding: 0; }
    .page-break { page-break-after: always; }
}
</style>

<!-- Layout dua kolom -->
<div style="display:grid;grid-template-columns:260px 1fr;gap:20px;align-items:start;">

  <!-- ── Panel kiri: Filter ── -->
  <div class="card no-print" style="position:sticky;top:80px;">
    <div class="card-header" style="background:linear-gradient(135deg,#0f2544,#1e4d8c);border-radius:var(--radius) var(--radius) 0 0;padding:14px 20px;">
      <span class="card-title" style="color:#fff;">
        <i class="fas fa-filter" style="margin-right:8px;"></i>Filter
      </span>
    </div>
    <div class="card-body">
      <form method="GET">
        <!-- Kelas -->
        <div class="form-group">
          <label class="form-label">Kelas</label>
          <select name="kelas_id" class="form-control" onchange="this.form.submit()">
            <option value="">-- Pilih Kelas --</option>
            <?php foreach ($kelasList as $k): ?>
            <option value="<?= $k['id'] ?>" <?= $kelasId==$k['id']?'selected':'' ?>>
              <?= htmlspecialchars($k['nama_kelas']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>

        <?php if ($kelasId): ?>
        <!-- Siswa -->
        <div class="form-group">
          <label class="form-label">Siswa</label>
          <select name="siswa_id" class="form-control" onchange="this.form.submit()">
            <option value="">-- Pilih Siswa --</option>
            <?php foreach ($siswaList as $s): ?>
            <option value="<?= $s['id'] ?>" <?= $siswaId==$s['id']?'selected':'' ?>>
              <?= htmlspecialchars($s['nama']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
        <?php endif; ?>

        <!-- Atur Kop -->
        <div style="margin-top:14px;border-top:1px solid var(--border);padding-top:14px;">
          <div style="font-size:12px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;">
            <i class="fas fa-heading" style="margin-right:5px;color:var(--primary);"></i>Atur Kop Surat
          </div>
          <?php
            $kop1 = $_GET['kop1'] ?? ($pengaturan['kop_baris1'] ?? 'PEMERINTAH KABUPATEN LAMONGAN');
            $kop2 = $_GET['kop2'] ?? ($pengaturan['kop_baris2'] ?? 'DINAS PENDIDIKAN');
            $kop3 = $_GET['kop3'] ?? ($pengaturan['nama_sekolah'] ?? '');
            $kop4 = $_GET['kop4'] ?? ($pengaturan['alamat'] ?? '');
            $kop5 = $_GET['kop5'] ?? ($pengaturan['telepon'] ?? '');
          ?>
          <div class="form-group">
            <label class="form-label" style="font-size:11px;">Baris 1</label>
            <input type="text" name="kop1" class="form-control" style="font-size:12px;"
                   value="<?= htmlspecialchars($kop1) ?>" placeholder="Misal: Pemerintah Kab. ...">
          </div>
          <div class="form-group">
            <label class="form-label" style="font-size:11px;">Baris 2</label>
            <input type="text" name="kop2" class="form-control" style="font-size:12px;"
                   value="<?= htmlspecialchars($kop2) ?>" placeholder="Misal: Dinas Pendidikan">
          </div>
          <div class="form-group">
            <label class="form-label" style="font-size:11px;">Baris 3 (Nama Sekolah)</label>
            <input type="text" name="kop3" class="form-control" style="font-size:12px;font-weight:700;"
                   value="<?= htmlspecialchars($kop3) ?>" placeholder="Nama Sekolah">
          </div>
          <div class="form-group">
            <label class="form-label" style="font-size:11px;">Baris 4 (Alamat)</label>
            <input type="text" name="kop4" class="form-control" style="font-size:12px;"
                   value="<?= htmlspecialchars($kop4) ?>" placeholder="Alamat Sekolah">
          </div>
          <div class="form-group">
            <label class="form-label" style="font-size:11px;">Baris 5</label>
            <input type="text" name="kop5" class="form-control" style="font-size:12px;"
                   value="<?= htmlspecialchars($kop5) ?>" placeholder="Misal: Telp/Email/Website">
          </div>
        </div>

        <!-- Tempat & Tanggal -->
        <div style="margin-top:14px;border-top:1px solid var(--border);padding-top:14px;">
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-map-marker-alt" style="color:var(--primary);margin-right:5px;"></i>
              Tempat
            </label>
            <input type="text" name="tempat_cetak" class="form-control"
                   value="<?= htmlspecialchars($tempatCetak) ?>"
                   placeholder="Contoh: Kalitengah">
          </div>
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-calendar-alt" style="color:var(--primary);margin-right:5px;"></i>
              Tanggal Cetak
            </label>
            <input type="date" name="tgl_cetak" class="form-control"
                   value="<?= htmlspecialchars($tglCetak) ?>">
            <small style="font-size:11px;color:var(--text-muted);margin-top:4px;display:block;">
              <i class="fas fa-info-circle"></i> Tampil di TTD hasil cetak
            </small>
          </div>
          <button type="submit" class="btn btn-sm"
                  style="width:100%;background:linear-gradient(135deg,#1e4d8c,#2563eb);color:#fff;border:none;font-weight:700;">
            <i class="fas fa-sync-alt"></i> Terapkan
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- ── Panel kanan: Preview ── -->
  <div class="card">
    <div class="card-header" style="background:linear-gradient(135deg,#064e3b,#047857);border-radius:var(--radius) var(--radius) 0 0;padding:14px 20px;">
      <span class="card-title" style="color:#fff;">
        <i class="fas fa-eye" style="margin-right:8px;opacity:.9;"></i>
        Preview Rapor PTS
      </span>
      <?php if ($kelasId && $siswaId && $selectedSiswa): ?>
      <div style="display:flex;gap:8px;">
        <!-- Cetak 1 siswa -->
        <a href="?kelas_id=<?= $kelasId ?>&siswa_id=<?= $siswaId ?>&cetak=1&tgl_cetak=<?= urlencode($tglCetak) ?>&tempat_cetak=<?= urlencode($tempatCetak) ?>&kop1=<?= urlencode($kop1??'') ?>&kop2=<?= urlencode($kop2??'') ?>&kop3=<?= urlencode($kop3??'') ?>&kop4=<?= urlencode($kop4??'') ?>&kop5=<?= urlencode($kop5??'') ?>"
           target="_blank" class="btn btn-sm"
           style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4);font-weight:700;">
          <i class="fas fa-print"></i> Cetak Siswa Ini
        </a>
        <!-- Cetak semua siswa kelas -->
        <a href="?kelas_id=<?= $kelasId ?>&cetak_semua=1&tgl_cetak=<?= urlencode($tglCetak) ?>&tempat_cetak=<?= urlencode($tempatCetak) ?>&kop1=<?= urlencode($kop1??'') ?>&kop2=<?= urlencode($kop2??'') ?>&kop3=<?= urlencode($kop3??'') ?>&kop4=<?= urlencode($kop4??'') ?>&kop5=<?= urlencode($kop5??'') ?>"
           target="_blank" class="btn btn-sm"
           style="background:linear-gradient(135deg,#b45309,#f59e0b);color:#fff;border:none;font-weight:700;">
          <i class="fas fa-users"></i> Cetak Semua (<?= count($siswaList) ?> siswa)
        </a>
      </div>
      <?php endif; ?>
    </div>

    <div style="padding:24px;background:#f8f9fa;">
      <?php if (!$kelasId): ?>
      <div style="text-align:center;padding:48px;color:var(--text-muted);">
        <i class="fas fa-file-alt" style="font-size:48px;opacity:.2;display:block;margin-bottom:14px;"></i>
        <p>Pilih kelas dan siswa untuk preview rapor PTS</p>
      </div>

      <?php elseif (!$siswaId): ?>
      <div style="text-align:center;padding:48px;color:var(--text-muted);">
        <i class="fas fa-user-graduate" style="font-size:48px;opacity:.2;display:block;margin-bottom:14px;"></i>
        <p>Pilih siswa dari dropdown di kiri</p>
      </div>

      <?php else: ?>
      <!-- ══ PREVIEW RAPOR ══ -->
      <?php
        $kelompokMap = [];
        foreach ($nilaiList as $n) {
            $kel = $n['kelompok'] ?: 'A';
            $kelompokMap[$kel][] = $n;
        }
        ksort($kelompokMap);
        $noUrut = 1;
      ?>
      <div class="rapor-preview">

        <!-- Header sekolah dengan kop kustom -->
        <?php
          $kop1 = $_GET['kop1'] ?? ($pengaturan['kop_baris1'] ?? 'PEMERINTAH KABUPATEN LAMONGAN');
          $kop2 = $_GET['kop2'] ?? ($pengaturan['kop_baris2'] ?? 'DINAS PENDIDIKAN');
          $kop3 = $_GET['kop3'] ?? ($pengaturan['nama_sekolah'] ?? '');
          $kop4 = $_GET['kop4'] ?? ($pengaturan['alamat'] ?? '');
          $kop5 = $_GET['kop5'] ?? ($pengaturan['telepon'] ?? '');
        ?>
        <div class="rapor-header-sekolah">
          <?php
            // Coba beberapa kemungkinan path logo
            $logoFile = $pengaturan['logo_sekolah'] ?? '';
            $logoSrc  = '';
            if ($logoFile) {
                // Bersihkan slash di depan jika ada
                $logoFile = ltrim($logoFile, '/');
                $logoSrc  = BASE_URL . '/' . $logoFile;
            }
          ?>
          <?php if ($logoSrc): ?>
            <img src="<?= htmlspecialchars($logoSrc) ?>" class="rapor-logo" alt="Logo"
                 onerror="this.style.display='none';this.nextElementSibling.style.display='flex';">
            <div class="rapor-logo-placeholder" style="display:none;"><i class="fas fa-school"></i></div>
          <?php else: ?>
            <div class="rapor-logo-placeholder"><i class="fas fa-school"></i></div>
          <?php endif; ?>
          <div class="rapor-sekolah-info">
            <?php if ($kop1): ?><div class="kop-baris1"><?= htmlspecialchars($kop1) ?></div><?php endif; ?>
            <?php if ($kop2): ?><div class="kop-baris2"><?= htmlspecialchars($kop2) ?></div><?php endif; ?>
            <?php if ($kop3): ?><div class="kop-baris3"><?= htmlspecialchars($kop3) ?></div><?php endif; ?>
            <?php if ($kop4): ?><div class="kop-baris4"><?= htmlspecialchars($kop4) ?></div><?php endif; ?>
            <?php if ($kop5): ?><div class="kop-baris5"><?= htmlspecialchars($kop5) ?></div><?php endif; ?>
          </div>
        </div>

        <!-- Judul -->
        <div class="rapor-judul">
          Laporan Penilaian Tengah Semester (PTS)
        </div>

        <!-- Identitas siswa -->
        <table class="rapor-identitas">
          <tr>
            <td>Nama Siswa</td><td>:</td>
            <td><strong><?= htmlspecialchars($selectedSiswa['nama']) ?></strong></td>
            <td width="30"></td>
            <td width="130">Kelas</td><td width="10">:</td>
            <td><strong><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></strong></td>
          </tr>
          <tr>
            <td>NIS</td><td>:</td>
            <td><?= htmlspecialchars($selectedSiswa['nis']) ?></td>
            <td></td>
            <td>Tahun Pelajaran</td><td>:</td>
            <td><?= $ta ?></td>
          </tr>
          <tr>
            <td>NISN</td><td>:</td>
            <td><?= htmlspecialchars($selectedSiswa['nisn'] ?? '-') ?></td>
            <td></td>
            <td>Semester</td><td>:</td>
            <td><?= $sem == '1' ? 'Ganjil' : 'Genap' ?></td>
          </tr>
          <?php if ($waliKelas): ?>
          <tr>
            <td>Wali Kelas</td><td>:</td>
            <td colspan="5"><?= htmlspecialchars($waliKelas['nama']) ?></td>
          </tr>
          <?php endif; ?>
        </table>

        <!-- Tabel Nilai -->
        <table class="rapor-tbl">
          <thead>
            <tr>
              <th rowspan="2" style="width:42px;">No</th>
              <th rowspan="2" style="min-width:160px;">Mata Pelajaran</th>
              <?php for ($i=1; $i<=$jsSumatif; $i++): ?>
              <th rowspan="2" style="width:40px;">S<?= $i ?></th>
              <?php endfor; ?>
              <th rowspan="2" style="width:50px;">Rata-rata Sumatif</th>
              <?php if ($formula['sts'] > 0): ?>
              <th rowspan="2" style="width:40px;">STS</th>
              <?php endif; ?>

            </tr>
            <tr></tr>
          </thead>
          <tbody>
            <?php foreach ($kelompokMap as $kode => $mapels): ?>
            <?php foreach ($mapels as $n): ?>
            <?php
              $na  = $n['nilai_akhir'] !== null ? round(floatval($n['nilai_akhir'])) : null;
              $rat = $n['rata_sumatif'] !== null ? number_format(floatval($n['rata_sumatif']),0) : null;
              $sts = $n['sts'] !== null ? round(floatval($n['sts'])) : null;
            ?>
            <tr>
              <td><?= $noUrut++ ?></td>
              <td class="mapel"><?= htmlspecialchars($n['nama_mapel']) ?></td>
              <?php for ($i=1; $i<=$jsSumatif; $i++):
                $col = 'sumatif_'.$i;
                $val = $n[$col] !== null ? round(floatval($n[$col])) : null;
              ?>
              <td class="<?= $val===null?'kosong':'' ?>"><?= $val !== null ? $val : '-' ?></td>
              <?php endfor; ?>
              <td class="<?= $rat===null?'kosong':'' ?>" style="font-weight:600;"><?= $rat !== null ? $rat : '-' ?></td>
              <?php if ($formula['sts'] > 0): ?>
              <td class="<?= $sts===null?'kosong':'' ?>"><?= $sts !== null ? $sts : '-' ?></td>
              <?php endif; ?>

            </tr>
            <?php endforeach; ?>
            <?php endforeach; ?>
          </tbody>
        </table>
        <div style="font-size:9pt;color:#555;margin-top:4px;margin-bottom:12px;font-style:italic;">
          <strong>Keterangan:</strong>
          S = Sumatif &nbsp;&bull;&nbsp;
          STS = Sumatif Tengah Semester
        </div>

        <!-- Absensi -->
        <div class="rapor-section-title"><i class="fas fa-calendar-check"></i> Ketidakhadiran</div>
        <table class="abs-tbl">
          <thead>
            <tr>
              <th>Sakit</th><th>Izin</th><th>Tanpa Keterangan</th><th>Jumlah</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style="text-align:center;"><?= intval($absensi['sakit'] ?? 0) ?> hari</td>
              <td style="text-align:center;"><?= intval($absensi['izin']  ?? 0) ?> hari</td>
              <td style="text-align:center;"><?= intval($absensi['alpha'] ?? 0) ?> hari</td>
              <td style="text-align:center;font-weight:bold;"><?= intval($absensi['sakit']??0)+intval($absensi['izin']??0)+intval($absensi['alpha']??0) ?> hari</td>
            </tr>
          </tbody>
        </table>

        <!-- Ekstrakurikuler -->
        <?php if (!empty($ekstraList)): ?>
        <div class="rapor-section-title"><i class="fas fa-trophy"></i> Ekstrakurikuler</div>
        <table class="ekstra-tbl">
          <thead>
            <tr><th style="text-align:left;">Kegiatan</th><th style="width:80px;">Predikat</th><th style="text-align:left;">Keterangan</th></tr>
          </thead>
          <tbody>
            <?php foreach ($ekstraList as $e): ?>
            <tr>
              <td><?= htmlspecialchars($e['nama']) ?></td>
              <td style="text-align:center;font-weight:bold;"><?= htmlspecialchars($e['predikat']) ?></td>
              <td><?= htmlspecialchars($e['keterangan'] ?? '') ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <?php endif; ?>

        <!-- TTD -->
        <div class="ttd-wrap">
          <div class="ttd-col">
            <div>Mengetahui,</div>
            <div>Kepala Sekolah</div>
            <div class="ttd-nama"><?= htmlspecialchars($pengaturan['kepala_sekolah'] ?? '') ?></div>
            <?php if (!empty($pengaturan['nip_kepsek'])): ?>
            <div class="ttd-nip">NIP. <?= htmlspecialchars($pengaturan['nip_kepsek']) ?></div>
            <?php endif; ?>
          </div>
          <div class="ttd-col">
            <div><?= htmlspecialchars($tempatTgl) ?></div>
            <div>Wali Kelas,</div>
            <div class="ttd-nama"><?= htmlspecialchars($waliKelas['nama'] ?? '') ?></div>
            <?php if (!empty($waliKelas['nip'])): ?>
            <div class="ttd-nip">NIP. <?= htmlspecialchars($waliKelas['nip']) ?></div>
            <?php endif; ?>
          </div>
        </div>

      </div><!-- end rapor-preview -->
      <?php endif; ?>
    </div>
  </div>

</div><!-- end grid -->

<?php
// ── MODE CETAK SEMUA SISWA (buka tab baru) ──────────────────
if ($cetakSemua && $siswaList):
?>
<script>
// Sudah dibuka di tab baru via link — tidak perlu JS
</script>
<?php endif; ?>

<script>
// Auto-focus siswa select saat kelas dipilih
document.addEventListener('DOMContentLoaded', function() {
    var selSiswa = document.querySelector('select[name="siswa_id"]');
    if (selSiswa && selSiswa.value === '') {
        selSiswa.focus();
    }
});
</script>

<?php include '../../templates/footer.php'; ?>