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

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

// Get source data
$stmt = $conn->prepare("SELECT * FROM pdta_asal_usul WHERE id_asal = ?");
$stmt->bind_param("i", $id_asal);
$stmt->execute();
$result = $stmt->get_result();
$asal = $result->fetch_assoc();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sumber_asal = $_POST['sumber_asal'];
    
    // Check if source already exists (excluding current one)
    $check = $conn->prepare("SELECT id_asal FROM pdta_asal_usul WHERE sumber_asal = ? AND id_asal != ?");
    $check->bind_param("si", $sumber_asal, $id_asal);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Sumber asal sudah ada";
    } else {
        $stmt = $conn->prepare("UPDATE pdta_asal_usul SET sumber_asal = ? WHERE id_asal = ?");
        $stmt->bind_param("si", $sumber_asal, $id_asal);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Data asal usul berhasil diperbarui!";
            header("Location: index.php");
            exit();
        } else {
            $_SESSION['error'] = "Gagal memperbarui data 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-pencil-square"></i> Edit 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" 
                           value="<?= htmlspecialchars($asal['sumber_asal']) ?>" 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'; ?>