-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.js
More file actions
896 lines (790 loc) · 33.1 KB
/
admin.js
File metadata and controls
896 lines (790 loc) · 33.1 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
// 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);
const auth = firebase.auth();
const db = firebase.firestore();
const storage = firebase.storage();
let allData = { pyqs: [], users: [], pendingUploads: [], contributors: [] };
const ADMIN_EMAIL = 'kush210431@gmail.com';
function isAdminUser(user) {
return !!user && user.email === ADMIN_EMAIL;
}
document.addEventListener('DOMContentLoaded', function() {
setupSectionCollapseBehavior();
// Auth state listener
auth.onAuthStateChanged(user => {
if (user) {
if (!isAdminUser(user)) {
auth.signOut();
document.getElementById('loginError').textContent = 'You do not have admin access.';
document.getElementById('loginError').style.display = 'block';
document.getElementById('loginSection').style.display = 'block';
document.getElementById('adminSection').style.display = 'none';
return;
}
// User is signed in
document.getElementById('loginSection').style.display = 'none';
document.getElementById('adminSection').style.display = 'block';
loadData();
} else {
// User is signed out
resetLazyLoadState();
document.getElementById('loginSection').style.display = 'block';
document.getElementById('adminSection').style.display = 'none';
}
});
// Login form
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const errorDiv = document.getElementById('loginError');
auth.signInWithEmailAndPassword(email, password)
.then(() => {
errorDiv.style.display = 'none';
})
.catch(error => {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
});
});
// Logout
document.getElementById('logoutBtn').addEventListener('click', function() {
auth.signOut();
});
// Generate sitemap button
const genBtn = document.getElementById('generateSitemapBtn');
if (genBtn) {
genBtn.addEventListener('click', function() {
if (!auth.currentUser) {
alert('You must be signed in to generate the sitemap.');
return;
}
generateSitemap();
});
}
// Add PYQ form
document.getElementById('addPyqForm').addEventListener('submit', async function(e) {
e.preventDefault();
const course = document.getElementById('pyqCourse').value.trim();
const semester = document.getElementById('pyqSemester').value.trim();
const subject = document.getElementById('pyqSubject').value.trim();
const session = document.getElementById('pyqSession').value.trim();
const file = document.getElementById('pyqFile').value;
if (!course || !semester || !subject || !session || !file) {
alert('Please fill in course, semester, subject, session, and file URL.');
return;
}
let currentSubject = subject;
let title = buildPyqTitle(course, semester, currentSubject, session);
let duplicateExists = await pyqTitleExists(title);
if (duplicateExists === null) {
return;
}
while (duplicateExists) {
const shouldRename = confirm(
`A PYQ with this title already exists:\n\n${title}\n\nDo you want to provide another subject name?`
);
if (!shouldRename) {
return;
}
const alternativeSubject = prompt('Enter another subject name for this PYQ:', currentSubject);
if (alternativeSubject === null) {
return;
}
currentSubject = alternativeSubject.trim();
if (!currentSubject) {
alert('Subject name cannot be empty.');
continue;
}
title = buildPyqTitle(course, semester, currentSubject, session);
duplicateExists = await pyqTitleExists(title);
if (duplicateExists === null) {
return;
}
}
addItem('pyqs', { title, file, course, semester, subject: currentSubject, session });
this.reset();
});
// Edit form
document.getElementById('editForm').addEventListener('submit', function(e) {
e.preventDefault();
const type = document.getElementById('editType').value;
const index = parseInt(document.getElementById('editIndex').value);
const title = document.getElementById('editTitle').value;
const file = document.getElementById('editFile').value;
const course = document.getElementById('editCourse').value;
const semester = document.getElementById('editSemester').value;
editItem(type, index, { title, file, course, semester });
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
});
});
function setupSectionCollapseBehavior() {
const adminSection = document.getElementById('adminSection');
if (!adminSection || !window.bootstrap || !window.bootstrap.Collapse) {
return;
}
const collapses = Array.from(adminSection.querySelectorAll('.section-card .collapse'));
collapses.forEach(currentCollapse => {
currentCollapse.addEventListener('show.bs.collapse', function() {
collapses.forEach(otherCollapse => {
if (otherCollapse === currentCollapse || !otherCollapse.classList.contains('show')) {
return;
}
window.bootstrap.Collapse.getOrCreateInstance(otherCollapse, { toggle: false }).hide();
});
});
});
}
function loadData() {
// Auto-load pending uploads and registered users so counts and panels show immediately.
loadPendingOnDemand();
loadUsersOnDemand();
}
function resetLazyLoadState() {
pyqsLoaded = false;
pendingLoaded = false;
usersLoaded = false;
contributorsLoaded = false;
}
function generateSitemap() {
// Build sitemap XML from allData
try {
const baseUrl = 'https://dsmnru-pyq.netlify.app/';
const urls = [];
// Add homepage
urls.push({ loc: baseUrl, priority: 1.0, changefreq: 'daily' });
// Add index.html explicitly
urls.push({ loc: baseUrl + 'index.html', priority: 0.9, changefreq: 'daily' });
// Add each PYQ file URL if present
allData.pyqs.forEach(item => {
if (item.file) urls.push({ loc: item.file, priority: 0.8, changefreq: 'monthly' });
});
const xmlParts = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
urls.forEach(u => {
xmlParts.push(' <url>');
xmlParts.push(` <loc>${escapeXml(u.loc)}</loc>`);
if (u.changefreq) xmlParts.push(` <changefreq>${u.changefreq}</changefreq>`);
if (u.priority !== undefined) xmlParts.push(` <priority>${u.priority.toFixed(2)}</priority>`);
xmlParts.push(' </url>');
});
xmlParts.push('</urlset>');
const sitemapXml = xmlParts.join('\n');
// Download as file instead of uploading to Firebase
const blob = new Blob([sitemapXml], { type: 'application/xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'sitemap.xml';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
updateSitemapStatus('done', 'sitemap.xml');
alert(`✓ Sitemap generated successfully!\n\nGenerated ${urls.length} URLs:\n- Homepage\n- ${allData.pyqs.length} PYQ items\n\nFile downloaded as sitemap.xml`);
} catch (err) {
console.error('Error generating sitemap:', err);
updateSitemapStatus('error');
alert('Error generating sitemap: ' + err.message);
}
}
function escapeXml(unsafe) {
return (unsafe || '').replace(/[<>&'\"]/g, function(c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case "'": return ''';
case '"': return '"';
}
});
}
function updateSitemapStatus(state, url) {
const container = document.getElementById('sitemapStatus');
const msg = document.getElementById('sitemapMessage');
const link = document.getElementById('sitemapUrl');
if (!container || !msg || !link) return;
if (state === 'ready') {
container.style.display = 'none';
} else if (state === 'uploading') {
container.style.display = 'block';
msg.textContent = 'Generating sitemap and uploading...';
link.style.display = 'none';
} else if (state === 'done') {
container.style.display = 'block';
msg.textContent = 'Sitemap uploaded. Public URL:';
link.href = url;
link.textContent = url;
link.style.display = 'block';
} else if (state === 'error') {
container.style.display = 'block';
msg.textContent = 'Error generating sitemap. See console.';
link.style.display = 'none';
}
}
function renderLists() {
renderPyqs();
renderUsers();
updateDashboardStats();
}
function updateDashboardStats() {
const setCount = (id, value) => {
const element = document.getElementById(id);
if (element) {
element.textContent = value;
}
};
setCount('pyqsCount', allData.pyqs.length);
setCount('pyqsHeaderCount', allData.pyqs.length);
setCount('usersCount', allData.users.length);
setCount('usersHeaderCount', allData.users.length);
setCount('pendingCount', allData.pendingUploads.length);
setCount('pendingHeaderCount', allData.pendingUploads.length);
setCount('contributorsCount', allData.contributors.length);
setCount('contributorsHeaderCount', allData.contributors.length);
}
function escapeHtml(value) {
return (value || '')
.toString()
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function copyToClipboard(text) {
const value = (text || '').toString();
if (!value) {
alert('Nothing to copy.');
return;
}
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(value)
.then(() => alert('Copied to clipboard.'))
.catch(() => fallbackCopy(value));
return;
}
fallbackCopy(value);
}
function fallbackCopy(value) {
const tempInput = document.createElement('input');
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
alert('Copied to clipboard.');
}
function renderPyqs() {
const list = document.getElementById('pyqsList');
if (!list) return;
if (!allData.pyqs.length) {
list.innerHTML = '<div class="resource-empty">No PYQs added yet.</div>';
updateDashboardStats();
return;
}
list.innerHTML = allData.pyqs.map((pyq, index) => `
<article class="resource-card">
<div class="resource-top">
<div>
<div class="resource-kicker">PYQ ${index + 1}</div>
<h5 class="resource-title">${escapeHtml(pyq.title)}</h5>
<div class="resource-meta">
${pyq.course ? `<span class="resource-pill">${escapeHtml(pyq.course)}</span>` : ''}
${pyq.semester ? `<span class="resource-pill">${escapeHtml(pyq.semester)} semester</span>` : ''}
${pyq.session ? `<span class="resource-pill">${escapeHtml(pyq.session)} session</span>` : ''}
</div>
</div>
<div class="resource-actions">
<button class="btn btn-sm btn-outline-light" onclick='copyToClipboard(${JSON.stringify(pyq.file || '')})'>Copy URL</button>
<button class="btn btn-sm btn-outline-primary" onclick="editPyq(${index})">Edit</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteItem('pyqs', ${index})">Delete</button>
</div>
</div>
<div class="resource-detail">${escapeHtml(pyq.file)}</div>
</article>
`).join('');
updateDashboardStats();
}
function renderUsers() {
const list = document.getElementById('usersList');
if (!list) return;
if (!allData.users.length) {
list.innerHTML = '<div class="resource-empty">No registered users found.</div>';
updateDashboardStats();
return;
}
list.innerHTML = allData.users.map((user, index) => {
const createdAt = user.createdAt ? new Date(user.createdAt.toDate()).toLocaleString() : 'Unknown';
return `
<article class="resource-card">
<div class="resource-top">
<div class="d-flex align-items-start gap-3">
<div class="contributor-avatar-small">${escapeHtml((user.name || user.signupName || 'U').slice(0, 2).toUpperCase())}</div>
<div>
<div class="resource-kicker">Registered user ${index + 1}</div>
<h5 class="resource-title">${escapeHtml(user.name || user.signupName || 'Unnamed User')}</h5>
<div class="resource-meta">
<span class="resource-pill">${escapeHtml(user.role || 'user')}</span>
<span class="resource-pill">${escapeHtml(user.course || user.signupCourse || 'N/A')}</span>
</div>
</div>
</div>
<div class="resource-actions">
<button class="btn btn-sm btn-outline-primary" onclick="editUser('${user.uid}')"><i class="fas fa-edit me-1"></i>Edit</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteUser('${user.uid}', '${(user.name || user.signupName || 'user').replace(/'/g, "\\'")}')"><i class="fas fa-trash me-1"></i>Delete</button>
</div>
</div>
<div class="resource-detail">
<div>Email: ${escapeHtml(user.email || user.signupEmail || 'No email')}</div>
<div>Phone: ${escapeHtml(user.phone || 'N/A')}</div>
<div>Created: ${escapeHtml(createdAt)}</div>
<div>UID: ${escapeHtml(user.uid || 'N/A')}</div>
</div>
</article>
`;
}).join('');
updateDashboardStats();
}
function addItem(type, item) {
// Add document to Firestore collection
db.collection(type).add(item)
.then(docRef => {
allData[type].push({ id: docRef.id, ...item });
renderLists();
alert('Item added successfully!');
})
.catch(error => {
console.error('Error adding item:', error);
alert('Error adding item. Please try again.');
});
}
function editItem(type, index, item) {
const existing = allData[type][index];
if (!existing || !existing.id) {
alert('Unable to find item id to update.');
return;
}
db.collection(type).doc(existing.id).set(item, { merge: true })
.then(() => {
allData[type][index] = { id: existing.id, ...item };
renderLists();
alert('Item updated successfully!');
})
.catch(error => {
console.error('Error updating item:', error);
alert('Error updating item. Please try again.');
});
}
function deleteItem(type, index) {
if (confirm('Are you sure you want to delete this item?')) {
const existing = allData[type][index];
if (!existing || !existing.id) {
alert('Unable to find item id to delete.');
return;
}
db.collection(type).doc(existing.id).delete()
.then(() => {
allData[type].splice(index, 1);
renderLists();
alert('Item deleted successfully!');
})
.catch(error => {
console.error('Error deleting item:', error);
alert('Error deleting item. Please try again.');
});
}
}
function saveData() {
// Deprecated for Firestore-based flows. Keep for compatibility but warn.
console.warn('saveData() called - this project now uses Firestore. Use addItem/editItem/deleteItem instead.');
}
function buildPyqTitle(course, semester, subject, session) {
return `${normalizePyqText(course)} ${normalizePyqText(semester)} Sem ${normalizePyqText(subject)} {${normalizePyqText(session)}}`;
}
function normalizePyqText(value) {
return (value || '').toString().replace(/\s+/g, ' ').trim();
}
function pyqTitleExists(title) {
return db.collection('pyqs').where('title', '==', title).get()
.then(snapshot => !snapshot.empty)
.catch(error => {
console.error('Error checking for duplicate PYQ title:', error);
alert('Unable to validate duplicate PYQ titles right now. Please try again.');
return null;
});
}
// Global functions for onclick
window.editPyq = function(index) {
const pyq = allData.pyqs[index];
document.getElementById('editType').value = 'pyqs';
document.getElementById('editIndex').value = index;
document.getElementById('editTitle').value = pyq.title;
document.getElementById('editFile').value = pyq.file;
document.getElementById('editCourseDiv').style.display = 'none';
document.getElementById('editSemesterDiv').style.display = 'none';
new bootstrap.Modal(document.getElementById('editModal')).show();
};
window.deleteItem = deleteItem;
window.editUser = function(uid) {
const user = allData.users.find(item => item.uid === uid);
if (!user) {
alert('User not found.');
return;
}
document.getElementById('userEditUid').value = user.uid || '';
document.getElementById('userEditName').value = user.name || user.signupName || '';
document.getElementById('userEditEmail').value = user.email || user.signupEmail || '';
document.getElementById('userEditCourse').value = user.course || user.signupCourse || '';
document.getElementById('userEditPhone').value = user.phone || '';
document.getElementById('userEditRole').value = user.role || 'user';
document.getElementById('userEditCreatedAt').value = user.createdAt ? new Date(user.createdAt.toDate()).toLocaleString() : 'Unknown';
const modal = new bootstrap.Modal(document.getElementById('userEditModal'));
modal.show();
};
window.deleteUser = function(uid, name) {
if (confirm(`Are you sure you want to delete ${name}?`)) {
db.collection('users').doc(uid).delete()
.then(() => {
allData.users = allData.users.filter(item => item.uid !== uid);
renderUsers();
alert('User record deleted successfully!');
})
.catch(error => {
console.error('Error deleting user:', error);
alert('Error deleting user: ' + error.message);
});
}
};
document.addEventListener('DOMContentLoaded', function() {
const userEditForm = document.getElementById('userEditForm');
if (!userEditForm) return;
userEditForm.addEventListener('submit', function(e) {
e.preventDefault();
const uid = document.getElementById('userEditUid').value;
const name = document.getElementById('userEditName').value.trim();
const email = document.getElementById('userEditEmail').value.trim();
const course = document.getElementById('userEditCourse').value.trim();
const phone = document.getElementById('userEditPhone').value.trim();
const role = document.getElementById('userEditRole').value.trim();
if (!uid || !name || !email || !course || !phone || !role) {
alert('All user fields are required.');
return;
}
const updatedUser = {
uid,
name,
email,
course,
phone,
role,
signupName: name,
signupEmail: email,
signupCourse: course
};
db.collection('users').doc(uid).set(updatedUser, { merge: true })
.then(() => {
const index = allData.users.findIndex(item => item.uid === uid);
if (index !== -1) {
allData.users[index] = { ...allData.users[index], ...updatedUser };
}
renderUsers();
bootstrap.Modal.getInstance(document.getElementById('userEditModal')).hide();
alert('User updated successfully!');
})
.catch(error => {
console.error('Error updating user:', error);
alert('Error updating user: ' + error.message);
});
});
});
// Pending Uploads Management
function loadPendingUploads() {
db.collection('pendingUploads').where('status', '==', 'pending').get()
.then(snapshot => {
allData.pendingUploads = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
const pendingCount = allData.pendingUploads.length;
updateDashboardStats();
if (pendingCount === 0) {
document.getElementById('pendingUploadsList').innerHTML = '';
document.getElementById('noPendingMessage').style.display = 'block';
} else {
document.getElementById('noPendingMessage').style.display = 'none';
renderPendingUploads(allData.pendingUploads);
}
})
.catch(error => {
console.error('Error loading pending uploads:', error);
});
}
function renderPendingUploads(pendingDocs) {
const list = document.getElementById('pendingUploadsList');
if (!list) return;
if (!pendingDocs.length) {
list.innerHTML = '<div class="resource-empty">No pending uploads found.</div>';
updateDashboardStats();
return;
}
list.innerHTML = pendingDocs.map((doc, index) => {
// doc is already a converted object with { id, ...data }
const data = doc;
const uploadDate = data.uploadedAt ? new Date(data.uploadedAt.toDate()).toLocaleString() : 'Unknown';
return `
<article class="resource-card">
<div class="resource-top">
<div>
<div class="resource-kicker">Pending upload ${index + 1}</div>
<h5 class="resource-title">${escapeHtml(data.title)}</h5>
<div class="resource-meta">
<span class="resource-pill">${escapeHtml(data.course || 'N/A')}</span>
<span class="resource-pill">${escapeHtml(data.semester || 'N/A')}</span>
</div>
</div>
<div class="resource-actions">
<button class="btn btn-sm btn-outline-light" onclick='copyToClipboard(${JSON.stringify(data.downloadUrl || '')})'>Copy URL</button>
<button class="btn btn-sm btn-outline-info" onclick="downloadPendingFile('${data.downloadUrl}', '${data.fileName.replace(/'/g, "\\'")}')">
<i class="fas fa-download me-1"></i> Download
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deletePendingUpload('${doc.id}')">
<i class="fas fa-trash me-1"></i> Delete
</button>
</div>
</div>
<div class="resource-detail">
<div>File: <code>${escapeHtml(data.fileName)}</code></div>
<div>Uploaded by: <strong>${escapeHtml(data.studentName || 'Anonymous')}</strong></div>
<div>${escapeHtml(uploadDate)}</div>
</div>
</article>
`;
}).join('');
updateDashboardStats();
}
function downloadPendingFile(downloadUrl, fileName) {
const a = document.createElement('a');
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function deletePendingUpload(docId) {
if (confirm('Delete this pending upload from the list? The file on gofile.io will auto-delete after 30 days.')) {
// Delete from Firestore only
db.collection('pendingUploads').doc(docId).delete()
.then(() => {
alert('Upload removed from pending list!');
loadPendingUploads();
})
.catch(error => {
console.error('Error deleting upload:', error);
alert('Error deleting upload: ' + error.message);
});
}
}
// Global function for onclick
window.downloadPendingFile = downloadPendingFile;
window.deletePendingUpload = deletePendingUpload;
// Lazy loading functions - only load data when section is expanded
let pyqsLoaded = false;
let syllabusLoaded = false;
let pendingLoaded = false;
let usersLoaded = false;
window.loadPyqsOnDemand = function() {
if (pyqsLoaded) return;
pyqsLoaded = true;
db.collection('pyqs').get()
.then(pyqSnap => {
allData.pyqs = pyqSnap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
document.getElementById('pyqsCount').textContent = allData.pyqs.length;
renderPyqs();
})
.catch(error => {
console.error('Error loading PYQs:', error);
document.getElementById('pyqsList').innerHTML = '<div class="alert alert-danger">Error loading PYQs</div>';
});
};
window.loadPendingOnDemand = function() {
if (pendingLoaded) return;
pendingLoaded = true;
loadPendingUploads();
};
window.loadUsersOnDemand = function() {
if (usersLoaded) return;
usersLoaded = true;
db.collection('users').orderBy('createdAt', 'desc').get()
.then(snapshot => {
allData.users = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
document.getElementById('usersCount').textContent = allData.users.length;
renderUsers();
})
.catch(error => {
console.error('Error loading users:', error);
const list = document.getElementById('usersList');
if (list) {
list.innerHTML = '<div class="alert alert-danger">Error loading users</div>';
}
});
};
// Contributor Management Functions
let contributorsLoaded = false;
window.loadContributorsOnDemand = function() {
if (contributorsLoaded) return;
contributorsLoaded = true;
loadContributors();
};
function loadContributors() {
db.collection('contributors').orderBy('name').get()
.then(snapshot => {
const contributors = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
allData.contributors = contributors;
contributorsLoaded = true;
renderContributors(contributors);
updateDashboardStats();
})
.catch(error => {
console.error('Error loading contributors:', error);
document.getElementById('contributorsList').innerHTML = '<div class="alert alert-danger">Error loading contributors</div>';
});
}
function renderContributors(contributors) {
const list = document.getElementById('contributorsList');
if (!list) return;
if (!contributors.length) {
list.innerHTML = '<div class="resource-empty">No contributors yet. Add one using the form above.</div>';
updateDashboardStats();
return;
}
list.innerHTML = contributors.map(contributor => `
<article class="resource-card">
<div class="resource-top">
<div class="d-flex align-items-start gap-3">
<div class="contributor-avatar-small">${escapeHtml(contributor.avatar)}</div>
<div>
<div class="resource-kicker">Contributor</div>
<h5 class="resource-title">${escapeHtml(contributor.name)}</h5>
<div class="resource-meta">
<span class="resource-pill">${escapeHtml(contributor.role)}</span>
</div>
</div>
</div>
<div class="resource-actions">
<button class="btn btn-sm btn-outline-primary" onclick="editContributor('${contributor.id}', '${contributor.name}', '${contributor.avatar}', '${contributor.role}')">
<i class="fas fa-edit me-1"></i>Edit
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteContributor('${contributor.id}', '${contributor.name}')">
<i class="fas fa-trash me-1"></i>Delete
</button>
</div>
</div>
</article>
`).join('');
updateDashboardStats();
}
function getContributorInitials(name) {
return name
.trim()
.split(/\s+/)
.filter(part => part.length)
.map(part => part[0].toUpperCase())
.join('')
.slice(0, 4);
}
const allowedContributorRoles = [
'PYQs Provider',
'Syllabus Provider',
'PYQs + Syllabus Provider'
];
document.addEventListener('DOMContentLoaded', function() {
// Contributor form submission
const addContributorForm = document.getElementById('addContributorForm');
if (addContributorForm) {
const nameInput = document.getElementById('contributorName');
const avatarInput = document.getElementById('contributorAvatar');
const roleInput = document.getElementById('contributorRole');
if (nameInput && avatarInput) {
nameInput.addEventListener('input', function() {
const initials = getContributorInitials(nameInput.value);
avatarInput.value = initials;
});
}
addContributorForm.addEventListener('submit', function(e) {
e.preventDefault();
const name = nameInput.value.trim();
const avatar = getContributorInitials(name);
const role = roleInput.value;
if (!name || !avatar || !role) {
alert('Please fill all fields');
return;
}
if (!allowedContributorRoles.includes(role)) {
alert('Please select a valid role');
return;
}
db.collection('contributors').add({
name,
avatar,
role
})
.then(() => {
addContributorForm.reset();
loadContributors();
})
.catch(error => {
console.error('Error adding contributor:', error);
alert('Error adding contributor: ' + error.message);
});
});
// Load contributors on page init
loadContributors();
}
});
window.editContributor = function(id, name, avatar, role) {
const newName = prompt('Edit name:', name);
if (newName === null) return;
const newRole = prompt('Edit role (PYQs Provider / Syllabus Provider / PYQs + Syllabus Provider):', role);
if (newRole === null) return;
const trimmedName = newName.trim();
const trimmedRole = newRole.trim();
const newAvatar = getContributorInitials(trimmedName);
if (!trimmedName || !newAvatar || !trimmedRole) {
alert('All fields are required');
return;
}
if (!allowedContributorRoles.includes(trimmedRole)) {
alert('Please enter a valid role');
return;
}
db.collection('contributors').doc(id).set({
name: trimmedName,
avatar: newAvatar,
role: trimmedRole
})
.then(() => {
loadContributors();
})
.catch(error => {
console.error('Error updating contributor:', error);
alert('Error updating contributor: ' + error.message);
});
};
window.deleteContributor = function(id, name) {
if (confirm(`Are you sure you want to delete ${name}?`)) {
db.collection('contributors').doc(id).delete()
.then(() => {
loadContributors();
})
.catch(error => {
console.error('Error deleting contributor:', error);
alert('Error deleting contributor: ' + error.message);
});
}
};