<?php
require_once '../../includes/functions.php';
requireAdmin();
$pageTitle = 'Tambah Mata Pelajaran';
$activeMenu = 'mapel';
$data = [];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    if (empty($data['kode_mapel'])) $errors['kode_mapel'] = 'Kode wajib diisi';
    if (empty($data['nama_mapel'])) $errors['nama_mapel'] = 'Nama wajib diisi';

    if (empty($errors)) {
        db_insert('mata_pelajaran', [
            'kode_mapel' => sanitize($data['kode_mapel']),
            'nama_mapel' => sanitize($data['nama_mapel']),
            'urutan' => intval($data['urutan'] ?? 0),
            'status' => 'aktif',
        ]);
        setFlash('success', 'Mata pelajaran berhasil ditambahkan!');
        header('Location: list.php'); exit;
    }
}
include '../../templates/header.php';
?>
<div class="card" style="max-width:600px;">
  <div class="card-header">
    <span class="card-title">Tambah Mata Pelajaran</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 <span class="required">*</span></label>
        <input type="text" name="kode_mapel" class="form-control" value="<?= htmlspecialchars($data['kode_mapel'] ?? '') ?>" placeholder="e.g. MTK, BIN">
      </div>
      <div class="form-group">
        <label class="form-label">Nama Mata Pelajaran <span class="required">*</span></label>
        <input type="text" name="nama_mapel" class="form-control" value="<?= htmlspecialchars($data['nama_mapel'] ?? '') ?>" placeholder="Nama lengkap mata pelajaran">
      </div>
      <div class="form-group">
        <label class="form-label">Urutan Tampil</label>
        <input type="number" name="urutan" class="form-control" value="<?= $data['urutan'] ?? 0 ?>" min="0">
      </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'; ?>
