<?php include __DIR__ . '/../../views/layouts/header.php'; ?>
<div class="wrapper">
<?php include __DIR__ . '/../../views/layouts/sidebar.php'; ?>
<div class="main-content">
<?php include __DIR__ . '/../../views/layouts/topbar.php'; ?>

<div class="page-content">
  <div class="page-header">
    <h1><i class="bi bi-pencil-square me-2 text-primary"></i>Input Nilai Rapor</h1>
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/index.php?page=nilai">Nilai Rapor</a></li>
        <li class="breadcrumb-item active">Input Nilai</li>
      </ol>
    </nav>
  </div>

  <?php if ($flash): ?>
  <div class="alert alert-<?= $flash['type'] ?> alert-dismissible alert-auto-dismiss fade show">
    <i class="bi bi-check-circle-fill me-2"></i><?= e($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  <?php endif; ?>

  <?php if (!empty($errors)): ?>
  <div class="alert alert-danger">
    <?php foreach ($errors as $err): ?><div><?= e($err) ?></div><?php endforeach; ?>
  </div>
  <?php endif; ?>

  <!-- Filter Kelas & Mapel -->
  <div class="search-bar mb-3">
    <form method="GET" class="row g-2 align-items-end">
      <input type="hidden" name="page" value="nilai_input">
      <div class="col-12 col-md-3">
        <label class="form-label mb-1">Kelas <span class="text-danger">*</span></label>
        <select class="form-select" name="kelas_id" onchange="this.form.submit()">
          <option value="">-- Pilih Kelas --</option>
          <?php foreach ($kelasList as $k): ?>
          <option value="<?= $k['id'] ?>" <?= $kelasId == $k['id'] ? 'selected' : '' ?>>
            <?= e($k['nama_kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($kelasId): ?>
      <div class="col-12 col-md-3">
        <label class="form-label mb-1">Mata Pelajaran <span class="text-danger">*</span></label>
        <select class="form-select" name="mapel_id" onchange="this.form.submit()">
          <option value="">-- Pilih Mapel --</option>
          <?php foreach ($mapelList as $m): ?>
          <option value="<?= $m['id'] ?>" <?= $mapelId == $m['id'] ? 'selected' : '' ?>>
            <?= e($m['nama']) ?><?= !empty($m['nama_guru']) ? ' — ' . e($m['nama_guru']) : '' ?> (KKM: <?= $m['kkm'] ?>)
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label mb-1">Semester</label>
        <select class="form-select" name="semester_no" onchange="this.form.submit()">
          <?php foreach ($semesterList as $no => $label): ?>
          <option value="<?= $no ?>" <?= $semesterNo == $no ? 'selected' : '' ?>>
            Semester <?= $no ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label mb-1">Tahun Ajaran</label>
        <input type="text" class="form-control" name="tahun_ajaran"
               value="<?= e($tahunAjaran) ?>" placeholder="2024/2025">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary">
          <i class="bi bi-arrow-clockwise"></i>
        </button>
      </div>
      <?php endif; ?>
    </form>
  </div>

  <?php if ($kelasId && $mapelId && !empty($siswaList)): ?>
  <!-- Form Input Nilai -->
  <div class="card">
    <div class="card-header">
      <h6 class="mb-0">
        <i class="bi bi-pencil me-2"></i>
        Input Nilai Rapor
        <?php
        $selectedMapel = null;
        foreach ($mapelList as $m) { if ($m['id'] == $mapelId) { $selectedMapel = $m; break; } }
        ?>
        <?php if ($selectedMapel): ?>
        — <span class="text-primary"><?= e($selectedMapel['nama']) ?></span>
        &nbsp;|&nbsp; Semester <?= $semesterNo ?>
        &nbsp;|&nbsp; KKM: <strong><?= $selectedMapel['kkm'] ?></strong>
        <?php endif; ?>
      </h6>
    </div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="csrf_token"    value="<?= e($csrfToken) ?>">
        <input type="hidden" name="kelas_id"      value="<?= $kelasId ?>">
        <input type="hidden" name="mapel_id"      value="<?= $mapelId ?>">
        <input type="hidden" name="tahun_ajaran"  value="<?= e($tahunAjaran) ?>">
        <input type="hidden" name="semester_no"   value="<?= $semesterNo ?>">

        <div class="table-responsive">
          <table class="table">
            <thead>
              <tr>
                <th style="width:50px">No</th>
                <th>Nama Siswa</th>
                <th>NIS</th>
                <th style="width:160px">
                  Nilai Rapor
                  <span class="text-muted fw-400" style="font-size:.75rem;">(0–100)</span>
                </th>
                <th style="width:80px" class="text-center">Predikat</th>
                <th style="width:160px">Keterangan</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($siswaList as $i => $s):
                $existing = $existingNilai[$s['id']] ?? null;
                $nilaiVal = $existing ? $existing['nilai_rapor'] : '';
                $predikat = $existing ? $existing['predikat'] : '';
                $ket      = $existing ? $existing['keterangan'] : '';
                $kkm      = $selectedMapel ? $selectedMapel['kkm'] : 70;
                $lulus    = $nilaiVal !== '' && (float)$nilaiVal >= $kkm;
              ?>
              <tr>
                <td class="text-muted"><?= $i + 1 ?></td>
                <td class="fw-600"><?= e($s['nama']) ?></td>
                <td class="text-muted"><?= e($s['nis'] ?? '-') ?></td>
                <td>
                  <input type="number"
                         class="form-control form-control-sm nilai-input"
                         name="nilai[<?= $s['id'] ?>][nilai_rapor]"
                         value="<?= e($nilaiVal) ?>"
                         min="0" max="100" step="0.01"
                         placeholder="0–100"
                         data-kkm="<?= $kkm ?>"
                         data-idx="<?= $s['id'] ?>">
                </td>
                <td class="text-center">
                  <span class="badge predikat-badge-<?= $s['id'] ?>
                    <?= $nilaiVal !== '' ? ($lulus ? 'bg-success' : 'bg-danger') : 'bg-secondary' ?>">
                    <?= $predikat ?: '-' ?>
                  </span>
                </td>
                <td>
                  <input type="text" class="form-control form-control-sm"
                         name="nilai[<?= $s['id'] ?>][keterangan]"
                         value="<?= e($ket) ?>"
                         placeholder="Opsional">
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <div class="d-flex gap-2 mt-3">
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-save me-1"></i> Simpan Nilai Rapor
          </button>
          <a href="<?= BASE_URL ?>/index.php?page=nilai&kelas_id=<?= $kelasId ?>&semester_no=<?= $semesterNo ?>&tahun_ajaran=<?= urlencode($tahunAjaran) ?>"
             class="btn btn-outline-secondary">
            Lihat Semua Nilai
          </a>
        </div>
      </form>
    </div>
  </div>

  <?php elseif ($kelasId && !$mapelId): ?>
  <div class="empty-state card py-4">
    <div class="empty-icon">📚</div>
    <p>Pilih <strong>Mata Pelajaran</strong> untuk mulai input nilai</p>
  </div>
  <?php else: ?>
  <div class="empty-state card py-4">
    <div class="empty-icon">🏫</div>
    <p>Pilih <strong>Kelas</strong> terlebih dahulu</p>
  </div>
  <?php endif; ?>
</div>

<?php
$extraJs = '<script>
// Auto-update predikat saat nilai diketik
document.querySelectorAll(".nilai-input").forEach(function(input) {
    input.addEventListener("input", function() {
        var val  = parseFloat(this.value);
        var kkm  = parseFloat(this.dataset.kkm) || 70;
        var idx  = this.dataset.idx;
        var badge = document.querySelector(".predikat-badge-" + idx);
        if (!badge) return;
        if (isNaN(val) || this.value === "") {
            badge.textContent = "-";
            badge.className = "badge bg-secondary predikat-badge-" + idx;
            return;
        }
        var pred = val >= 90 ? "A" : val >= 80 ? "B" : val >= 70 ? "C" : "D";
        var cls  = val >= kkm ? "bg-success" : "bg-danger";
        badge.textContent = pred;
        badge.className = "badge " + cls + " predikat-badge-" + idx;
    });
});
</script>';
?>

<?php include __DIR__ . '/../../views/layouts/footer.php'; ?>
</div>
</div>
