<?php
/**
 * SisPen Snesaka - Cetak Nilai PSAJ
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle   = 'Cetak Nilai PSAJ';
$activeMenu  = 'psaj-cetak';
$pengaturan  = getPengaturan();
$isAdmin     = $_SESSION['role'] === 'admin';
$currentUser = getCurrentUser();
$guruId      = $currentUser['guru_id'] ?? null;
$ta          = $pengaturan['tahun_ajaran_aktif'];

$bobot = array(
    'tertulis'   => floatval($pengaturan['psaj_bobot_tertulis']   ?? 40),
    'praktik'    => floatval($pengaturan['psaj_bobot_praktik']    ?? 20),
    'proyek'     => floatval($pengaturan['psaj_bobot_proyek']     ?? 15),
    'portofolio' => floatval($pengaturan['psaj_bobot_portofolio'] ?? 15),
    'presentasi' => floatval($pengaturan['psaj_bobot_presentasi'] ?? 10),
);

$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');
$tglHariIni = intval(date('j')).' '.$namaBulan[intval(date('n'))].' '.date('Y');
$kecamatan  = trim($pengaturan['kecamatan'] ?? '');
$tempatTgl  = ($kecamatan !== '' ? $kecamatan : 'Sekaran').', '.$tglHariIni;

$kelasId = intval($_GET['kelas_id'] ?? 0);
$mapelId = intval($_GET['mapel_id'] ?? 0);
$doCetak = isset($_GET['cetak']);

// Daftar kelas 9
if ($isAdmin) {
    $kelasList = db_fetchAll("SELECT * FROM kelas WHERE tingkat='9' AND tahun_ajaran=? ORDER BY nama_kelas", array($ta));
    $mapelList = $kelasId ? db_fetchAll("SELECT * FROM mata_pelajaran WHERE status='aktif' ORDER BY kelompok, urutan") : array();
} else {
    $kelasList = $guruId ? db_fetchAll(
        "SELECT DISTINCT k.* FROM pengampu p JOIN kelas k ON k.id=p.kelas_id
         WHERE p.guru_id=? AND k.tingkat='9' AND p.tahun_ajaran=? ORDER BY k.nama_kelas",
        array($guruId, $ta)
    ) : array();
    $mapelList = ($kelasId && $guruId) ? db_fetchAll(
        "SELECT m.* FROM pengampu p JOIN mata_pelajaran m ON m.id=p.mapel_id
         WHERE p.guru_id=? AND p.kelas_id=? AND p.tahun_ajaran=?",
        array($guruId, $kelasId, $ta)
    ) : array();
}

$siswas = $nilais = array();
$selectedKelas = $selectedMapel = $guruMapel = null;

if ($kelasId && $mapelId) {
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", array($kelasId));
    $selectedMapel = db_fetch("SELECT * FROM mata_pelajaran WHERE id=?", array($mapelId));
    $pengampu = db_fetch(
        "SELECT g.nama, g.nip FROM pengampu p JOIN guru g ON g.id=p.guru_id
         WHERE p.mapel_id=? AND p.kelas_id=? AND p.tahun_ajaran=? LIMIT 1",
        array($mapelId, $kelasId, $ta)
    );
    $guruMapel = $pengampu;
    $siswas = db_fetchAll(
        "SELECT * FROM siswa WHERE kelas_id=? AND status='aktif' ORDER BY nama",
        array($kelasId)
    );
    $rows = db_fetchAll(
        "SELECT * FROM nilai_psaj WHERE kelas_id=? AND mapel_id=? AND tahun_ajaran=?",
        array($kelasId, $mapelId, $ta)
    );
    foreach ($rows as $r) $nilais[$r['siswa_id']] = $r;
}

$komponen = array(
    'tertulis'   => 'Tes Tertulis',
    'praktik'    => 'Praktik/<br>Unjuk Kerja',
    'proyek'     => 'Proyek',
    'portofolio' => 'Portofolio',
    'presentasi' => 'Presentasi/<br>Penugasan',
);

// ── MODE CETAK ────────────────────────────────────────────
if ($doCetak && $kelasId && $mapelId): ?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Nilai PSAJ - <?= htmlspecialchars($selectedKelas['nama_kelas'] ?? '') ?></title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: Arial, sans-serif; font-size:10pt; color:#000; background:#fff; }
.page { width:210mm; margin:0 auto; padding:14mm 14mm 14mm; }

/* Header dokumen */
.doc-header { text-align:center; margin-bottom:10px; }
.doc-header .baris1 { font-size:13pt; font-weight:bold; text-transform:uppercase; letter-spacing:.5px; }
.doc-header .baris2 { font-size:11pt; font-weight:bold; margin-top:2px; }
.doc-header .baris3 { font-size:11pt; font-weight:bold; margin-top:1px; }
.doc-header .baris4 { font-size:10pt; margin-top:2px; }
.doc-header .garis  { border:none; border-top:2px solid #000; margin:8px 0 10px; }

/* Info mapel & kelas */
.info-bar { font-size:10.5pt; margin-bottom:8px; }

/* Tabel nilai */
.nilai-table { width:100%; border-collapse:collapse; }
.nilai-table th, .nilai-table td {
  border:1px solid #000; padding:3px 5px;
  text-align:center; font-size:9pt;
  white-space:nowrap;
}
.nilai-table th { font-weight:bold; background:#fff; }
.nilai-table td.nama-col { text-align:left; padding-left:6px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:180px; }
.nilai-table .nr-col { font-weight:bold; }

/* TTD */
.ttd-table { width:100%; border-collapse:collapse; margin-top:14px; }
.ttd-table td { padding:2px 4px; vertical-align:top; font-size:10pt; }
.ttd-space { height:44px; }

@media print {
  @page { size:A4 portrait; margin:13mm; }
  html,body { margin:0; padding:0; }
  .page { width:100%; padding:0; }

  .doc-header .baris1 { font-size:12pt; }
  .doc-header .baris2 { font-size:10.5pt; }
  .doc-header .baris3 { font-size:10.5pt; }
  .doc-header .baris4 { font-size:9.5pt; }
  .info-bar            { font-size:9.5pt; margin-bottom:5px; }

  .nilai-table th,
  .nilai-table td      { font-size:8pt; padding:0 3px; height:var(--row-h,7mm); line-height:1.2; white-space:nowrap; }
  .nilai-table thead th{ height:auto; padding:2px 3px; }
  .nilai-table td.nama-col { font-size:8pt; }

  .ttd-table  { margin-top:10px; page-break-inside:avoid; page-break-before:avoid; }
  .ttd-table td { font-size:9pt; line-height:1.5; }
  .ttd-space  { height:36px; }
  .nilai-table { page-break-inside:avoid; }
  tr          { page-break-inside:avoid; }
}
</style>
</head>
<body>
<div class="page" id="mainpage">
<script>
(function(){
  var n = <?= max(count($siswas), 5) ?>;
  var available = 170;
  var rowH = Math.min(8, Math.max(4.5, available / n));
  document.documentElement.style.setProperty('--row-h', rowH.toFixed(1)+'mm');
})();
</script>

<!-- HEADER DOKUMEN -->
<div class="doc-header">
  <div class="baris1">DAFTAR NILAI SISWA</div>
  <div class="baris2">Penilaian Sumatif Akhir Jenjang (PSAJ)</div>
  <div class="baris3"><?= htmlspecialchars($pengaturan['nama_sekolah'] ?? '') ?></div>
  <div class="baris4">Tahun Pelajaran <?= htmlspecialchars($ta) ?></div>
  <hr class="garis">
</div>

<!-- INFO MAPEL & KELAS -->
<div class="info-bar">
  <strong>Mata Pelajaran:</strong> <?= htmlspecialchars($selectedMapel['nama_mapel'] ?? '') ?>
  &nbsp;&nbsp;&nbsp;
  <strong>Kelas:</strong> <?= htmlspecialchars($selectedKelas['nama_kelas'] ?? '') ?>
</div>

<!-- TABEL NILAI -->
<table class="nilai-table">
  <thead>
    <tr>
      <th rowspan="2" style="width:26px;">NO</th>
      <th rowspan="2" style="min-width:160px;text-align:left;padding-left:6px;">NAMA SISWA</th>
      <th rowspan="2" style="width:70px;">NIS</th>
      <th rowspan="2" style="width:28px;">L/P</th>
      <th colspan="<?= count($komponen) ?>">JENIS NILAI</th>
      <th rowspan="2" class="nr-col" style="width:70px;">NILAI<br>AKHIR</th>
    </tr>
    <tr>
      <?php foreach ($komponen as $key => $label): ?>
      <th style="width:55px;font-size:8.5pt;"><?= $label ?><br><span style="font-weight:normal;font-size:8pt;">(<?= $bobot[$key] ?>%)</span></th>
      <?php endforeach; ?>
    </tr>
  </thead>
  <tbody>
    <?php if (empty($siswas)): ?>
    <tr><td colspan="<?= 4 + count($komponen) + 1 ?>" style="padding:20px;">Belum ada data</td></tr>
    <?php else: ?>
    <?php foreach ($siswas as $i => $s):
      $n = $nilais[$s['id']] ?? null;
    ?>
    <tr>
      <td><?= $i+1 ?></td>
      <td class="nama-col"><?= htmlspecialchars($s['nama']) ?></td>
      <td><?= htmlspecialchars($s['nis']) ?></td>
      <td><?= htmlspecialchars($s['jenis_kelamin'] ?? $s['jk'] ?? '-') ?></td>
      <?php foreach ($komponen as $key => $label):
        $val = ($n && isset($n[$key]) && $n[$key] !== null) ? number_format($n[$key], 0) : '';
      ?>
      <td><?= $val ?></td>
      <?php endforeach; ?>
      <td class="nr-col"><?= ($n && $n['nilai_akhir'] !== null) ? number_format($n['nilai_akhir'],0) : '' ?></td>
    </tr>
    <?php endforeach; ?>
    <!-- Baris kosong jika siswa sedikit -->
    <?php for ($e = count($siswas); $e < 5; $e++): ?>
    <tr>
      <td><?= $e+1 ?></td><td></td><td></td><td></td>
      <?php for ($j=0; $j<count($komponen)+1; $j++): ?><td></td><?php endfor; ?>
    </tr>
    <?php endfor; ?>
    <?php endif; ?>
  </tbody>
</table>

<!-- TTD / PENGESAHAN -->
<table class="ttd-table">
  <tr>
    <td style="width:50%;padding-left:80px;">Mengetahui,<br>Kepala Sekolah</td>
    <td style="width:50%;padding-left:120px;"><?= htmlspecialchars($tempatTgl) ?><br>Guru Mata Pelajaran</td>
  </tr>
  <tr>
    <td class="ttd-space"></td>
    <td class="ttd-space"></td>
  </tr>
  <tr>
    <td style="padding-left:80px;">
      <?php
        $_nm = htmlspecialchars($pengaturan['kepala_sekolah'] ?? '');
        $_pos = strpos($_nm, ',');
        if ($_pos !== false) {
          echo '<strong style="text-transform:uppercase;">' . substr($_nm, 0, $_pos) . '</strong><strong>' . substr($_nm, $_pos) . '</strong>';
        } else {
          echo '<strong style="text-transform:uppercase;">' . $_nm . '</strong>';
        }
      ?><br>
      NIP. <?= htmlspecialchars($pengaturan['nip_kepsek'] ?? '') ?>
    </td>
    <td style="padding-left:120px;">
      <?php if ($guruMapel): ?>
      <?php
        $_nm = htmlspecialchars($guruMapel['nama']);
        $_pos = strpos($_nm, ',');
        if ($_pos !== false) {
          echo '<strong style="text-transform:uppercase;">' . substr($_nm, 0, $_pos) . '</strong><strong>' . substr($_nm, $_pos) . '</strong>';
        } else {
          echo '<strong style="text-transform:uppercase;">' . $_nm . '</strong>';
        }
      ?><br>
      NIP. <?= htmlspecialchars($guruMapel['nip'] ?? '') ?>
      <?php else: ?>
      <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong><br>
      NIP.
      <?php endif; ?>
    </td>
  </tr>
</table>

</div>
<script>window.onload=function(){window.print();}</script>
</body>
</html>
<?php exit; endif;

// ── TAMPILAN NORMAL ───────────────────────────────────────
include '../../templates/header.php';
?>

<div style="display:grid;grid-template-columns:280px 1fr;gap:20px;align-items:start;">

  <!-- Panel kiri: filter -->
  <div class="card" style="position:sticky;top:80px;">
    <div class="card-header">
      <span class="card-title"><i class="fas fa-filter" style="color:var(--primary);margin-right:8px;"></i>Filter</span>
    </div>
    <div class="card-body">
      <form method="GET">
        <div class="form-group">
          <label class="form-label">Kelas 9</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): ?>
        <div class="form-group">
          <label class="form-label">Mata Pelajaran</label>
          <select name="mapel_id" class="form-control" onchange="this.form.submit()">
            <option value="">-- Pilih --</option>
            <?php foreach ($mapelList as $m): ?>
            <option value="<?= $m['id'] ?>" <?= $mapelId==$m['id']?'selected':'' ?>>
              <?= htmlspecialchars($m['nama_mapel']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
        <?php endif; ?>
      </form>
    </div>
  </div>

  <!-- Panel kanan: preview -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-eye" style="color:var(--primary);margin-right:8px;"></i>
        Preview Nilai PSAJ
      </span>
      <?php if ($kelasId && $mapelId): ?>
      <a href="?kelas_id=<?= $kelasId ?>&mapel_id=<?= $mapelId ?>&cetak=1"
         target="_blank" class="btn btn-accent btn-sm">
        <i class="fas fa-print"></i> Print Nilai PSAJ
      </a>
      <?php endif; ?>
    </div>

    <?php if ($kelasId && $mapelId && $selectedKelas && $selectedMapel): ?>
    <div style="padding:24px;background:#f8f9fa;">
      <div style="background:#fff;border:1px solid #ccc;border-radius:4px;padding:20px 24px;max-width:800px;margin:0 auto;font-family:Arial,sans-serif;">

        <!-- Header preview -->
        <div style="text-align:center;margin-bottom:10px;">
          <div style="font-size:13pt;font-weight:bold;text-transform:uppercase;">DAFTAR NILAI SISWA</div>
          <div style="font-size:11pt;font-weight:bold;margin-top:2px;">Penilaian Sumatif Akhir Jenjang (PSAJ)</div>
          <div style="font-size:11pt;font-weight:bold;margin-top:1px;"><?= htmlspecialchars($pengaturan['nama_sekolah'] ?? '') ?></div>
          <div style="font-size:10pt;margin-top:2px;">Tahun Pelajaran <?= $ta ?></div>
          <hr style="border:none;border-top:2px solid #000;margin:8px 0 10px;">
        </div>

        <div style="font-size:10.5pt;margin-bottom:8px;">
          <strong>Mata Pelajaran:</strong> <?= htmlspecialchars($selectedMapel['nama_mapel']) ?>
          &nbsp;&nbsp;&nbsp;
          <strong>Kelas:</strong> <?= htmlspecialchars($selectedKelas['nama_kelas']) ?>
        </div>

        <!-- Tabel nilai preview -->
        <table style="width:100%;border-collapse:collapse;font-size:9pt;">
          <thead>
            <tr>
              <th rowspan="2" style="border:1px solid #000;padding:4px 6px;text-align:center;width:26px;">NO</th>
              <th rowspan="2" style="border:1px solid #000;padding:4px 8px;text-align:left;min-width:150px;">NAMA SISWA</th>
              <th rowspan="2" style="border:1px solid #000;padding:4px 6px;text-align:center;width:70px;">NIS</th>
              <th rowspan="2" style="border:1px solid #000;padding:4px 4px;text-align:center;width:28px;">L/P</th>
              <th colspan="<?= count($komponen) ?>" style="border:1px solid #000;padding:4px;text-align:center;">JENIS NILAI</th>
              <th rowspan="2" style="border:1px solid #000;padding:4px;text-align:center;width:70px;font-weight:bold;">NILAI<br>AKHIR</th>
            </tr>
            <tr>
              <?php foreach ($komponen as $key => $label): ?>
              <th style="border:1px solid #000;padding:4px 3px;text-align:center;width:55px;font-size:8pt;">
                <?= $label ?><br><span style="font-weight:normal;">(<?= $bobot[$key] ?>%)</span>
              </th>
              <?php endforeach; ?>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($siswas as $i => $s):
              $n = $nilais[$s['id']] ?? null;
            ?>
            <tr>
              <td style="border:1px solid #000;padding:4px;text-align:center;"><?= $i+1 ?></td>
              <td style="border:1px solid #000;padding:4px 8px;text-align:left;white-space:nowrap;"><?= htmlspecialchars($s['nama']) ?></td>
              <td style="border:1px solid #000;padding:4px;text-align:center;font-size:8pt;"><?= htmlspecialchars($s['nis']) ?></td>
              <td style="border:1px solid #000;padding:4px;text-align:center;"><?= htmlspecialchars($s['jenis_kelamin'] ?? '-') ?></td>
              <?php foreach ($komponen as $key => $label):
                $val = ($n && isset($n[$key]) && $n[$key] !== null) ? number_format($n[$key],0) : '';
              ?>
              <td style="border:1px solid #000;padding:4px;text-align:center;"><?= $val ?></td>
              <?php endforeach; ?>
              <td style="border:1px solid #000;padding:4px;text-align:center;font-weight:bold;">
                <?= ($n && $n['nilai_akhir'] !== null) ? number_format($n['nilai_akhir'],0) : '' ?>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($siswas)): ?>
            <tr><td colspan="<?= 4+count($komponen)+1 ?>" style="border:1px solid #000;padding:20px;text-align:center;color:#999;">Belum ada data siswa</td></tr>
            <?php endif; ?>
          </tbody>
        </table>

        <!-- TTD preview -->
        <table style="width:100%;border-collapse:collapse;margin-top:20px;font-size:10pt;">
          <tr>
            <td style="width:50%;vertical-align:top;padding-left:80px;">Mengetahui,<br>Kepala Sekolah</td>
            <td style="width:50%;vertical-align:top;padding-left:120px;"><?= htmlspecialchars($tempatTgl) ?><br>Guru Mata Pelajaran</td>
          </tr>
          <tr><td style="height:48px;"></td><td></td></tr>
          <tr>
            <td style="padding-left:80px;">
              <?php
                $_nm = htmlspecialchars($pengaturan['kepala_sekolah'] ?? '________________________');
                $_pos = strpos($_nm, ',');
                if ($_pos !== false) {
                  echo '<strong style="text-transform:uppercase;">' . substr($_nm, 0, $_pos) . '</strong><strong>' . substr($_nm, $_pos) . '</strong>';
                } else {
                  echo '<strong style="text-transform:uppercase;">' . $_nm . '</strong>';
                }
              ?><br>
              NIP. <?= htmlspecialchars($pengaturan['nip_kepsek'] ?? '') ?>
            </td>
            <td style="padding-left:120px;">
              <?php if ($guruMapel): ?>
              <?php
        $_nm = htmlspecialchars($guruMapel['nama']);
        $_pos = strpos($_nm, ',');
        if ($_pos !== false) {
          echo '<strong style="text-transform:uppercase;">' . substr($_nm, 0, $_pos) . '</strong><strong>' . substr($_nm, $_pos) . '</strong>';
        } else {
          echo '<strong style="text-transform:uppercase;">' . $_nm . '</strong>';
        }
      ?><br>
              NIP. <?= htmlspecialchars($guruMapel['nip'] ?? '') ?>
              <?php else: ?>
              <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong><br>
              NIP.
              <?php endif; ?>
            </td>
          </tr>
        </table>
      </div>
    </div>
    <?php else: ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted);">
      <i class="fas fa-graduation-cap" style="font-size:48px;display:block;margin-bottom:16px;opacity:.25;"></i>
      <p>Pilih kelas 9 dan mata pelajaran untuk melihat preview.</p>
    </div>
    <?php endif; ?>
  </div>

</div>

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