import React, { useState, useEffect } from 'react'; import axios from 'axios'; import {useNavigate, useParams} from 'react-router-dom'; import StarRating from "./StarRating"; import {jwtDecode} from "jwt-decode"; const ReservationEdit = () => { const navigate = useNavigate(); const { reservationId } = useParams(); const [isLoading, setIsLoading] = useState(true); const [formData, setFormData] = useState({}); const [tableNumber, setTableNumber] = useState({}); const [table, setTable] = useState({}); const [restaurant, setRestaurant] = useState({}); const [restaurantId, setRestaurantId] = useState({}); const [timeSlots, setTimeSlots] = useState([]); const [filteredTimeSlots, setFilteredTimeSlots] = useState([]); const [checkInTime, setCheckInTime] = useState([]); const [tableReservations, setTableReservations] = useState([]); const timeSlotInterval = 15; const [selectedDate, setSelectedDate] = useState(''); const [selectedTime, setSelectedTime] = useState(''); const [timeOptions, setTimeOptions] = useState([]); useEffect(() => { const fetchReservation = async () => { try { setIsLoading(true); const response = await axios.get(`http://localhost:8081/api/reservations/${reservationId}`); console.log(response) setCheckInTime(response.data.reservationDateTime); setFormData(response.data); setRestaurant(response.data.restaurantName); setRestaurantId(response.data.restaurantId); setTableNumber(response.data.tableNumber); const tableResponse = await axios.get(`http://localhost:8081/api/tables/${response.data.tableNumber}`); setTable(tableResponse.data) setIsLoading(false); } catch (error) { console.error('Error fetching reservation:', error); } }; fetchReservation(); }, [reservationId]); useEffect(() => { const fetchTableReservations = async () => { try { const response = await axios.get(`http://localhost:8081/api/table-reservations/${table.tableId}`); setTableReservations(response.data); setIsLoading(false); } catch (error) { console.error('Error fetching table reservations:', error); } }; if (table?.tableId) { fetchTableReservations(); } }, [table]); const generateTimeSlots = (operatingHours, interval) => { const slots = []; const [startTimeStr, endTimeStr] = operatingHours.split('-'); const [startHours, startMinutes] = startTimeStr.split(':').map(Number); const [endHours, endMinutes] = endTimeStr.split(':').map(Number); const startTime = new Date(); startTime.setHours(startHours, startMinutes, 0, 0); const endTime = new Date(); endTime.setHours(endHours, endMinutes, 0, 0); let currentTime = startTime; while (currentTime <= endTime) { slots.push(new Date(currentTime).toISOString()); currentTime = new Date(currentTime.getTime() + interval * 60000); } return slots; }; const generateTimeOptions = (operatingHours) => { const { startTime, endTime } = parseOperatingHours(operatingHours); const now = new Date(); const selectedDateObj = new Date(selectedDate); const isToday = selectedDateObj.toDateString() === now.toDateString(); const isTomorrow = selectedDateObj > now && selectedDateObj.getDate() === now.getDate() + 1; let currentTime; if (isToday) { currentTime = roundToNext15Minutes(new Date()); } else { currentTime = new Date(startTime); } const options = []; while (currentTime <= endTime) { options.push(currentTime.toTimeString().slice(0, 5)); currentTime = new Date(currentTime.getTime() + 15 * 60 * 1000); } return options; }; useEffect(() => { const operatingHours = table?.restaurant?.operatingHours || "09:00-00:00"; const allTimeSlots = generateTimeSlots(operatingHours, timeSlotInterval); const availableSlots = allTimeSlots.filter((slot) => !tableReservations.includes(slot) ); setFilteredTimeSlots(availableSlots); }, [tableReservations, table]); const handleInputChange = (e) => { const { name, value } = e.target; if (name === 'partySize') { const valueAsNumber = Math.min(value, table?.capacity); setFormData(prevState => ({ ...prevState, [name]: valueAsNumber })); } else { setFormData(prevState => ({ ...prevState, [name]: value })); } }; const handleSubmit = async (e) => { e.preventDefault(); try { const token = localStorage.getItem("token"); if (!token) { console.error("No token found"); return; } const decodedToken = jwtDecode(token); const userId = decodedToken.iss; const updatedReservationData = { ...formData, reservationDateTime: `${selectedDate}T${selectedTime}`, checkInTime: checkInTime, reservationID: reservationId, }; await axios.post( `http://localhost:8081/api/reservations/${reservationId}/${userId}`, updatedReservationData, { headers: { 'Content-Type': 'application/json', } } ); console.log(updatedReservationData) navigate(`/reservations`); } catch (error) { console.error('Error updating reservation:', error); } }; const formatTimeSlot = (timeSlot) => { const date = new Date(timeSlot); const formattedDate = date.toLocaleDateString(); const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return `${formattedDate} - ${formattedTime}`; }; const today = new Date(); const year = today.getFullYear(); const month = String(today.getMonth() + 1).padStart(2, '0'); const day = String(today.getDate()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; const parseOperatingHours = (operatingHours) => { const [start, end] = operatingHours.split('-'); return { startTime: new Date(`1970-01-01T${start}:00`), endTime: new Date(`1970-01-01T${end}:00`) }; }; useEffect(() => { if (formData?.restaurant?.operatingHours && selectedDate) { const options = generateTimeOptions(formData.restaurant.operatingHours); setTimeOptions(options); } }, [restaurant, selectedDate]); // useEffect(() => { // if (checkInTime) { // const checkInDateObj = new Date(checkInTime); // setSelectedDate(checkInDateObj.toISOString().split("T")[0]); // setSelectedTime(checkInDateObj.toTimeString().slice(0, 5)); // } // }, [checkInTime]); return (
Loading...
) : ( <>{formData.restaurant.name}
{formData.restaurant.operatingHours}
Ul. {formData.restaurant.address}