<?php
require_once '../../config/database.php';
require_once '../../includes/auth.php';

$id_jenis = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get item type data
$stmt = $conn->prepare("SELECT * FROM pdta_jenis_barang WHERE id_jenis = ?");
$stmt->bind_param("i", $id_jenis);
$stmt->execute();
$result = $stmt->get_result();
$jenis = $result->fetch_assoc();

if (!$jenis) {
    $_SESSION['error'] = "Data jenis barang tidak ditemukan";
    header("Location: index.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama_jenis = $_POST['nama_jenis'];
    
    // Check if item type already exists (excluding current one)
    $check = $conn->prepare("SELECT id_jenis FROM pdta_jenis_barang WHERE nama_jenis = ? AND id_jenis != ?");
    $check->bind_param("si", $nama_jenis, $id_jenis);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Jenis barang sudah ada";
    } else {
        $stmt = $conn->prepare("UPDATE pdta_jenis_barang SET nama_jenis = ? WHERE id_jenis = ?");
        $stmt->bind_param("si", $nama_jenis, $id_jenis);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Data jenis barang berhasil diperbarui!";
            header("Location: index.php");
            exit();
        } else {
            $_SESSION['error'] = "Gagal memperbarui data jenis barang: " . $conn->error;
        }
    }
}
?>

<?php include '../../includes/header.php'; ?>
<?php include '../../includes/navbar.php'; ?>

<div class="container mt-4">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"><i class="bi bi-pencil-square"></i> Edit Jenis Barang</h4>
        </div>
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label for="nama_jenis" class="form-label">Nama Jenis <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="nama_jenis" name="nama_jenis" 
                           value="<?= htmlspecialchars($jenis['nama_jenis']) ?>" required>
                </div>
                
                <div class="d-flex justify-content-between mt-4">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i> Kembali
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../../assets/js/jquery.min.js"></script>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>

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