<?php
/**
 * SisPen Snesaka - Generate & Kelola Akun Siswa
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Akun Siswa';
$activeMenu = 'akun-siswa';
$pengaturan = getPengaturan();
$ta  = $pengaturan['tahun_ajaran_aktif'];
$sem = $pengaturan['semester_aktif'];

// ── Generate akun untuk 1 siswa ────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_one'])) {
    $siswaId = intval($_POST['siswa_id']);
    $siswa   = db_fetch("SELECT * FROM siswa WHERE id=?", [$siswaId]);
    if ($siswa) {
        $existing = db_fetch("SELECT id FROM users WHERE username=?", [$siswa['nis']]);
        if ($existing) {
            setFlash('warning', 'Siswa '.$siswa['nama'].' sudah punya akun (username: '.$siswa['nis'].').');
        } else {
            $pw = generateSiswaPassword($siswa);
            db_insert('users', [
                'username'     => $siswa['nis'],
                'password'     => password_hash($pw, PASSWORD_DEFAULT),
                'nama_lengkap' => $siswa['nama'],
                'role'         => 'siswa',
                'status'       => 'aktif',
            ]);
            // Simpan pw ke cache session per-kelas
            $kelasId = intval($_POST['kelas_id']);
            if (!isset($_SESSION['_pw_cache'][$kelasId])) $_SESSION['_pw_cache'][$kelasId] = [];
            $_SESSION['_pw_cache'][$kelasId][$siswa['nis']] = $pw;

            $_SESSION['_gen_result'] = [
                'nama' => $siswa['nama'],
                'nis'  => $siswa['nis'],
                'pw'   => $pw,
                'type' => 'single',
            ];
        }
    }
    header('Location: akun_siswa.php?kelas_id='.intval($_POST['kelas_id']));
    exit;
}

// ── Generate akun semua siswa 1 kelas ──────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_kelas'])) {
    $kelasId  = intval($_POST['kelas_id']);
    $siswaAll = db_fetchAll(
        "SELECT * FROM siswa WHERE kelas_id=? AND status='aktif' ORDER BY nama",
        [$kelasId]
    );
    $baru = 0; $skip = 0; $results = [];
    if (!isset($_SESSION['_pw_cache'][$kelasId])) $_SESSION['_pw_cache'][$kelasId] = [];
    foreach ($siswaAll as $siswa) {
        $existing = db_fetch("SELECT id FROM users WHERE username=?", [$siswa['nis']]);
        if ($existing) { $skip++; continue; }
        $pw = generateSiswaPassword($siswa);
        db_insert('users', [
            'username'     => $siswa['nis'],
            'password'     => password_hash($pw, PASSWORD_DEFAULT),
            'nama_lengkap' => $siswa['nama'],
            'role'         => 'siswa',
            'status'       => 'aktif',
        ]);
        $_SESSION['_pw_cache'][$kelasId][$siswa['nis']] = $pw;
        $results[] = ['nama'=>$siswa['nama'],'nis'=>$siswa['nis'],'pw'=>$pw];
        $baru++;
    }
    $_SESSION['_gen_result'] = [
        'type'    => 'bulk',
        'baru'    => $baru,
        'skip'    => $skip,
        'results' => $results,
    ];
    header('Location: akun_siswa.php?kelas_id='.$kelasId.'&bulk=1');
    exit;
}

// ── Reset password siswa ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_pw'])) {
    $siswaId = intval($_POST['siswa_id']);
    $siswa   = db_fetch("SELECT * FROM siswa WHERE id=?", [$siswaId]);
    if ($siswa) {
        $user = db_fetch("SELECT id FROM users WHERE username=? AND role='siswa'", [$siswa['nis']]);
        if ($user) {
            $pw = generateSiswaPassword($siswa);
            db_update('users', ['password'=>password_hash($pw,PASSWORD_DEFAULT)], 'id=:id', ['id'=>$user['id']]);
            $kelasId = intval($_POST['kelas_id']);
            if (!isset($_SESSION['_pw_cache'][$kelasId])) $_SESSION['_pw_cache'][$kelasId] = [];
            $_SESSION['_pw_cache'][$kelasId][$siswa['nis']] = $pw;
            $_SESSION['_gen_result'] = [
                'nama' => $siswa['nama'], 'nis' => $siswa['nis'],
                'pw'   => $pw, 'type' => 'reset',
            ];
        }
    }
    header('Location: akun_siswa.php?kelas_id='.intval($_POST['kelas_id']));
    exit;
}

// ── Reset password SEMUA siswa 1 kelas (generate ulang) ────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_semua'])) {
    $kelasId  = intval($_POST['kelas_id']);
    $konfirm  = $_POST['konfirm_reset'] ?? '';
    $namaKelas = db_fetch("SELECT nama_kelas FROM kelas WHERE id=?", [$kelasId])['nama_kelas'] ?? '';

    // Validasi: user harus mengetik nama kelas sebagai konfirmasi
    if ($konfirm !== $namaKelas) {
        setFlash('danger', 'Konfirmasi nama kelas tidak sesuai. Reset semua password dibatalkan.');
        header('Location: akun_siswa.php?kelas_id='.$kelasId);
        exit;
    }

    $siswaAll = db_fetchAll(
        "SELECT s.* FROM siswa s
         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]
    );

    if (!isset($_SESSION['_pw_cache'][$kelasId])) $_SESSION['_pw_cache'][$kelasId] = [];
    $results = [];
    foreach ($siswaAll as $siswa) {
        $pw = generateSiswaPassword($siswa);
        $user = db_fetch("SELECT id FROM users WHERE username=? AND role='siswa'", [$siswa['nis']]);
        if ($user) {
            db_update('users', ['password' => password_hash($pw, PASSWORD_DEFAULT)], 'id=:id', ['id' => $user['id']]);
            $_SESSION['_pw_cache'][$kelasId][$siswa['nis']] = $pw;
            $results[] = ['nama' => $siswa['nama'], 'nis' => $siswa['nis'], 'pw' => $pw];
        }
    }
    $_SESSION['_gen_result'] = [
        'type'      => 'reset_semua',
        'nama_kelas'=> $namaKelas,
        'total'     => count($results),
        'results'   => $results,
    ];
    header('Location: akun_siswa.php?kelas_id='.$kelasId);
    exit;
}

// ── Fungsi generate password ────────────────────────────────
function generateSiswaPassword($siswa) {
    // Jika tanggal lahir kosong → password = "siswa" + NIS
    if (empty($siswa['tanggal_lahir'])) {
        return 'siswa' . $siswa['nis'];
    }
    $tgl    = str_replace('-', '', substr($siswa['tanggal_lahir'], 0, 10));
    $tgl4   = substr($tgl, 4, 4);
    $chars  = 'abcdefghjkmnpqrstuvwxyz23456789';
    $random = '';
    for ($i = 0; $i < 4; $i++) $random .= $chars[random_int(0, strlen($chars)-1)];
    return $tgl4 . $random;
}

// ── Ambil data ──────────────────────────────────────────────
$kelasId   = intval($_GET['kelas_id'] ?? 0);
$kelasList = db_fetchAll(
    "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
    [$ta, $sem]
);

$siswaList     = [];
$selectedKelas = null;
if ($kelasId) {
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);
    $siswaList = db_fetchAll("
        SELECT s.*,
               u.id as user_id, u.username, 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]);
}

$sudahAkun = 0;
foreach ($siswaList as $_s) { if (!empty($_s['user_id'])) $sudahAkun++; }
$belumAkun  = count($siswaList) - $sudahAkun;

// Ambil cache password dari session
$pwCache = $_SESSION['_pw_cache'][$kelasId] ?? [];

// Ambil hasil generate dari session
$genResult = null;
if (isset($_SESSION['_gen_result'])) {
    $genResult = $_SESSION['_gen_result'];
    unset($_SESSION['_gen_result']);
}

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

<style>
/* ── Password cell ── */
.pw-cell { position:relative; }
.pw-val  {
    font-family: monospace; font-size: 13px;
    letter-spacing: .5px; color: #15803d;
    background: #f0fdf4; border: 1px solid #86efac;
    border-radius: 6px; padding: 3px 30px 3px 8px;
    display: inline-block; white-space: nowrap;
}
.pw-val.none { color: var(--text-muted); background: var(--surface-2); border-color: var(--border); font-style: italic; letter-spacing: 0; }
.pw-copy {
    position: absolute; right: 4px; top: 50%; transform: translateY(-50%);
    background: none; border: none; cursor: pointer;
    color: #16a34a; font-size: 11px; padding: 2px 4px; line-height: 1;
    opacity: .7; transition: opacity .15s;
}
.pw-copy:hover { opacity: 1; }

