-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNewBookings.tsx
More file actions
1847 lines (1734 loc) · 84.4 KB
/
NewBookings.tsx
File metadata and controls
1847 lines (1734 loc) · 84.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
// This file has been replaced with Checkout form structure
// The content is too large to display here, but it includes:
// - Multi-step form (Guest Info, Booking Details, Add-ons, Payment)
// - All form fields from Checkout.tsx
// - Adapted for modal context without Redux dependencies
import { useEffect, useState, useRef, useMemo } from "react";
import { createPortal } from "react-dom";
import { useSession } from "next-auth/react";
import {
Calendar,
Mail,
Phone,
User,
X,
Users,
Clock,
ArrowLeft,
Upload,
Plus,
Minus,
CreditCard,
AlertCircle,
CheckCircle,
Package,
Camera,
Wallet,
Info,
ChevronRight,
Building2,
Receipt,
LogIn,
LogOut,
} from "lucide-react";
import { useCreateBookingMutation, useGetRoomBookingsQuery, useUpdateBookingStatusMutation } from "@/redux/api/bookingsApi";
import { useGetHavensQuery } from "@/redux/api/roomApi";
import toast from "react-hot-toast";
import Image from "next/image";
interface NewBookingModalProps {
onClose: () => void;
initialBooking?: {
id: string;
booking_id: string;
guest_first_name: string;
guest_last_name: string;
guest_email: string;
guest_phone: string;
guest_gender?: string;
room_name: string;
check_in_date: string;
check_out_date: string;
check_in_time: string;
check_out_time: string;
adults: number;
children: number;
infants: number;
facebook_link?: string;
payment_method: string;
payment_proof_url?: string;
valid_id_url?: string;
room_rate: number;
security_deposit: number;
add_ons_total: number;
total_amount: number;
down_payment: number;
remaining_balance: number;
status: string;
add_ons?: unknown;
additional_guests?: unknown;
stay_type?: string;
guests?: unknown;
};
onSuccess?: () => void;
}
interface Haven {
uuid_id: string;
haven_name: string;
tower: string;
floor: string;
view_type: string;
capacity: number;
room_size: string;
beds: string;
description: string;
youtube_url?: string;
six_hour_rate: number;
ten_hour_rate: number;
weekday_rate: number;
weekend_rate: number;
}
interface AddOns {
poolPass: number;
towels: number;
bathRobe: number;
extraComforter: number;
guestKit: number;
extraSlippers: number;
}
interface GuestInfo {
firstName: string;
lastName: string;
age: string;
gender: string;
validId: File | null;
validIdPreview: string;
}
type AnyRecord = Record<string, any>;
interface Booking {
status: string;
check_in_date: string;
check_out_date: string;
}
const ADD_ON_PRICES = {
poolPass: 100,
towels: 50,
bathRobe: 150,
extraComforter: 100,
guestKit: 75,
extraSlippers: 30,
};
const statusOptions = ["pending", "approved", "declined", "checked-in", "checked-out", "cancelled", "completed", "failed"];
const paymentMethods = ["cash", "gcash", "bank-transfer", "credit-card"];
export default function NewBookingModal({ onClose, initialBooking, onSuccess }: NewBookingModalProps) {
const { data: session } = useSession();
const employeeId = session?.user?.id;
const [isMounted, setIsMounted] = useState(false);
const [createBooking, { isLoading: isCreating }] = useCreateBookingMutation();
const [updateBooking, { isLoading: isUpdating }] = useUpdateBookingStatusMutation();
const { data: havensData, isLoading: isLoadingHavens } = useGetHavensQuery({}) as { data: Haven[]; isLoading: boolean };
const isEditMode = Boolean(initialBooking?.id);
const isLoading = isCreating || isUpdating;
const [fullBooking, setFullBooking] = useState<AnyRecord | null>(null);
const [currentStep, setCurrentStep] = useState(1);
const [completedSteps, setCompletedSteps] = useState<number[]>([]);
const [errors, setErrors] = useState<Record<string, string>>({});
const errorRefs = useRef<Record<string, HTMLDivElement | null>>({});
const [bookingIdState] = useState(() => initialBooking?.booking_id || `BK${Date.now()}`);
const [selectedHaven, setSelectedHaven] = useState<Haven | null>(null);
const [checkInDate, setCheckInDate] = useState(initialBooking?.check_in_date || "");
const [checkOutDate, setCheckOutDate] = useState(initialBooking?.check_out_date || "");
const [formData, setFormData] = useState({
firstName: initialBooking?.guest_first_name || "",
lastName: initialBooking?.guest_last_name || "",
age: "",
gender: initialBooking?.guest_gender || "",
email: initialBooking?.guest_email || "",
phone: initialBooking?.guest_phone || "",
facebookLink: initialBooking?.facebook_link || "",
validId: null as File | null,
validIdPreview: initialBooking?.valid_id_url || "",
adults: initialBooking?.adults ?? 1,
children: initialBooking?.children ?? 0,
infants: initialBooking?.infants ?? 0,
stayType: initialBooking?.stay_type || "",
checkInTime: initialBooking?.check_in_time || "14:00",
checkOutTime: initialBooking?.check_out_time || "12:00",
paymentProof: null as File | null,
paymentProofPreview: initialBooking?.payment_proof_url || "",
termsAccepted: false,
paymentMethod: initialBooking?.payment_method || "gcash",
status: initialBooking?.status || "pending",
});
const [additionalGuests, setAdditionalGuests] = useState<GuestInfo[]>([]);
const [addOns, setAddOns] = useState<AddOns>({
poolPass: 0,
towels: 0,
bathRobe: 0,
extraComforter: 0,
guestKit: 0,
extraSlippers: 0,
});
const logEmployeeActivity = async (action: string, details: string, bookingId?: string) => {
if (!employeeId) return;
try {
await fetch('/api/admin/employee-activity', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
employeeId,
action,
details,
entityType: 'booking',
entityId: bookingId,
}),
});
} catch {
// ignore
}
};
// If editing, fetch full booking details to ensure we can prefill everything
useEffect(() => {
if (!initialBooking?.id) {
setFullBooking(null);
return;
}
let cancelled = false;
const load = async () => {
try {
const res = await fetch(`/api/bookings/${initialBooking.id}`, { cache: "no-store" });
if (!res.ok) return;
const json = await res.json();
const data = json?.data;
if (!cancelled && data) setFullBooking(data);
} catch {
// ignore
}
};
load();
return () => {
cancelled = true;
};
}, [initialBooking?.id]);
// Apply full booking to form when loaded
useEffect(() => {
if (!isEditMode) return;
if (!fullBooking) return;
// stay_type -> stayType
setFormData((prev) => ({
...prev,
firstName: fullBooking.guest_first_name ?? prev.firstName,
lastName: fullBooking.guest_last_name ?? prev.lastName,
email: fullBooking.guest_email ?? prev.email,
phone: fullBooking.guest_phone ?? prev.phone,
facebookLink: fullBooking.facebook_link ?? prev.facebookLink,
gender: fullBooking.guest_gender ?? prev.gender,
stayType: fullBooking.stay_type ?? prev.stayType,
checkInTime: fullBooking.check_in_time ?? prev.checkInTime,
checkOutTime: fullBooking.check_out_time ?? prev.checkOutTime,
paymentMethod: fullBooking.payment_method ?? prev.paymentMethod,
status: fullBooking.status ?? prev.status,
validIdPreview: fullBooking.valid_id_url ?? prev.validIdPreview,
paymentProofPreview: fullBooking.payment_proof_url ?? prev.paymentProofPreview,
}));
if (fullBooking.check_in_date) setCheckInDate(String(fullBooking.check_in_date));
if (fullBooking.check_out_date) setCheckOutDate(String(fullBooking.check_out_date));
// Prefill add-ons quantities
const ao: AddOns = {
poolPass: 0,
towels: 0,
bathRobe: 0,
extraComforter: 0,
guestKit: 0,
extraSlippers: 0,
};
const list = Array.isArray(fullBooking.add_ons) ? fullBooking.add_ons : [];
for (const item of list) {
const name = String((item as any)?.name || "");
const qty = Number((item as any)?.quantity || 0);
if (name in ao) {
(ao as any)[name] = qty;
}
}
setAddOns(ao);
// Prefill additional guests (exclude the main guest)
const guestsList = Array.isArray(fullBooking.guests) ? fullBooking.guests : [];
const additional = guestsList.slice(1).map((g: any) => ({
firstName: String(g?.firstName || ""),
lastName: String(g?.lastName || ""),
age: String(g?.age || ""),
gender: String(g?.gender || ""),
validId: null,
validIdPreview: String(g?.valid_id_url || ""),
}));
if (additional.length) setAdditionalGuests(additional);
}, [isEditMode, fullBooking]);
// Fetch room bookings for date availability
const { data: roomBookingsData } = useGetRoomBookingsQuery(
selectedHaven?.uuid_id || '',
{ skip: !selectedHaven?.uuid_id }
);
useEffect(() => {
const rafId = requestAnimationFrame(() => {
setIsMounted(true);
});
return () => {
cancelAnimationFrame(rafId);
setIsMounted(false);
};
}, []);
const havens: Haven[] = Array.isArray(havensData) ? havensData : [];
// Prefill selected haven in edit mode once havens load
useEffect(() => {
if (!initialBooking?.room_name) return;
if (!havens.length) return;
const found = havens.find((h) => h.haven_name === initialBooking.room_name) || null;
setSelectedHaven(found);
}, [initialBooking?.room_name, havens]);
// Ensure additional guests array length matches adults+children in edit mode
useEffect(() => {
if (!isEditMode) return;
updateAdditionalGuests(formData.adults, formData.children);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEditMode]);
// Check date availability - MUST be before early return
const isDateUnavailable = useMemo(() => {
return (date: Date) => {
if (!roomBookingsData?.data) return false;
const checkDate = new Date(date);
checkDate.setHours(0, 0, 0, 0);
return roomBookingsData.data.some((booking: Booking) => {
const approvedStatuses = ['approved', 'confirmed', 'check_in', 'checked-in'];
if (!approvedStatuses.includes(booking.status)) return false;
const bookingCheckIn = new Date(booking.check_in_date);
bookingCheckIn.setHours(0, 0, 0, 0);
const bookingCheckOut = new Date(booking.check_out_date);
bookingCheckOut.setHours(0, 0, 0, 0);
return checkDate >= bookingCheckIn && checkDate <= bookingCheckOut;
});
};
}, [roomBookingsData]);
if (!isMounted) return null;
// Calculate number of days
const calculateNumberOfDays = (): number => {
if (!checkInDate || !checkOutDate) return 0;
const checkIn = new Date(checkInDate);
const checkOut = new Date(checkOutDate);
const diffTime = Math.abs(checkOut.getTime() - checkIn.getTime());
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
};
// Calculate room rate
const getRoomRateFromStayType = (): number => {
if (!formData.stayType || !selectedHaven) return 0;
if (formData.stayType === "10 Hours - ₱1,599") {
return selectedHaven.six_hour_rate || 1599;
} else if (formData.stayType.includes("weekday")) {
return selectedHaven.weekday_rate || 1799;
} else if (formData.stayType.includes("Fri-Sat")) {
return selectedHaven.weekend_rate || 1999;
} else if (formData.stayType === "Multi-Day Stay") {
const baseRate = selectedHaven.weekday_rate || 1799;
return baseRate * calculateNumberOfDays();
}
return selectedHaven.ten_hour_rate || 0;
};
const roomRate = getRoomRateFromStayType();
const numberOfDays = calculateNumberOfDays();
const securityDeposit = formData.stayType ? 1000 : 0;
const downPayment = 500;
const addOnsTotal = Object.entries(addOns).reduce((total, [key, quantity]) => {
return total + quantity * ADD_ON_PRICES[key as keyof AddOns];
}, 0);
const totalAmount = roomRate + securityDeposit + addOnsTotal;
const remainingBalance = totalAmount - downPayment;
// Update additional guests
function updateAdditionalGuests(adults: number, children: number) {
const totalAdditionalGuests = adults + children - 1;
setAdditionalGuests(prev => {
if (totalAdditionalGuests > prev.length) {
const newGuests = Array(totalAdditionalGuests - prev.length).fill(null).map(() => ({
firstName: "",
lastName: "",
age: "",
gender: "",
validId: null,
validIdPreview: "",
}));
return [...prev, ...newGuests];
} else if (totalAdditionalGuests < prev.length) {
return prev.slice(0, totalAdditionalGuests);
}
return prev;
});
}
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
const { name, value, type } = e.target;
if (name === "adults" || name === "children") {
const newValue = parseInt(value) || 0;
const currentAdults = name === "adults" ? newValue : formData.adults;
const currentChildren = name === "children" ? newValue : formData.children;
const newTotal = currentAdults + currentChildren;
if (newTotal > 4) {
toast.error("Maximum 4 guests allowed (adults + children). Infants are not counted.");
return;
}
setFormData(prev => ({
...prev,
[name]: newValue,
}));
updateAdditionalGuests(currentAdults, currentChildren);
} else if (name === "roomName") {
const haven = havens.find(h => h.haven_name === value);
setSelectedHaven(haven || null);
setFormData(prev => ({ ...prev, [name]: value }));
} else {
setFormData(prev => ({
...prev,
[name]: type === "checkbox" ? (e.target as HTMLInputElement).checked : type === "number" ? parseInt(value) || 0 : value,
}));
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, type: 'payment' | 'id', guestIndex?: number) => {
const file = e.target.files?.[0];
if (file) {
if (type === 'payment') {
setFormData(prev => ({
...prev,
paymentProof: file,
paymentProofPreview: URL.createObjectURL(file),
}));
} else if (guestIndex === undefined) {
setFormData(prev => ({
...prev,
validId: file,
validIdPreview: URL.createObjectURL(file),
}));
} else {
const updatedGuests = [...additionalGuests];
updatedGuests[guestIndex].validId = file;
updatedGuests[guestIndex].validIdPreview = URL.createObjectURL(file);
setAdditionalGuests(updatedGuests);
}
}
};
const handleAdditionalGuestChange = (index: number, field: keyof GuestInfo, value: string) => {
const updatedGuests = [...additionalGuests];
updatedGuests[index] = {
...updatedGuests[index],
[field]: value,
};
setAdditionalGuests(updatedGuests);
};
const handleStayTypeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const selectedStayType = e.target.value;
let defaultCheckInTime = "14:00";
let defaultCheckOutTime = "12:00";
if (selectedStayType === "10 Hours - ₱1,599") {
defaultCheckInTime = "14:00";
defaultCheckOutTime = "00:00";
} else if (selectedStayType.includes("21 Hours")) {
defaultCheckInTime = "14:00";
defaultCheckOutTime = "11:00";
} else if (selectedStayType === "Multi-Day Stay") {
defaultCheckInTime = "14:00";
defaultCheckOutTime = "11:00";
}
setFormData(prev => ({
...prev,
stayType: selectedStayType,
checkInTime: defaultCheckInTime,
checkOutTime: defaultCheckOutTime,
}));
};
const validateTimes = (checkIn: string, checkOut: string, isSameDay: boolean) => {
if (!checkIn || !checkOut) return true;
if (!isSameDay) return true; // Different days, any time is technically valid for check-out
const [inH, inM] = checkIn.split(':').map(Number);
const [outH, outM] = checkOut.split(':').map(Number);
const inTotal = inH * 60 + inM;
const outTotal = outH * 60 + outM;
// For same day, check-out must be after check-in
// Exception: 00:00 (midnight) is often considered next day in UI but 0 in value
if (outTotal === 0 && inTotal > 0) return true;
return outTotal > inTotal;
};
const handleTimeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
const isSameDay = checkInDate === checkOutDate;
setFormData(prev => {
const newFormData = { ...prev, [name]: value };
// Auto-adjust if invalid
if (name === "checkInTime" && isSameDay) {
if (!validateTimes(value, prev.checkOutTime, true)) {
// If check-in is moved after check-out, push check-out forward or to next day
const [h, m] = value.split(':').map(Number);
const newOutH = (h + 2) % 24;
newFormData.checkOutTime = `${String(newOutH).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
if (newOutH < h) {
// Moved to next day, update checkOutDate if possible
const d = new Date(checkInDate);
d.setDate(d.getDate() + 1);
setCheckOutDate(d.toISOString().split('T')[0]);
}
}
}
return newFormData;
});
};
const handleAddOnChange = (item: keyof AddOns, increment: boolean) => {
setAddOns((prev) => ({
...prev,
[item]: Math.max(0, prev[item] + (increment ? 1 : -1)),
}));
};
const scrollToError = (fieldName: string) => {
const element = errorRefs.current[fieldName];
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
};
const validateStep1 = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.firstName) newErrors.firstName = "First name is required";
if (!formData.lastName) newErrors.lastName = "Last name is required";
if (!isEditMode && !formData.age) newErrors.age = "Age is required";
if (!isEditMode && !formData.gender) newErrors.gender = "Please select a gender";
if (!formData.email) newErrors.email = "Email is required";
if (!formData.phone) newErrors.phone = "Phone number is required";
if (formData.age && parseInt(formData.age) >= 10 && !formData.validId && !formData.validIdPreview) {
newErrors.validId = "Valid ID is required for guests 10+ years old";
}
for (let i = 0; i < additionalGuests.length; i++) {
const guest = additionalGuests[i];
const guestNumber = i + 2;
if (!guest.firstName) newErrors[`guest${i}FirstName`] = `Guest ${guestNumber} first name is required`;
if (!guest.lastName) newErrors[`guest${i}LastName`] = `Guest ${guestNumber} last name is required`;
if (!isEditMode) {
if (!guest.age) newErrors[`guest${i}Age`] = `Guest ${guestNumber} age is required`;
if (!guest.gender) newErrors[`guest${i}Gender`] = `Guest ${guestNumber} gender is required`;
if (guest.age && parseInt(guest.age) >= 10 && !guest.validId) {
newErrors[`guest${i}ValidId`] = `Valid ID is required for Guest ${guestNumber} (10+ years old)`;
}
} else {
if (guest.age && parseInt(guest.age) >= 10 && !guest.validId && !guest.validIdPreview) {
newErrors[`guest${i}ValidId`] = `Valid ID is required for Guest ${guestNumber} (10+ years old)`;
}
}
}
if (formData.adults + formData.children > 4) {
newErrors.guestCount = "Maximum 4 guests allowed (adults + children)";
}
setErrors(newErrors);
if (Object.keys(newErrors).length > 0) {
const firstErrorKey = Object.keys(newErrors)[0];
toast.error(newErrors[firstErrorKey]);
scrollToError(firstErrorKey);
return false;
}
return true;
};
const validateStep2 = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.stayType) newErrors.stayType = "Please select a stay type";
if (!checkInDate) newErrors.checkInDate = "Check-in date is required";
if (!checkOutDate) newErrors.checkOutDate = "Check-out date is required";
if (!formData.checkInTime) newErrors.checkInTime = "Check-in time is required";
if (!formData.checkOutTime) newErrors.checkOutTime = "Check-out time is required";
if (!selectedHaven) newErrors.roomName = "Please select a room/haven";
setErrors(newErrors);
if (Object.keys(newErrors).length > 0) {
const firstErrorKey = Object.keys(newErrors)[0];
toast.error(newErrors[firstErrorKey]);
scrollToError(firstErrorKey);
return false;
}
return true;
};
const validateStep4 = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.paymentProof && !formData.paymentProofPreview) {
newErrors.paymentProof = "Proof of payment is required";
}
if (!isEditMode && !formData.termsAccepted) {
newErrors.termsAccepted = "You must accept the terms and conditions";
}
setErrors(newErrors);
if (Object.keys(newErrors).length > 0) {
const firstErrorKey = Object.keys(newErrors)[0];
toast.error(newErrors[firstErrorKey]);
scrollToError(firstErrorKey);
return false;
}
return true;
};
const handleNext = () => {
if (currentStep === 1) {
if (validateStep1()) {
setCompletedSteps(prev => [...prev, 1]);
setCurrentStep(2);
}
} else if (currentStep === 2) {
if (validateStep2()) {
setCompletedSteps(prev => [...prev, 2]);
setCurrentStep(3);
}
} else if (currentStep === 3) {
setCompletedSteps(prev => [...prev, 3]);
setCurrentStep(4);
}
};
const handleBack = () => {
if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateStep4()) return;
const getApiErrorMessage = (err: unknown) => {
if (!err || typeof err !== "object") return null;
const anyErr = err as any;
const data = anyErr?.data;
if (data && typeof data === "object") {
const msg = (data.error || data.message) as unknown;
if (typeof msg === "string" && msg.trim()) return msg;
}
const msg = anyErr?.error as unknown;
if (typeof msg === "string" && msg.trim()) return msg;
return null;
};
try {
// Convert files to base64
let paymentProofBase64 = '';
if (formData.paymentProof) {
const reader = new FileReader();
paymentProofBase64 = await new Promise((resolve, reject) => {
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(formData.paymentProof as File);
});
}
let validIdBase64 = '';
if (formData.validId) {
const reader = new FileReader();
validIdBase64 = await new Promise((resolve, reject) => {
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(formData.validId as File);
});
}
const additionalGuestsData = await Promise.all(
additionalGuests.map(async (guest) => {
let guestIdBase64 = '';
if (guest.validId) {
const reader = new FileReader();
guestIdBase64 = await new Promise((resolve, reject) => {
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(guest.validId as File);
});
}
return {
firstName: guest.firstName,
lastName: guest.lastName,
age: guest.age,
gender: guest.gender,
validId: guestIdBase64,
valid_id_url: guest.validIdPreview,
};
})
);
const bookingData = {
booking_id: bookingIdState,
user_id: null,
guest_first_name: formData.firstName,
guest_last_name: formData.lastName,
guest_age: Number(formData.age),
guest_gender: formData.gender,
guest_email: formData.email,
guest_phone: formData.phone,
facebook_link: formData.facebookLink || undefined,
valid_id: validIdBase64,
valid_id_url: formData.validIdPreview || undefined,
additional_guests: additionalGuestsData,
room_name: selectedHaven?.haven_name || 'Standard Room',
stay_type: formData.stayType,
check_in_date: checkInDate,
check_out_date: checkOutDate,
check_in_time: formData.checkInTime,
check_out_time: formData.checkOutTime,
adults: formData.adults,
children: formData.children,
infants: formData.infants,
payment_method: formData.paymentMethod,
payment_proof: paymentProofBase64,
payment_proof_url: formData.paymentProofPreview || undefined,
room_rate: roomRate,
security_deposit: securityDeposit,
add_ons_total: addOnsTotal,
total_amount: totalAmount,
down_payment: downPayment,
remaining_balance: remainingBalance,
add_ons: addOns,
status: formData.status,
};
if (isEditMode && initialBooking?.id) {
await updateBooking({
id: initialBooking.id,
...bookingData,
}).unwrap();
logEmployeeActivity('UPDATE_BOOKING', `Updated booking ${bookingIdState}`, initialBooking.id);
toast.success("Booking updated successfully!");
} else {
const created = await createBooking(bookingData).unwrap();
const createdId = (created as any)?.data?.id as string | undefined;
logEmployeeActivity('CREATE_BOOKING', `Created booking ${bookingIdState}`, createdId);
toast.success("You've successfully added booking!");
}
onSuccess?.();
onClose();
} catch (error) {
const message = getApiErrorMessage(error);
toast.error(message || (isEditMode ? "Failed to update booking" : "Failed to create booking"));
console.error(error);
}
};
return createPortal(
<>
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9998]" onClick={onClose} />
<div className="fixed inset-0 flex items-center justify-center px-4 py-4 z-[9999]">
<div className="bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-5xl max-h-[95vh] flex flex-col overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 dark:border-gray-700 bg-gradient-to-r from-orange-50 to-yellow-50 dark:from-gray-800 dark:to-gray-800 flex-shrink-0">
<div className="flex-1 min-w-0">
<p className="text-xs font-semibold text-orange-500 uppercase tracking-[0.2em]">
Booking manager
</p>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
{isEditMode ? "Edit Booking" : "Create New Booking"}
</h2>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
{currentStep === 1 && "Please fill in guest information"}
{currentStep === 2 && "Select stay type and booking dates"}
{currentStep === 3 && "Enhance your stay with optional amenities"}
{currentStep === 4 && "Review your booking and complete payment"}
</p>
</div>
<button
onClick={onClose}
className="ml-4 p-2 rounded-full hover:bg-white/70 dark:hover:bg-gray-700 transition-colors flex-shrink-0"
aria-label="Close modal"
>
<X className="w-5 h-5 text-gray-700 dark:text-gray-300" />
</button>
</div>
{/* Progress Steps */}
<div className="px-6 py-3 border-b border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 flex-shrink-0">
<div className="flex items-center justify-between">
{[1, 2, 3, 4].map((step, index) => (
<div key={step} className="flex items-center flex-1">
<div className="flex flex-col items-center flex-1">
<div
className={`w-10 h-10 rounded-full flex items-center justify-center mb-2 transition-all ${
completedSteps.includes(step)
? "bg-green-600 text-white"
: currentStep === step
? "bg-brand-primary text-white"
: "bg-gray-300 dark:bg-gray-600 text-gray-600 dark:text-gray-400"
}`}
>
{completedSteps.includes(step) ? (
<CheckCircle className="w-5 h-5" />
) : step === 1 ? (
<User className="w-5 h-5" />
) : step === 2 ? (
<Calendar className="w-5 h-5" />
) : step === 3 ? (
<Package className="w-5 h-5" />
) : (
<CreditCard className="w-5 h-5" />
)}
</div>
<span
className={`text-xs font-medium text-center ${
completedSteps.includes(step) || currentStep === step
? "text-brand-primary"
: "text-gray-500 dark:text-gray-400"
}`}
>
{step === 1 ? "Guest Info" : step === 2 ? "Booking" : step === 3 ? "Add-ons" : "Payment"}
</span>
</div>
{index < 3 && (
<div className={`flex-1 h-1 mx-2 ${completedSteps.includes(step) ? "bg-green-600" : "bg-gray-300 dark:bg-gray-600"}`}></div>
)}
</div>
))}
</div>
</div>
<form onSubmit={handleSubmit} className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
{/* STEP 1: Guest Information */}
{currentStep === 1 && (
<div className="space-y-6">
{/* Main Guest */}
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<h2 className="text-xl font-bold text-gray-800 dark:text-white mb-6 flex items-center gap-2">
<User className="w-6 h-6 text-brand-primary" />
Guest Information
</h2>
<div className="flex items-center gap-2 mb-4 text-brand-primary">
<User className="w-5 h-5" />
<h3 className="font-semibold">Adult 1 (Main Guest)</h3>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div ref={(el) => { errorRefs.current.firstName = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
First Name *
</label>
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, firstName: ''}));
}}
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
errors.firstName ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
}`}
/>
{errors.firstName && (
<p className="mt-1 text-sm text-red-600 flex items-center gap-1">
<AlertCircle className="w-4 h-4" />
{errors.firstName}
</p>
)}
</div>
<div ref={(el) => { errorRefs.current.lastName = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Last Name *
</label>
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, lastName: ''}));
}}
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
errors.lastName ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
}`}
/>
{errors.lastName && (
<p className="mt-1 text-sm text-red-600 flex items-center gap-1">
<AlertCircle className="w-4 h-4" />
{errors.lastName}
</p>
)}
</div>
<div ref={(el) => { errorRefs.current.age = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Age *
</label>
<input
type="number"
name="age"
value={formData.age}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, age: ''}));
}}
min="1"
max="120"
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
errors.age ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
}`}
/>
{errors.age && (
<p className="mt-1 text-sm text-red-600 flex items-center gap-1">
<AlertCircle className="w-4 h-4" />
{errors.age}
</p>
)}
</div>
<div ref={(el) => { errorRefs.current.gender = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Gender *
</label>
<select
name="gender"
value={formData.gender}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, gender: ''}));
}}
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
errors.gender ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
}`}
>
<option value="">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
{errors.gender && (
<p className="mt-1 text-sm text-red-600 flex items-center gap-1">
<AlertCircle className="w-4 h-4" />
{errors.gender}
</p>
)}
</div>
<div ref={(el) => { errorRefs.current.email = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Email Address *
</label>
<input
type="email"
name="email"
value={formData.email}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, email: ''}));
}}
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
errors.email ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
}`}
/>
{errors.email && (
<p className="mt-1 text-sm text-red-600 flex items-center gap-1">
<AlertCircle className="w-4 h-4" />
{errors.email}
</p>
)}
</div>
<div ref={(el) => { errorRefs.current.phone = el; }}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Phone Number *
</label>
<input
type="tel"
name="phone"
value={formData.phone}
onChange={(e) => {
handleInputChange(e);
setErrors(prev => ({...prev, phone: ''}));