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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sumber_asal = $_POST['sumber_asal'];
    
    // Check if source already exists
    $check = $conn->prepare("SELECT id_asal FROM pdta_asal_usul WHERE sumber_asal = ?");
    $check->bind_param("s", $sumber_asal);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Sumber asal sudah ada";
    } else {
        $stmt = $conn->prepare("INSERT INTO pdta_asal_usul (sumber_asal) VALUES (?)");
        $stmt->bind_param("s", $sumber_asal);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Asal usul berhasil ditambahkan!";
            header("Location: index.php");
            exit();
        } else {
            $_SESSION['error'] = "Gagal menambahkan asal usul: " . $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-plus-circle"></i> Tambah Asal Usul Barang</h4>
        </div>
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label for="sumber_asal" class="form-label">Sumber Asal <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="sumber_asal" name="sumber_asal" required>
                    <small class="text-muted">Contoh: Pembelian, Hibah, Bantuan</small>
                </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
                    </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'; ?>