<?php
/**
 * SisPen Snesaka - Cetak / Simpan PDF Akun Siswa
 * Dibuka di tab baru; langsung trigger print dialog (Ctrl+P / Save as PDF)
 */
require_once '../../includes/functions.php';
requireAdmin();

$pengaturan = getPengaturan();
$ta  = $pengaturan['tahun_ajaran_aktif'];
$sem = $pengaturan['semester_aktif'];

$kelasId = intval($_GET['kelas_id'] ?? 0);
if (!$kelasId) { echo 'Kelas tidak ditemukan.'; exit; }

$selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);
if (!$selectedKelas) { echo 'Kelas tidak ditemukan.'; exit; }

$siswaList = db_fetchAll("
    SELECT s.*, u.username, u.id as user_id, u.status as akun_status
    FROM siswa s
    LEFT JOIN users u ON u.username=s.nis AND u.role='siswa'
    WHERE s.kelas_id=? AND s.status='aktif'
    ORDER BY s.nama
", [$kelasId]);

// Ambil cache password dari session
$pwCache = $_SESSION['_pw_cache'][$kelasId] ?? [];
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Akun Siswa — <?= htmlspecialchars($selectedKelas['nama_kelas']) ?></title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 12px;
    color: #111;
    background: #fff;
    padding: 24px 30px;
}

