<?php
/**
 * SISPENRA - Pengaturan Pengampu (Guru Mengajar Mapel di Kelas)
 */
require_once '../../includes/functions.php';
requireAdmin();

$guruId = intval($_GET['guru_id'] ?? 0);
$guru = db_fetch("SELECT g.*, u.username FROM guru g JOIN users u ON u.id = g.user_id WHERE g.id = ?", [$guruId]);
if (!$guru) {
    setFlash('danger', 'Data guru tidak ditemukan.');
    header('Location: list.php'); exit;
}

$pageTitle = 'Pengaturan Pengampu';
$activeMenu = 'guru';

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

$mapelList = db_fetchAll("SELECT * FROM mata_pelajaran WHERE status = 'aktif' ORDER BY kelompok, urutan, nama_mapel");
$kelasList = db_fetchAll("SELECT * FROM kelas WHERE tahun_ajaran = ? AND semester = ? ORDER BY tingkat, nama_kelas", [$ta, $sem]);

// Handle TAMBAH pengampu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    if ($_POST['action'] === 'tambah') {
        $mapelId = intval($_POST['mapel_id'] ?? 0);
        $kelasId = intval($_POST['kelas_id'] ?? 0);

        if (!$mapelId || !$kelasId) {
            setFlash('danger', 'Pilih mata pelajaran dan kelas terlebih dahulu.');
        } else {
            // Cek apakah sudah ada
            $existing = db_fetch(
                "SELECT id FROM pengampu WHERE guru_id=? AND mapel_id=? AND kelas_id=? AND tahun_ajaran=? AND semester=?",
                [$guruId, $mapelId, $kelasId, $ta, $sem]
            );
            if ($existing) {
                setFlash('warning', 'Pengampu sudah ada untuk kombinasi ini.');
            } else {
                db_insert('pengampu', [
                    'guru_id'      => $guruId,
                    'mapel_id'     => $mapelId,
                    'kelas_id'     => $kelasId,
                    'tahun_ajaran' => $ta,
                    'semester'     => $sem,
                ]);
                setFlash('success', 'Pengampu berhasil ditambahkan!');
            }
        }
        header("Location: pengampu.php?guru_id=$guruId"); exit;
    }

    if ($_POST['action'] === 'hapus') {
        $pengampuId = intval($_POST['pengampu_id'] ?? 0);
        db_query("DELETE FROM pengampu WHERE id = ? AND guru_id = ?", [$pengampuId, $guruId]);
        setFlash('success', 'Pengampu berhasil dihapus.');
        header("Location: pengampu.php?guru_id=$guruId"); exit;
    }

    if ($_POST['action'] === 'hapus_semua') {
        db_query("DELETE FROM pengampu WHERE guru_id = ? AND tahun_ajaran = ? AND semester = ?", [$guruId, $ta, $sem]);
        setFlash('success', 'Semua pengampu semester ini berhasil dihapus.');
        header("Location: pengampu.php?guru_id=$guruId"); exit;
    }
}

