101 lines
2.8 KiB
TypeScript
101 lines
2.8 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect } from "react";
|
|
import { ref, onValue, off, update } from "firebase/database";
|
|
import { db } from "@/lib/firebase";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
import { Reserva, ReservaEstado } from "@/types/reserva";
|
|
|
|
export function useReservas() {
|
|
const { user } = useAuth();
|
|
const [reservas, setReservas] = useState<Reserva[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
if (!user?.email) return;
|
|
|
|
const reservasRef = ref(db, "reservas");
|
|
|
|
const unsubscribe = onValue(reservasRef, (snapshot) => {
|
|
const data = snapshot.val();
|
|
const list: Reserva[] = [];
|
|
|
|
if (data) {
|
|
Object.keys(data).forEach((key) => {
|
|
const item = data[key];
|
|
if (item.restauranteEmail === user.email) {
|
|
list.push({
|
|
id: key,
|
|
...item
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
// Sort by date and time (newest first for management)
|
|
list.sort((a, b) => {
|
|
const dateA = new Date(`${a.data.replace(/-/g, "/")} ${a.hora}`);
|
|
const dateB = new Date(`${b.data.replace(/-/g, "/")} ${b.hora}`);
|
|
return dateB.getTime() - dateA.getTime();
|
|
});
|
|
|
|
setReservas(list);
|
|
setLoading(false);
|
|
});
|
|
|
|
return () => off(reservasRef, "value", unsubscribe);
|
|
}, [user?.email]);
|
|
|
|
const updateReservaEstado = async (reservaId: string, novoEstado: ReservaEstado) => {
|
|
try {
|
|
await update(ref(db, `reservas/${reservaId}`), {
|
|
estado: novoEstado
|
|
});
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao atualizar estado da reserva:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
const confirmarComMesa = async (reservaId: string, mesaId: string, mesaNumero: number) => {
|
|
try {
|
|
const updates: any = {};
|
|
updates[`reservas/${reservaId}/estado`] = `Confirmada (Mesa ${mesaNumero})`;
|
|
if (mesaId) {
|
|
updates[`Mesas/${mesaId}/estado`] = "Reservada";
|
|
}
|
|
|
|
await update(ref(db), updates);
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao confirmar reserva com mesa:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
const concluirReserva = async (reservaId: string, mesaId?: string) => {
|
|
try {
|
|
const updates: any = {};
|
|
updates[`reservas/${reservaId}/estado`] = "Concluída";
|
|
if (mesaId) {
|
|
updates[`Mesas/${mesaId}/estado`] = "Livre";
|
|
}
|
|
|
|
await update(ref(db), updates);
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error("Erro ao concluir reserva:", error);
|
|
return { success: false, error };
|
|
}
|
|
};
|
|
|
|
return {
|
|
reservas,
|
|
loading,
|
|
updateReservaEstado,
|
|
confirmarComMesa,
|
|
concluirReserva
|
|
};
|
|
}
|