/* ── KOP SURAT ── */
.kop {
    display: flex;
    align-items: center;
    gap: 16px;
    border-bottom: 3px solid #1e3a5f;
    padding-bottom: 12px;
    margin-bottom: 14px;
}
.kop-logo {
    width: 64px; height: 64px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center;
    border: 2px solid #1e3a5f; border-radius: 50%;
    font-size: 28px; font-weight: 900; color: #1e3a5f;
    background: #eef2f8;
}
.kop-logo img { width: 58px; height: 58px; object-fit: contain; border-radius: 50%; }
.kop-text { flex: 1; text-align: center; }
.kop-sekolah { font-size: 16px; font-weight: 800; color: #1e3a5f; letter-spacing: .3px; }
.kop-sub     { font-size: 11px; color: #444; margin-top: 3px; }
.kop-alamat  { font-size: 10px; color: #666; margin-top: 2px; }

/* ── JUDUL DOKUMEN ── */
.doc-title {
    text-align: center;
    margin-bottom: 14px;
}
.doc-title h2 {
    font-size: 14px; font-weight: 800; color: #1e3a5f;
    text-transform: uppercase; letter-spacing: .5px;
    border: 2px solid #1e3a5f;
    display: inline-block; padding: 5px 20px; border-radius: 4px;
    margin-bottom: 6px;
}
.doc-meta {
    font-size: 11px; color: #555;
    display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;
}
.doc-meta span { display: flex; align-items: center; gap: 4px; }

/* ── INFO KELAS ── */
.info-row {
    display: flex; gap: 20px; margin-bottom: 14px; flex-wrap: wrap;
}
.info-box {
    background: #f0f4fa; border: 1px solid #c7d5ea; border-radius: 8px;
    padding: 8px 16px; font-size: 11px; flex: 1; min-width: 140px;
}
.info-box .ib-label { color: #555; font-weight: 600; margin-bottom: 2px; }
.info-box .ib-val   { font-size: 14px; font-weight: 800; color: #1e3a5f; }

/* ── TABEL ── */
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 16px;
}
thead tr {
    background: #1e3a5f;
    color: #fff;
}
thead th {
    padding: 8px 10px;
    text-align: left;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: .3px;
    white-space: nowrap;
}
thead th.center { text-align: center; }
tbody tr:nth-child(even) { background: #f5f8fc; }
tbody tr { border-bottom: 1px solid #e0e7ef; }
tbody td {
    padding: 7px 10px;
    font-size: 12px;
    vertical-align: middle;
}
tbody td.center { text-align: center; }
.td-nama  { font-weight: 700; }
.td-nis   { font-family: monospace; font-size: 12px; }
.td-pw    { font-family: monospace; font-size: 13px; font-weight: 700;
            letter-spacing: .8px; color: #15803d; }
.td-pw.none { color: #94a3b8; font-style: italic; font-weight: 400; letter-spacing: 0; }
.badge-l  { background: #dbeafe; color: #1e40af; border-radius: 4px; padding: 1px 6px; font-size: 10px; font-weight: 700; }
.badge-p  { background: #fef3c7; color: #92400e; border-radius: 4px; padding: 1px 6px; font-size: 10px; font-weight: 700; }
.badge-ok { background: #dcfce7; color: #15803d; border-radius: 4px; padding: 1px 6px; font-size: 10px; font-weight: 700; }
.badge-no { background: #fef9c3; color: #854d0e; border-radius: 4px; padding: 1px 6px; font-size: 10px; font-weight: 700; }

/* ── FOOTER KETERANGAN ── */
.footer-note {
    border-top: 1px solid #e0e7ef;
    padding-top: 10px;
    font-size: 10px;
    color: #666;
    line-height: 1.6;
}
.footer-note strong { color: #1e3a5f; }

/* ── TOMBOL AKSI (hanya layar) ── */
.action-bar {
    display: flex; gap: 10px; margin-bottom: 20px; justify-content: flex-end;
}
.btn-act {
    padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 700;
    cursor: pointer; border: none; display: inline-flex; align-items: center; gap: 6px;
    text-decoration: none;
}
.btn-cetak { background: #1e3a5f; color: #fff; }
.btn-tutup { background: #f1f5f9; color: #334155; }

/* ── PRINT ── */
@media print {
    .action-bar { display: none !important; }
    body { padding: 14px 18px; }
    thead tr { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .info-box  { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
</style>
</head>
<body>

<!-- Tombol aksi (hanya tampil di layar) -->
<div class="action-bar">
  <a href="javascript:window.close()" class="btn-act btn-tutup">
    ✕ Tutup
  </a>
  <button onclick="window.print()" class="btn-act btn-cetak">
    🖨 Cetak / Simpan PDF
  </button>
</div>

<!-- KOP SEKOLAH -->
<div class="kop">
  <div class="kop-logo">
    <?php
      $logoPath = !empty($pengaturan['logo_sekolah']) ? '../../' . $pengaturan['logo_sekolah'] : '';
      if ($logoPath && file_exists($logoPath)):
    ?>
      <img src="<?= '../../' . htmlspecialchars($pengaturan['logo_sekolah']) ?>" alt="Logo">
    <?php else: ?>
      S
    <?php endif; ?>
  </div>
  <div class="kop-text">
    <div class="kop-sekolah"><?= htmlspecialchars($pengaturan['nama_sekolah'] ?? 'SisPen Snesaka') ?></div>
    <?php if (!empty($pengaturan['npsn'])): ?>
    <div class="kop-sub">NPSN: <?= htmlspecialchars($pengaturan['npsn']) ?><?= !empty($pengaturan['nss']) ? ' &nbsp;|&nbsp; NSS: '.htmlspecialchars($pengaturan['nss']) : '' ?></div>
    <?php endif; ?>
    <?php if (!empty($pengaturan['alamat'])): ?>
    <div class="kop-alamat"><?= htmlspecialchars($pengaturan['alamat']) ?><?= !empty($pengaturan['telepon']) ? ' &nbsp;| Telp. '.htmlspecialchars($pengaturan['telepon']) : '' ?></div>
    <?php endif; ?>
  </div>
</div>

<!-- JUDUL DOKUMEN -->
<div class="doc-title">
  <h2>Daftar Akun Login Siswa</h2>
  <div class="doc-meta">
    <span>📚 Kelas: <strong><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></strong></span>
    <span>📅 TA <?= $ta ?></span>
    <span>📋 Semester <?= $sem ?></span>
    <span>📆 Dicetak: <?= date('d/m/Y H:i') ?></span>
  </div>
</div>

<!-- INFO STATISTIK -->
<?php
$sudahAkun = 0;
foreach ($siswaList as $s) { if ($s['user_id']) $sudahAkun++; }
$hasPw = count($pwCache);
?>
<div class="info-row">
  <div class="info-box">
    <div class="ib-label">Total Siswa</div>
    <div class="ib-val"><?= count($siswaList) ?> siswa</div>
  </div>
  <div class="info-box">
    <div class="ib-label">Sudah Punya Akun</div>
    <div class="ib-val"><?= $sudahAkun ?> siswa</div>
  </div>
  <div class="info-box">
    <div class="ib-label">Password Tersedia</div>
    <div class="ib-val"><?= $hasPw ?> siswa</div>
  </div>
  <div class="info-box">
    <div class="ib-label">URL Login</div>
    <div style="font-size:11px;font-weight:700;color:#1e3a5f;word-break:break-all;margin-top:2px;"><?= rtrim(BASE_URL,'/') ?>/siswa.php</div>
  </div>
</div>

<!-- TABEL AKUN -->
<table>
  <thead>
    <tr>
      <th style="width:32px;" class="center">No</th>
      <th>Nama Siswa</th>
      <th class="center">NIS</th>
      <th class="center">Username</th>
      <th class="center">Password</th>
      <th class="center">Status</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($siswaList as $idx => $s):
      $cachedPw = $pwCache[$s['nis']] ?? null;
    ?>
    <tr>
      <td class="center" style="color:#94a3b8;"><?= $idx+1 ?></td>
      <td class="td-nama">
        <?= htmlspecialchars($s['nama']) ?>
        <span class="<?= $s['jenis_kelamin']==='L' ? 'badge-l' : 'badge-p' ?>"><?= $s['jenis_kelamin'] ?></span>
      </td>
      <td class="center td-nis"><?= htmlspecialchars($s['nis']) ?></td>
      <td class="center">
        <?php if ($s['user_id']): ?>
          <span class="td-nis"><?= htmlspecialchars($s['username']) ?></span>
        <?php else: ?>
          <span style="color:#94a3b8;">—</span>
        <?php endif; ?>
      </td>
      <td class="center">
        <?php if ($cachedPw): ?>
          <span class="td-pw"><?= htmlspecialchars($cachedPw) ?></span>
        <?php elseif ($s['user_id']): ?>
          <span class="td-pw none">tersembunyi</span>
        <?php else: ?>
          <span class="td-pw none">belum dibuat</span>
        <?php endif; ?>
      </td>
      <td class="center">
        <?php if ($s['user_id']): ?>
          <span class="badge-ok">✓ Aktif</span>
        <?php else: ?>
          <span class="badge-no">Belum</span>
        <?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<!-- CATATAN KAKI -->
<div class="footer-note">
  <strong>⚠ Penting:</strong>
  Dokumen ini bersifat rahasia. Password hanya tampil satu sesi setelah di-generate atau direset.
  Untuk keamanan, minta siswa mengganti password setelah login pertama.
  &nbsp;|&nbsp;
  <strong>Format password:</strong> 4 digit bulan+tgl lahir + 4 karakter acak. Contoh: <code>0312ab7x</code> (lahir 12 Maret).
  &nbsp;|&nbsp;
  <strong>Username = NIS siswa.</strong>
</div>

<script>
// Auto-trigger print dialog saat halaman siap
window.addEventListener('load', function() {
    // Tunda sedikit agar layout selesai render
    setTimeout(function(){ window.print(); }, 600);
});
</script>
</body>
</html>