-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1354 lines (1173 loc) · 58.6 KB
/
Copy pathscript.js
File metadata and controls
1354 lines (1173 loc) · 58.6 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
// Import the functions you need from the SDKs you need
// UPDATED: Using Firebase SDK version 11.6.1 for better compatibility and features.
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut, sendPasswordResetEmail } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, doc, setDoc, getDoc, updateDoc, onSnapshot, collection, query, orderBy, addDoc, deleteDoc, writeBatch } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js"; // Added writeBatch
// Your web app's Firebase configuration
// IMPORTANT: Ensure this configuration matches your Firebase project's config.
// The apiKey here is a placeholder. If running in a Canvas environment,
// __firebase_config will provide the actual config.
const firebaseConfig = {
apiKey: "AIzaSyA4xfUevmevaMDxK2_gLgvZUoqm0gmCn_k",
authDomain: "store-7b9bd.firebaseapp.com",
projectId: "store-7b9bd",
storageBucket: "store-7b9bd.firebase-storage.app",
messagingSenderId: "1015427798898",
appId: "1:1015427798898:web:a15c71636506fac128afeb",
measurementId: "G-NR4JS3FLWG"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app); // Initialize Firestore
let currentUserId = null; // To store the current authenticated user's ID
let isAdmin = false; // Flag to check if the current user is an admin
// IMPORTANT: Replace "YOUR_ACTUAL_ADMIN_UID_HERE" with the actual UID of your admin user from Firebase Authentication.
// You can find your UID in the Firebase Console -> Authentication -> Users tab.
const ADMIN_UID = "LigBezoWV9eVo8lglsijoWinKmA2"; // Placeholder for Admin UID
let cart = []; // Global cart array
let userOrders = []; // Global array to store user's orders (for user history)
let allProducts = []; // Global array to store all products from Firestore
let sellerIsOnline = false; // New: Global variable for seller status
// New global variable for filtering
let currentCategory = 'all'; // Initialize with 'all' category
// Global variables to store unsubscribe functions for real-time listeners
let unsubscribeUserOrders = null;
let unsubscribeProducts = null;
let unsubscribeSiteSettings = null; // New: Unsubscribe for site settings listener
let flashSaleTimers = {}; // Object to store setInterval IDs for flash sale countdowns
// Reference to the admin panel initialization function from admin.js
let initAdminPanelModule = null;
let adminCleanupFunction = null;
// New: Variable to hold the interval for refreshing the cart when modal is open
let cartRefreshInterval = null;
// --- DOM elements for Authentication ---
const authEmailInput = document.getElementById("auth-email");
const authPasswordInput = document.getElementById("auth-password");
const registerButton = document.getElementById("register-button");
const loginButton = document.getElementById("login-button");
const loginRegisterButton = document.getElementById("login-register-button");
const logoutButton = document.getElementById("logout-button");
const myOrdersButton = document.getElementById("my-orders-button");
// adminPanelButton is now managed by admin.js, but its visibility by script.js
const adminPanelButton = document.getElementById("admin-panel-button");
const authMessage = document.getElementById("auth-message");
const userDisplay = document.getElementById("user-display");
const authModal = document.getElementById("auth-modal");
const closeAuthModalBtn = document.getElementById("close-auth-modal");
const forgotPasswordButton = document.getElementById("forgot-password-button"); // New: Forgot Password button
// --- DOM elements for Cart/Checkout ---
const cartIconBtn = document.getElementById("cart-icon-btn");
const cartCountBadge = document.getElementById("cart-count");
const cartModal = document.getElementById("cart-modal");
const closeCartModalBtn = document.getElementById("close-cart-modal");
const cartItemsContainer = document.getElementById("cart-items-container");
const cartSubtotalSpan = document.getElementById("cart-subtotal");
const cartTotalSpan = document.getElementById("cart-total");
const placeOrderBtn = document.getElementById("place-order-btn");
const robloxUsernameInput = document.getElementById("roblox-username-input");
// NEW: DOM elements for payment contact details
const paymentContactNumberSpan = document.getElementById("payment-contact-number");
const copyContactNumberBtn = document.getElementById("copy-contact-number-btn");
// --- DOM elements for Order History ---
const orderHistoryModal = document.getElementById("order-history-modal");
const closeOrderHistoryModalBtn = document.getElementById("close-order-history-modal");
const orderHistoryList = document.getElementById("order-history-list");
const orderHistoryTitle = document.getElementById("order-history-title");
const orderDetailsView = document.getElementById("order-details-view");
const detailOrderId = document.getElementById("detail-order-id");
const detailOrderDate = document.getElementById("detail-order-date");
const detailOrderStatus = document.getElementById("detail-order-status");
const detailOrderPrice = document.getElementById("detail-order-price");
const detailPaymentMethod = document.getElementById("detail-payment-method");
const detailRobloxUsername = document.getElementById("detail-roblox-username");
const detailItemsList = document.getElementById("detail-items-list");
const backToOrderListBtn = document.getElementById("back-to-order-list");
// --- New DOM elements for Seller Status ---
const sellerStatusDisplay = document.getElementById("seller-status-display");
// --- Custom Alert/Confirm Modals ---
// Function to show a custom alert modal instead of native alert()
function showCustomAlert(message) {
const alertModal = document.createElement('div');
alertModal.className = 'custom-modal';
alertModal.innerHTML = `
<div class="custom-modal-content">
<span class="custom-modal-close-btn">×</span>
<p>${message}</p>
<button class="custom-modal-ok-btn">OK</button>
</div>
`;
document.body.appendChild(alertModal);
const closeBtn = alertModal.querySelector('.custom-modal-close-btn');
const okBtn = alertModal.querySelector('.custom-modal-ok-btn');
const closeModal = () => {
alertModal.classList.remove('show');
setTimeout(() => alertModal.remove(), 300);
};
closeBtn.addEventListener('click', closeModal);
okBtn.addEventListener('click', closeModal);
alertModal.addEventListener('click', (event) => {
if (event.target === alertModal) {
closeModal();
}
});
setTimeout(() => alertModal.classList.add('show'), 10);
}
// Function to show a custom confirmation modal instead of native confirm()
function showCustomConfirm(message, onConfirm, onCancel = () => {}) {
const confirmModal = document.createElement('div');
confirmModal.className = 'custom-modal';
confirmModal.innerHTML = `
<div class="custom-modal-content">
<span class="custom-modal-close-btn">×</span>
<p>${message}</p>
<div class="custom-modal-buttons">
<button class="custom-modal-confirm-btn">Yes</button>
<button class="custom-modal-cancel-btn">No</button>
</div>
</div>
`;
document.body.appendChild(confirmModal);
const closeBtn = confirmModal.querySelector('.custom-modal-close-btn');
const confirmBtn = confirmModal.querySelector('.custom-modal-confirm-btn');
const cancelBtn = confirmModal.querySelector('.custom-modal-cancel-btn');
const closeModal = () => {
confirmModal.classList.remove('show');
setTimeout(() => confirmModal.remove(), 300);
};
closeBtn.addEventListener('click', () => { closeModal(); onCancel(); });
cancelBtn.addEventListener('click', () => { closeModal(); onCancel(); });
confirmBtn.addEventListener('click', () => {
onConfirm();
closeModal();
});
confirmModal.addEventListener('click', (event) => {
if (event.target === confirmModal) {
closeModal();
onCancel();
}
});
setTimeout(() => confirmModal.classList.add('show'), 10);
}
// --- Authentication Functions ---
registerButton.addEventListener("click", () => {
const email = authEmailInput.value;
const password = authPasswordInput.value;
if (!email || !password) { authMessage.textContent = "Please enter email and password."; return; }
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
authMessage.textContent = `Registered and logged in as: ${userCredential.user.email}`;
authMessage.style.color = 'green';
console.log("User registered:", userCredential.user.email);
authModal.classList.remove('show');
})
.catch((error) => {
if (error.code === 'auth/email-already-in-use') {
authMessage.textContent = "Registration failed: This email is already in use. Try logging in.";
} else {
authMessage.textContent = `Registration failed: ${error.message}`;
}
authMessage.style.color = 'red';
console.error("Registration error:", error);
});
});
loginButton.addEventListener("click", () => {
const email = authEmailInput.value;
const password = authPasswordInput.value;
if (!email || !password) { authMessage.textContent = "Please enter email and password."; return; }
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
authMessage.textContent = `Logged in as: ${userCredential.user.email}`;
authMessage.style.color = 'green';
console.log("User logged in:", userCredential.user.email);
authModal.classList.remove('show');
})
.catch((error) => {
switch (error.code) {
case 'auth/user-not-found':
case 'auth/wrong-password':
case 'auth/invalid-credential':
authMessage.textContent = "Login failed: Invalid email or password.";
break;
case 'auth/invalid-email':
authMessage.textContent = "Login failed: The email address is not valid.";
break;
case 'auth/user-disabled':
authMessage.textContent = "Login failed: This account has been disabled.";
break;
default:
authMessage.textContent = `Login failed: ${error.message}`;
}
authMessage.style.color = 'red';
console.error("Login error:", error);
});
});
logoutButton.addEventListener("click", () => {
signOut(auth)
.then(() => {
authMessage.textContent = "Logged out successfully.";
authMessage.style.color = 'green';
console.log("User logged out.");
})
.catch((error) => {
authMessage.textContent = `Logout failed: ${error.message}`;
authMessage.style.color = 'red';
console.error("Logout error:", error);
});
});
loginRegisterButton.addEventListener('click', () => {
authModal.classList.add('show');
authMessage.textContent = "";
authMessage.style.color = 'red';
authEmailInput.value = "";
authPasswordInput.value = "";
});
closeAuthModalBtn.addEventListener('click', () => {
cartModal.classList.remove('show'); // Make sure cart modal is closed if auth is opened from it
authModal.classList.remove('show');
});
authModal.addEventListener('click', (event) => {
if (event.target === authModal) {
authModal.classList.remove('show');
}
});
// --- Forgot Password Functionality ---
forgotPasswordButton.addEventListener('click', () => {
const email = authEmailInput.value.trim();
if (!email) {
authMessage.textContent = "Please enter your email to reset your password.";
authMessage.style.color = 'red';
return;
}
sendPasswordResetEmail(auth, email)
.then(() => {
authMessage.textContent = `Password reset email sent to ${email}. Check your inbox!`;
authMessage.style.color = 'green';
authEmailInput.value = "";
authPasswordInput.value = "";
})
.catch((error) => {
switch (error.code) {
case 'auth/invalid-email':
authMessage.textContent = "Password reset failed: The email address is not valid.";
break;
case 'auth/user-not-found':
authMessage.textContent = "Password reset failed: No user found with that email address.";
break;
default:
authMessage.textContent = `Password reset failed: ${error.message}`;
}
authMessage.style.color = 'red';
console.error("Password reset error:", error);
});
});
// --- Authentication State Observer (Crucial for loading user data) ---
onAuthStateChanged(auth, async (user) => {
// Unsubscribe from any existing listeners that are managed here
if (unsubscribeUserOrders) {
unsubscribeUserOrders();
unsubscribeUserOrders = null;
}
// Product listener is always active, no need to unsubscribe here.
// Clean up admin panel if currently active
if (adminCleanupFunction) {
adminCleanupFunction();
adminCleanupFunction = null;
}
// Clear all existing flash sale timers when auth state changes (e.g., logout)
stopAllFlashSaleTimers();
if (user) {
currentUserId = user.uid; // Set current user ID
isAdmin = (currentUserId === ADMIN_UID); // Check if current user is admin
userDisplay.textContent = `Welcome, ${user.email}`;
loginRegisterButton.style.display = "none";
logoutButton.style.display = "inline-block";
myOrdersButton.style.display = "inline-block";
if (isAdmin) {
adminPanelButton.style.display = "inline-block"; // Show Admin Panel button
// Dynamically import and initialize admin module
if (!initAdminPanelModule) {
try {
// Ensure the path is correct relative to script.js
const adminModule = await import('./admin.js');
initAdminPanelModule = adminModule.initAdminPanel;
adminCleanupFunction = adminModule.cleanupAdminPanel; // Get cleanup function
} catch (error) {
console.error("Error loading admin.js:", error);
// Hide admin button if load fails
adminPanelButton.style.display = "none";
}
}
if (initAdminPanelModule) {
// Pass Firestore and Auth instances, plus user info, toggle function, and a GETTER for current seller status
initAdminPanelModule(db, auth, currentUserId, isAdmin, toggleSellerStatus, () => sellerIsOnline);
}
} else {
adminPanelButton.style.display = "none";
}
robloxUsernameInput.style.display = "block";
await loadCartFromFirestore(currentUserId);
await syncCartOnLogin(currentUserId);
unsubscribeUserOrders = setupUserOrderHistoryListener(currentUserId);
} else {
currentUserId = null;
isAdmin = false;
userDisplay.textContent = "";
loginRegisterButton.style.display = "inline-block";
logoutButton.style.display = "none";
myOrdersButton.style.display = "none";
adminPanelButton.style.display = "none";
robloxUsernameInput.style.display = "none";
cart = loadCartFromLocalStorage();
userOrders = [];
}
authEmailInput.value = "";
authPasswordInput.value = "";
authMessage.textContent = "";
authMessage.style.color = 'red';
renderCart(); // Re-render cart after auth state changes to reflect stock adjustments or pricing for guest
// Products are always rendered via the setupProductsListener called globally.
});
// --- Firestore Collection Paths ---
const APP_ID = 'tempest-store-app';
const PRODUCTS_COLLECTION_PATH = `artifacts/${APP_ID}/products`;
const USER_CARTS_COLLECTION_PATH = (userId) => `artifacts/${APP_ID}/users/${userId}/carts`;
const USER_ORDERS_COLLECTION_PATH = (userId) => `artifacts/${APP_ID}/users/${userId}/orders`;
const ALL_ORDERS_COLLECTION_PATH = `artifacts/${APP_ID}/allOrders`;
const SITE_SETTINGS_COLLECTION_PATH = `artifacts/${APP_ID}/settings`; // New: Path for site settings
// --- Product Display (Accessible to all) ---
function setupProductsListener() {
const productsColRef = collection(db, PRODUCTS_COLLECTION_PATH);
return onSnapshot(productsColRef, (snapshot) => {
const fetchedProducts = [];
snapshot.forEach(doc => {
fetchedProducts.push({ id: doc.id, ...doc.data() });
});
allProducts = fetchedProducts;
console.log("Fetched Products from Firestore:", allProducts); // Added for debugging
applyFilters(); // Call applyFilters after products are fetched and updated
renderCart(); // Also re-render the cart to update any stock-related warnings/quantity adjustments
}, (error) => {
console.error("Error listening to products:", error);
});
}
// Call setupProductsListener once when the script loads to always show products
unsubscribeProducts = setupProductsListener();
// --- New: Site Settings Listener and Functions ---
function setupSiteSettingsListener() {
// Listen to a specific document (e.g., 'global') in the settings collection
const settingsDocRef = doc(db, SITE_SETTINGS_COLLECTION_PATH, 'global');
return onSnapshot(settingsDocRef, (docSnap) => {
if (docSnap.exists()) {
const data = docSnap.data();
sellerIsOnline = data.sellerOnline || false; // Default to offline if not set
updateSellerStatusDisplay();
} else {
console.log("No 'global' settings document found. Initializing with default status.");
// If document doesn't exist, create it with default status
// This is allowed by the new rules which allow anyone to read, and admin to write.
// If the document doesn't exist, a read will return !docSnap.exists(), and an admin can create it.
// For general read, it just means no status is set yet.
// No need to try creating it here in JS, just let the admin panel handle initial setup.
sellerIsOnline = false; // Default to offline if no settings doc
updateSellerStatusDisplay();
}
}, (error) => {
console.error("Error listening to site settings:", error);
});
}
function updateSellerStatusDisplay() {
if (sellerIsOnline) {
sellerStatusDisplay.textContent = "Seller Status: Online";
sellerStatusDisplay.classList.remove("status-offline");
sellerStatusDisplay.classList.add("status-online");
} else {
sellerStatusDisplay.textContent = "Seller Status: Offline";
sellerStatusDisplay.classList.remove("status-online");
sellerStatusDisplay.classList.add("status-offline");
}
}
async function toggleSellerStatus(isOnline) {
try {
const settingsDocRef = doc(db, SITE_SETTINGS_COLLECTION_PATH, 'global');
await setDoc(settingsDocRef, { sellerOnline: isOnline }, { merge: true }); // Use setDoc with merge to create if not exists or update
console.log("Seller status updated to:", isOnline);
} catch (e) {
console.error("Error updating seller status:", e);
showCustomAlert("Error updating seller status: " + e.message); // Using custom alert
}
}
// Call setupSiteSettingsListener once when the script loads
unsubscribeSiteSettings = setupSiteSettingsListener();
// --- Cart Persistence (Customer-side) ---
async function saveCartToFirestore(userId, cartData) {
try {
const userCartRef = doc(db, USER_CARTS_COLLECTION_PATH(userId), 'currentCart');
await setDoc(userCartRef, { items: JSON.stringify(cartData) });
console.log("Cart saved to Firestore for user:", userId);
} catch (e) {
console.error("Error saving cart to Firestore:", e);
}
}
async function loadCartFromFirestore(userId) {
try {
const userCartRef = doc(db, USER_CARTS_COLLECTION_PATH(userId), 'currentCart');
const docSnap = await getDoc(userCartRef);
if (docSnap.exists()) {
const data = docSnap.data();
cart = JSON.parse(data.items || '[]');
console.log("Cart loaded from Firestore for user:", userId, cart);
} else {
cart = [];
console.log("No cart found in Firestore for user:", userId);
}
}
catch (e) {
console.error("Error loading cart from Firestore:", e);
cart = [];
}
}
function saveCartToLocalStorage(cartData) {
localStorage.setItem('tempestStoreCart', JSON.stringify(cartData));
}
function loadCartFromLocalStorage() {
const storedCart = localStorage.getItem('tempestStoreCart');
return storedCart ? JSON.parse(storedCart) : [];
}
async function syncCartOnLogin(userId) {
const localCart = loadCartFromLocalStorage();
if (localCart.length > 0) {
const userCartRef = doc(db, USER_CARTS_COLLECTION_PATH(userId), 'currentCart');
const docSnap = await getDoc(userCartRef);
let firestoreCart = [];
if (docSnap.exists()) {
firestoreCart = JSON.parse(docSnap.data().items || '[]');
}
localCart.forEach(localItem => {
const existingItemIndex = firestoreCart.findIndex(item => item.id === localItem.id);
const productDetails = allProducts.find(p => p.id === localItem.id);
// Determine the current effective price for the product from allProducts
let currentEffectivePrice = productDetails ? (
productDetails.flashSale && productDetails.flashSalePrice && productDetails.flashSaleEndTime && new Date(productDetails.flashSaleEndTime) > new Date()
? productDetails.flashSalePrice :
(productDetails.sale && productDetails.salePrice ? productDetails.salePrice : productDetails.price)
) : localItem.effectivePrice || localItem.price; // Fallback to item's price if productDetails not found
// Ensure price is a number before storing or processing further.
currentEffectivePrice = parseFloat(String(currentEffectivePrice).replace('₱', ''));
if (existingItemIndex > -1) {
// Merge quantity if item exists, ensuring it doesn't exceed current stock
if (productDetails) {
const combinedQuantity = firestoreCart[existingItemIndex].quantity + localItem.quantity;
firestoreCart[existingItemIndex].quantity = Math.min(combinedQuantity, productDetails.stock || 0);
firestoreCart[existingItemIndex].effectivePrice = currentEffectivePrice;
} else {
// If product no longer exists, set quantity to 0
firestoreCart[existingItemIndex].quantity = 0;
}
} else {
// Add new item, checking stock
if (productDetails && productDetails.stock > 0) {
firestoreCart.push({ ...localItem, quantity: Math.min(localItem.quantity, productDetails.stock), effectivePrice: currentEffectivePrice });
} else {
console.warn(`Product ${localItem.name} not found or out of stock during sync, not adding from local storage.`);
}
}
});
// Now, we do NOT filter out items with 0 quantity here, allowing them to remain in the cart for visual display.
cart = firestoreCart;
await saveCartToFirestore(userId, cart);
localStorage.removeItem('tempestStoreCart');
renderCart();
}
}
// --- Customer Order History (User-side) ---
function setupUserOrderHistoryListener(userId) {
const ordersCollectionRef = collection(db, USER_ORDERS_COLLECTION_PATH(userId));
const q = query(ordersCollectionRef, orderBy("orderDate", "desc"));
return onSnapshot(q, (snapshot) => {
const fetchedOrders = [];
snapshot.forEach(doc => {
fetchedOrders.push({ id: doc.id, ...doc.data() });
});
userOrders = fetchedOrders;
renderOrderHistory();
}, (error) => {
console.error("Error listening to user order history:", error);
});
}
// --- Cart Management Functions ---
function addToCart(product) {
const productDetails = allProducts.find(p => p.id === product.id);
if (!productDetails || productDetails.stock <= 0) {
showCustomAlert(`${product.name} is currently out of stock.`);
return;
}
const existingItem = cart.find(item => item.id === product.id);
// Determine the effective price at the time of adding to cart
let effectivePrice;
const now = new Date();
if (productDetails.flashSale && productDetails.flashSalePrice && productDetails.flashSaleEndTime && new Date(productDetails.flashSaleEndTime) > now) {
effectivePrice = productDetails.flashSalePrice;
} else if (productDetails.sale && productDetails.salePrice) {
effectivePrice = productDetails.salePrice;
} else {
effectivePrice = productDetails.price;
}
// Ensure effectivePrice is a number before storing.
effectivePrice = parseFloat(String(effectivePrice).replace('₱', ''));
if (existingItem) {
if (existingItem.quantity < productDetails.stock) {
existingItem.quantity++;
existingItem.effectivePrice = effectivePrice; // Update effective price in cart item
showCustomAlert(`Added another ${product.name} to cart. Total: ${existingItem.quantity}`);
} else {
showCustomAlert(`Cannot add more ${product.name}. Max stock reached: ${productDetails.stock}.`);
return; // Don't save/render if no change
}
} else {
cart.push({ ...product, quantity: 1, effectivePrice: effectivePrice }); // Use effectivePrice
showCustomAlert(`Added ${product.name} to cart.`);
}
saveCart();
renderCart();
console.log("Cart contents:", cart);
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
saveCart();
renderCart();
showCustomAlert("Item removed from cart.");
}
function updateCartQuantity(productId, newQuantity) {
const itemIndex = cart.findIndex(item => item.id === productId);
if (itemIndex > -1) {
const productDetails = allProducts.find(p => p.id === productId);
const currentStock = productDetails ? productDetails.stock : 0;
if (newQuantity <= 0) {
// Set quantity to 0 and visually mark as out of stock/disabled
cart[itemIndex].quantity = 0;
} else if (newQuantity > currentStock) {
cart[itemIndex].quantity = currentStock; // Cap quantity at available stock
if (currentStock === 0) { // Should be covered by newQuantity <= 0, but as safeguard
cart[itemIndex].quantity = 0;
} else {
showCustomAlert(`Cannot set quantity for ${cart[itemIndex].name} to ${newQuantity}. Only ${currentStock} available. Quantity adjusted.`);
}
} else {
cart[itemIndex].quantity = newQuantity;
}
saveCart();
renderCart();
}
}
function saveCart() {
if (currentUserId) {
saveCartToFirestore(currentUserId, cart);
} else {
saveCartToLocalStorage(cart);
}
updateCartCountBadge();
}
function updateCartCountBadge() {
// The badge should show the count of unique items in the cart,
// regardless of their current stock quantity.
const totalDistinctItemsInCart = cart.length;
// Get the actual countable items for the place order button and total.
const { total, itemsWithZeroQuantity, totalItemsInCart } = calculateCartTotals();
cartCountBadge.textContent = totalDistinctItemsInCart;
cartCountBadge.style.display = totalDistinctItemsInCart > 0 ? 'inline-block' : 'none';
// The place order button text should still reflect only items that can be ordered
placeOrderBtn.textContent = `Place Order (${totalItemsInCart} item${totalItemsInCart !== 1 ? 's' : ''}) ₱${total.toFixed(2)}`;
// Disable place order button if cart is effectively empty (no items with >0 quantity),
// Roblox username not entered (if logged in), or if there are items with zero quantity.
placeOrderBtn.disabled = totalItemsInCart === 0 || (currentUserId && robloxUsernameInput.value.trim() === '') || itemsWithZeroQuantity > 0;
// Optional: Add a tooltip or message if disabled due to seller being offline
if (itemsWithZeroQuantity > 0) {
placeOrderBtn.title = "Cannot place order: Some items in your cart are out of stock.";
} else if (robloxUsernameInput.value.trim() === '' && currentUserId) {
placeOrderBtn.title = "Please enter your Roblox Username.";
} else if (totalItemsInCart === 0) {
placeOrderBtn.title = "Your cart is empty.";
} else {
placeOrderBtn.title = ""; // Clear tooltip
}
}
function renderCart() {
cartItemsContainer.innerHTML = '';
if (cart.length === 0) {
cartItemsContainer.innerHTML = '<p class="empty-message">Your cart is empty.</p>';
} else {
const itemsToRender = []; // Use this to collect items before filtering
cart.forEach(item => {
const productDetails = allProducts.find(p => p.id === item.id);
let priceToDisplay;
let currentStock = productDetails ? productDetails.stock : 0;
let itemStatusMessage = '';
let isItemOutOfStock = false;
// Logic to adjust quantity and set status based on current stock
if (productDetails) {
if (currentStock === 0) { // If product is truly out of stock
item.quantity = 0; // Force quantity to 0
isItemOutOfStock = true;
itemStatusMessage = '<div class="cart-item-out-of-stock-message">Out of Stock!</div>'; // New div for message
} else if (item.quantity > currentStock) { // If user has more than available stock
item.quantity = currentStock; // Cap quantity at available stock
itemStatusMessage = `<div class="cart-item-status-message">Qty adjusted (Max: ${currentStock})</div>`; // New div for message
}
// Determine the effective price based on current flash sale status
const now = new Date();
if (productDetails.flashSale && productDetails.flashSalePrice && productDetails.flashSaleEndTime && new Date(productDetails.flashSaleEndTime) > now) {
priceToDisplay = productDetails.flashSalePrice;
} else if (productDetails.sale && productDetails.salePrice) {
priceToDisplay = productDetails.salePrice;
} else {
priceToDisplay = productDetails.price;
}
// Ensure priceToDisplay is a number for internal calculations, then format for display if needed.
item.effectivePrice = parseFloat(String(priceToDisplay).replace('₱', '')); // Update item's effectivePrice in cart to match latest
priceToDisplay = `₱${item.effectivePrice.toFixed(2)}`; // Format for display
} else {
// Product no longer exists (deleted by admin or sync issue)
item.quantity = 0; // Set quantity to 0
isItemOutOfStock = true;
itemStatusMessage = '<div class="cart-item-out-of-stock-message">Product Not Found / Out of Stock!</div>'; // New div for message
item.effectivePrice = parseFloat(String(item.effectivePrice || item.price || '0').replace('₱', '')); // Fallback and ensure number
priceToDisplay = `₱${item.effectivePrice.toFixed(2)}`; // Format for display
}
// Always add the item to itemsToRender, regardless of its quantity, to keep it in the cart visually
itemsToRender.push(item);
const imageUrl = `images/${item.image}`;
const cartItemDiv = document.createElement('div');
cartItemDiv.className = 'cart-item';
if (isItemOutOfStock) {
cartItemDiv.classList.add('out-of-stock-cart-item');
}
cartItemDiv.innerHTML = `
<img src="${imageUrl}" alt="${item.name}" onerror="this.onerror=null;this.src='https://placehold.co/70x70/f0f0f0/888?text=Image%20N/A';" />
<div class="cart-item-details">
<h4>${item.name}</h4>
${itemStatusMessage} <!-- Display the status message here -->
<div class="cart-item-price">${priceToDisplay}</div>
</div>
<div class="cart-item-quantity-control">
<button data-id="${item.id}" data-action="decrease" ${isItemOutOfStock || item.quantity === 0 ? 'disabled' : ''}>-</button>
<input type="number" value="${item.quantity}" min="0" data-id="${item.id}" ${isItemOutOfStock ? 'readonly' : ''}>
<button data-id="${item.id}" data-action="increase" ${isItemOutOfStock || item.quantity >= currentStock ? 'disabled' : ''}>+</button>
</div>
<button class="cart-item-remove" data-id="${item.id}">×</button>
`;
cartItemsContainer.appendChild(cartItemDiv);
});
// Update the global cart with the (potentially adjusted) items. This now explicitly includes
// items with quantity 0, as per your request to keep them visually in the cart.
cart = itemsToRender;
saveCart(); // This will persist the quantity adjustments in Firestore/Local Storage
cartItemsContainer.querySelectorAll('.cart-item-quantity-control button').forEach(button => {
button.addEventListener('click', (event) => {
const productId = event.target.dataset.id;
const action = event.target.dataset.action;
const input = event.target.parentElement.querySelector('input');
let newQuantity = parseInt(input.value);
if (action === 'increase') {
newQuantity++;
} else if (action === 'decrease') {
newQuantity--;
}
updateCartQuantity(productId, newQuantity);
});
});
cartItemsContainer.querySelectorAll('.cart-item-quantity-control input[type="number"]').forEach(input => {
input.addEventListener('change', (event) => {
const productId = event.target.dataset.id;
const newQuantity = parseInt(event.target.value);
updateCartQuantity(productId, newQuantity);
});
});
cartItemsContainer.querySelectorAll('.cart-item-remove').forEach(button => {
button.addEventListener('click', (event) => {
const productId = event.target.dataset.id;
showCustomConfirm("Are you sure you want to remove this item from your cart?", () => {
removeFromCart(productId);
});
});
});
}
calculateCartTotals();
updateCartCountBadge(); // This will also disable the place order button if hasOutOfStockItems is true
}
function calculateCartTotals() {
let subtotal = 0;
let totalItemsInCart = 0;
let itemsWithZeroQuantity = 0; // New: Counter for items forced to 0 quantity
cart.forEach(item => {
// Only count items with quantity > 0 for calculating totals and for the totalItemsInCart count
if (item.quantity > 0) {
// Use item.effectivePrice, which is updated in renderCart to reflect current sale status
const priceValue = parseFloat(String(item.effectivePrice || item.price).replace('₱', ''));
subtotal += priceValue * item.quantity;
totalItemsInCart += item.quantity;
} else {
// Count items that are in the cart array but have a quantity of 0
itemsWithZeroQuantity++;
}
});
const total = subtotal;
cartSubtotalSpan.textContent = `₱${subtotal.toFixed(2)}`;
cartTotalSpan.textContent = `₱${total.toFixed(2)}`;
return { subtotal, total, totalItemsInCart, itemsWithZeroQuantity };
}
// --- Cart Modal Event Listeners ---
cartIconBtn.addEventListener('click', () => {
cartModal.classList.add('show');
renderCart(); // Call renderCart to ensure stock checks are done before showing
robloxUsernameInput.style.display = currentUserId ? 'block' : 'none';
updateCartCountBadge();
// Start cart refresh interval when cart modal is opened
if (cartRefreshInterval) { // Clear any existing interval just in case
clearInterval(cartRefreshInterval);
}
cartRefreshInterval = setInterval(renderCart, 1000); // Refresh cart every 1 second (was 5000ms)
});
closeCartModalBtn.addEventListener('click', () => {
cartModal.classList.remove('show');
// Clear cart refresh interval when cart modal is closed
if (cartRefreshInterval) {
clearInterval(cartRefreshInterval);
cartRefreshInterval = null;
}
});
cartModal.addEventListener('click', (event) => {
if (event.target === cartModal) {
cartModal.classList.remove('show');
// Clear cart refresh interval if modal is closed by clicking outside
if (cartRefreshInterval) {
clearInterval(cartRefreshInterval);
cartRefreshInterval = null;
}
}
});
robloxUsernameInput.addEventListener('input', updateCartCountBadge);
// NEW: Event listener for the Copy button
copyContactNumberBtn.addEventListener('click', () => {
console.log("Copy button clicked."); // Debugging: Check if this logs for admin
const contactNumber = paymentContactNumberSpan.textContent;
const tempInput = document.createElement('textarea'); // Use textarea for multi-line support / better copy behavior
tempInput.value = contactNumber;
document.body.appendChild(tempInput);
tempInput.select();
try {
document.execCommand('copy');
showCustomAlert("Number copied to clipboard!");
} catch (err) {
console.error('Failed to copy text: ', err);
showCustomAlert("Failed to copy number. Please copy it manually.");
}
document.body.removeChild(tempInput);
});
// Handles the process of placing an order.
placeOrderBtn.addEventListener('click', async () => {
if (cart.length === 0) {
showCustomAlert("Your cart is empty. Please add items before placing an order.");
return;
}
const { totalItemsInCart, itemsWithZeroQuantity } = calculateCartTotals();
if (itemsWithZeroQuantity > 0) {
showCustomAlert("Cannot place order: Some items in your cart are out of stock or quantities were adjusted. Please review your cart.");
return;
}
const robloxUsername = robloxUsernameInput.value.trim();
if (!currentUserId) {
showCustomAlert("Please login or register to complete your order.");
authModal.classList.add('show'); // Open auth modal
authMessage.textContent = "Please login or register to complete your order.";
authEmailInput.value = "";
authPasswordInput.value = "";
return;
}
if (robloxUsername === '') {
showCustomAlert("Please enter your Roblox Username to proceed with the order.");
return;
}
placeOrderBtn.disabled = true; // Disable button immediately to prevent double clicks
const batch = writeBatch(db); // Initialize a new batch for atomic updates
let orderCanProceed = true;
let outOfStockProductNames = [];
const productSnapshots = new Map(); // Store product data fetched in the first loop
// First, verify stock for all items within the transaction
for (const item of cart) {
// Skip stock verification for items that are already 0 quantity in cart
if (item.quantity === 0) {
continue;
}
const productRef = doc(db, PRODUCTS_COLLECTION_PATH, item.id);
const productSnap = await getDoc(productRef); // Get latest product data
if (!productSnap.exists()) {
orderCanProceed = false;
outOfStockProductNames.push(`${item.name} (Product Not Found)`);
break;
}
const productData = productSnap.data();
productSnapshots.set(item.id, productData); // Store the fetched product data
const availableStock = productData.stock || 0;
if (item.quantity > availableStock) {
orderCanProceed = false;
outOfStockProductNames.push(`${item.name} (Only ${availableStock} left)`);
break;
}
}
if (!orderCanProceed) {
showCustomAlert(`Order cannot be placed due to insufficient stock for: ${outOfStockProductNames.join(', ')}. Please adjust your cart.`);
placeOrderBtn.disabled = false;
return;
}
try {
// If all checks pass, proceed with deducting stock and creating order
for (const item of cart) {
// Only deduct stock for items with quantity > 0
if (item.quantity > 0) {
const productRef = doc(db, PRODUCTS_COLLECTION_PATH, item.id);
const productDataForUpdate = productSnapshots.get(item.id); // Retrieve the stored product data
if (productDataForUpdate) { // Defensive check
batch.update(productRef, {
stock: productDataForUpdate.stock - item.quantity
});
}
}
}
// Recalculate totals right before placing order with latest effective prices
const { subtotal, total } = calculateCartTotals();
const orderDetails = {
userId: currentUserId,
// Deep copy cart items to ensure order details are immutable if cart changes later
// IMPORTANT: Filter out items with 0 quantity from the order details themselves.
items: JSON.parse(JSON.stringify(cart.filter(item => item.quantity > 0))),
subtotal: subtotal,
total: total,
orderDate: new Date().toISOString(),
status: 'Pending',
paymentMethod: document.querySelector('input[name="payment-method"]:checked').value,
robloxUsername: robloxUsername
};
console.log("Placing Order:", orderDetails);
const userOrdersColRef = collection(db, USER_ORDERS_COLLECTION_PATH(currentUserId));
// Add to user-specific collection
const newUserOrderRef = doc(userOrdersColRef); // Create a new document reference with an-generated ID
batch.set(newUserOrderRef, orderDetails); // Use set for new document
const allOrdersColRef = collection(db, ALL_ORDERS_COLLECTION_PATH);
// SetDoc here will act as a create if doc does not exist, which is now allowed by rules
batch.set(doc(allOrdersColRef, newUserOrderRef.id), orderDetails); // Use same ID for allOrders
await batch.commit(); // Commit all batch operations atomically
showCustomAlert("Successfully Placed Order!");
console.log("Order saved to Firestore and stock deducted!");
cart = []; // Clear cart after successful order
saveCart(); // This will clear local storage/Firestore cart and update badge
cartModal.classList.remove('show');
robloxUsernameInput.value = '';
} catch (e) {
console.error("Error placing order and deducting stock:", e);
showCustomAlert("There was an error placing your order or deducting stock. Please try again. Error: " + e.message);
} finally {
placeOrderBtn.disabled = false; // Re-enable button
}
});
// --- Order History Functions (User-side) ---
myOrdersButton.addEventListener('click', () => {