<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rapor PTS — <?= htmlspecialchars($selectedSiswa['nama']) ?></title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: Arial, sans-serif;
    font-size: 10.5pt;
    color: #000;
    background: #fff;
}
.rapor-page {
    width: 210mm;
    min-height: 297mm;
    margin: 0 auto;
    padding: 15mm 18mm;
    page-break-after: always;
}
.rapor-page:last-child { page-break-after: auto; }

/* Header sekolah */
.rapor-header {
    display: flex;
    align-items: center;
    gap: 14px;
    border-bottom: 3px double #000;
    padding-bottom: 8px;
    margin-bottom: 10px;
}
.rapor-logo { width: 65px; height: 65px; object-fit: contain; }
.rapor-logo-placeholder {
    width: 65px; height: 65px;
    border: 2px solid #999; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 22px; color: #999;
}
.rapor-sekolah-info { flex: 1; text-align: center; }
.rapor-sekolah-info .kop-baris1 { font-size: 10.5pt; 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: 13.5pt; font-weight: 900; text-transform: uppercase; margin-bottom: 2px; }
.rapor-sekolah-info .kop-baris4 { font-size: 8.5pt;  color: #333; margin: 1px 0; }
.rapor-sekolah-info .kop-baris5 { font-size: 8.5pt;  color: #333; margin: 1px 0; }

/* Judul */
.rapor-judul {
    text-align: center;
    font-size: 11.5pt;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: .8px;
    border: 2px solid #000;
    padding: 5px;
    background: #f0f0f0;
    margin: 8px 0 12px;
}

/* Identitas */
.rapor-identitas { width: 100%; border-collapse: collapse; font-size: 10pt; margin-bottom: 12px; }
.rapor-identitas td { padding: 2px 6px; }
.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: 9pt; margin-bottom: 12px; }
.rapor-tbl th, .rapor-tbl td { border: 1px solid #000; padding: 3px 5px; text-align: center; vertical-align: middle; }
.rapor-tbl th { background: #bfbfbf; color: #000; font-size: 8.5pt; }
.rapor-tbl td.mapel { text-align: left; font-weight: 600; padding-left: 8px; }
.rapor-tbl td.kosong { color: #bbb; }
.rapor-tbl tr:nth-child(even) td { background: #f9f9f9; }


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

/* TTD */
.ttd-wrap { display: flex; justify-content: space-between; margin-top: 18px; font-size: 9.5pt; }
.ttd-col { text-align: center; width: 44%; }
.ttd-nama { font-weight: bold; text-transform: uppercase; margin-top: 42px; border-top: 1px solid #000; padding-top: 3px; }
.ttd-nip  { font-size: 8.5pt; }

@page { size: A4 portrait; margin: 0; }
@media print {
    body { margin: 0; }
    .rapor-page { margin: 0; }
}
</style>
</head>
<body>
<?php
// Mode cetak semua atau satu siswa
if (isset($cetakSemua) && $cetakSemua) {
    $semuaSiswa = $siswaList;
} else {
    $semuaSiswa = [$selectedSiswa];
}


// Kop surat dari GET
$kop1 = $_GET['kop1'] ?? '';
$kop2 = $_GET['kop2'] ?? '';
$kop3 = $_GET['kop3'] ?? ($pengaturan['nama_sekolah'] ?? '');
$kop4 = $_GET['kop4'] ?? ($pengaturan['alamat'] ?? '');
$kop5 = $_GET['kop5'] ?? '';

foreach ($semuaSiswa as $sw):
    // Jika cetak semua — ambil data per siswa
    if (isset($cetakSemua) && $cetakSemua) {
        $swId = $sw['id'];
        $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",
            [$swId, $kelasId, $ta, $sem]
        );
        $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]
        );
        $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",
            [$swId, $ta, $sem]
        );
    } else {
        $swId = $selectedSiswa['id'];
    }

    // Kelompok mapel
    $kelompokMap = [];
    foreach ($nilaiList as $n) {
        $kel = $n['kelompok'] ?: 'A';
        $kelompokMap[$kel][] = $n;
    }
    ksort($kelompokMap);
    $noUrut = 1;
?>
<div class="rapor-page">

  <!-- Header Sekolah -->
  <div class="rapor-header">
    <?php
      $logoFile = $pengaturan['logo_sekolah'] ?? '';
      $logoSrc  = '';
      if ($logoFile) {
          $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;">🏫</div>
    <?php else: ?>
      <div class="rapor-logo-placeholder">🏫</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($sw['nama']) ?></strong></td>
      <td width="20"></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($sw['nis']) ?></td>
      <td></td>
      <td>Tahun Pelajaran</td><td>:</td>
      <td><?= $ta ?></td>
    </tr>
    <tr>
      <td>NISN</td><td>:</td>
      <td><?= htmlspecialchars($sw['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:40px;">No</th>
        <th rowspan="2" style="min-width:150px;">Mata Pelajaran</th>
        <?php for ($i=1; $i<=$jsSumatif; $i++): ?>
        <th rowspan="2" style="width:36px;">S<?= $i ?></th>
        <?php endfor; ?>
        <th rowspan="2" style="width:48px;">Rata<br>Sumatif</th>
        <?php if ($formula['sts'] > 0): ?>
        <th rowspan="2" style="width:36px;">STS</th>
        <?php endif; ?>
      </tr>
      <tr></tr>
    </thead>
    <tbody>
      <?php foreach ($kelompokMap as $kode => $mapels): ?>
      <?php foreach ($mapels as $n):
        $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:8.5pt;color:#444;margin-top:3px;margin-bottom:10px;font-style:italic;">
    <strong>Keterangan:</strong>
    S = Sumatif &nbsp;&bull;&nbsp;
    STS = Sumatif Tengah Semester
  </div>

  <!-- Absensi -->
  <div class="section-title">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><?= intval($absensi['sakit'] ?? 0) ?> hari</td>
        <td><?= intval($absensi['izin']  ?? 0) ?> hari</td>
        <td><?= intval($absensi['alpha'] ?? 0) ?> hari</td>
        <td><strong><?= intval($absensi['sakit']??0)+intval($absensi['izin']??0)+intval($absensi['alpha']??0) ?> hari</strong></td>
      </tr>
    </tbody>
  </table>

  <!-- Ekskul -->
  <?php if (!empty($ekstraList)): ?>
  <div class="section-title">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-page -->
<?php endforeach; ?>

<script>window.onload = function(){ window.print(); }</script>
</body>
</html>