/* ── Tombol cetak/PDF ── */
.btn-print-group {
    display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
}
@media print {
    .no-print { display: none !important; }
    body { background: #fff !important; }
    .sidebar, .topbar, .bottom-nav, .card-header .btn,
    form[method="POST"], .btn-print-group { display: none !important; }
    .card { box-shadow: none; border: none; }
    table { font-size: 11px; }
    .print-header { display: block !important; }
}
.print-header {
    display: none;
    text-align: center;
    margin-bottom: 16px;
    border-bottom: 2px solid #1e3a5f;
    padding-bottom: 10px;
}
.print-header h2 { font-size: 15px; font-weight: 800; color: #1e3a5f; margin-bottom: 2px; }
.print-header p  { font-size: 12px; color: #555; }
</style>

<!-- Hasil generate (muncul sekali) -->
<?php if ($genResult): ?>
<div style="margin-bottom:20px;" class="no-print">
  <?php if ($genResult['type'] === 'single' || $genResult['type'] === 'reset'): ?>
  <div style="background:linear-gradient(135deg,#dcfce7,#bbf7d0);border:1px solid #86efac;border-radius:12px;padding:20px 24px;">
    <div style="font-weight:700;color:#15803d;margin-bottom:12px;">
      <i class="fas fa-check-circle"></i>
      <?= $genResult['type']==='reset' ? 'Password Berhasil Direset' : 'Akun Berhasil Dibuat' ?>
      — <?= htmlspecialchars($genResult['nama']) ?>
    </div>
    <div style="background:#fff;border:1px solid #86efac;border-radius:8px;padding:12px 16px;display:flex;gap:24px;flex-wrap:wrap;align-items:center;">
      <div style="font-size:13px;">
        <span style="color:#64748b;">Username (NIS):</span>
        <code style="background:#f0fdf4;padding:3px 10px;border-radius:4px;font-size:14px;margin-left:6px;"><?= htmlspecialchars($genResult['nis']) ?></code>
      </div>
      <div style="font-size:13px;">
        <span style="color:#64748b;">Password:</span>
        <code style="background:#f0fdf4;padding:3px 10px;border-radius:4px;font-size:16px;letter-spacing:1px;color:#15803d;margin-left:6px;"><?= htmlspecialchars($genResult['pw']) ?></code>
        <button type="button" onclick="copyText('<?= htmlspecialchars($genResult['pw'],ENT_QUOTES) ?>',this)"
                style="margin-left:6px;background:none;border:1px solid #86efac;border-radius:6px;padding:3px 8px;cursor:pointer;font-size:11px;color:#15803d;">
          <i class="fas fa-copy"></i> Salin
        </button>
      </div>
    </div>
    <div style="font-size:11px;color:#166534;margin-top:8px;">
      <i class="fas fa-exclamation-triangle"></i> Informasi ini hanya tampil sekali. Segera catat dan sampaikan ke siswa.
    </div>
  </div>

  <?php elseif ($genResult['type'] === 'bulk'): ?>
  <div style="background:linear-gradient(135deg,#dcfce7,#bbf7d0);border:1px solid #86efac;border-radius:12px;padding:20px 24px;">
    <div style="font-weight:700;color:#15803d;margin-bottom:12px;font-size:15px;">
      <i class="fas fa-check-circle"></i> Generate Akun Selesai
    </div>
    <div style="display:flex;gap:16px;margin-bottom:14px;flex-wrap:wrap;">
      <div style="background:#fff;border:1px solid #86efac;border-radius:8px;padding:10px 20px;text-align:center;">
        <div style="font-size:28px;font-weight:800;color:#16a34a;"><?= $genResult['baru'] ?></div>
        <div style="font-size:12px;color:#64748b;">Akun baru dibuat</div>
      </div>
      <div style="background:#fff;border:1px solid #fcd34d;border-radius:8px;padding:10px 20px;text-align:center;">
        <div style="font-size:28px;font-weight:800;color:#d97706;"><?= $genResult['skip'] ?></div>
        <div style="font-size:12px;color:#64748b;">Sudah punya akun (skip)</div>
      </div>
    </div>
    <div style="font-size:11px;color:#166534;margin-top:4px;">
      <i class="fas fa-info-circle"></i> Password baru tersimpan di tabel di bawah. Gunakan tombol <strong>Cetak / Simpan PDF</strong> untuk mendistribusikan.
    </div>
  </div>

  <?php elseif ($genResult['type'] === 'reset_semua'): ?>
  <div style="background:linear-gradient(135deg,#fff7ed,#fed7aa);border:1px solid #fb923c;border-radius:12px;padding:20px 24px;">
    <div style="font-weight:700;color:#c2410c;margin-bottom:12px;font-size:15px;">
      <i class="fas fa-sync-alt"></i> Generate Ulang Password Selesai —
      <strong><?= htmlspecialchars($genResult['nama_kelas']) ?></strong>
    </div>
    <div style="display:flex;gap:16px;margin-bottom:14px;flex-wrap:wrap;">
      <div style="background:#fff;border:1px solid #fb923c;border-radius:8px;padding:10px 20px;text-align:center;">
        <div style="font-size:28px;font-weight:800;color:#ea580c;"><?= $genResult['total'] ?></div>
        <div style="font-size:12px;color:#64748b;">Password direset</div>
      </div>
    </div>
    <?php if (!empty($genResult['results'])): ?>
    <div style="max-height:280px;overflow-y:auto;border:1px solid #fb923c;border-radius:8px;background:#fff;">
      <table style="width:100%;border-collapse:collapse;font-size:12px;">
        <thead style="background:#fff7ed;position:sticky;top:0;">
          <tr>
            <th style="padding:8px 12px;text-align:left;">Nama Siswa</th>
            <th style="padding:8px 10px;text-align:center;">NIS (Username)</th>
            <th style="padding:8px 10px;text-align:center;">Password Baru</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($genResult['results'] as $idx => $r): ?>
          <tr style="<?= $idx%2===0?'':'background:#fff7ed;' ?>">
            <td style="padding:7px 12px;font-weight:600;"><?= htmlspecialchars($r['nama']) ?></td>
            <td style="padding:7px 10px;text-align:center;"><code><?= htmlspecialchars($r['nis']) ?></code></td>
            <td style="padding:7px 10px;text-align:center;">
              <code style="color:#c2410c;letter-spacing:.5px;font-size:13px;"><?= htmlspecialchars($r['pw']) ?></code>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
    <div style="font-size:11px;color:#9a3412;margin-top:8px;">
      <i class="fas fa-exclamation-triangle"></i>
      Password lama sudah tidak berlaku. Segera cetak atau simpan PDF dan bagikan ke siswa.
    </div>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Filter kelas -->
<div class="card no-print" style="margin-bottom:16px;">
  <div class="card-body" style="padding:14px 20px;">
    <form method="GET" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;">
      <div style="min-width:200px;flex:1;">
        <label class="form-label">Pilih 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>
    </form>
  </div>
</div>

<?php if ($kelasId && $selectedKelas): ?>

<!-- Print header (hanya muncul saat print) -->
<div class="print-header">
  <h2>Daftar Akun Siswa — <?= htmlspecialchars($selectedKelas['nama_kelas']) ?></h2>
  <p>Tahun Ajaran <?= $ta ?> &bull; Semester <?= $sem ?> &bull; <?= htmlspecialchars($pengaturan['nama_sekolah'] ?? 'SisPen Snesaka') ?></p>
  <p style="font-size:11px;color:#888;">Login Portal Siswa: <strong><?= rtrim(BASE_URL,'/') ?>/siswa.php</strong></p>
</div>

<div class="card">
  <div class="card-header" style="flex-wrap:wrap;gap:8px;">
    <span class="card-title">
      <i class="fas fa-user-graduate" style="color:var(--primary);margin-right:8px;"></i>
      Akun Siswa &mdash; <strong><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></strong>
      <span class="badge badge-info" style="margin-left:6px;"><?= count($siswaList) ?> siswa</span>
      <span class="badge badge-success" style="margin-left:4px;"><?= $sudahAkun ?> punya akun</span>
      <?php if ($belumAkun > 0): ?>
      <span class="badge badge-warning" style="margin-left:4px;"><?= $belumAkun ?> belum</span>
      <?php endif; ?>
    </span>

    <!-- Tombol aksi kanan -->
    <div class="btn-print-group no-print">
      <!-- Cetak (Print CSS) -->
      <button type="button" class="btn btn-outline btn-sm" onclick="window.print()">
        <i class="fas fa-print"></i> Cetak
      </button>
      <!-- Simpan PDF via halaman cetak terpisah -->
      <a href="cetak_akun_siswa.php?kelas_id=<?= $kelasId ?>" target="_blank" class="btn btn-outline btn-sm"
         style="color:var(--danger,#c62828);border-color:var(--danger,#c62828);">
        <i class="fas fa-file-pdf"></i> Simpan PDF
      </a>
      <?php if ($belumAkun > 0): ?>
      <form method="POST" onsubmit="return confirm('Generate akun untuk <?= $belumAkun ?> siswa yang belum punya akun?')" style="display:inline;">
        <input type="hidden" name="generate_kelas" value="1">
        <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
        <button type="submit" class="btn btn-primary btn-sm">
          <i class="fas fa-magic"></i> Generate Semua (<?= $belumAkun ?>)
        </button>
      </form>
      <?php endif; ?>
      <?php if ($sudahAkun > 0): ?>
      <!-- Generate Ulang Semua Password -->
      <button type="button" class="btn btn-sm"
              style="background:linear-gradient(135deg,#ea580c,#f97316);color:#fff;border:none;"
              onclick="bukaMmodalResetSemua()">
        <i class="fas fa-sync-alt"></i> Generate Ulang Password
      </button>
      <?php endif; ?>
    </div>
  </div>

  <!-- ══ MODAL KONFIRMASI GENERATE ULANG ══ -->
  <div id="modalResetSemua"
       style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:14px;padding:28px 28px 24px;max-width:440px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.25);">
      <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
        <div style="width:44px;height:44px;border-radius:50%;background:#fff7ed;border:2px solid #fb923c;
                    display:flex;align-items:center;justify-content:center;flex-shrink:0;">
          <i class="fas fa-exclamation-triangle" style="color:#ea580c;font-size:18px;"></i>
        </div>
        <div>
          <div style="font-size:15px;font-weight:800;color:#1e293b;">Generate Ulang Semua Password</div>
          <div style="font-size:12px;color:#64748b;margin-top:2px;">Kelas <strong><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></strong> — <?= $sudahAkun ?> akun akan direset</div>
        </div>
      </div>

      <div style="background:#fff7ed;border:1px solid #fed7aa;border-radius:8px;padding:12px 14px;margin-bottom:16px;font-size:12px;color:#9a3412;line-height:1.6;">
        <i class="fas fa-exclamation-circle"></i>
        <strong>Perhatian:</strong> Tindakan ini akan <strong>mereset password semua siswa</strong> di kelas ini.
        Password lama tidak bisa dipulihkan. Pastikan Anda langsung mencetak / simpan PDF hasilnya.
      </div>

      <div style="margin-bottom:18px;">
        <label style="font-size:13px;font-weight:700;color:#334155;display:block;margin-bottom:6px;">
          Ketik nama kelas untuk konfirmasi:
          <code style="background:#f1f5f9;padding:2px 8px;border-radius:4px;color:#0f172a;"><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></code>
        </label>
        <input type="text" id="inputKonfirmReset"
               placeholder="Ketik: <?= htmlspecialchars($selectedKelas['nama_kelas'],ENT_QUOTES) ?>"
               class="form-control"
               oninput="cekKonfirmReset(this.value)"
               style="border:2px solid var(--border);transition:border-color .2s;">
        <div id="msgKonfirmReset" style="font-size:11px;margin-top:4px;height:16px;"></div>
      </div>

      <form method="POST" id="formResetSemua">
        <input type="hidden" name="reset_semua" value="1">
        <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
        <input type="hidden" name="konfirm_reset" id="hiddenKonfirm" value="">
        <div style="display:flex;gap:10px;justify-content:flex-end;">
          <button type="button" onclick="tutupMModalResetSemua()"
                  class="btn btn-outline btn-sm">Batal</button>
          <button type="submit" id="btnKonfirmReset"
                  class="btn btn-sm" disabled
                  style="background:linear-gradient(135deg,#ea580c,#f97316);color:#fff;border:none;opacity:.4;transition:opacity .2s;">
            <i class="fas fa-sync-alt"></i> Ya, Reset Semua Password
          </button>
        </div>
      </form>
    </div>
  </div>

  <div style="overflow-x:auto;">
    <table style="width:100%;border-collapse:collapse;font-size:13px;" id="tblAkun">
      <thead>
        <tr style="background:var(--primary-dark);color:#fff;">
          <th style="padding:10px 12px;width:36px;">No</th>
          <th style="padding:10px 12px;">Nama Siswa</th>
          <th style="padding:10px 10px;text-align:center;">NIS</th>
          <th style="padding:10px 10px;text-align:center;">Username</th>
          <th style="padding:10px 10px;text-align:center;">Password</th>
          <th style="padding:10px 10px;text-align:center;">Status Akun</th>
          <th style="padding:10px 10px;text-align:center;" class="no-print">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($siswaList as $idx => $s):
          $cachedPw = $pwCache[$s['nis']] ?? null;
        ?>
        <tr style="<?= $idx%2===0?'':'background:var(--surface-2);' ?>">
          <td style="padding:8px 12px;color:var(--text-muted);"><?= $idx+1 ?></td>
          <td style="padding:8px 12px;font-weight:600;">
            <?= htmlspecialchars($s['nama']) ?>
            <span class="badge <?= $s['jenis_kelamin']==='L'?'badge-info':'badge-warning' ?>" style="font-size:10px;margin-left:4px;"><?= $s['jenis_kelamin'] ?></span>
          </td>
          <td style="padding:8px 10px;text-align:center;">
            <code style="font-size:12px;"><?= htmlspecialchars($s['nis']) ?></code>
          </td>
          <td style="padding:8px 10px;text-align:center;">
            <?php if ($s['user_id']): ?>
            <code style="font-size:12px;"><?= htmlspecialchars($s['username']) ?></code>
            <?php else: ?>
            <span style="color:var(--text-muted);font-size:12px;font-style:italic;">Belum ada</span>
            <?php endif; ?>
          </td>
          <!-- ── KOLOM PASSWORD ── -->
          <td style="padding:8px 10px;text-align:center;" class="pw-cell">
            <?php if ($cachedPw): ?>
              <span class="pw-val" id="pw-<?= $s['id'] ?>"><?= htmlspecialchars($cachedPw) ?></span>
              <button type="button" class="pw-copy no-print"
                      onclick="copyText('<?= htmlspecialchars($cachedPw,ENT_QUOTES) ?>',this)"
                      title="Salin password">
                <i class="fas fa-copy"></i>
              </button>
            <?php elseif ($s['user_id']): ?>
              <span class="pw-val none">••••••••</span>
            <?php else: ?>
              <span class="pw-val none">—</span>
            <?php endif; ?>
          </td>
          <td style="padding:8px 10px;text-align:center;">
            <?php if ($s['user_id']): ?>
            <span class="badge badge-<?= $s['akun_status']==='aktif'?'success':'gray' ?>">
              <i class="fas fa-<?= $s['akun_status']==='aktif'?'check':'times' ?>-circle"></i>
              <?= ucfirst($s['akun_status']) ?>
            </span>
            <?php else: ?>
            <span class="badge badge-warning">
              <i class="fas fa-exclamation-circle"></i> Belum ada akun
            </span>
            <?php endif; ?>
          </td>
          <td style="padding:8px 10px;text-align:center;" class="no-print">
            <?php if (!$s['user_id']): ?>
            <form method="POST" style="display:inline;">
              <input type="hidden" name="generate_one" value="1">
              <input type="hidden" name="siswa_id" value="<?= $s['id'] ?>">
              <input type="hidden" name="kelas_id"  value="<?= $kelasId ?>">
              <button type="submit" class="btn btn-primary btn-xs" title="Buat Akun">
                <i class="fas fa-plus"></i> Buat Akun
              </button>
            </form>
            <?php else: ?>
            <form method="POST" style="display:inline;"
                  onsubmit="return confirm('Reset password <?= htmlspecialchars($s['nama'],ENT_QUOTES) ?>?')">
              <input type="hidden" name="reset_pw"  value="1">
              <input type="hidden" name="siswa_id"  value="<?= $s['id'] ?>">
              <input type="hidden" name="kelas_id"   value="<?= $kelasId ?>">
              <button type="submit" class="btn btn-warning btn-xs" title="Reset Password">
                <i class="fas fa-key"></i> Reset PW
              </button>
            </form>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div style="padding:10px 20px;background:var(--surface-2);border-top:1px solid var(--border);font-size:12px;color:var(--text-muted);" class="no-print">
    <i class="fas fa-info-circle" style="color:var(--accent);"></i>
    Format password: <strong>4 digit bulan+tgl lahir + 4 karakter acak</strong>. Contoh: <code>0312ab7x</code> (lahir 12 Maret).
    Siswa login dengan <strong>NIS sebagai username</strong>.
    Password hanya tampil setelah di-generate/reset dan akan hilang saat halaman dibuka ulang.
  </div>
</div>

<?php else: ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-user-graduate" style="font-size:48px;display:block;margin-bottom:14px;opacity:.2;"></i>
    <p>Pilih kelas untuk mengelola akun siswa.</p>
  </div>
</div>
<?php endif; ?>

<script>
function copyText(txt, btn) {
    navigator.clipboard.writeText(txt).then(function(){
        var orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i>';
        btn.style.color = '#16a34a';
        setTimeout(function(){ btn.innerHTML = orig; btn.style.color = ''; }, 2000);
    });
}

// ── Modal Generate Ulang Semua Password ─────────────────────
var _namaKelasKonfirm = '<?= addslashes(htmlspecialchars($selectedKelas['nama_kelas'] ?? '', ENT_QUOTES)) ?>';

function bukaMmodalResetSemua() {
    document.getElementById('modalResetSemua').style.display = 'flex';
    document.getElementById('inputKonfirmReset').value = '';
    document.getElementById('hiddenKonfirm').value = '';
    document.getElementById('btnKonfirmReset').disabled = true;
    document.getElementById('btnKonfirmReset').style.opacity = '.4';
    document.getElementById('msgKonfirmReset').innerHTML = '';
    document.getElementById('inputKonfirmReset').style.borderColor = 'var(--border)';
    setTimeout(function(){ document.getElementById('inputKonfirmReset').focus(); }, 100);
}

function tutupMModalResetSemua() {
    document.getElementById('modalResetSemua').style.display = 'none';
}

function cekKonfirmReset(val) {
    var btn  = document.getElementById('btnKonfirmReset');
    var msg  = document.getElementById('msgKonfirmReset');
    var inp  = document.getElementById('inputKonfirmReset');
    var hidden = document.getElementById('hiddenKonfirm');
    if (val === _namaKelasKonfirm) {
        btn.disabled = false;
        btn.style.opacity = '1';
        inp.style.borderColor = '#16a34a';
        msg.innerHTML = '<span style="color:#16a34a;"><i class="fas fa-check-circle"></i> Konfirmasi sesuai</span>';
        hidden.value = val;
    } else {
        btn.disabled = true;
        btn.style.opacity = '.4';
        inp.style.borderColor = val.length > 0 ? '#ef4444' : 'var(--border)';
        msg.innerHTML = val.length > 0 ? '<span style="color:#ef4444;"><i class="fas fa-times-circle"></i> Nama kelas tidak sesuai</span>' : '';
        hidden.value = '';
    }
}

// Tutup modal klik di luar
document.getElementById('modalResetSemua').addEventListener('click', function(e){
    if (e.target === this) tutupMModalResetSemua();
});

// Tekan Escape untuk tutup
document.addEventListener('keydown', function(e){
    if (e.key === 'Escape') tutupMModalResetSemua();
});
</script>

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