<?php
require_once '../auth/cek_login.php';
require_role('admin');
require_once '../config/koneksi.php';

$id = (int)($_GET['id'] ?? 0);

if ($id <= 0) {
    die('ID mapel tidak valid');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = trim($_POST['nama_mapel'] ?? '');
    $urutan = (int)($_POST['urutan'] ?? 0);

    if ($nama !== '') {
        $stmt = $conn->prepare("
            UPDATE mapel 
            SET nama_mapel = ?, urutan = ? 
            WHERE id = ?
        ");
        $stmt->bind_param('sii', $nama, $urutan, $id);
        $stmt->execute();
    }

    header('Location: mapel.php?edit_ok=1');
    exit;
}

include 'header.php';

$stmt = $conn->prepare("SELECT * FROM mapel WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$mapel = $stmt->get_result()->fetch_assoc();

if (!$mapel) {
    die('Data mata pelajaran tidak ditemukan');
}
?>

<h3 class="fw-bold mb-3">Edit Mata Pelajaran</h3>

<form method="post" class="card p-4">

    <div class="mb-3">
        <label>Nama Mata Pelajaran</label>
        <input
            name="nama_mapel"
            class="form-control"
            value="<?= e($mapel['nama_mapel'] ?? '') ?>"
            required>
    </div>

    <div class="mb-3">
        <label>Urutan</label>
        <input
            type="number"
            name="urutan"
            class="form-control"
            value="<?= e($mapel['urutan'] ?? 0) ?>">
    </div>

    <button class="btn btn-primary">
        Update
    </button>

    <a href="mapel.php" class="btn btn-secondary">
        Kembali
    </a>

</form>

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