<?php
session_start();
if (!isset($_SESSION['id_admin'])) {
    header('Location: login_admin.php');
    exit;
}

include 'includes/config.php';
include 'includes/header.php';
include 'includes/sidebar_admin.php';

$id = $_GET['id'] ?? 0;
if (!$id) {
    die("ID admin tidak sah.");
}

// Dapatkan maklumat admin
$stmt = mysqli_prepare($conn, "SELECT nama, no_ic, jawatan, no_telefon, unit_jabatan, jenis_admin FROM admin WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$admin = mysqli_fetch_assoc($result);

if (!$admin) {
    die("Admin tidak ditemui.");
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama = trim($_POST['nama']);
    $no_ic = trim($_POST['no_ic']);
    $jawatan = trim($_POST['jawatan']);
    $no_telefon = trim($_POST['no_telefon']);
    $unit_jabatan = trim($_POST['unit_jabatan']);

    $stmt = mysqli_prepare($conn, "UPDATE admin SET nama = ?, no_ic = ?, jawatan = ?, no_telefon = ?, unit_jabatan = ? WHERE id = ?");
    mysqli_stmt_bind_param($stmt, 'sssssi', $nama, $no_ic, $jawatan, $no_telefon, $unit_jabatan, $id);

    if (mysqli_stmt_execute($stmt)) {
        echo "<script>alert('Maklumat admin berjaya dikemaskini.'); window.location='senarai_admin.php';</script>";
        exit;
    } else {
        $error = "Ralat: Tidak dapat kemaskini maklumat.";
    }
}
?>

<div style="margin-left:200px; padding:100px 20px;">
    <h2>Edit Maklumat Admin</h2>
    <?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <form method="post" style="max-width: 500px;">
        <div class="mb-3">
            <label>Nama Penuh</label>
            <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($admin['nama']) ?>" required>
        </div>
        <div class="mb-3">
            <label>No. Kad Pengenalan</label>
            <input type="text" name="no_ic" class="form-control" value="<?= htmlspecialchars($admin['no_ic']) ?>" required>
        </div>
        <div class="mb-3">
            <label>Jawatan</label>
            <input type="text" name="jawatan" class="form-control" value="<?= htmlspecialchars($admin['jawatan']) ?>" required>
        </div>
        <div class="mb-3">
            <label>No. Telefon</label>
            <input type="text" name="no_telefon" class="form-control" value="<?= htmlspecialchars($admin['no_telefon']) ?>" required>
        </div>
        <div class="mb-3">
            <label>Unit / Jabatan</label>
            <input type="text" name="unit_jabatan" class="form-control" value="<?= htmlspecialchars($admin['unit_jabatan']) ?>" required>
        </div>
        <button type="submit" class="btn btn-primary">Kemaskini</button>
        <a href="senarai_admin.php" class="btn btn-secondary">Batal</a>
    </form>
</div>

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