<?php
require_once '../../includes/functions.php';
requireAdmin();
$pageTitle = 'Data Guru';
$activeMenu = 'guru';

$search = trim($_GET['search'] ?? '');
$params = [];
$where = "WHERE 1=1";
if ($search) {
    $where .= " AND (g.nama LIKE ? OR g.nip LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

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

$total = db_fetch("SELECT COUNT(*) as c FROM guru g $where", $params)['c'];
$gurus = db_fetchAll("SELECT g.*, u.username FROM guru g JOIN users u ON u.id = g.user_id $where ORDER BY g.nama", $params);

// Ambil data pengampu per guru
$pengampuMap = [];
if (!empty($gurus)) {
    $guruIds = array_column($gurus, 'id');
    $placeholders = implode(',', array_fill(0, count($guruIds), '?'));
    $pengampuRows = db_fetchAll("
        SELECT p.guru_id, m.nama_mapel, m.kode_mapel, k.nama_kelas
        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 IN ($placeholders) AND p.tahun_ajaran = ? AND p.semester = ?
        ORDER BY k.nama_kelas, m.nama_mapel
    ", array_merge($guruIds, [$ta, $sem]));

    foreach ($pengampuRows as $row) {
        $pengampuMap[$row['guru_id']][] = $row;
    }
}

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

<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-chalkboard-teacher" style="color:var(--primary);margin-right:8px;"></i>
      Data Guru
      <span class="badge badge-blue" style="margin-left:8px;"><?= $total ?> guru</span>
    </span>
    <div class="d-flex gap-8">
      <a href="add.php" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> Tambah Guru</a>
      <a href="import.php" class="btn btn-outline btn-sm"><i class="fas fa-file-upload"></i> Import CSV</a>
    </div>
  </div>

  <div class="card-body" style="border-bottom:1px solid var(--border);">
    <form method="GET" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
      <input type="text" name="search" class="form-control" style="max-width:260px;"
             placeholder="Cari nama / NIP..." value="<?= htmlspecialchars($search) ?>">
      <button type="submit" class="btn btn-outline btn-sm"><i class="fas fa-search"></i> Cari</button>
      <a href="list.php" class="btn btn-outline btn-sm"><i class="fas fa-times"></i> Reset</a>
      <span style="margin-left:auto;font-size:12px;color:var(--text-muted);">
        <i class="fas fa-info-circle"></i> TA <?= $ta ?> &bull; Semester <?= $sem ?>
      </span>
    </form>
  </div>

  <div class="table-responsive">
    <table class="table" id="mainTable">
      <thead>
        <tr>
          <th width="40">No</th>
          <th>NIP</th>
          <th>Nama Guru</th>
          <th>L/P</th>
          <th>Mengajar (Mapel &amp; Kelas)</th>
          <th>Username</th>
          <th>Status</th>
          <th width="130">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($gurus)): ?>
        <tr>
          <td colspan="8" class="text-center" style="padding:40px;color:var(--text-muted);">
            <i class="fas fa-users-slash" style="font-size:32px;display:block;margin-bottom:10px;opacity:.3;"></i>
            Belum ada data guru
          </td>
        </tr>
        <?php else: ?>
        <?php foreach ($gurus as $i => $g): ?>
        <?php $jadwal = $pengampuMap[$g['id']] ?? []; ?>
        <tr>
          <td class="text-muted"><?= $i + 1 ?></td>
          <td><code style="font-size:12px;"><?= htmlspecialchars($g['nip'] ?? '-') ?></code></td>
          <td>
            <strong><?= htmlspecialchars($g['nama']) ?></strong>
          </td>
          <td>
            <span class="badge <?= $g['jenis_kelamin'] === 'L' ? 'badge-info' : 'badge-warning' ?>">
              <?= $g['jenis_kelamin'] === 'L' ? 'L' : 'P' ?>
            </span>
          </td>
          <td>
            <?php if (empty($jadwal)): ?>
              <span style="color:var(--text-light);font-size:12px;font-style:italic;">
                <i class="fas fa-exclamation-circle" style="color:var(--warning);"></i>
                Belum ada Mapel dan Kelas
              </span>
            <?php else: ?>
              <div style="display:flex;flex-wrap:wrap;gap:4px;">
                <?php foreach ($jadwal as $j): ?>
                <span style="display:inline-flex;align-items:center;gap:4px;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:3px 8px;font-size:11.5px;">
                  <span style="font-weight:600;color:var(--primary);"><?= htmlspecialchars($j['kode_mapel']) ?></span>
                  <span style="color:var(--text-muted);">→</span>
                  <span class="badge badge-blue" style="padding:2px 6px;font-size:10px;"><?= htmlspecialchars($j['nama_kelas']) ?></span>
                </span>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </td>
          <td style="font-size:13px;"><?= htmlspecialchars($g['username']) ?></td>
          <td>
            <span class="badge badge-<?= $g['status'] === 'aktif' ? 'success' : 'gray' ?>">
              <?= ucfirst($g['status']) ?>
            </span>
          </td>
          <td>
            <a href="pengampu.php?guru_id=<?= $g['id'] ?>"
               class="btn btn-accent btn-xs" title="Atur Pengampu / Jadwal Mengajar">
              <i class="fas fa-chalkboard"></i> Pengampu
            </a>
            <a href="edit.php?id=<?= $g['id'] ?>" class="btn btn-outline btn-xs" title="Edit Data Guru">
              <i class="fas fa-edit"></i>
            </a>
            <a href="reset_password.php?id=<?= $g['id'] ?>" class="btn btn-warning btn-xs" title="Reset Password">
              <i class="fas fa-key"></i>
            </a>
            <a href="delete.php?id=<?= $g['id'] ?>" class="btn btn-danger btn-xs" title="Hapus Guru"
               data-confirm="Hapus guru <?= htmlspecialchars($g['nama']) ?>? Semua data pengampu juga akan terhapus.">
              <i class="fas fa-trash"></i>
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <div style="padding:12px 20px;border-top:1px solid var(--border);background:var(--surface-2);font-size:12px;color:var(--text-muted);">
    <i class="fas fa-lightbulb" style="color:var(--accent);"></i>
    Klik tombol <strong>Pengampu</strong> untuk mengatur guru mengajar mapel apa di kelas mana.
  </div>
</div>

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