-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile.html
More file actions
1084 lines (963 loc) · 52 KB
/
profile.html
File metadata and controls
1084 lines (963 loc) · 52 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Profile</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="profile.css">
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
<div class="flex flex-col md:flex-row w-full max-w-6xl gap-6">
<aside class="sidebar w-full md:w-1/4 flex flex-col items-center md:items-start p-6 space-y-4">
<a href="seed.html"
class="flex items-center w-full px-4 py-3 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors duration-200">
<i class="fas fa-home text-xl mr-3"></i>
Dashboard
</a>
<a href="#" id="profile-link"
class="flex items-center w-full px-4 py-3 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors duration-200">
<i class="fas fa-user-circle text-xl mr-3"></i>
My Profile
</a>
<a href="#" id="wishlist-link"
class="flex items-center w-full px-4 py-3 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors duration-200">
<i class="fas fa-heart text-xl mr-3"></i>
Wishlist
</a>
<a href="#" id="settings-link"
class="flex items-center w-full px-4 py-3 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors duration-200 active">
<i class="fas fa-cog text-xl mr-3"></i>
Settings
</a>
<a href="#" id="order-history-link"
class="flex items-center w-full px-4 py-3 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors duration-200">
<i class="fas fa-history text-xl mr-3"></i>
Order History
</a>
</aside>
<div id="content-container" class="w-full md:w-3/4">
<main id="profile-content" class="main-content p-8">
<div class="profile-card-header">
My Profile
</div>
<div class="flex flex-col md:flex-row items-center md:items-start mt-8 gap-8">
<div class="flex-grow">
<div id="read-only-view" class="space-y-4">
<div class="relative mb-6">
<h1 id="user-name-display" class="text-5xl font-extrabold mb-1">Loading...</h1>
<button id="edit-btn"
class="absolute top-0 right-0 text-white text-lg hover:text-gray-300 transition-colors duration-200">
<i class="fas fa-pencil-alt"></i>
</button>
</div>
<div class="space-y-4 text-sm">
<div>
<p class="text-gray-400">Email Address:</p>
<p id="user-email-display" class="font-medium text-white">Loading...</p>
</div>
<div>
<p class="text-gray-400">Phone Number:</p>
<p id="user-phone-display" class="font-medium text-white">Loading...</p>
</div>
<div>
<p class="text-gray-400">Address:</p>
<p id="user-address-display" class="font-medium text-white">Loading...</p>
</div>
<div>
<p class="text-gray-400">Gender:</p>
<p id="user-gender-display" class="font-medium text-white">Loading...</p>
</div>
<div>
<p class="text-gray-400">Date of Birth:</p>
<p id="user-dob-display" class="font-medium text-white">Loading...</p>
</div>
</div>
</div>
<div id="editable-view" class="hidden">
<div class="relative mb-6">
<h1 class="text-5xl font-extrabold mb-1">My Profile</h1>
<button id="save-btn"
class="absolute top-0 right-0 text-white text-lg hover:text-gray-300 transition-colors duration-200">
<i class="fas fa-check"></i>
</button>
</div>
<div class="space-y-4">
<div>
<label for="fullName" class="form-label block mb-2">Full Name:</label>
<input type="text" id="fullName" class="form-input-group w-full">
</div>
<div>
<label for="email" class="form-label block mb-2">Email Address:</label>
<input type="email" id="email" class="form-input-group w-full">
</div>
<div>
<label for="phone" class="form-label block mb-2">Phone Number:</label>
<input type="tel" id="phone" class="form-input-group w-full">
</div>
<div>
<label for="address" class="form-label block mb-2">Address:</label>
<input type="text" id="address" class="form-input-group w-full">
</div>
<div>
<label class="form-label block mb-2">Gender:</label>
<div class="flex items-center space-x-6">
<div class="flex items-center">
<input type="radio" id="male" name="gender" value="male" class="form-radio"
checked>
<label for="male" class="ml-2 text-white">Male</label>
</div>
<div class="flex items-center">
<input type="radio" id="female" name="gender" value="female"
class="form-radio">
<label for="female" class="ml-2 text-white">Female</label>
</div>
<div class="flex items-center">
<input type="radio" id="other" name="gender" value="other"
class="form-radio">
<label for="other" class="ml-2 text-white">Other</label>
</div>
</div>
</div>
<div>
<label class="form-label block mb-2">Date of Birth:</label>
<div class="flex space-x-4">
<select id="dob-date" class="form-input-group w-1/3 text-black-900">
<option value="">Date</option>
</select>
<select id="dob-month" class="form-input-group w-1/3 text-black-900">
<option value="">Month</option>
</select>
<select id="dob-year" class="form-input-group w-1/3 text-black-900">
<option value="">Year</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div
class="flex-shrink-0 w-32 h-32 md:w-48 md:h-48 rounded-full bg-white flex items-center justify-center overflow-hidden border-4 border-white shadow-lg">
<img id="profile-image" class="w-full h-full object-cover"
src="https://placehold.co/200x200/cccccc/333333?text=Profile" alt="Profile Picture">
</div>
</div>
<div id="image-upload-section" class="mt-8 flex justify-center md:justify-end hidden">
<input type="file" id="image-upload" class="hidden">
<button id="upload-image-btn"
class="bg-orange-500 hover:bg-orange-600 text-white font-bold py-2 px-6 rounded-full transition-colors duration-200 shadow-lg">Upload
image</button>
</div>
<div class="mt-8 flex justify-center md:justify-end hidden" id="apply-changes-container">
<button id="apply-changes-btn"
class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-12 rounded-full transition-colors duration-200 shadow-lg">APPLY
CHANGES</button>
</div>
</main>
<main id="wishlist-content" class="wishlist-container p-8 hidden">
<div class="wishlist-header">
<i class="fas fa-arrow-left"></i>
<h2>User's Fave</h2>
</div>
<div id="wishlist-list-container" class="space-y-4">
</div>
<div id="empty-wishlist-message" class="empty-order-card hidden">
<span class="confused-emoji">✨</span>
<h2>Your wishlist is empty! Find your new favorite items now.</h2>
</div>
</main>
<main id="order-history-content" class="order-history-container p-8 hidden">
<div class="order-history-header">
<i class="fas fa-arrow-left"></i>
<h2>Order History</h2>
<span id="order-count-display" class="order-count">(0 Orders)</span>
</div>
<div id="orders-list-container" class="space-y-4">
</div>
<div id="empty-orders-message" class="empty-order-card hidden">
<span class="confused-emoji">😕</span>
<h2>You haven't placed any orders yet. Start shopping now!</h2>
</div>
</main>
<main id="settings-content" class="settings-container p-8 hidden">
<div class="settings-header">
<i class="fas fa-cog"></i>
<h2>Settings</h2>
</div>
<nav class="flex flex-col space-y-4 mb-8">
<a href="#" id="banks-link"
class="flex items-center justify-between bg-white text-gray-800 p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow">
<div class="flex items-center">
<i class="fas fa-credit-card text-2xl mr-4 text-orange-500"></i>
<h3 class="font-semibold">Banks & Card</h3>
</div>
<i class="fas fa-chevron-right text-gray-400"></i>
</a>
<a href="#" id="privacy-link"
class="flex items-center justify-between bg-white text-gray-800 p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow">
<div class="flex items-center">
<i class="fas fa-lock text-2xl mr-4 text-orange-500"></i>
<h3 class="font-semibold">Privacy Settings</h3>
</div>
<i class="fas fa-chevron-right text-gray-400"></i>
</a>
<a href="#" id="notifications-link"
class="flex items-center justify-between bg-white text-gray-800 p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow">
<div class="flex items-center">
<i class="fas fa-bell text-2xl mr-4 text-orange-500"></i>
<h3 class="font-semibold">Notification Settings</h3>
</div>
<i class="fas fa-chevron-right text-gray-400"></i>
</a>
<a href="#" id="address-link"
class="flex items-center justify-between bg-white text-gray-800 p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow">
<div class="flex items-center">
<i class="fas fa-map-marker-alt text-2xl mr-4 text-orange-500"></i>
<h3 class="font-semibold">Address</h3>
</div>
<i class="fas fa-chevron-right text-gray-400"></i>
</a>
</nav>
</main>
<main id="banks-content" class="settings-container p-8 hidden">
<div class="settings-header">
<a href="#" class="text-white hover:text-gray-300 transition-colors" id="banks-back-link">
<i class="fas fa-arrow-left"></i>
</a>
<i class="fas fa-credit-card ml-4"></i>
<h2 class="ml-4">Banks & Card</h2>
</div>
<div class="settings-card">
<div class="card-header">
<i class="fas fa-university"></i>
<h3>My Banks</h3>
</div>
<p class="text-gray-500 mb-4">You have not added any bank accounts yet.</p>
<button
class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-full transition-colors duration-200">
ADD NEW BANK
</button>
</div>
<div class="settings-card">
<div class="card-header">
<i class="fas fa-credit-card"></i>
<h3>My Cards</h3>
</div>
<p class="text-gray-500 mb-4">You have not added any cards yet.</p>
<button
class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-full transition-colors duration-200">
ADD NEW CARD
</button>
</div>
</main>
<main id="privacy-content" class="settings-container p-8 hidden">
<div class="settings-header">
<a href="#" class="text-white hover:text-gray-300 transition-colors" id="privacy-back-link">
<i class="fas fa-arrow-left"></i>
</a>
<i class="fas fa-lock ml-4"></i>
<h2 class="ml-4">Privacy Settings</h2>
</div>
<div class="settings-card">
<div class="card-header">
<i class="fas fa-shield-alt"></i>
<h3>Account Privacy</h3>
</div>
<div class="settings-item">
<div class="settings-item-info">
<h4 class="settings-item-title">Private account</h4>
<p class="settings-item-description">Only followers can see your profile and activity.</p>
</div>
<label class="toggle-switch-container">
<input type="checkbox">
<span class="toggle-slider"></span>
</label>
</div>
<div class="settings-item">
<div class="settings-item-info">
<h4 class="settings-item-title">Activity status</h4>
<p class="settings-item-description">Allow accounts you follow and anyone you've messaged to
see when you were last active.</p>
</div>
<label class="toggle-switch-container">
<input type="checkbox" checked>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</main>
<main id="notifications-content" class="settings-container p-8 hidden">
<div class="settings-header">
<a href="#" class="text-white hover:text-gray-300 transition-colors" id="notifications-back-link">
<i class="fas fa-arrow-left"></i>
</a>
<i class="fas fa-bell ml-4"></i>
<h2 class="ml-4">Notification Settings</h2>
</div>
<div class="settings-card">
<div class="settings-item">
<div class="settings-item-info">
<h4 class="settings-item-title">Email Notifications</h4>
<p class="settings-item-description">Receive promotional emails.</p>
</div>
<label class="toggle-switch-container">
<input type="checkbox" checked>
<span class="toggle-slider"></span>
</label>
</div>
<div class="settings-item">
<div class="settings-item-info">
<h4 class="settings-item-title">Push Notifications</h4>
<p class="settings-item-description">Receive notifications about orders and promotions.</p>
</div>
<label class="toggle-switch-container">
<input type="checkbox" checked>
<span class="toggle-slider"></span>
</label>
</div>
<div class="settings-item">
<div class="settings-item-info">
<h4 class="settings-item-title">SMS Notifications</h4>
<p class="settings-item-description">Receive delivery updates via SMS.</p>
</div>
<label class="toggle-switch-container">
<input type="checkbox">
<span class="toggle-slider"></span>
</label>
</div>
</div>
</main>
<main id="address-content" class="settings-container p-8 hidden">
<div class="settings-header">
<a href="#" class="text-white hover:text-gray-300 transition-colors" id="address-back-link">
<i class="fas fa-arrow-left"></i>
</a>
<i class="fas fa-map-marker-alt ml-4"></i>
<h2 class="ml-4">Address</h2>
</div>
<div class="settings-card">
<div class="card-header">
<i class="fas fa-home"></i>
<h3>Primary Address</h3>
</div>
<div class="flex items-center justify-between mb-4">
<div class="flex-grow">
<h4 class="font-semibold text-lg" id="shipping-name-display">Loading Name...</h4>
<p class="text-gray-600" id="shipping-address-display">Loading Address...</p>
</div>
<button id="edit-shipping-address-btn" class="text-blue-600 hover:text-blue-700 font-semibold">EDIT</button>
</div>
<hr class="my-4">
<button
class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-full transition-colors duration-200">
ADD NEW ADDRESS
</button>
</div>
</main>
</div>
</div>
<div id="message-box" class="message-box">
Changes applied successfully!
</div>
<script type="module">
// Corrected lines for profile.html
import { initializeApp } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-app.js";
// UPDATED IMPORTS: Added deleteDoc and addDoc for wishlist actions
import { getFirestore, doc, getDoc, setDoc, collection, getDocs, deleteDoc, addDoc } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-firestore.js";
import { getStorage, ref, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-storage.js";
import { getAuth, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/12.3.0/firebase-auth.js";
// Firebase Configuration with your new details
const firebaseConfig = {
apiKey: "AIzaSyAqDLocdi1CDHDeD5Z_LOlVZOycI2tuJpk",
authDomain: "digisoria-baa83.firebaseapp.com",
projectId: "digisoria-baa83",
storageBucket: "digisoria-baa83.firebasestorage.app",
messagingSenderId: "1042609120554",
appId: "1:1042609120554:web:0500a100e9ae42ead32a53",
measurementId: "G-TM8CBPSRR9"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const storage = getStorage(app);
const auth = getAuth(app);
// NO HARDCODED UID. It will be set upon successful authentication.
let currentUserUid = null;
const editBtn = document.getElementById('edit-btn');
const saveBtn = document.getElementById('save-btn');
const applyChangesBtn = document.getElementById('apply-changes-btn');
const readOnlyView = document.getElementById('read-only-view');
const editableView = document.getElementById('editable-view');
const applyChangesContainer = document.getElementById('apply-changes-container');
const imageUploadSection = document.getElementById('image-upload-section');
const messageBox = document.getElementById('message-box');
const userNameDisplay = document.getElementById('user-name-display');
const userEmailDisplay = document.getElementById('user-email-display');
const userPhoneDisplay = document.getElementById('user-phone-display');
const userAddressDisplay = document.getElementById('user-address-display');
const userGenderDisplay = document.getElementById('user-gender-display');
const userDobDisplay = document.getElementById('user-dob-display');
const userNameInput = document.getElementById('fullName');
const userEmailInput = document.getElementById('email');
const userPhoneInput = document.getElementById('phone');
const userAddressInput = document.getElementById('address');
const genderRadios = document.getElementsByName('gender');
const dobDateSelect = document.getElementById('dob-date');
const dobMonthSelect = document.getElementById('dob-month');
const dobYearSelect = document.getElementById('dob-year');
const profileImage = document.getElementById('profile-image');
const uploadImageBtn = document.getElementById('upload-image-btn');
const imageUploadInput = document.getElementById('image-upload');
const profileLink = document.getElementById('profile-link');
const wishlistLink = document.getElementById('wishlist-link');
const orderHistoryLink = document.getElementById('order-history-link');
const settingsLink = document.getElementById('settings-link');
const profileContent = document.getElementById('profile-content');
const wishlistContent = document.getElementById('wishlist-content');
const orderHistoryContent = document.getElementById('order-history-content');
const settingsContent = document.getElementById('settings-content');
const banksContent = document.getElementById('banks-content');
const privacyContent = document.getElementById('privacy-content');
const notificationsContent = document.getElementById('notifications-content');
const addressContent = document.getElementById('address-content');
const banksLink = document.getElementById('banks-link');
const privacyLink = document.getElementById('privacy-link');
const notificationsLink = document.getElementById('notifications-link');
const addressLink = document.getElementById('address-link');
const banksBackLink = document.getElementById('banks-back-link');
const privacyBackLink = document.getElementById('privacy-back-link');
const notificationsBackLink = document.getElementById('notifications-back-link');
const addressBackLink = document.getElementById('address-back-link');
// DOM elements for Order History
const ordersListContainer = document.getElementById('orders-list-container');
const emptyOrdersMessage = document.getElementById('empty-orders-message');
const orderCountDisplay = document.getElementById('order-count-display');
// NEW: DOM elements for Wishlist
const wishlistListContainer = document.getElementById('wishlist-list-container');
const emptyWishlistMessage = document.getElementById('empty-wishlist-message');
// NEW: DOM elements for Address Content (for the fix)
const shippingNameDisplay = document.getElementById('shipping-name-display');
const shippingAddressDisplay = document.getElementById('shipping-address-display');
// Placeholder for user profile data
let userProfile = {
name: "N/A",
email: "N/A",
phone: "N/A",
address: "N/A",
gender: "N/A",
dob: {
date: "",
month: "",
year: ""
},
image: "https://placehold.co/200x200/cccccc/333333?text=Profile"
};
// NEW: Helper function to generate star icons based on rating
function getRatingStars(rating) {
let stars = '';
const fullStars = Math.floor(rating);
const hasHalfStar = rating % 1 !== 0;
for (let i = 0; i < 5; i++) {
if (i < fullStars) {
stars += '<i class="fas fa-star filled"></i>';
} else if (i === fullStars && hasHalfStar) {
stars += '<i class="fas fa-star-half-alt filled"></i>';
} else {
stars += '<i class="far fa-star"></i>'; // Use 'far' for empty star
}
}
return stars;
}
// NEW: Function to create HTML for a single wishlist item card
function createWishlistItemHtml(item) {
// Assuming default values for robust rendering
const inStock = item.stockStatus === 'In stock' || item.stockStatus === 'In Stock';
const stockClass = inStock ? 'text-green-500' : 'text-red-500';
const stockText = inStock ? 'In stock' : 'Out of stock';
const price = item.price ? `$${parseFloat(item.price).toFixed(2)}` : 'N/A';
const ratingHtml = getRatingStars(item.rating || 0);
return `
<div class="wishlist-item-card">
<div class="item-info">
<span class="stock-status ${stockClass}">${stockText}</span>
<h3 class="product-name">${item.name || 'Product Name'}</h3>
<div class="rating">
${ratingHtml}
</div>
<span class="product-price">${price}</span>
</div>
<div class="item-actions">
<button class="add-to-cart-btn" data-product-id="${item.id}">ADD TO CART</button>
<button class="delete-btn" data-product-id="${item.id}">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</div>
`;
}
// NEW: Function to handle 'Delete' and 'Add to Cart' actions
async function handleWishlistAction(productId, actionType) {
if (!currentUserUid) {
showMessage("User not authenticated. Please log in.", "error");
return;
}
const itemRef = doc(db, "users", currentUserUid, "wishlist", productId);
let success = false;
try {
if (actionType === 'delete') {
// Action 1: Delete from Wishlist
await deleteDoc(itemRef);
showMessage("Item successfully removed from wishlist!");
success = true;
} else if (actionType === 'add-to-cart') {
// Action 2: Move to Cart
// 1. Fetch the item data first to get name/price
const itemSnap = await getDoc(itemRef);
if (!itemSnap.exists()) {
showMessage("Error: Wishlist item not found.", "error");
return;
}
const itemData = itemSnap.data();
// 2. Add item to the 'cart' subcollection
// Note: In a real app, you might want to check if the item already exists in the cart.
const cartCollectionRef = collection(db, "users", currentUserUid, "cart");
await addDoc(cartCollectionRef, {
productId: productId,
name: itemData.name,
price: itemData.price,
quantity: 1, // Default to 1 item
addedAt: new Date().toISOString()
});
// 3. Remove the item from the wishlist afterwards
await deleteDoc(itemRef);
showMessage("Item moved to cart and removed from wishlist!");
success = true;
}
} catch (error) {
console.error(`Error performing ${actionType} action:`, error);
showMessage(`Failed to perform ${actionType} action. Check Firestore rules.`, "error");
}
// Refresh the wishlist view if the action was successful
if (success) {
fetchAndDisplayWishlist();
}
}
// NEW: Function to fetch and display wishlist
async function fetchAndDisplayWishlist() {
if (!currentUserUid) {
showMessage("User not authenticated. Cannot load wishlist.", "error");
return;
}
wishlistListContainer.innerHTML = '';
emptyWishlistMessage.classList.add('hidden');
// Target the assumed 'wishlist' subcollection under the user's document
const wishlistCollectionRef = collection(db, "users", currentUserUid, "wishlist");
try {
const querySnapshot = await getDocs(wishlistCollectionRef);
if (querySnapshot.empty) {
console.log("No wishlist items found.");
emptyWishlistMessage.classList.remove('hidden'); // Show empty state
return;
}
querySnapshot.forEach((doc) => {
const itemData = doc.data();
const wishlistItem = {
id: doc.id,
// Spread all other data (name, price, rating, stockStatus)
...itemData
};
const itemCardHtml = createWishlistItemHtml(wishlistItem);
wishlistListContainer.insertAdjacentHTML('beforeend', itemCardHtml);
});
console.log("Wishlist loaded successfully.");
} catch (error) {
console.error("Error fetching wishlist:", error);
showMessage("Failed to load wishlist. Check Firestore rules or collection path.", "error");
}
}
// NEW: Function to create HTML for a single order card
function createOrderCardHtml(order) {
const date = new Date(order.date).toLocaleDateString();
// Create the list of items for the card body
const itemsHtml = order.items.map(item => `
<p class="text-sm text-gray-700">${item.name} x ${item.quantity} ($${item.price.toFixed(2)})</p>
`).join('');
return `
<div class="bg-white text-gray-800 rounded-xl shadow-lg p-6 hover:shadow-xl transition-shadow">
<div class="flex justify-between items-center border-b pb-3 mb-3">
<h3 class="text-xl font-bold text-blue-800">Order ID: #${order.id.substring(0, 8)}</h3>
<span class="text-sm font-semibold text-green-600">${order.status || 'Delivered'}</span>
</div>
<div class="space-y-1 mb-4">
<p class="text-gray-500 text-sm">Order Date: ${date}</p>
${itemsHtml}
</div>
<div class="flex justify-between items-center pt-3 border-t">
<span class="text-lg font-bold">Total: $${order.total.toFixed(2)}</span>
<button class="text-sm bg-orange-500 hover:bg-orange-600 text-white font-semibold py-2 px-4 rounded-full transition-colors">
View Details
</button>
</div>
</div>
`;
}
// UPDATED: Function to fetch and display orders with count logic
async function fetchAndDisplayOrders() {
if (!currentUserUid) {
showMessage("User not authenticated. Cannot load order history.", "error");
orderCountDisplay.textContent = '(0 Orders)';
return;
}
ordersListContainer.innerHTML = '';
orderCountDisplay.textContent = '(Loading...)';
emptyOrdersMessage.classList.add('hidden');
// Target the assumed 'orders' subcollection under the user's document
const ordersCollectionRef = collection(db, "users", currentUserUid, "orders");
try {
// Fetch all documents from the 'orders' subcollection
const querySnapshot = await getDocs(ordersCollectionRef);
// --- START OF ORDER COUNT LOGIC ---
const orderCount = querySnapshot.size; // Get the number of orders
// Update the count display
orderCountDisplay.textContent = `(${orderCount} Order${orderCount !== 1 ? 's' : ''})`;
// --- END OF ORDER COUNT LOGIC ---
if (querySnapshot.empty) {
console.log("No orders found.");
emptyOrdersMessage.classList.remove('hidden'); // Show empty state
return;
}
querySnapshot.forEach((doc) => {
const orderData = doc.data();
// Assuming default values if data is missing for robust rendering
const orderWithId = {
id: doc.id,
// Note: If you use Firestore Timestamp, you may need to convert it: orderData.date.toDate().toISOString()
date: orderData.date || new Date().toISOString(),
total: orderData.total || 0,
status: orderData.status || 'Processing',
items: orderData.items || [] // Must be an array of items for rendering
};
const orderCardHtml = createOrderCardHtml(orderWithId);
ordersListContainer.insertAdjacentHTML('beforeend', orderCardHtml);
});
console.log("Order history loaded successfully.");
} catch (error) {
console.error("Error fetching order history:", error);
showMessage("Failed to load order history. Check Firestore rules or collection path.", "error");
orderCountDisplay.textContent = '(Error Loading)';
}
}
async function fetchUserProfile(uid) {
const docRef = doc(db, "users", uid);
try {
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
const data = docSnap.data();
// 1. Merge the existing userProfile (which holds the Auth email set in onAuthStateChanged)
// with the Firestore data.
userProfile = {
...userProfile, // Contains authenticated email, and existing defaults
...data // Overwrites fields with Firestore data
};
// --- START OF FIX: Explicitly ensure the email from the live auth object is used ---
if (auth.currentUser && auth.currentUser.email) {
userProfile.email = auth.currentUser.email;
}
// --- END OF FIX ---
console.log("User profile loaded:", userProfile);
updateDisplayData();
} else {
console.log(`No user profile found for UID: ${uid}. Showing default data.`);
// If no profile exists for the signed-in user, use default data and prompt user to edit
showMessage("Your profile data is missing. Please use the edit button to create it.", "warning");
updateDisplayData();
}
} catch (error) {
console.error("Error fetching user profile:", error);
// MODIFIED: Differentiate network errors from security/other errors
if (error.code === 'unavailable' || String(error).includes('offline')) {
showMessage("Failed to load profile. Please check your network connection.", "error");
} else {
showMessage("Failed to load profile data. Check Firestore rules.", "error");
}
}
}
async function saveUserProfile() {
if (!currentUserUid) {
showMessage("User not authenticated. Cannot save profile.", "error");
return;
}
const uid = currentUserUid;
const docRef = doc(db, "users", uid);
let newProfileData = {
name: userNameInput.value,
email: userEmailInput.value,
phone: userPhoneInput.value,
address: userAddressInput.value,
gender: Array.from(genderRadios).find(radio => radio.checked).value,
dob: {
date: dobDateSelect.value,
// Get the month name from the selected option's text
month: dobMonthSelect.options[dobMonthSelect.selectedIndex].textContent,
year: dobYearSelect.value
},
image: profileImage.src // Keep the current image URL
};
const file = imageUploadInput.files[0];
if (file) {
try {
const storageRef = ref(storage, `profile_pictures/${uid}/${file.name}`);
const snapshot = await uploadBytes(storageRef, file);
const downloadURL = await getDownloadURL(snapshot.ref);
newProfileData.image = downloadURL;
profileImage.src = downloadURL;
} catch (error) {
console.error("Error uploading image:", error);
showMessage("Image upload failed.", "error");
// Continue saving other data even if image upload fails
}
}
try {
await setDoc(docRef, newProfileData, {
merge: true
});
console.log("Profile updated successfully!");
userProfile = newProfileData; // Update local state
updateDisplayData(); // Update the UI with new data
showMessage("Changes applied successfully!");
} catch (error) {
console.error("Error writing document:", error);
// MODIFIED: Differentiate network errors from security/other errors
if (error.code === 'unavailable' || String(error).includes('offline')) {
showMessage("Failed to save changes. Please check your network connection.", "error");
} else {
showMessage("Failed to save changes. Check Firestore rules.", "error");
}
}
toggleEditMode(false);
}
function showSection(sectionToShow) {
const allSections = [
profileContent,
wishlistContent,
orderHistoryContent,
settingsContent,
banksContent,
privacyContent,
notificationsContent,
addressContent
];
allSections.forEach(section => {
if (section === sectionToShow) {
section.classList.remove('hidden');
} else {
section.classList.add('hidden');
}
});
}
// --- Event Listeners ---
profileLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(profileContent);
});
// MODIFIED: Wishlist link now calls fetchAndDisplayWishlist
wishlistLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(wishlistContent);
fetchAndDisplayWishlist();
});
// MODIFIED: Order History link now calls fetchAndDisplayOrders
orderHistoryLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(orderHistoryContent);
fetchAndDisplayOrders();
});
settingsLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(settingsContent);
});
banksLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(banksContent);
});
privacyLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(privacyContent);
});
notificationsLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(notificationsContent);
});
addressLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(addressContent);
// NEW: Update the address content when the section is shown
updateAddressContent();
});
banksBackLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(settingsContent);
});
privacyBackLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(settingsContent);
});
notificationsBackLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(settingsContent);
});
addressBackLink.addEventListener('click', (event) => {
event.preventDefault();
showSection(settingsContent);
});
editBtn.addEventListener('click', () => {
toggleEditMode(true);
});
saveBtn.addEventListener('click', saveUserProfile);
applyChangesBtn.addEventListener('click', saveUserProfile);
uploadImageBtn.addEventListener('click', () => {
imageUploadInput.click();
});
imageUploadInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
profileImage.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
// NEW: Event Delegation for Wishlist Buttons
wishlistListContainer.addEventListener('click', (event) => {
const clickedButton = event.target.closest('button');
if (clickedButton) {
const productId = clickedButton.dataset.productId;
if (clickedButton.classList.contains('delete-btn')) {
// Action 1: Delete
handleWishlistAction(productId, 'delete');
} else if (clickedButton.classList.contains('add-to-cart-btn')) {
// Action 2: Add to Cart (and remove from wishlist)
handleWishlistAction(productId, 'add-to-cart');
}
}
});
function toggleEditMode(isEditing) {
if (isEditing) {
readOnlyView.classList.add('hidden');
editableView.classList.remove('hidden');
applyChangesContainer.classList.remove('hidden');
imageUploadSection.classList.remove('hidden');
populateFormFields();
} else {
readOnlyView.classList.remove('hidden');
editableView.classList.add('hidden');
applyChangesContainer.classList.add('hidden');
imageUploadSection.classList.add('hidden');
}
}
function populateFormFields() {
// FIX: Ensure DOB selects are populated before trying to set their values
populateDateOfBirth();
userNameInput.value = userProfile.name;
userEmailInput.value = userProfile.email;
userPhoneInput.value = userProfile.phone;
userAddressInput.value = userProfile.address;
Array.from(genderRadios).forEach(radio => {
if (radio.value.toLowerCase() === userProfile.gender.toLowerCase()) {
radio.checked = true;
}
});
// FIX/RETAIN: Correctly set DOB values using month name to index mapping
dobDateSelect.value = userProfile.dob.date;
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const monthIndex = months.indexOf(userProfile.dob.month);
if (monthIndex > -1) {
// The value of the select option is 1-indexed (1 to 12)
dobMonthSelect.value = monthIndex + 1;
} else {
dobMonthSelect.value = ''; // Reset to default "Month" if no match
}
dobYearSelect.value = userProfile.dob.year;
}
function updateDisplayData() {
userNameDisplay.textContent = userProfile.name;
userEmailDisplay.textContent = userProfile.email;
userPhoneDisplay.textContent = userProfile.phone;
userAddressDisplay.textContent = userProfile.address;
// Check for 'N/A' before capitalizing for better display
userGenderDisplay.textContent = userProfile.gender === "N/A" ? "N/A" : userProfile.gender.charAt(0).toUpperCase() + userProfile.gender.slice(1);
userDobDisplay.textContent = `${userProfile.dob.date}, ${userProfile.dob.month}, ${userProfile.dob.year}`;
profileImage.src = userProfile.image;