diff --git a/src/app/add_accommodation/page.tsx b/src/app/add_accommodation/page.tsx new file mode 100644 index 0000000..7f8e655 --- /dev/null +++ b/src/app/add_accommodation/page.tsx @@ -0,0 +1,173 @@ +'use client'; + +import { ChangeEvent, FormEvent, useState, useContext } from "react"; +import { addDoc, collection } from 'firebase/firestore'; +import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage'; +import { db, storage } from '@/lib/firebase'; +import toast from "react-hot-toast"; +import { UserContext } from '@/lib/context'; +import { createHash } from "crypto"; +import ConfirmationModal from "@/components/AsyncConfirmationModal"; +import HostCheck from "@/components/usertype_check/HostCheck"; + +export default function AddAccommodation() { + const [location, setLocation] = useState(''); + const [title, setTitle] = useState(''); + const [description, setDescription] = useState(''); + const [photos, setPhotos] = useState([]); + const [numberOfRooms, setNumberOfRooms] = useState(1); + const [price, setPrice] = useState(100); + const [showModal, setShowModal] = useState(false); + + const { user } = useContext(UserContext); + + const handlePhotoUpload = (e: ChangeEvent) => { + if (e.target.files) { + setPhotos(Array.from(e.target.files)); + } + }; + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault(); + + // Generate a unique ID and add the location data to Firestore + try { + + let images = []; + + for(let i = 0; i < photos.length; i++) { + const buffer = await photos[i].arrayBuffer(); + const name = photos[i].name; + const hashName = createHash('sha256') + .update(new Uint8Array(buffer)) + .digest('hex'); + const extension = name.split('.').pop(); + const storageUri = `accommodations/${hashName}.${extension}`; + const storageRef = ref(storage, storageUri); + if (buffer !== undefined) { + await uploadBytesResumable(storageRef, buffer); + images.push(await getDownloadURL(storageRef)); + } + } + + await addDoc(collection(db, 'accommodations'), { + uid: user.uid, + title, + location, + description, + numberOfRooms, + price, + photos: images, // set the photos url + }); + + // Reset the form + setTitle(''); + setLocation(''); + setDescription(''); + setPhotos([]); + setNumberOfRooms(1); + setPrice(100); + setShowModal(false); + + toast.success("Successfully created accommodation!") + } catch (e) { + toast.error("Could not create accommodation, contact Admin! Error: "+e); + } + }; + + const handleFormSubmit = async (e: FormEvent) => { + e.preventDefault(); + setShowModal(true); + }; + + + return ( + +
+
+

Add accommodation

+
+
+ + setTitle(e.target.value)} + className="mt-1 p-2 border border-gray-300 rounded w-full" + required + /> +
+
+ + setLocation(e.target.value)} + className="mt-1 p-2 border border-gray-300 rounded w-full" + required + /> +
+
+ +