// Ambil pengampu aktif guru ini
$pengampuAktif = db_fetchAll("
    SELECT p.*, m.nama_mapel, m.kode_mapel, m.kelompok, k.nama_kelas, k.tingkat,
           (SELECT COUNT(*) FROM siswa s WHERE s.kelas_id = k.id AND s.status='aktif') as jumlah_siswa,
           (SELECT COUNT(*) FROM nilai n WHERE n.guru_id = ? AND n.mapel_id = p.mapel_id AND n.kelas_id = p.kelas_id AND n.tahun_ajaran = ? AND n.semester = ?) as sudah_input
    FROM pengampu p
    JOIN mata_pelajaran m ON m.id = p.mapel_id
    JOIN kelas k ON k.id = p.kelas_id
    WHERE p.guru_id = ? AND p.tahun_ajaran = ? AND p.semester = ?
    ORDER BY k.tingkat, k.nama_kelas, m.kelompok, m.urutan
", [$guruId, $ta, $sem, $guruId, $ta, $sem]);

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

<!-- Breadcrumb info guru -->
<div style="background:linear-gradient(135deg,var(--primary-dark),var(--primary));border-radius:10px;padding:18px 24px;margin-bottom:20px;color:#fff;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">
  <div style="display:flex;align-items:center;gap:14px;">
    <div style="width:48px;height:48px;background:rgba(255,255,255,.15);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0;">
      <i class="fas fa-user-tie"></i>
    </div>
    <div>
      <div style="font-size:17px;font-weight:700;"><?= htmlspecialchars($guru['nama']) ?></div>
      <div style="font-size:12px;opacity:.75;">
        NIP: <?= htmlspecialchars($guru['nip'] ?? '-') ?> &bull;
        Username: <?= htmlspecialchars($guru['username']) ?> &bull;
        TA <?= $ta ?> / Semester <?= $sem ?>
      </div>
    </div>
  </div>
  <a href="list.php" class="btn btn-outline btn-sm" style="color:#fff;border-color:rgba(255,255,255,.4);">
    <i class="fas fa-arrow-left"></i> Kembali
  </a>
</div>

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

  <!-- FORM TAMBAH -->
  <div class="card">
    <div class="card-header">
      <span class="card-title"><i class="fas fa-plus-circle" style="color:var(--success);margin-right:8px;"></i>Tambah Pengampu</span>
    </div>
    <div class="card-body">
      <form method="POST" action="">
        <input type="hidden" name="action" value="tambah">

        <div class="form-group">
          <label class="form-label">Mata Pelajaran <span class="required">*</span></label>
          <select name="mapel_id" class="form-control" required>
            <option value="">-- Pilih Mata Pelajaran --</option>
            <?php
            $kelompokSaja = '';
            foreach ($mapelList as $m):
                if ($m['kelompok'] !== $kelompokSaja):
                    if ($kelompokSaja) echo '</optgroup>';
                    $namaKelompok = ['A' => 'Kelompok A - Wajib Nasional', 'B' => 'Kelompok B - Wajib Daerah', 'C' => 'Kelompok C - Muatan Lokal'];
                    echo '<optgroup label="' . ($namaKelompok[$m['kelompok']] ?? $m['kelompok']) . '">';
                    $kelompokSaja = $m['kelompok'];
                endif;
            ?>
            <option value="<?= $m['id'] ?>">[<?= htmlspecialchars($m['kode_mapel']) ?>] <?= htmlspecialchars($m['nama_mapel']) ?></option>
            <?php endforeach; ?>
            <?php if ($kelompokSaja) echo '</optgroup>'; ?>
          </select>
        </div>

        <div class="form-group">
          <label class="form-label">Kelas <span class="required">*</span></label>
          <select name="kelas_id" class="form-control" required>
            <option value="">-- Pilih Kelas --</option>
            <?php
            $tingkatSaja = '';
            foreach ($kelasList as $k):
                if ($k['tingkat'] !== $tingkatSaja):
                    if ($tingkatSaja) echo '</optgroup>';
                    echo '<optgroup label="Kelas ' . $k['tingkat'] . '">';
                    $tingkatSaja = $k['tingkat'];
                endif;
            ?>
            <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama_kelas']) ?></option>
            <?php endforeach; ?>
            <?php if ($tingkatSaja) echo '</optgroup>'; ?>
          </select>
        </div>

        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;">
          <i class="fas fa-plus"></i> Tambahkan
        </button>
      </form>

      <?php if (!empty($pengampuAktif)): ?>
      <hr style="border:none;border-top:1px solid var(--border);margin:16px 0;">
      <form method="POST" onsubmit="return confirm('Hapus SEMUA pengampu semester ini?')">
        <input type="hidden" name="action" value="hapus_semua">
        <button type="submit" class="btn btn-danger btn-sm" style="width:100%;justify-content:center;">
          <i class="fas fa-trash-alt"></i> Hapus Semua Semester Ini
        </button>
      </form>
      <?php endif; ?>

      <div style="margin-top:14px;padding:10px 12px;background:var(--bg);border-radius:8px;font-size:12px;color:var(--text-muted);line-height:1.6;">
        <i class="fas fa-info-circle" style="color:var(--info);"></i>
        Pengampu menentukan guru mana yang bisa input nilai untuk mapel di kelas tertentu.
      </div>
    </div>
  </div>

  <!-- DAFTAR PENGAMPU -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-list" style="color:var(--primary);margin-right:8px;"></i>
        Jadwal Mengajar Aktif
        <span class="badge badge-blue" style="margin-left:8px;"><?= count($pengampuAktif) ?> pengampu</span>
      </span>
    </div>

    <?php if (empty($pengampuAktif)): ?>
    <div style="padding:48px;text-align:center;color:var(--text-muted);">
      <i class="fas fa-chalkboard" style="font-size:40px;display:block;margin-bottom:12px;opacity:.25;"></i>
      <p style="font-size:14px;">Guru ini belum memiliki jadwal mengajar.</p>
      <p style="font-size:12px;margin-top:4px;">Gunakan form di sebelah kiri untuk menambahkan.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>Mata Pelajaran</th>
            <th>Kelas</th>
            <th>Kel.</th>
            <th style="text-align:center;">Jml Siswa</th>
            <th style="text-align:center;">Input Nilai</th>
            <th style="text-align:center;">Progress</th>
            <th width="80">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($pengampuAktif as $p): ?>
          <?php $pct = $p['jumlah_siswa'] > 0 ? round(($p['sudah_input'] / $p['jumlah_siswa']) * 100) : 0; ?>
          <tr>
            <td>
              <div style="font-weight:600;font-size:13px;"><?= htmlspecialchars($p['nama_mapel']) ?></div>
              <div style="font-size:11px;color:var(--text-muted);">Kode: <?= htmlspecialchars($p['kode_mapel']) ?></div>
            </td>
            <td>
              <span class="badge badge-blue"><?= htmlspecialchars($p['nama_kelas']) ?></span>
            </td>
            <td>
              <span class="badge <?= $p['kelompok'] === 'A' ? 'badge-blue' : ($p['kelompok'] === 'B' ? 'badge-success' : 'badge-warning') ?>">
                <?= $p['kelompok'] ?>
              </span>
            </td>
            <td style="text-align:center;">
              <strong><?= $p['jumlah_siswa'] ?></strong>
            </td>
            <td style="text-align:center;">
              <span style="font-weight:600;color:<?= $pct >= 100 ? 'var(--success)' : ($pct > 0 ? 'var(--primary)' : 'var(--text-muted)') ?>;">
                <?= $p['sudah_input'] ?>/<?= $p['jumlah_siswa'] ?>
              </span>
            </td>
            <td style="min-width:120px;">
              <div style="display:flex;align-items:center;gap:6px;">
                <div class="progress" style="flex:1;">
                  <div class="progress-bar" style="width:<?= $pct ?>%;background:<?= $pct >= 100 ? 'var(--success)' : 'var(--primary)' ?>;"></div>
                </div>
                <span style="font-size:11px;color:var(--text-muted);white-space:nowrap;"><?= $pct ?>%</span>
              </div>
            </td>
            <td>
              <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus pengampu ini?')">
                <input type="hidden" name="action" value="hapus">
                <input type="hidden" name="pengampu_id" value="<?= $p['id'] ?>">
                <button type="submit" class="btn btn-danger btn-xs" title="Hapus pengampu ini">
                  <i class="fas fa-times"></i>
                </button>
              </form>
              <a href="<?= BASE_URL ?>/modules/nilai/input.php?kelas_id=<?= $p['kelas_id'] ?>&mapel_id=<?= $p['mapel_id'] ?>"
                 class="btn btn-primary btn-xs" title="Input Nilai">
                <i class="fas fa-edit"></i>
              </a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Ringkasan -->
    <div style="padding:12px 20px;border-top:1px solid var(--border);background:var(--surface-2);display:flex;gap:20px;flex-wrap:wrap;">
      <?php
      $totalSiswa = array_sum(array_column($pengampuAktif, 'jumlah_siswa'));
      $totalInput = array_sum(array_column($pengampuAktif, 'sudah_input'));
      $totalPct   = $totalSiswa > 0 ? round(($totalInput / $totalSiswa) * 100) : 0;
      ?>
      <span style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-chalkboard"></i> Total: <strong><?= count($pengampuAktif) ?></strong> kelas diampu
      </span>
      <span style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-users"></i> Total siswa: <strong><?= $totalSiswa ?></strong>
      </span>
      <span style="font-size:12px;color:<?= $totalPct >= 100 ? 'var(--success)' : 'var(--primary)' ?>;">
        <i class="fas fa-check-circle"></i> Input nilai: <strong><?= $totalInput ?>/<?= $totalSiswa ?></strong> (<?= $totalPct ?>%)
      </span>
    </div>
    <?php endif; ?>
  </div>

</div>

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