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

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

$message = "";

/* ============ PROSES FORM ============ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name        = trim($_POST['name']);
    $description = trim($_POST['description']);
    $lokasi      = trim($_POST['lokasi']);
    $imagePath   = '';                                    // path relativ yg disimpan

    /* --- Upload gambar --- */
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowedExt  = ['jpg', 'jpeg', 'png', 'gif'];
        $ext         = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, $allowedExt)) {
            $message = "File harus berupa JPG, JPEG, PNG, atau GIF.";
        } else {
            $uploadDir = __DIR__ . '/../assets/img/';     // jalur fisik
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);            // buat folder jika belum ada
            }

            $imageName = uniqid('img_', true) . '.' . $ext;
            $target    = $uploadDir . $imageName;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
                $imagePath = 'assets/img/' . $imageName;  // path relatif utk database
            } else {
                $message = "Gagal mengunggah gambar.";
            }
        }
    } else {
        $message = "Silakan pilih gambar (JPG/PNG/GIF).";
    }

    /* --- Simpan ke database --- */
    if (!$message && $name && $description && $lokasi && $imagePath) {
        $stmt = $conn->prepare(
            "INSERT INTO places (name, description, image, lokasi) VALUES (?, ?, ?, ?)"
        );
        $stmt->bind_param("ssss", $name, $description, $imagePath, $lokasi);

        if ($stmt->execute()) {
            header('Location: kelola_tempat.php');
            exit;
        } else {
            $message = "Gagal menambahkan tempat: " . $conn->error;
        }
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah Tempat</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <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">Tambah Tempat</h1>

        <?php if ($message): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" id="addPlaceForm">
            <div class="mb-3">
                <label for="name" class="form-label">Nama Tempat</label>
                <input type="text" id="name" name="name" class="form-control" required>
            </div>

            <div class="mb-3">
                <label for="description" class="form-label">Deskripsi</label>
                <textarea id="description" name="description" rows="4" class="form-control" required></textarea>
            </div>

            <div class="mb-3">
                <label for="lokasi" class="form-label">Lokasi</label>
                <textarea id="lokasi" name="lokasi" rows="4" class="form-control" required></textarea>
            </div>

            <div class="mb-3">
                <label for="image" class="form-label">Upload Gambar</label>
                <input type="file" id="image" name="image" class="form-control" accept=".jpg,.jpeg,.png,.gif" required>
            </div>

            <button type="button" class="btn btn-primary" onclick="confirmAdd()">Tambah</button>
            <a href="kelola_tempat.php" class="btn btn-secondary">Batal</a>
        </form>
    </div>

    <script>
        function confirmAdd() {
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: 'Data tempat akan ditambahkan!',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, tambahkan!',
                cancelButtonText: 'Batal'
            }).then((r) => {
                if (r.isConfirmed) document.getElementById('addPlaceForm').submit();
            });
        }
    </script>
</body>

</html>