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

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

// Get location data
$stmt = $conn->prepare("SELECT * FROM pdta_lokasi WHERE id_lokasi = ?");
$stmt->bind_param("i", $id_lokasi);
$stmt->execute();
$result = $stmt->get_result();
$lokasi = $result->fetch_assoc();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama_lokasi = $_POST['nama_lokasi'];
    
    // Check if location already exists (excluding current one)
    $check = $conn->prepare("SELECT id_lokasi FROM pdta_lokasi WHERE nama_lokasi = ? AND id_lokasi != ?");
    $check->bind_param("si", $nama_lokasi, $id_lokasi);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Lokasi sudah ada";
    } else {
        $stmt = $conn->prepare("UPDATE pdta_lokasi SET nama_lokasi = ? WHERE id_lokasi = ?");
        $stmt->bind_param("si", $nama_lokasi, $id_lokasi);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Data lokasi berhasil diperbarui!";
            header("Location: index.php");
            exit();
        } else {
            $_SESSION['error'] = "Gagal memperbarui data lokasi: " . $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 Lokasi</h4>
        </div>
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label for="nama_lokasi" class="form-label">Nama Lokasi <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="nama_lokasi" name="nama_lokasi" 
                           value="<?= htmlspecialchars($lokasi['nama_lokasi']) ?>" 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'; ?>