-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2262 lines (1963 loc) · 95.4 KB
/
script.js
File metadata and controls
2262 lines (1963 loc) · 95.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
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyBRlsk-knQs-AMlaTFxlneBMTwlSfwyFaQ",
authDomain: "dsmnru-data.firebaseapp.com",
projectId: "dsmnru-data",
storageBucket: "dsmnru-data.firebasestorage.app",
messagingSenderId: "62250453477",
appId: "1:62250453477:web:087c07403e4fead220470c",
measurementId: "G-VL6V3T96YX"
};
firebase.initializeApp(firebaseConfig);
// Firebase Storage and Firestore references
const db = firebase.firestore();
const storage = firebase.storage();
const auth = firebase.auth();
db.enablePersistence({ synchronizeTabs: true }).catch((error) => {
// Multi-tab and unsupported-browser failures are safe to ignore for this app.
if (error.code !== 'failed-precondition' && error.code !== 'unimplemented') {
console.warn('Firestore persistence unavailable:', error.message);
}
});
// ===== USER AUTHENTICATION & PROFILE MANAGEMENT =====
// Global user state
let currentUser = null;
let searchGateVisible = false;
function isGoogleUser(user) {
if (!user || !Array.isArray(user.providerData)) return false;
return user.providerData.some(provider => provider && provider.providerId === 'google.com');
}
function requiresEmailVerification(user) {
return !!user && !isGoogleUser(user) && !user.emailVerified;
}
async function ensureUserDocumentSynced(user) {
if (!user) return;
const googleAccount = isGoogleUser(user);
const userRef = db.collection('users').doc(user.uid);
const existingDoc = await userRef.get();
const existingData = existingDoc.exists ? existingDoc.data() : {};
await userRef.set({
uid: user.uid,
email: user.email || existingData.email || '',
name: existingData.name || existingData.signupName || user.displayName || 'User',
signupName: existingData.signupName || existingData.name || user.displayName || 'User',
signupEmail: existingData.signupEmail || existingData.email || user.email || '',
signupCourse: existingData.signupCourse || existingData.course || '',
course: existingData.course || existingData.signupCourse || '',
phone: existingData.phone || '',
role: existingData.role || 'user',
emailVerified: !!user.emailVerified || googleAccount,
createdAt: existingData.createdAt || firebase.firestore.FieldValue.serverTimestamp(),
lastSeenAt: firebase.firestore.FieldValue.serverTimestamp()
}, { merge: true });
}
// Update UI based on auth state
function updateUploadAccessUI() {
const uploadSection = document.querySelector('.upload-section');
const uploadOverlay = document.getElementById('uploadFormLockOverlay');
const uploadForm = document.getElementById('userUploadForm');
if (!uploadSection || !uploadOverlay || !uploadForm) return;
const formControls = uploadForm.querySelectorAll('input, button');
if (currentUser && !requiresEmailVerification(currentUser)) {
uploadSection.classList.remove('upload-locked');
uploadOverlay.style.display = 'none';
formControls.forEach(control => {
control.disabled = false;
});
} else {
uploadSection.classList.add('upload-locked');
uploadOverlay.style.display = 'flex';
formControls.forEach(control => {
control.disabled = true;
});
}
}
// Monitor auth state changes
auth.onAuthStateChanged(user => {
currentUser = user;
updateUserUI();
updateUploadAccessUI();
if (user) {
// Check if email is verified
user.reload()
.then(async () => {
await ensureUserDocumentSynced(user);
if (requiresEmailVerification(user)) {
// Show verification prompt modal
showEmailVerificationPrompt();
} else {
loadUserProfile();
checkAndShowProfileCompletionReminder();
const searchInput = document.getElementById('searchInput');
if (searchInput && searchInput.value.trim()) {
performSearch();
}
}
})
.catch(error => {
console.error('Error syncing auth user with Firestore profile:', error);
});
}
});
// Update UI based on auth state
function updateUserUI() {
const loggedOutMenu = document.getElementById('userLoggedOutMenu');
const loggedInMenu = document.getElementById('userLoggedInMenu');
const profileBtn = document.getElementById('profileBtn');
const userDisplayName = document.getElementById('userDisplayName');
if (currentUser) {
loggedOutMenu.style.display = 'none';
loggedInMenu.style.display = 'block';
userDisplayName.textContent = currentUser.displayName || currentUser.email.split('@')[0];
document.getElementById('userNameDisplay').textContent = currentUser.displayName || 'User';
document.getElementById('userEmailDisplay').textContent = currentUser.email;
// Show verification badge if email not verified
const verificationBadge = document.getElementById('emailVerificationBadge');
if (verificationBadge) {
if (requiresEmailVerification(currentUser)) {
verificationBadge.style.display = 'inline-block';
} else {
verificationBadge.style.display = 'none';
}
}
} else {
loggedOutMenu.style.display = 'block';
loggedInMenu.style.display = 'none';
userDisplayName.textContent = 'Login';
}
}
// Profile dropdown toggle
function toggleProfileDropdown() {
const dropdown = document.getElementById('profileDropdown');
dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
}
// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
const profileSection = document.querySelector('.user-profile-section');
if (!profileSection.contains(event.target)) {
document.getElementById('profileDropdown').style.display = 'none';
}
});
// ===== LOGIN FUNCTIONS =====
function openLoginModal() {
document.getElementById('profileDropdown').style.display = 'none';
const modal = new bootstrap.Modal(document.getElementById('loginModal'));
modal.show();
}
function closeLoginModal() {
const modal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (modal) modal.hide();
}
async function signInWithGoogle(providerEntryPoint) {
try {
const provider = new firebase.auth.GoogleAuthProvider();
const result = await auth.signInWithPopup(provider);
await result.user.reload();
await ensureUserDocumentSynced(result.user);
// --- NEW CODE: SEND GOOGLE SIGNUPS TO MAKE.COM ---
// Firebase tells us if this is their first time ever logging in
const isNewUser = result.additionalUserInfo?.isNewUser || providerEntryPoint === 'signup';
if (isNewUser) {
const displayName = result.user.displayName || result.user.email.split('@')[0] || 'User';
await sendSubscriberToMake(displayName, result.user.email);
}
// -------------------------------------------------
const loginModal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (loginModal) loginModal.hide();
const signupModal = bootstrap.Modal.getInstance(document.getElementById('signupModal'));
if (signupModal) signupModal.hide();
document.getElementById('loginForm').reset();
document.getElementById('signupForm').reset();
Swal.fire({
title: 'Signed in with Google',
text: providerEntryPoint === 'signup' ? 'Your Google account was created and signed in.' : 'You are now signed in with your Google account.',
icon: 'success'
});
} catch (error) {
const message = error.code === 'auth/popup-closed-by-user'
? 'Google sign-in was cancelled.'
: error.message;
const errorDiv = providerEntryPoint === 'signup'
? document.getElementById('signupError')
: document.getElementById('loginError');
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.style.display = 'block';
} else {
Swal.fire('Error', message, 'error');
}
}
}
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
const email = document.getElementById('loginEmail').value;
const password = document.getElementById('loginPassword').value;
const errorDiv = document.getElementById('loginError');
try {
errorDiv.style.display = 'none';
const result = await auth.signInWithEmailAndPassword(email, password);
await result.user.reload();
closeLoginModal();
document.getElementById('loginForm').reset();
if (!requiresEmailVerification(result.user)) {
Swal.fire('Success', 'Logged in successfully!', 'success');
} else {
Swal.fire({
title: 'Welcome Back!',
html: '<p>Your email is not verified yet.</p><p>Please verify your email to unlock all features.</p>',
icon: 'info'
});
showEmailVerificationPrompt();
}
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
}
});
// Function to send new users to the beehiiv/Make.com mailing list
async function sendSubscriberToMake(name, email) {
const webhookUrl = "https://hook.us2.make.com/sc9ldu43pg3hnq48y9d6s6fds6j48bqk";
try {
await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name, email: email })
});
console.log('Subscriber sent to Make.com successfully!');
} catch (err) {
console.error('Make.com webhook failed:', err);
}
}
// ===== SIGNUP FUNCTIONS =====
function openSignupModal() {
document.getElementById('profileDropdown').style.display = 'none';
const modal = new bootstrap.Modal(document.getElementById('signupModal'));
modal.show();
}
function closeSearchGateModal() {
const modalElement = document.getElementById('searchGateModal');
const modal = bootstrap.Modal.getInstance(modalElement) || bootstrap.Modal.getOrCreateInstance(modalElement);
modal.hide();
searchGateVisible = false;
}
function openSearchGateModal() {
if (searchGateVisible) return;
const modalElement = document.getElementById('searchGateModal');
const modal = bootstrap.Modal.getOrCreateInstance(modalElement, {
backdrop: 'static',
keyboard: false
});
searchGateVisible = true;
modal.show();
}
const searchGateModalElement = document.getElementById('searchGateModal');
if (searchGateModalElement) {
searchGateModalElement.addEventListener('shown.bs.modal', function() {
const backdrop = document.querySelector('.modal-backdrop:last-of-type');
if (backdrop) {
backdrop.classList.add('search-gate-backdrop');
}
});
searchGateModalElement.addEventListener('hidden.bs.modal', function() {
searchGateVisible = false;
document.querySelectorAll('.modal-backdrop.search-gate-backdrop').forEach(backdrop => {
backdrop.classList.remove('search-gate-backdrop');
});
});
}
function continueBrowsingWithoutSearch() {
closeSearchGateModal();
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.value = '';
}
performSearch();
}
function closeSignupModal() {
const modal = bootstrap.Modal.getInstance(document.getElementById('signupModal'));
if (modal) modal.hide();
}
document.getElementById('signupForm').addEventListener('submit', async function(e) {
e.preventDefault();
// 1. Lock the submit button to prevent double-clicks
const submitBtn = e.target.querySelector('button[type="submit"]');
const originalBtnText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Creating...';
const email = document.getElementById('signupEmail').value.trim();
const password = document.getElementById('signupPassword').value;
const confirmPassword = document.getElementById('signupConfirmPassword').value;
const errorDiv = document.getElementById('signupError');
if (!email || !password || !confirmPassword) {
errorDiv.textContent = 'Email, password, and password confirmation are required.';
errorDiv.style.display = 'block';
resetButton();
return;
}
if (password !== confirmPassword) {
errorDiv.textContent = 'Passwords do not match';
errorDiv.style.display = 'block';
resetButton();
return;
}
try {
errorDiv.style.display = 'none';
const userCredential = await auth.createUserWithEmailAndPassword(email, password);
const user = userCredential.user;
const displayName = email.split('@')[0] || 'User';
// Update user profile
await user.updateProfile({ displayName });
// Send verification email only for non-Google password accounts
if (!isGoogleUser(user)) {
await user.sendEmailVerification();
}
// Create user document in Firestore
await db.collection('users').doc(user.uid).set({
uid: user.uid,
email: email,
signupEmail: email,
name: displayName,
signupName: displayName,
course: '',
signupCourse: '',
emailVerified: isGoogleUser(user) ? true : false,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
bookmarks: [],
phone: '',
preferences: {},
role: 'user'
}, { merge: true });
// 2. Safely call the webhook ONLY after Firestore succeeds
await sendSubscriberToMake(displayName, email);
closeSignupModal();
document.getElementById('signupForm').reset();
// Show success message with verification instruction
Swal.fire({
title: 'Account Created!',
html: isGoogleUser(user)
? '<p>Google account created successfully.</p><p>You can use the app immediately. No email verification is needed.</p>'
: `<p>Account created successfully!</p><p>A verification email has been sent to <strong>${email}</strong>.</p><p>Please check your email and click the verification link to activate your account.</p><p>You can add your name, course, and phone number later from your profile.</p>`,
icon: 'success',
confirmButtonText: 'OK'
});
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
} finally {
// Always unlock the button when finished
resetButton();
}
function resetButton() {
submitBtn.disabled = false;
submitBtn.innerHTML = originalBtnText;
}
});
// ===== PROFILE FUNCTIONS =====
function openProfileModal() {
document.getElementById('profileDropdown').style.display = 'none';
if (currentUser) {
loadUserProfile();
const modal = new bootstrap.Modal(document.getElementById('profileModal'));
modal.show();
}
}
async function loadUserProfile() {
if (!currentUser) return;
try {
await ensureUserDocumentSynced(currentUser);
const userDoc = await db.collection('users').doc(currentUser.uid).get();
if (userDoc.exists) {
const userData = userDoc.data();
const nameValue = userData.name || userData.signupName || currentUser.displayName || '';
const emailValue = userData.email || userData.signupEmail || currentUser.email || '';
const courseValue = userData.course || userData.signupCourse || '';
const phoneValue = userData.phone || '';
document.getElementById('profileName').value = nameValue;
document.getElementById('profileEmail').value = emailValue;
document.getElementById('profileCourse').value = courseValue;
document.getElementById('profilePhone').value = phoneValue;
document.getElementById('profileEmail').readOnly = true;
if (userData.createdAt) {
const date = new Date(userData.createdAt.toDate()).toLocaleDateString();
document.getElementById('profileCreatedDate').textContent = date;
}
} else {
document.getElementById('profileName').value = currentUser.displayName || 'User';
document.getElementById('profileEmail').value = currentUser.email || '';
document.getElementById('profileCourse').value = '';
document.getElementById('profilePhone').value = '';
}
} catch (error) {
console.error('Error loading profile:', error);
}
}
document.getElementById('profileForm').addEventListener('submit', async function(e) {
e.preventDefault();
if (!currentUser) return;
const name = document.getElementById('profileName').value.trim();
const course = document.getElementById('profileCourse').value.trim();
const phone = document.getElementById('profilePhone').value.trim();
const errorDiv = document.getElementById('profileError');
const successDiv = document.getElementById('profileSuccess');
if (!phone) {
errorDiv.textContent = 'Phone number is required.';
errorDiv.style.display = 'block';
return;
}
try {
errorDiv.style.display = 'none';
successDiv.style.display = 'none';
// Update auth profile
await currentUser.updateProfile({
displayName: name
});
// Update Firestore user document
await db.collection('users').doc(currentUser.uid).set({
name: name,
course: course,
phone: phone,
email: currentUser.email,
uid: currentUser.uid,
signupName: name,
signupEmail: currentUser.email,
signupCourse: course
}, { merge: true });
successDiv.textContent = 'Profile updated successfully!';
successDiv.style.display = 'block';
updateUserUI();
// Clear dismissal timestamp so reminder won't show again for this profile
localStorage.removeItem('profileCompletionDismissed');
// Close the profile completion reminder modal if it's open
const profileCompletionModal = bootstrap.Modal.getInstance(document.getElementById('profileCompletionModal'));
if (profileCompletionModal) {
profileCompletionModal.hide();
}
setTimeout(() => {
successDiv.style.display = 'none';
}, 3000);
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
}
});
// ===== SETTINGS FUNCTIONS =====
function openSettingsModal() {
document.getElementById('profileDropdown').style.display = 'none';
const modal = new bootstrap.Modal(document.getElementById('settingsModal'));
modal.show();
}
function openChangePasswordModal() {
const settingsModal = bootstrap.Modal.getInstance(document.getElementById('settingsModal'));
if (settingsModal) settingsModal.hide();
const modal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
modal.show();
}
document.getElementById('changePasswordForm').addEventListener('submit', async function(e) {
e.preventDefault();
if (!currentUser) return;
const currentPassword = document.getElementById('currentPassword').value;
const newPassword = document.getElementById('newPassword').value;
const confirmPassword = document.getElementById('confirmNewPassword').value;
const errorDiv = document.getElementById('passwordError');
const successDiv = document.getElementById('passwordSuccess');
if (newPassword !== confirmPassword) {
errorDiv.textContent = 'New passwords do not match';
errorDiv.style.display = 'block';
return;
}
try {
errorDiv.style.display = 'none';
successDiv.style.display = 'none';
// Re-authenticate user
const credential = firebase.auth.EmailAuthProvider.credential(
currentUser.email,
currentPassword
);
await currentUser.reauthenticateWithCredential(credential);
// Update password
await currentUser.updatePassword(newPassword);
successDiv.textContent = 'Password updated successfully!';
successDiv.style.display = 'block';
document.getElementById('changePasswordForm').reset();
setTimeout(() => {
const modal = bootstrap.Modal.getInstance(document.getElementById('changePasswordModal'));
if (modal) modal.hide();
}, 2000);
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
}
});
function deleteAccountConfirm() {
Swal.fire({
title: 'Delete Account?',
text: 'This action cannot be undone. All your data will be permanently deleted.',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: 'Yes, delete my account'
}).then(async (result) => {
if (result.isConfirmed) {
try {
const user = auth.currentUser;
await db.collection('users').doc(user.uid).delete();
await user.delete();
Swal.fire('Deleted', 'Your account has been deleted.', 'success');
} catch (error) {
Swal.fire('Error', error.message, 'error');
}
}
});
}
// ===== EMAIL VERIFICATION FUNCTIONS =====
function showEmailVerificationPrompt() {
const modalElement = document.getElementById('emailVerificationModal');
if (modalElement) {
const modal = new bootstrap.Modal(modalElement);
document.getElementById('verificationEmail').textContent = currentUser.email;
modal.show();
}
}
async function logoutAndChangeEmail() {
Swal.fire({
title: 'Use Different Email?',
html: '<p>This will log you out so you can create a new account with a different email address.</p><p><strong>Note:</strong> Your current unverified account will be deleted.</p>',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#d33',
confirmButtonText: 'Yes, logout and change email',
cancelButtonText: 'Cancel'
}).then(async (result) => {
if (result.isConfirmed) {
try {
const user = auth.currentUser;
const uid = user.uid;
// Close verification modal
const modal = bootstrap.Modal.getInstance(document.getElementById('emailVerificationModal'));
if (modal) modal.hide();
// Delete user data from Firestore
await db.collection('users').doc(uid).delete();
// Delete Firebase Auth user
await user.delete();
// Sign out
await auth.signOut();
Swal.fire({
title: 'Account Deleted',
text: 'Your account has been deleted. You can now sign up with a different email.',
icon: 'success'
}).then(() => {
// Show signup modal
openSignupModal();
});
} catch (error) {
if (error.code === 'auth/requires-recent-login') {
Swal.fire({
title: 'Re-authentication Required',
text: 'Please log out and log back in to delete your account. Then try again.',
icon: 'warning'
}).then(async () => {
await auth.signOut();
window.location.reload();
});
} else {
Swal.fire('Error', error.message, 'error');
}
}
}
});
}
async function resendVerificationEmail() {
try {
const resendBtn = document.getElementById('resendVerificationBtn');
const originalText = resendBtn.innerHTML;
resendBtn.disabled = true;
await currentUser.sendEmailVerification();
Swal.fire({
title: 'Email Sent!',
text: 'Verification email has been sent to ' + currentUser.email,
icon: 'success',
timer: 3000
});
resendBtn.disabled = false;
resendBtn.innerHTML = originalText;
} catch (error) {
Swal.fire('Error', error.message, 'error');
resendBtn.disabled = false;
}
}
async function checkEmailVerification() {
try {
await currentUser.reload();
if (currentUser.emailVerified) {
// Update Firestore document
await db.collection('users').doc(currentUser.uid).set({
emailVerified: true
}, { merge: true });
const modal = bootstrap.Modal.getInstance(document.getElementById('emailVerificationModal'));
if (modal) modal.hide();
Swal.fire({
title: 'Email Verified!',
text: 'Your email has been verified successfully. You now have full access to all features.',
icon: 'success'
});
updateUploadAccessUI();
} else {
Swal.fire({
title: 'Email Not Verified Yet',
text: 'Please check your email and click the verification link. Then try again.',
icon: 'info'
});
}
} catch (error) {
Swal.fire('Error', error.message, 'error');
}
}
// ===== PROFILE COMPLETION REMINDER FUNCTIONS =====
function isProfileComplete(userData) {
if (!userData) return false;
// Check if all required fields are present and not empty
const hasName = userData.name && userData.name.trim() && userData.name !== 'User';
const hasCourse = userData.course && userData.course.trim();
const hasPhone = userData.phone && userData.phone.trim();
return hasName && hasCourse && hasPhone;
}
async function checkAndShowProfileCompletionReminder() {
if (!currentUser) return;
try {
// Fetch user document to check profile completeness
const userDoc = await db.collection('users').doc(currentUser.uid).get();
const userData = userDoc.exists ? userDoc.data() : {};
// Check if profile is incomplete
if (!isProfileComplete(userData)) {
// Check if user has dismissed the reminder recently (within 24 hours)
const lastDismissed = localStorage.getItem('profileCompletionDismissed');
if (lastDismissed) {
const hoursSinceDismissed = (Date.now() - parseInt(lastDismissed)) / (1000 * 60 * 60);
if (hoursSinceDismissed < 24) {
// User dismissed recently, don't show again
return;
}
}
// Show the reminder modal
showProfileCompletionReminder();
}
} catch (error) {
console.error('Error checking profile completion:', error);
}
}
function showProfileCompletionReminder() {
const modalElement = document.getElementById('profileCompletionModal');
if (modalElement) {
const modal = new bootstrap.Modal(modalElement, {
backdrop: 'static',
keyboard: false
});
modal.show();
}
}
function dismissProfileCompletionReminder() {
const modal = bootstrap.Modal.getInstance(document.getElementById('profileCompletionModal'));
if (modal) modal.hide();
// Store timestamp of dismissal in localStorage
localStorage.setItem('profileCompletionDismissed', Date.now().toString());
}
function openProfileModalFromReminder() {
const modal = bootstrap.Modal.getInstance(document.getElementById('profileCompletionModal'));
if (modal) modal.hide();
// Clear the dismissal timestamp so reminder can show again after completion
localStorage.removeItem('profileCompletionDismissed');
// Open profile modal
openProfileModal();
}
// ===== LOGOUT FUNCTION =====
function logout() {
Swal.fire({
title: 'Logout?',
text: 'You will be logged out from your account.',
icon: 'question',
showCancelButton: true,
confirmButtonText: 'Yes, logout'
}).then(async (result) => {
if (result.isConfirmed) {
try {
await auth.signOut();
document.getElementById('profileDropdown').style.display = 'none';
Swal.fire('Logged Out', 'You have been logged out successfully.', 'success');
} catch (error) {
Swal.fire('Error', error.message, 'error');
}
}
});
}
// ===== BOOKMARKS MODAL =====
function openBookmarksModal() {
document.getElementById('profileDropdown').style.display = 'none';
// You can expand this to show user's bookmarks
Swal.fire({
title: 'My Bookmarks',
text: 'View your bookmarked documents from the Bookmarks tab',
icon: 'info'
});
}
// User Upload Handler
function setupUserUploadHandler() {
const uploadForm = document.getElementById('userUploadForm');
if (!uploadForm) return;
uploadForm.addEventListener('submit', async function(e) {
e.preventDefault();
if (!currentUser) {
Swal.fire({
icon: 'info',
title: 'Sign up to upload',
text: 'Only registered users can upload documents and be listed among top contributors.',
showCancelButton: true,
confirmButtonText: 'Sign Up Now',
cancelButtonText: 'Not now'
}).then(result => {
if (result.isConfirmed) {
openSignupModal();
}
});
return;
}
// Check if email is verified
if (requiresEmailVerification(currentUser)) {
Swal.fire({
icon: 'warning',
title: 'Email Not Verified',
html: `<p>Please verify your email to upload documents.</p><p>Check your inbox at <strong>${currentUser.email}</strong> and click the verification link.</p>`,
showCancelButton: true,
confirmButtonText: 'Verify Email',
cancelButtonText: 'Later'
}).then(result => {
if (result.isConfirmed) {
showEmailVerificationPrompt();
}
});
return;
}
const title = document.getElementById('uploadTitle').value;
const course = document.getElementById('uploadCourse').value;
const semester = document.getElementById('uploadSemester').value;
const file = document.getElementById('uploadFile').files[0];
if (!file) {
alert('Please select a file');
return;
}
// Validate file size (unlimited for gofile, but set reasonable limit)
const maxSize = 500 * 1024 * 1024; // 500MB max
if (file.size > maxSize) {
alert('File size exceeds 500MB limit');
return;
}
// Validate file type
if (file.type !== 'application/pdf') {
alert('Only PDF files are allowed');
return;
}
const statusDiv = document.getElementById('uploadStatus');
const statusMessage = document.getElementById('uploadStatusMessage');
const progressDiv = document.getElementById('uploadProgress');
const progressBar = document.getElementById('uploadProgressBar');
statusDiv.style.display = 'block';
statusMessage.textContent = 'Fetching your profile...';
progressDiv.style.display = 'block';
try {
// Fetch user profile from Firestore to get name and course
if (!currentUser) {
throw new Error('User not authenticated');
}
const userDoc = await db.collection('users').doc(currentUser.uid).get();
if (!userDoc.exists) {
throw new Error('User profile not found in database');
}
const userData = userDoc.data();
const userName = userData.name || userData.signupName || currentUser.displayName || 'Anonymous';
const userCourse = userData.course || userData.signupCourse || course || 'General';
statusMessage.textContent = 'Uploading file to database...';
// Upload to gofile.io (CORS enabled, unlimited file storage)
// First, get an available server
const serverResponse = await fetch('https://api.gofile.io/servers');
if (!serverResponse.ok) {
throw new Error('Failed to get upload server');
}
const serverData = await serverResponse.json();
if (serverData.status !== 'ok' || !serverData.data || !serverData.data.servers || serverData.data.servers.length === 0) {
throw new Error('No upload servers available');
}
// Use the first available server
const server = serverData.data.servers[0];
const uploadUrl = `https://${server.name}.gofile.io/uploadFile`;
// Now upload the file
const formData = new FormData();
formData.append('file', file);
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`Upload failed with status ${response.status}`);
}
const result = await response.json();
if (result.status !== 'ok' || !result.data || !result.data.downloadPage) {
throw new Error('Upload failed: Invalid response from server');
}
// gofile.io returns downloadPage URL directly
const fileUrl = result.data.downloadPage;
progressBar.style.width = '100%';
statusMessage.textContent = 'File uploaded successfully! Saving metadata...';
// Save metadata to Firestore pendingUploads collection
await db.collection('pendingUploads').add({
title: title,
course: course,
semester: semester,
studentName: userName,
studentCourse: userCourse,
userId: currentUser.uid,
fileName: file.name,
downloadUrl: fileUrl,
fileSize: file.size,
uploadedAt: firebase.firestore.FieldValue.serverTimestamp(),
status: 'pending'
});
statusMessage.innerHTML = '<strong class="text-success">✓ File uploaded successfully! Our team will review it soon.</strong>';
progressDiv.style.display = 'none';
uploadForm.reset();
// Hide success message after 5 seconds
setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
} catch (error) {
console.error('Upload error:', error);
statusMessage.innerHTML = `<strong class="text-danger">Error: ${error.message}</strong>`;
progressDiv.style.display = 'none';
}
});
}
document.addEventListener('DOMContentLoaded', function() {
// Initialize modals
const pdfModal = new bootstrap.Modal(document.getElementById('pdfModal'));
const shareModal = new bootstrap.Modal(document.getElementById('shareModal'));
const pdfViewer = document.getElementById('pdfViewer');
const downloadBtn = document.getElementById('downloadBtn');
const shareLink = document.getElementById('shareLink');
const copyLinkBtn = document.getElementById('copyLinkBtn');
const pyqList = document.getElementById('pyqList');
document.getElementById('pdfModal').addEventListener('hidden.bs.modal', function() {
pdfViewer.src = '';
});
// Global data storage
let allData = { pyqs: [] };
let filteredPyqs = [];
let bookmarks = { pyqs: [] };
const serverPageSize = 20;
let pyqLastVisible = null;
let pyqHasMore = true;