<?php
require_once '../../includes/functions.php';
requireAdmin();
$id = intval($_GET['id'] ?? 0);
$mapel = db_fetch("SELECT * FROM mata_pelajaran WHERE id = ?", [$id]);
if (!$mapel) { setFlash('danger', 'Data tidak ditemukan'); header('Location: list.php'); exit; }
$pageTitle = 'Edit Mata Pelajaran';
$activeMenu = 'mapel';
$data = $mapel;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    db_update('mata_pelajaran', [
        'kode_mapel' => sanitize($data['kode_mapel']),
        'nama_mapel' => sanitize($data['nama_mapel']),
        'urutan' => intval($data['urutan']),
        'status' => $data['status'],
    ], 'id = :id', ['id' => $id]);
    setFlash('success', 'Mata pelajaran 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: <?= htmlspecialchars($mapel['nama_mapel']) ?></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-group">
        <label class="form-label">Kode Mapel</label>
        <input type="text" name="kode_mapel" class="form-control" value="<?= htmlspecialchars($data['kode_mapel']) ?>">
      </div>
      <div class="form-group">
        <label class="form-label">Nama Mata Pelajaran</label>
        <input type="text" name="nama_mapel" class="form-control" value="<?= htmlspecialchars($data['nama_mapel']) ?>">
      </div>
      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">Urutan</label>
          <input type="number" name="urutan" class="form-control" value="<?= $data['urutan'] ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Status</label>
          <select name="status" class="form-control">
            <option value="aktif" <?= $data['status'] === 'aktif' ? 'selected' : '' ?>>Aktif</option>
            <option value="nonaktif" <?= $data['status'] === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
          </select>
        </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'; ?>
