<?php
include '../db.php';
session_start();

// Pastikan admin sudah login
if (!isset($_SESSION['admin_id'])) {
    header('Location: login_admin.php');
    exit;
}

// Ambil Data Tempat Berdasarkan ID
$id = $_GET['id'] ?? null;

// Validasi ID
if (!$id || !is_numeric($id)) {
    echo "ID tidak valid.";
    exit;
}

$stmt = $conn->prepare("SELECT * FROM places WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$place = $result->fetch_assoc();
$stmt->close();

// Jika data tempat tidak ditemukan
if (!$place) {
    echo "Data tempat tidak ditemukan.";
    exit;
}

// Proses Update Tempat
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $lokasi = trim($_POST['lokasi']);
    $image = $place['image']; // Gambar lama

    // Proses Upload Gambar Baru
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $fileExtension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

        // Validasi ekstensi file
        if (in_array($fileExtension, $allowedExtensions)) {
            $uploadDir = __DIR__ . '/../assets/img/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true); // Membuat direktori jika belum ada
            }

            $imageName = uniqid('img_', true) . '.' . $fileExtension; // Buat nama file unik
            $imagePath = $uploadDir . $imageName;

            // Pindahkan file ke direktori target
            if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
                $image = 'assets/img/' . $imageName; // Path relatif untuk database
            } else {
                echo "Gagal mengunggah gambar.";
                exit;
            }
        } else {
            echo "File harus berupa JPG, JPEG, PNG, atau GIF.";
            exit;
        }
    }

    // Update data di database
    $stmt = $conn->prepare("UPDATE places SET name = ?, description = ?, image = ?, lokasi = ? WHERE id = ?");
    $stmt->bind_param("ssssi", $name, $description, $image, $lokasi, $id);

    if ($stmt->execute()) {
        header('Location: kelola_tempat.php');
        exit;
    } else {
        echo "Gagal memperbarui data: " . $conn->error;
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Tempat</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
    <link rel="icon" href="../assets/img/logotng.png" type="image/x-icon">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
    <div class="container mt-5">
        <h1 class="mb-4">Edit Tempat</h1>

        <form method="post" enctype="multipart/form-data" id="editForm">
            <div class="mb-3">
                <label for="placeName" class="form-label">Nama Tempat</label>
                <input type="text" class="form-control" id="placeName" name="name" value="<?= htmlspecialchars($place['name']); ?>" required>
            </div>

            <div class="mb-3">
                <label for="placeDescription" class="form-label">Deskripsi</label>
                <textarea class="form-control" id="placeDescription" name="description" rows="4" required><?= htmlspecialchars($place['description']); ?></textarea>
            </div>

            <div class="mb-3">
                <label for="placeLokasi" class="form-label">Lokasi</label>
                <textarea class="form-control" id="placeLokasi" name="lokasi" rows="4" required><?= htmlspecialchars($place['lokasi']); ?></textarea>
            </div>

            <div class="mb-3">
                <label for="placeImage" class="form-label">Gambar</label>
                <input type="file" class="form-control" id="placeImage" name="image" accept=".jpg,.jpeg,.png,.gif">
                <div class="mt-3">
                    <img src="../<?= htmlspecialchars($place['image']); ?>" alt="<?= htmlspecialchars($place['name']); ?>" style="width: 150px; height: auto; border-radius: 5px;">
                </div>
            </div>

            <button type="button" class="btn btn-primary mt-3" onclick="confirmSave()">Simpan</button>
            <a href="kelola_tempat.php" class="btn btn-secondary mt-3">Batal</a>
        </form>
    </div>

    <script>
        function confirmSave() {
            // SweetAlert untuk konfirmasi simpan
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: "Data yang Anda masukkan akan diperbarui!",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, simpan!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('editForm').submit();
                }
            });
        }
    </script>
</body>

</html>
