<?php
require_once '../../includes/functions.php';
requireAdmin();
$id = intval($_GET['id'] ?? 0);
$kelas = db_fetch("SELECT * FROM kelas WHERE id = ?", [$id]);
if (!$kelas) { setFlash('danger', 'Kelas tidak ditemukan'); header('Location: list.php'); exit; }
$pageTitle = 'Edit Kelas';
$activeMenu = 'kelas';
$guruList = db_fetchAll("SELECT * FROM guru WHERE status='aktif' ORDER BY nama");
$data = $kelas;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    db_update('kelas', [
        'nama_kelas' => sanitize($data['nama_kelas']),
        'tingkat' => $data['tingkat'],
        'wali_kelas_id' => $data['wali_kelas_id'] ?: null,
        'kapasitas' => intval($data['kapasitas'] ?? 32),
    ], 'id = :id', ['id' => $id]);
    setFlash('success', 'Kelas berhasil diperbarui!');
    header('Location: list.php'); exit;
}
include '../../templates/header.php';
?>
<div class="card" style="max-width:600px;">
  <div class="card-header">
    <span class="card-title">Edit Kelas: <?= htmlspecialchars($kelas['nama_kelas']) ?></span>
    <a href="list.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Kembali</a>
  </div>
  <div class="card-body">
    <form method="POST">
      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">Nama Kelas</label>
          <input type="text" name="nama_kelas" class="form-control" value="<?= htmlspecialchars($data['nama_kelas']) ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">Tingkat</label>
          <select name="tingkat" class="form-control">
            <option value="7" <?= $data['tingkat'] === '7' ? 'selected' : '' ?>>Kelas 7</option>
            <option value="8" <?= $data['tingkat'] === '8' ? 'selected' : '' ?>>Kelas 8</option>
            <option value="9" <?= $data['tingkat'] === '9' ? 'selected' : '' ?>>Kelas 9</option>
          </select>
        </div>
      </div>
      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">Wali Kelas</label>
          <select name="wali_kelas_id" class="form-control">
            <option value="">-- Pilih --</option>
            <?php foreach ($guruList as $g): ?>
            <option value="<?= $g['id'] ?>" <?= $data['wali_kelas_id'] == $g['id'] ? 'selected' : '' ?>><?= htmlspecialchars($g['nama']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Kapasitas</label>
          <input type="number" name="kapasitas" class="form-control" value="<?= $data['kapasitas'] ?>">
        </div>
      </div>
      <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        <a href="list.php" class="btn btn-outline">Batal</a>
      </div>
    </form>
  </div>
</div>
<?php include '../../templates/footer.php'; ?>
