<?php
/**
 * SisPen Snesaka - Input Nilai Ekstrakurikuler
 * Akses: Admin → semua ekskul
 *        Pembina → hanya ekskul yang dibina
 *        Guru lain → akses ditolak
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle  = 'Nilai Ekstrakurikuler';
$activeMenu = 'ekstra';
$pengaturan = getPengaturan();
$ta         = $pengaturan['tahun_ajaran_aktif'];
$sem        = $pengaturan['semester_aktif'];
$isAdmin    = $_SESSION['role'] === 'admin';
$guruId     = $_SESSION['guru_id'] ?? 0;

// ── Tentukan ekskul yang boleh diakses ──────────────────────
if ($isAdmin) {
    // Admin: semua ekskul aktif
    $ekstraList = db_fetchAll(
        "SELECT e.*, g.nama as nama_pembina
         FROM ekstrakurikuler e
         LEFT JOIN guru g ON g.id=e.pembina_id
         WHERE e.status='aktif' ORDER BY e.nama"
    );
    $isPembina = false;
} elseif ($guruId) {
    // Cek apakah guru ini jadi pembina ekskul manapun
    $ekstraList = db_fetchAll(
        "SELECT e.*, g.nama as nama_pembina
         FROM ekstrakurikuler e
         LEFT JOIN guru g ON g.id=e.pembina_id
         WHERE e.status='aktif' AND e.pembina_id=?
         ORDER BY e.nama",
        [$guruId]
    );
    $isPembina = !empty($ekstraList);

    if (!$isPembina) {
        // Guru biasa, bukan pembina → tolak
        include '../../templates/header.php';
        ?>
        <div class="card">
          <div class="card-body" style="text-align:center;padding:60px 40px;">
            <div style="font-size:56px;margin-bottom:16px;">🚫</div>
            <h3 style="color:#dc2626;margin-bottom:8px;">Akses Ditolak</h3>
            <p style="color:var(--text-muted);font-size:14px;line-height:1.8;">
              Halaman ini hanya dapat diakses oleh:<br>
              <strong>Administrator</strong> atau <strong>Pembina Ekstrakurikuler</strong>.
            </p>
            <a href="<?= BASE_URL ?>/guru.php" class="btn btn-outline" style="margin-top:16px;">
              <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
            </a>
          </div>
        </div>
        <?php
        include '../../templates/footer.php';
        exit;
    }
} else {
    $ekstraList = [];
    $isPembina  = false;
}

// ── Handle bulk save ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_save'])) {
    $ekstraId = intval($_POST['ekstra_id']);

    // Validasi: pastikan ekstraId ada di daftar yang boleh diakses
    $ekstraIds = array_column($ekstraList, 'id');
    if (!in_array($ekstraId, $ekstraIds)) {
        setFlash('danger', 'Anda tidak berhak mengisi nilai ekskul ini.');
        header('Location: nilai.php');
        exit;
    }

    $rows = $_POST['rows'] ?? array();
    foreach ($rows as $siswaId => $val) {
        $siswaId  = intval($siswaId);
        $predikat = in_array($val['predikat'], array('A','B','C','D')) ? $val['predikat'] : null;
        $ket      = sanitize($val['keterangan'] ?? '');

        if (!$predikat) continue;

        $existing = db_fetch(
            "SELECT id FROM nilai_ekstra WHERE siswa_id=? AND ekstra_id=? AND tahun_ajaran=? AND semester=?",
            [$siswaId, $ekstraId, $ta, $sem]
        );
        if ($existing) {
            db_update('nilai_ekstra',
                array('predikat'=>$predikat,'keterangan'=>$ket),
                'id=:id', array('id'=>$existing['id'])
            );
        } else {
            db_insert('nilai_ekstra', array(
                'siswa_id'     => $siswaId,
                'ekstra_id'    => $ekstraId,
                'tahun_ajaran' => $ta,
                'semester'     => $sem,
                'predikat'     => $predikat,
                'keterangan'   => $ket,
            ));
        }
    }
    setFlash('success', 'Nilai ekstrakurikuler berhasil disimpan.');
    header('Location: nilai.php?ekstra_id='.$ekstraId.'&kelas_id='.intval($_POST['kelas_id']));
    exit;
}

// ── Ambil data ──────────────────────────────────────────────
$ekstraId = intval($_GET['ekstra_id'] ?? 0);
$kelasId  = intval($_GET['kelas_id']  ?? 0);

// Auto-pilih jika pembina hanya punya 1 ekskul
if (!$ekstraId && $isPembina && count($ekstraList) === 1) {
    $ekstraId = $ekstraList[0]['id'];
}

$kelasList = db_fetchAll(
    "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
    [$ta, $sem]
);

$siswaList      = array();
$selectedEkstra = null;
$selectedKelas  = null;

if ($ekstraId && $kelasId) {
    // Validasi akses ke ekskul ini
    $ekstraIds = array_column($ekstraList, 'id');
    if (!in_array($ekstraId, $ekstraIds)) {
        setFlash('danger', 'Anda tidak berhak mengakses ekskul ini.');
        header('Location: nilai.php');
        exit;
    }

    $selectedEkstra = db_fetch(
        "SELECT e.*, g.nama as nama_pembina FROM ekstrakurikuler e
         LEFT JOIN guru g ON g.id=e.pembina_id WHERE e.id=?",
        [$ekstraId]
    );
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);

    $siswaList = db_fetchAll("
        SELECT s.id, s.nis, s.nama, s.jenis_kelamin,
               ne.predikat, ne.keterangan as ket_ekstra
        FROM siswa s
        LEFT JOIN nilai_ekstra ne ON ne.siswa_id=s.id
            AND ne.ekstra_id=? AND ne.tahun_ajaran=? AND ne.semester=?
        WHERE s.kelas_id=? AND s.status='aktif'
        ORDER BY s.nama
    ", [$ekstraId, $ta, $sem, $kelasId]);
}

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

<!-- Info role -->
<div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding:10px 16px;
            background:var(--surface);border:1px solid var(--border);border-radius:10px;font-size:13px;flex-wrap:wrap;">
  <i class="fas fa-<?= $isAdmin?'shield-alt':'star' ?>" style="color:var(--primary);"></i>
  <span>Login sebagai <strong><?= htmlspecialchars($_SESSION['nama'] ?? '') ?></strong></span>
  <span class="badge <?= $isAdmin?'badge-blue':'badge-warning' ?>">
    <?= $isAdmin ? 'Administrator' : 'Pembina Ekskul' ?>
  </span>
  <?php if ($isPembina && !$isAdmin): ?>
  <span style="color:var(--text-muted);">— hanya ekskul yang Anda bina:</span>
  <?php foreach ($ekstraList as $e): ?>
  <span class="badge badge-success" style="font-size:11px;"><?= htmlspecialchars($e['nama']) ?></span>
  <?php endforeach; ?>
  <?php endif; ?>
</div>

<!-- Filter -->
<div class="card" 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:220px;flex:2;">
        <label class="form-label">Ekstrakurikuler</label>
        <select name="ekstra_id" class="form-control" onchange="this.form.submit()">
          <option value="">-- Pilih Ekstrakurikuler --</option>
          <?php foreach ($ekstraList as $e): ?>
          <option value="<?= $e['id'] ?>" <?= $ekstraId==$e['id']?'selected':'' ?>>
            <?= htmlspecialchars($e['nama']) ?>
            <?php if ($isAdmin && $e['nama_pembina']): ?>
            (Pembina: <?= htmlspecialchars($e['nama_pembina']) ?>)
            <?php endif; ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div style="min-width:180px;flex:1;">
        <label class="form-label">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>
      <?php if ($ekstraId): ?><input type="hidden" name="ekstra_id" value="<?= $ekstraId ?>"><?php endif; ?>
    </form>
  </div>
</div>

<?php if ($ekstraId && $kelasId && $selectedEkstra && $selectedKelas): ?>
<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-trophy" style="color:var(--accent);margin-right:8px;"></i>
      <?= htmlspecialchars($selectedEkstra['nama']) ?> &mdash;
      <?= htmlspecialchars($selectedKelas['nama_kelas']) ?>
      <?php if ($selectedEkstra['nama_pembina']): ?>
      <span style="font-size:12px;font-weight:400;color:var(--text-muted);margin-left:8px;">
        <i class="fas fa-user-tie"></i> Pembina: <?= htmlspecialchars($selectedEkstra['nama_pembina']) ?>
      </span>
      <?php endif; ?>
    </span>
    <div style="font-size:12px;color:var(--text-muted);">
      <strong style="color:#16a34a;">SB</strong>=Sangat Baik &nbsp;
      <strong style="color:#2563a8;">B</strong>=Baik &nbsp;
      <strong style="color:#d97706;">C</strong>=Cukup &nbsp;
      <strong style="color:#dc2626;">D</strong>=Kurang
    </div>
  </div>

  <form method="POST">
    <input type="hidden" name="bulk_save" value="1">
    <input type="hidden" name="ekstra_id" value="<?= $ekstraId ?>">
    <input type="hidden" name="kelas_id"  value="<?= $kelasId ?>">

    <div style="overflow-x:auto;">
      <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <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 8px;text-align:center;width:80px;">NIS</th>
            <th style="padding:10px 8px;text-align:center;width:120px;">Predikat</th>
            <th style="padding:10px 8px;min-width:200px;">Keterangan</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($siswaList)): ?>
          <tr><td colspan="5" style="text-align:center;padding:32px;color:var(--text-muted);">Belum ada siswa</td></tr>
          <?php else: ?>
          <?php foreach ($siswaList as $idx => $s): ?>
          <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 6px;text-align:center;">
              <code style="font-size:11px;"><?= $s['nis'] ?></code>
            </td>
            <td style="padding:6px;text-align:center;">
              <select name="rows[<?= $s['id'] ?>][predikat]"
                      style="width:90px;padding:5px 8px;border:1px solid var(--border);border-radius:6px;font-size:13px;font-weight:700;text-align:center;">
                <option value="">-</option>
                <?php foreach (['SB'=>'#16a34a','B'=>'#2563a8','C'=>'#d97706','D'=>'#dc2626'] as $p=>$col): ?>
                <option value="<?= $p ?>" <?= ($s['predikat']??'')===$p?'selected':'' ?>
                        style="color:<?= $col ?>;"><?= $p ?></option>
                <?php endforeach; ?>
              </select>
            </td>
            <td style="padding:6px 8px;">
              <input type="text" name="rows[<?= $s['id'] ?>][keterangan]"
                     value="<?= htmlspecialchars($s['ket_ekstra'] ?? '') ?>"
                     placeholder="Catatan prestasi..."
                     style="width:100%;padding:5px 8px;border:1px solid var(--border);border-radius:6px;font-size:12px;">
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if (!empty($siswaList)): ?>
    <div style="padding:16px 20px;border-top:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
      <div style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-info-circle"></i> Biarkan kosong untuk siswa yang tidak ikut ekstrakurikuler ini.
      </div>
      <button type="submit" class="btn btn-primary">
        <i class="fas fa-save"></i> Simpan Nilai
      </button>
    </div>
    <?php endif; ?>
  </form>
</div>

<?php else: ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-trophy" style="font-size:48px;display:block;margin-bottom:14px;opacity:.2;"></i>
    <p>Pilih ekstrakurikuler dan kelas untuk menginput nilai.</p>
    <?php if (empty($ekstraList) && $isAdmin): ?>
    <a href="list.php" class="btn btn-primary" style="margin-top:12px;">
      <i class="fas fa-plus"></i> Tambah Ekstrakurikuler Dulu
    </a>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

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