-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudent-dashboard.html
More file actions
1128 lines (1053 loc) · 66.8 KB
/
student-dashboard.html
File metadata and controls
1128 lines (1053 loc) · 66.8 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" />
<meta name="description" content="Student dashboard for MGIT Feedback System — submit feedback for your enrolled teachers and subjects." />
<meta name="keywords" content="feedback, students, teachers, MGIT" />
<meta property="og:title" content="Student Dashboard — MGIT Feedback System" />
<meta property="og:description" content="Student dashboard for MGIT Feedback System." />
<meta property="og:url" content="https://mgitfeedback.me/student-dashboard.html" />
<meta property="og:type" content="website" />
<link rel="canonical" href="https://mgitfeedback.me/student-dashboard.html" />
<title>Student Dashboard — Feedback System</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🎓</text></svg>" />
<!-- Preconnect for Google Fonts (reduces FCP) -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<!-- Preload main stylesheet (reduces render-blocking) -->
<link rel="preload" href="css/style.css?v=2" as="style" />
<link rel="stylesheet" href="css/style.css?v=2" />
</head>
<body>
<div class="bg-orbs"></div>
<button class="mobile-menu-btn" onclick="document.querySelector('.sidebar').classList.toggle('open');document.querySelector('.sidebar-overlay').classList.toggle('show');" aria-label="Menu">☰</button>
<div class="page-wrapper dashboard-layout">
<div class="sidebar-overlay" onclick="document.querySelector('.sidebar').classList.remove('open');this.classList.remove('show');"></div>
<!-- Sidebar -->
<nav class="sidebar" id="sidebar">
<div class="sidebar-header">
<div class="sidebar-logo">SF</div>
<div>
<div class="sidebar-title">Student Feedback</div>
<div class="sidebar-subtitle" id="collegeName">System</div>
</div>
</div>
<div class="sidebar-nav">
<div class="nav-group-label">Menu</div>
<div class="nav-item" onclick="showSection('dashboard')">
<span class="nav-icon">📊</span> Dashboard
</div>
<div class="nav-item" onclick="showSection('academics')">
<span class="nav-icon">🎓</span> Academics
</div>
<div class="nav-item active" onclick="showSection('teachers')">
<span class="nav-icon">👨🏫</span> Feedback
</div>
<div class="nav-item" onclick="showSection('history')">
<span class="nav-icon">📋</span> Records
</div>
<div class="nav-item" onclick="showSection('notifications')">
<span class="nav-icon">🔔</span> Notifications <span id="notifBadge" style="background:var(--danger);color:#fff;font-size:10px;padding:1px 6px;border-radius:10px;margin-left:4px;display:none;">0</span>
</div>
<div class="nav-item" onclick="showSection('timetable')">
<span class="nav-icon">📅</span> Timetable
</div>
<div class="nav-group-label" style="margin-top:16px;">Account</div>
<div class="nav-item" onclick="showSection('profile')">
<span class="nav-icon">👤</span> Profile
</div>
<div class="nav-item" onclick="showSection('settings')">
<span class="nav-icon">⚙️</span> Settings
</div>
</div>
<div class="sidebar-footer">
<div class="user-avatar" id="sidebarAvatar">S</div>
<div class="user-info">
<div class="user-name" id="sidebarName">Student</div>
<div class="user-role">Student</div>
</div>
<button class="btn-logout" onclick="logout()" title="Logout" aria-label="Logout">⬡</button>
</div>
</nav>
<!-- Main -->
<main class="main-content">
<!-- Teachers Section -->
<div id="sectionTeachers">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>My Teachers</span></div>
<div class="page-title">Submit Feedback</div>
<div class="page-subtitle">Select a teacher to provide your feedback</div>
</div>
<label class="toggle-wrap" style="margin:0;" title="Submit without revealing your identity">
<div class="toggle"><input type="checkbox" id="anonToggle" /><span class="toggle-slider"></span></div>
<span class="toggle-label">Anonymous Mode</span>
</label>
</div>
<div class="stats-grid animate-in" id="summaryCards">
<div class="stat-card"><div class="stat-icon">👨🏫</div><div class="stat-value" id="totalTeachers">0</div><div class="stat-label">Assigned Teachers</div></div>
<div class="stat-card"><div class="stat-icon">✅</div><div class="stat-value" id="totalSubmitted">0</div><div class="stat-label">Submitted</div></div>
<div class="stat-card"><div class="stat-icon">⏳</div><div class="stat-value" id="totalPending">0</div><div class="stat-label">Pending</div></div>
</div>
<div id="teachersList" class="teachers-grid animate-in delay-1"></div>
<div id="noTeachers" class="empty-state" style="display:none;">
<div class="empty-icon">👨🏫</div>
<div class="empty-title">No Teachers Assigned</div>
<div class="empty-desc">Your administrator has not assigned any teachers yet. Please contact your admin.</div>
</div>
</div>
<!-- History Section -->
<div id="sectionHistory" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>Submission History</span></div>
<div class="page-title">My Feedback History</div>
<div class="page-subtitle">All feedback you've submitted</div>
</div>
</div>
<div class="section-card">
<div class="section-card-body">
<div id="historyList"></div>
<div id="noHistory" class="empty-state" style="display:none;">
<div class="empty-icon">📋</div>
<div class="empty-title">No Submissions Yet</div>
<div class="empty-desc">You haven't submitted any feedback. Go to My Teachers to start.</div>
</div>
</div>
</div>
</div>
<!-- Dashboard Section -->
<div id="sectionDashboard" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>Overview</span></div>
<div class="page-title">Welcome Back 👋</div>
<div class="page-subtitle" id="dashSubtitle">Here’s a snapshot of your academic activity</div>
</div>
</div>
<!-- Stat cards -->
<div class="stats-grid animate-in" id="dashStats"></div>
<!-- Attendance + Feedback Row -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:20px;">
<!-- Attendance Card -->
<div class="section-card animate-in">
<div class="section-card-header"><div class="section-card-title">📊 Attendance Status</div></div>
<div class="section-card-body" id="dashAttCard"></div>
</div>
<!-- Quick Actions -->
<div class="section-card animate-in">
<div class="section-card-header"><div class="section-card-title">⚡ Quick Actions</div></div>
<div class="section-card-body" style="display:flex;flex-direction:column;gap:10px;">
<button class="btn btn-primary" onclick="showSection('teachers')">📝 Give Feedback</button>
<button class="btn btn-secondary" onclick="showSection('history')">📋 View My Records</button>
<button class="btn btn-secondary" onclick="showSection('academics')">🎓 View Academics</button>
</div>
</div>
</div>
<!-- Recent Submissions -->
<div class="section-card animate-in delay-1" style="margin-top:20px;">
<div class="section-card-header"><div class="section-card-title">🕒 Recent Submissions</div></div>
<div class="section-card-body" style="padding:0;" id="dashRecent"></div>
</div>
</div>
<!-- Academics Section -->
<div id="sectionAcademics" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>Academics</span></div>
<div class="page-title">🎓 My Courses</div>
<div class="page-subtitle">Teachers and subjects enrolled for this semester</div>
</div>
</div>
<div id="academicsContent"></div>
</div>
<!-- Profile Section -->
<div id="sectionProfile" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>Profile</span></div>
<div class="page-title">👤 My Profile</div>
<div class="page-subtitle">Your personal and academic information</div>
</div>
</div>
<div id="profileContent"></div>
</div>
<!-- Settings Section -->
<!-- Notifications Section -->
<div id="sectionNotifications" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard > <span>Notifications</span></div>
<div class="page-title">🔔 Notifications</div>
<div class="page-subtitle">Latest updates from your institution</div>
</div>
<button class="btn btn-secondary btn-sm" onclick="markAllNotifRead()">✓ Mark all read</button>
</div>
<div class="section-card">
<div class="section-card-body" id="notifList">
<div style="color:var(--text-muted);text-align:center;padding:30px;">Loading notifications...</div>
</div>
</div>
</div>
<!-- Timetable Section -->
<div id="sectionTimetable" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard > <span>Timetable</span></div>
<div class="page-title">📅 Timetable</div>
<div class="page-subtitle">Your class schedule</div>
</div>
</div>
<div class="section-card">
<div class="section-card-body" id="timetableDisplay">
<div style="color:var(--text-muted);text-align:center;padding:30px;">No timetable uploaded yet. Check back later.</div>
</div>
</div>
</div>
<div id="sectionSettings" style="display:none;">
<div class="topbar">
<div>
<div class="breadcrumb">Student Dashboard › <span>Settings</span></div>
<div class="page-title">⚙️ Settings</div>
<div class="page-subtitle">Manage your account preferences</div>
</div>
</div>
<div id="settingsContent"></div>
</div>
</main>
</div>
<div class="toast-container" id="toastContainer"></div>
<script src="js/demo-isolator.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-firestore-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-auth-compat.js"></script>
<script src="js/firebase-config.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging-compat.js"></script>
<script src="js/data.js"></script>
<script src="js/auth.js"></script>
<script src="js/firebase-sync.js"></script>
<script src="js/notifications.js"></script>
<script>
fbInit();
const session = requireAuth('student');
startSessionListener();
if (!session) throw new Error('No session');
// ==================== FCM PUSH NOTIFICATION REGISTRATION ====================
(function registerFCM() {
if (!('Notification' in window) || !('serviceWorker' in navigator)) return;
Notification.requestPermission().then(function(permission) {
if (permission !== 'granted') { console.log('[FCM] Permission denied'); return; }
// Register service worker and get FCM token
navigator.serviceWorker.register('/feedback/firebase-messaging-sw.js')
.then(function(registration) {
var messaging = firebase.messaging();
messaging.getToken({
vapidKey: 'BGXBxnRNf2Zk4Xs4p_UXd11L9akGGZSTejpsYw29P4upXtWnBWfOzt-bRm2KXW5ZWe3_d7DgPFbRdICq14wpN1E',
serviceWorkerRegistration: registration
}).then(function(token) {
if (!token) { console.warn('[FCM] No token received'); return; }
console.log('[FCM] Token:', token.substring(0, 20) + '...');
// Store token in Firestore linked to this student
if (typeof db !== 'undefined') {
db.collection('fcm_tokens').doc(session.userId).set({
token: token,
userId: session.userId,
email: session.email,
name: session.name,
updatedAt: new Date().toISOString()
});
console.log('[FCM] Token stored in Firestore for', session.userId);
}
}).catch(function(err) { console.warn('[FCM] Token error:', err.message); });
// Handle foreground messages
var messaging2 = firebase.messaging();
messaging2.onMessage(function(payload) {
console.log('[FCM] Foreground message:', payload);
var notifTitle = (payload.notification && payload.notification.title) || 'New Notification';
var notifBody = (payload.notification && payload.notification.body) || '';
var notifType = (payload.data && payload.data.type) || 'general';
// Use NotificationsManager for vibration + sound + badge update
if (window.NotificationsManager) {
NotificationsManager.handleIncoming(notifTitle, notifBody, notifType);
} else {
if (typeof updateNotifBadge === 'function') updateNotifBadge();
}
// Show in-app toast with type-specific style
if (typeof showToast === 'function') {
var toastTypeMap = { assignment: 'assignment', urgent: 'urgent' };
var toastType = toastTypeMap[notifType] || 'success';
showToast(notifTitle + (notifBody ? ': ' + notifBody : ''), toastType);
}
});
}).catch(function(err) { console.warn('[FCM] SW registration error:', err.message); });
});
})();
// ==================== REAL-TIME ENROLLMENT LISTENER ====================
(function startEnrollmentWatcher() {
if (typeof db === 'undefined' || !db) return;
// Track enrollments we already know about to detect new ones
var knownEnrollKeys = {};
// Track keys that were already in localStorage when the page loaded
// so we can distinguish "pre-existing" from "new while offline"
var preloadedKeys = {};
var initialLoad = true;
try {
var existing = JSON.parse(localStorage.getItem('sfft_enrollments') || '[]');
existing.forEach(function(e) {
if (e.studentId === session.userId) {
var k = e.studentId + '_' + e.teacherId;
knownEnrollKeys[k] = true;
preloadedKeys[k] = true; // remember what was already known at page load
}
});
} catch(e) {}
db.collection('enrollments').onSnapshot(function(snapshot) {
snapshot.docChanges().forEach(function(change) {
if (change.type === 'removed') {
var data = change.doc.data();
if (data.studentId !== session.userId) return;
var key = data.studentId + '_' + data.teacherId;
delete knownEnrollKeys[key]; // clear so re-assignment triggers a new notification
delete preloadedKeys[key];
return;
}
if (change.type === 'added' || change.type === 'modified') {
var data = change.doc.data();
if (data.studentId !== session.userId) return; // not for this student
var key = data.studentId + '_' + data.teacherId;
if (knownEnrollKeys[key]) return; // already known — skip notification and re-processing
knownEnrollKeys[key] = true;
// Skip notification only if this enrollment was already loaded from localStorage
// (i.e., was known before Firestore connected). If it's new from Firestore even
// during initial load, the student was assigned while offline — do notify them.
if (initialLoad && preloadedKeys[key]) return;
// Sync enrollments to localStorage so UI updates
var enrollments = JSON.parse(localStorage.getItem('sfft_enrollments') || '[]');
var existingIdx = enrollments.findIndex(function(e) { return e.studentId === data.studentId && e.teacherId === data.teacherId; });
if (existingIdx === -1) {
enrollments.push(data);
} else {
enrollments[existingIdx] = data; // update existing record with latest subjects
}
localStorage.setItem('sfft_enrollments', JSON.stringify(enrollments));
var teacher = getUserById(data.teacherId);
var teacherName = teacher ? teacher.name : 'a new teacher';
// In-app toast
if (typeof showToast === 'function') {
showToast('🎓 New teacher assigned: ' + teacherName + '. Give your feedback!', 'assignment');
}
// Vibration + sound + browser notification (via NotificationsManager when available)
if (window.NotificationsManager) {
NotificationsManager.handleIncoming(
'New Teacher Assigned',
teacherName + ' has been assigned to you for feedback.',
'assignment',
{ tag: 'enroll-' + key }
);
} else if ('Notification' in window && Notification.permission === 'granted') {
try {
new Notification('New Teacher Assigned', {
body: teacherName + ' has been assigned to you for feedback.',
icon: 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎓</text></svg>',
requireInteraction: true,
tag: 'enroll-' + key
});
} catch(e) { console.warn('[Notification] Push failed:', e.message); }
}
// Also add to sf_notifications so it appears in Notifications panel
var notifs = JSON.parse(localStorage.getItem('sf_notifications') || '[]');
notifs.push({
id: 'enroll_' + Date.now(),
title: 'New Teacher Assigned: ' + teacherName,
message: teacherName + ' has been assigned to you. Please provide your feedback.',
category: 'Assignment',
timestamp: new Date().toISOString()
});
localStorage.setItem('sf_notifications', JSON.stringify(notifs));
if (typeof updateNotifBadge === 'function') updateNotifBadge();
if (typeof renderTeachers === 'function') renderTeachers(); // refresh teachers list
}
});
initialLoad = false;
}, function(err) {
console.warn('[Enrollment Watcher] Error:', err.message);
});
})();
const currentUser = getUserById(session.userId);
// UI Setup
document.getElementById('sidebarAvatar').textContent = session.name.charAt(0).toUpperCase();
document.getElementById('sidebarName').textContent = session.name;
document.getElementById('collegeName').textContent = getSettings().collegeName;
function showSection(sec, skipHistory) {
const sections = ['dashboard', 'academics', 'teachers', 'history', 'notifications', 'timetable', 'profile', 'settings'];
const navItems = document.querySelectorAll('.sidebar-nav .nav-item');
sections.forEach(s => {
const el = document.getElementById('section' + s.charAt(0).toUpperCase() + s.slice(1));
if (el) el.style.display = s === sec ? '' : 'none';
});
navItems.forEach(el => {
const m = el.getAttribute('onclick') && el.getAttribute('onclick').match(/'([^']+)'/);
if (m) el.classList.toggle('active', m[1] === sec);
});
if (sec === 'teachers') renderTeachers();
if (sec === 'history') renderHistory();
if (sec === 'dashboard') renderDashboard();
if (sec === 'academics') renderAcademics();
if (sec === 'profile') renderProfile();
if (sec === 'settings') renderSettings();
if (sec === 'notifications') renderNotifications();
if (sec === 'timetable') renderTimetable();
// Close sidebar on mobile
document.querySelector('.sidebar').classList.remove('open');
document.querySelector('.sidebar-overlay').classList.remove('show');
// Push browser history so back button works
if (!skipHistory) history.pushState({section: sec}, '', '#' + sec);
}
// Handle browser back button
window.addEventListener('popstate', function(e) {
if (e.state && e.state.section) showSection(e.state.section, true);
});
// Set initial history state
history.replaceState({section: 'teachers'}, '', '#teachers');
// Re-render after Firestore sync to show correct submission status on new devices
window.addEventListener('firestore-synced', function() {
console.log('[Dashboard] Re-rendering after Firestore sync...');
renderTeachers();
renderDashboard();
});
// ==================== NOTIFICATIONS ====================
function getNotifications() {
try { return JSON.parse(localStorage.getItem('sf_notifications') || '[]'); } catch(e) { return []; }
}
function renderNotifications() {
var notifs = getNotifications().sort(function(a,b) { return new Date(b.timestamp) - new Date(a.timestamp); });
var sessionId = (typeof session !== 'undefined' && session) ? session.id || session.userId || 'default' : 'default';
var readIds = JSON.parse(localStorage.getItem('sf_notif_read_' + sessionId) || '[]');
var el = document.getElementById('notifList');
if (!notifs.length) {
el.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-muted);"><div style="font-size:40px;margin-bottom:12px;">🔔</div><div style="font-weight:600;">No notifications yet</div><div style="font-size:13px;margin-top:4px;">Admin will push notifications here</div></div>';
return;
}
el.innerHTML = notifs.map(function(n) {
var isRead = readIds.indexOf(n.id) !== -1;
var cat = (n.category || '').toLowerCase();
var NOTIF_COLORS = {
assignment: { bg: 'rgba(59,130,246,0.12)', dot: '#60a5fa', catBg: 'rgba(59,130,246,0.15)', catColor: '#60a5fa' },
urgent: { bg: 'rgba(239,68,68,0.12)', dot: '#f87171', catBg: 'rgba(239,68,68,0.15)', catColor: '#f87171' }
};
var colors = NOTIF_COLORS[cat] || { bg: 'rgba(124,58,237,0.06)', dot: 'var(--accent-light)', catBg: 'rgba(124,58,237,0.15)', catColor: 'var(--accent-light)' };
return '<div style="padding:16px;border-bottom:1px solid var(--border-light);background:' + (isRead ? 'transparent' : colors.bg) + ';transition:var(--transition);">' +
'<div style="display:flex;justify-content:space-between;align-items:flex-start;">' +
'<div style="font-weight:700;font-size:15px;">' + (!isRead ? '<span style="color:' + colors.dot + ';margin-right:4px;">⬤</span>' : '') + (n.title || 'Notification') + '</div>' +
'<span style="font-size:11px;color:var(--text-muted);flex-shrink:0;">' + (n.timestamp ? new Date(n.timestamp).toLocaleDateString() : '') + '</span>' +
'</div>' +
'<div style="font-size:13px;color:var(--text-sub);margin-top:6px;line-height:1.6;">' + (n.message || '') + '</div>' +
(n.category ? '<span style="font-size:10px;padding:2px 8px;border-radius:12px;background:' + colors.catBg + ';color:' + colors.catColor + ';margin-top:8px;display:inline-block;">' + n.category + '</span>' : '') +
'</div>';
}).join('');
// Auto-mark all as read when viewing notifications section
var allIds = notifs.map(function(n) { return n.id; });
localStorage.setItem('sf_notif_read_' + sessionId, JSON.stringify(allIds));
updateNotifBadge();
}
function updateNotifBadge() {
if (window.NotificationsManager) {
NotificationsManager.updateBadge();
return;
}
var notifs = getNotifications();
var sessionId = (typeof session !== 'undefined' && session) ? session.id || session.userId || 'default' : 'default';
var readIds = JSON.parse(localStorage.getItem('sf_notif_read_' + sessionId) || '[]');
var unread = notifs.filter(function(n) { return readIds.indexOf(n.id) === -1; }).length;
var badge = document.getElementById('notifBadge');
if (badge) { badge.textContent = unread; badge.style.display = unread > 0 ? '' : 'none'; }
}
function markAllNotifRead() {
var notifs = getNotifications();
var readIds = notifs.map(function(n) { return n.id; });
var mSessionId = (typeof session !== 'undefined' && session) ? session.id || session.userId || 'default' : 'default';
localStorage.setItem('sf_notif_read_' + mSessionId, JSON.stringify(readIds));
renderNotifications();
updateNotifBadge();
showToast('All notifications marked as read', 'success');
}
updateNotifBadge();
// ==================== TIMETABLE ====================
function renderTimetable() {
var timetables = [];
try { timetables = JSON.parse(localStorage.getItem('sf_timetables') || '[]'); } catch(e) {}
var el = document.getElementById('timetableDisplay');
// Filter for student's department/section
var myTT = timetables.filter(function(t) {
if (t.department && session.department && t.department !== session.department) return false;
if (t.section && session.section && t.section !== session.section) return false;
return true;
});
if (!myTT.length) myTT = timetables; // fallback show all if no match
if (!myTT.length) {
el.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-muted);"><div style="font-size:40px;margin-bottom:12px;">📅</div><div style="font-weight:600;">No timetable available</div><div style="font-size:13px;margin-top:4px;">Your admin will upload timetables here</div></div>';
return;
}
el.innerHTML = myTT.map(function(tt) {
return '<div style="margin-bottom:20px;">' +
'<div style="font-weight:700;font-size:16px;margin-bottom:4px;">📅 ' + (tt.title || 'Timetable') + '</div>' +
'<div style="font-size:12px;color:var(--text-muted);margin-bottom:12px;">' + (tt.department || '') + (tt.section ? ' - ' + tt.section : '') + ' | Uploaded: ' + (tt.timestamp ? new Date(tt.timestamp).toLocaleDateString() : 'Unknown') + '</div>' +
(tt.content ? '<div style="background:var(--surface2);border-radius:var(--radius-sm);padding:16px;font-size:13px;line-height:1.8;white-space:pre-wrap;border:1px solid var(--border-light);">' + tt.content + '</div>' : '') +
(tt.imageUrl ? '<img src="' + tt.imageUrl + '" alt="Timetable for ' + (tt.department || '') + (tt.section ? ' ' + tt.section : '') + '" style="max-width:100%;border-radius:var(--radius-sm);margin-top:8px;border:1px solid var(--border-light);" />' : '') +
'</div>';
}).join('<hr style="border-color:var(--border-light);margin:16px 0;">');
}
// ==================== AI CHATBOT ====================
var chatOpen = false;
var chatHistory = [];
var botKnowledge = {
greetings: ['hello','hi','hey','good morning','good evening','sup','hola'],
feedback: ['feedback','review','rate','rating','submit feedback','give feedback','how to feedback','evaluate'],
attendance: ['attendance','absent','present','my attendance','attendance percentage','bunking'],
timetable: ['timetable','schedule','class schedule','time table','classes today','when is','lecture'],
notification: ['notification','notice','announcement','alert','update','news'],
grades: ['grade','marks','score','cgpa','sgpa','result','exam'],
profile: ['profile','my profile','account','my details','change password'],
navigation: ['where','how to','find','go to','open','navigate','show me'],
help: ['help','support','assist','guide','what can you do','features']
};
var botResponses = {
greetings: "Hey there! 👋 I'm your Student Assistant. I can help you with:\n\n• 📝 Giving feedback to teachers\n• 📊 Checking attendance\n• 📅 Viewing timetable\n• 🔔 Reading notifications\n\nWhat would you like help with?",
feedback: "To give feedback to a teacher:\n\n1️⃣ Go to the <b>Feedback</b> section from the sidebar\n2️⃣ Select a teacher card\n3️⃣ Rate each question using the scale\n4️⃣ Add optional comments\n5️⃣ Click <b>Submit</b>\n\n💡 Tip: You can toggle <b>Anonymous mode</b> to submit without revealing your identity!\n\n<button onclick=\"showSection('teachers');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">➡ Go to Feedback</button>",
attendance: "Your attendance information is tracked by the institution.\n\n📊 Go to <b>Dashboard</b> to see your attendance overview.\n\n💡 Tip: Keep attendance above 75% to avoid issues!\n\n<button onclick=\"showSection('dashboard');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">➡ View Dashboard</button>",
timetable: "Your class timetable is uploaded by the admin.\n\n<button onclick=\"showSection('timetable');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">📅 View Timetable</button>",
notification: "Check the latest notifications from your institution.\n\n<button onclick=\"showSection('notifications');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">🔔 View Notifications</button>",
grades: "Your academic records and grades can be found in the <b>Academics</b> section.\n\n<button onclick=\"showSection('academics');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">🎓 View Academics</button>",
profile: "You can view and update your profile information.\n\n<button onclick=\"showSection('profile');toggleChat()\" class=\"btn btn-primary btn-xs\" style=\"margin-top:8px;\">👤 My Profile</button>",
navigation: "Here are the main sections you can visit:\n\n• 📊 <b>Dashboard</b> - Overview & stats\n• 🎓 <b>Academics</b> - Grades & courses\n• 📝 <b>Feedback</b> - Rate teachers\n• 📋 <b>Records</b> - Past submissions\n• 🔔 <b>Notifications</b> - Announcements\n• 📅 <b>Timetable</b> - Class schedule\n\nJust click any section in the sidebar!",
help: "I'm your Smart Student Assistant! 🤖 Here's what I can help with:\n\n📝 <b>Feedback</b> - How to rate teachers\n📊 <b>Attendance</b> - Check your record\n📅 <b>Timetable</b> - View schedule\n🔔 <b>Notifications</b> - Read updates\n🎓 <b>Academics</b> - View grades\n👤 <b>Profile</b> - Edit your info\n\nJust type your question!",
unknown: "I'm not sure about that. 🤔 Try asking about:\n\n• How to give feedback\n• My attendance\n• Timetable / schedule\n• Notifications\n• Grades / academics\n\nOr type <b>help</b> to see everything I can do!"
};
function matchIntent(msg) {
var lower = msg.toLowerCase().trim();
var bestMatch = 'unknown';
var bestScore = 0;
for (var intent in botKnowledge) {
var keywords = botKnowledge[intent];
for (var i = 0; i < keywords.length; i++) {
if (lower.indexOf(keywords[i]) !== -1 && keywords[i].length > bestScore) {
bestMatch = intent;
bestScore = keywords[i].length;
}
}
}
return bestMatch;
}
function getBotReply(msg) {
var intent = matchIntent(msg);
return botResponses[intent] || botResponses.unknown;
}
function toggleChat() {
chatOpen = !chatOpen;
document.getElementById('chatWidget').style.display = chatOpen ? 'flex' : 'none';
document.getElementById('chatFab').style.display = chatOpen ? 'none' : 'flex';
if (chatOpen && chatHistory.length === 0) {
appendBotMsg(botResponses.greetings);
}
}
function appendBotMsg(text) {
chatHistory.push({role:'bot',text:text});
var el = document.getElementById('chatMessages');
el.innerHTML += '<div style="display:flex;gap:8px;margin-bottom:12px;"><div style="width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-light));display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">🤖</div><div style="background:var(--surface2);border-radius:12px 12px 12px 2px;padding:10px 14px;max-width:85%;font-size:13px;line-height:1.6;">' + text.replace(/\n/g,'<br>') + '</div></div>';
el.scrollTop = el.scrollHeight;
}
function appendUserMsg(text) {
chatHistory.push({role:'user',text:text});
var el = document.getElementById('chatMessages');
el.innerHTML += '<div style="display:flex;gap:8px;margin-bottom:12px;justify-content:flex-end;"><div style="background:var(--accent);color:#fff;border-radius:12px 12px 2px 12px;padding:10px 14px;max-width:85%;font-size:13px;line-height:1.6;">' + text + '</div></div>';
el.scrollTop = el.scrollHeight;
}
function sendChatMsg() {
var input = document.getElementById('chatInput');
var msg = input.value.trim();
if (!msg) return;
input.value = '';
appendUserMsg(msg);
// Simulate typing delay
var el = document.getElementById('chatMessages');
el.innerHTML += '<div id="typingIndicator" style="display:flex;gap:8px;margin-bottom:12px;"><div style="width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-light));display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">🤖</div><div style="background:var(--surface2);border-radius:12px;padding:10px 14px;font-size:13px;color:var(--text-muted);">typing<span class="typing-dots">...</span></div></div>';
el.scrollTop = el.scrollHeight;
setTimeout(function() {
var typing = document.getElementById('typingIndicator');
if (typing) typing.remove();
appendBotMsg(getBotReply(msg));
}, 600 + Math.random() * 400);
}
function renderDashboard() {
const teachers = getTeachersForStudent(session.userId);
const responses = getResponses().filter(r => r.studentId === session.userId);
const submitted = teachers.filter(t => hasSubmitted(session.userId, t.id, t._enrolledSubjectId)).length;
const pending = teachers.length - submitted;
const attRecord = getStudentAttendance(session.userId);
const eligible = attRecord ? attRecord.percentage >= 75 : true;
document.getElementById('dashSubtitle').textContent =
`Hello ${session.name} — ${new Date().toLocaleDateString('en-IN', { weekday:'long', year:'numeric', month:'long', day:'numeric' })}`;
document.getElementById('dashStats').innerHTML = [
{ icon: '👨🏫', val: teachers.length, label: 'Assigned Teachers' },
{ icon: '✅', val: submitted, label: 'Feedback Submitted' },
{ icon: '⏳', val: pending, label: 'Pending Feedback' },
{ icon: '📊', val: attRecord ? attRecord.percentage + '%' : '—', label: 'Attendance' },
].map(s => `<div class="stat-card"><div class="stat-icon">${s.icon}</div><div class="stat-value">${s.val}</div><div class="stat-label">${s.label}</div></div>`).join('');
// Attendance card
const attHtml = attRecord ? (() => {
const pct = attRecord.percentage;
const isPass = pct >= 75;
const barColor = isPass ? 'var(--success)' : 'var(--danger)';
return `
<div style="text-align:center;padding:10px 0 16px;">
<div style="font-size:42px;font-weight:800;color:${barColor};line-height:1;">${pct}%</div>
<div style="font-size:13px;color:var(--text-muted);margin:4px 0 12px;">Your Attendance</div>
<div style="height:10px;background:var(--border-light);border-radius:10px;overflow:hidden;">
<div style="height:100%;width:${pct}%;background:${barColor};border-radius:10px;transition:width 0.7s ease;"></div>
</div>
<div style="margin-top:12px;">${isPass
? '<span class="badge badge-green">🔓 Eligible to Submit Feedback</span>'
: '<span class="badge badge-red">🔒 Feedback Locked (Below 75%)</span>'}</div>
</div>`;
})() : `<div style="text-align:center;padding:20px;color:var(--text-muted);font-size:13px;">📊 Attendance record not uploaded yet.<br><span style="font-size:11px;">Contact your administrator.</span></div>`;
document.getElementById('dashAttCard').innerHTML = attHtml;
// Recent submissions
const el = document.getElementById('dashRecent');
if (!responses.length) {
el.innerHTML = `<div class="empty-state" style="padding:24px;"><div class="empty-icon">📝</div><div class="empty-title">No Submissions Yet</div></div>`;
} else {
el.innerHTML = `<table><thead><tr><th>Teacher</th><th>Subject</th><th>Rating</th><th>Date</th></tr></thead><tbody>
${responses.slice(-5).reverse().map(r => {
const t = getUserById(r.teacherId);
const sub = getSubjectById(r.subjectId);
const all = Object.values(r.scores || {}).flat();
const avg = all.length ? (all.reduce((a,b) => a+b,0)/all.length).toFixed(1) : '?';
return `<tr>
<td style="font-weight:600;">${t ? t.name : 'Unknown'}</td>
<td style="color:var(--text-muted);">${sub ? sub.name : 'N/A'}</td>
<td><span class="badge badge-purple">⭐ ${avg}/5</span></td>
<td style="font-size:12px;color:var(--text-muted);">${new Date(r.submittedAt).toLocaleDateString()}</td>
</tr>`;
}).join('')}
</tbody></table>`;
}
}
function renderAcademics() {
const teachers = getTeachersForStudent(session.userId);
const el = document.getElementById('academicsContent');
if (!teachers.length) {
el.innerHTML = `<div class="empty-state"><div class="empty-icon">🎓</div><div class="empty-title">No Courses Enrolled</div><div class="empty-desc">Your admin hasn't assigned teachers yet.</div></div>`;
return;
}
el.innerHTML = `
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:18px;">
${teachers.map(t => {
const sub = getSubjectById(t._enrolledSubjectId);
const done = hasSubmitted(session.userId, t.id, t._enrolledSubjectId);
const initials = t.name.split(' ').map(w => w[0]).join('').substring(0,2).toUpperCase();
return `
<div class="section-card animate-in" style="padding:0;">
<div style="background:linear-gradient(135deg,var(--accent),var(--accent-light));padding:18px;border-radius:14px 14px 0 0;display:flex;align-items:center;gap:12px;">
<div style="width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-weight:800;color:#fff;font-size:16px;flex-shrink:0;">${initials}</div>
<div>
<div style="font-weight:700;color:#fff;font-size:14px;">${t.name}</div>
<div style="font-size:11px;color:rgba(255,255,255,0.75);">${t.department || ''}${t.section ? ' · ' + t.section : ''}</div>
</div>
</div>
<div style="padding:14px 16px;">
${sub ? `<div style="font-size:13px;font-weight:600;margin-bottom:6px;">📚 ${sub.name}</div>` : '<div style="color:var(--text-muted);font-size:12px;">No subject assigned</div>'}
<div style="margin-top:10px;">${done
? '<span class="badge badge-green" style="font-size:11px;">✅ Feedback Submitted</span>'
: '<span class="badge badge-orange" style="font-size:11px;">⏳ Feedback Pending</span>'}
</div>
</div>
</div>`;
}).join('')}
</div>`;
}
function renderProfile() {
const userRecord = getUserById(session.userId) || {};
// Fall back to session data when localStorage record is missing or incomplete
const user = {
name: userRecord.name || session.name || '',
email: userRecord.email || session.email || '',
department: userRecord.department || session.department || '',
section: userRecord.section || session.section || '',
rollNo: userRecord.rollNo || '',
};
const attRecord = getStudentAttendance(session.userId);
const responses = getResponses().filter(r => r.studentId === session.userId);
const initials = (user.name || 'S').split(' ').map(w => w[0]).join('').substring(0,2).toUpperCase();
document.getElementById('profileContent').innerHTML = `
<div style="display:grid;grid-template-columns:auto 1fr;gap:24px;align-items:start;">
<!-- Avatar + Badges -->
<div class="section-card animate-in" style="text-align:center;padding:28px 24px;min-width:200px;">
<div style="width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-light));display:flex;align-items:center;justify-content:center;font-weight:800;color:#fff;font-size:28px;margin:0 auto 12px;">${initials}</div>
<div style="font-weight:700;font-size:16px;margin-bottom:4px;">${user.name || 'Student'}</div>
<div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">${user.email || ''}</div>
${user.rollNo ? `<div style="font-size:13px;font-weight:600;color:var(--text);margin-bottom:12px;">Roll No: ${user.rollNo}</div>` : ''}
<span class="badge badge-blue">🎓 Student</span>
${user.department ? `<span class="badge badge-purple" style="margin-left:4px;">${user.department}${user.section ? ' · ' + user.section : ''}</span>` : ''}
<div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-muted);">
<div style="font-weight:600;font-size:13px;margin-bottom:4px;">📊 Feedback Score</div>
<div style="font-size:24px;font-weight:800;color:var(--accent);">${responses.length}</div>
<div>submissions</div>
</div>
</div>
<!-- Info Card -->
<div class="section-card animate-in">
<div class="section-card-header"><div class="section-card-title">Personal Information</div></div>
<div class="section-card-body">
${[
['Full Name', user.name || '—'],
['Email Address', user.email || '—'],
['Department', user.department || '—'],
['Section', user.section || '—'],
['Role', 'Student'],
['Attendance', attRecord ? attRecord.percentage + '%' : 'Not uploaded'],
].map(([k,v]) => `
<div style="display:flex;justify-content:space-between;align-items:center;padding:12px 0;border-bottom:1px solid var(--border-light);">
<span style="font-size:13px;color:var(--text-muted)">${k}</span>
<span style="font-weight:600;font-size:13px;">${v}</span>
</div>`).join('')}
</div>
</div>
</div>
<!-- Change Password Section -->
<div class="section-card animate-in" style="margin-top:20px;">
<div class="section-card-header"><div class="section-card-title">🔒 Change Password</div></div>
<div class="section-card-body">
<div style="max-width:400px;">
<div class="form-group">
<label>Current Password</label>
<input type="password" id="cpCurrent" placeholder="Enter current password" />
</div>
<div class="form-group">
<label>New Password</label>
<input type="password" id="cpNew" placeholder="Min 6 characters" />
</div>
<div class="form-group">
<label>Confirm New Password</label>
<input type="password" id="cpConfirm" placeholder="Re-enter new password" />
</div>
<div id="cpMsg" style="font-size:13px;margin-bottom:10px;"></div>
<button class="btn btn-primary btn-sm" onclick="handleChangePassword()">🔒 Update Password</button>
</div>
</div>
</div>`;
}
function handleChangePassword() {
var msgEl = document.getElementById('cpMsg');
msgEl.textContent = '';
msgEl.style.color = '';
var cur = document.getElementById('cpCurrent').value;
var np = document.getElementById('cpNew').value;
var conf = document.getElementById('cpConfirm').value;
if (!cur) { msgEl.textContent = 'Please enter your current password.'; msgEl.style.color = 'var(--danger)'; return; }
if (!np || np.length < 6) { msgEl.textContent = 'New password must be at least 6 characters.'; msgEl.style.color = 'var(--danger)'; return; }
if (np !== conf) { msgEl.textContent = 'New passwords do not match.'; msgEl.style.color = 'var(--danger)'; return; }
try {
changePassword(session.userId, cur, np);
msgEl.textContent = '\u2705 Password changed successfully!';
msgEl.style.color = '#22c55e';
document.getElementById('cpCurrent').value = '';
document.getElementById('cpNew').value = '';
document.getElementById('cpConfirm').value = '';
} catch(e) {
msgEl.textContent = e.message;
msgEl.style.color = 'var(--danger)';
}
}
function renderSettings() {
document.getElementById('settingsContent').innerHTML = `
<div style="max-width:520px;">
<div class="section-card animate-in" style="margin-bottom:20px;">
<div class="section-card-header"><div class="section-card-title">🔒 Feedback Preferences</div></div>
<div class="section-card-body">
<div style="display:flex;justify-content:space-between;align-items:center;padding:10px 0;">
<div>
<div style="font-weight:600;font-size:13px;">Anonymous Mode</div>
<div style="font-size:12px;color:var(--text-muted);">Submit feedback without revealing your identity</div>
</div>
<label class="toggle-wrap" style="margin:0;">
<div class="toggle"><input type="checkbox" id="settingsAnonToggle" ${sessionStorage.getItem('sfft_default_anon')==='1'?'checked':''} onchange="sessionStorage.setItem('sfft_default_anon',this.checked?'1':'0'); document.getElementById('anonToggle').checked=this.checked; showToast('Preference saved','success');" /><span class="toggle-slider"></span></div>
</label>
</div>
</div>
</div>
<div class="section-card animate-in">
<div class="section-card-header"><div class="section-card-title">🔐 Account</div></div>
<div class="section-card-body">
<div style="font-size:13px;color:var(--text-muted);margin-bottom:14px;">Logged in as <strong>${session.name}</strong></div>
<button class="btn btn-secondary" onclick="if(confirm('Log out?')) logout()">🚪 Log Out</button>
</div>
</div>
</div>
<!-- Change Password Section -->
<div class="section-card animate-in" style="margin-top:20px;">
<div class="section-card-header"><div class="section-card-title">🔒 Change Password</div></div>
<div class="section-card-body">
<div style="max-width:400px;">
<div class="form-group">
<label>Current Password</label>
<input type="password" id="cpCurrent" placeholder="Enter current password" />
</div>
<div class="form-group">
<label>New Password</label>
<input type="password" id="cpNew" placeholder="Min 6 characters" />
</div>
<div class="form-group">
<label>Confirm New Password</label>
<input type="password" id="cpConfirm" placeholder="Re-enter new password" />
</div>
<div id="cpMsg" style="font-size:13px;margin-bottom:10px;"></div>
<button class="btn btn-primary btn-sm" onclick="handleChangePassword()">🔒 Update Password</button>
</div>
</div>
</div>`;
}
function handleChangePassword() {
var msgEl = document.getElementById('cpMsg');
msgEl.textContent = '';
msgEl.style.color = '';
var cur = document.getElementById('cpCurrent').value;
var np = document.getElementById('cpNew').value;
var conf = document.getElementById('cpConfirm').value;
if (!cur) { msgEl.textContent = 'Please enter your current password.'; msgEl.style.color = 'var(--danger)'; return; }
if (!np || np.length < 6) { msgEl.textContent = 'New password must be at least 6 characters.'; msgEl.style.color = 'var(--danger)'; return; }
if (np !== conf) { msgEl.textContent = 'New passwords do not match.'; msgEl.style.color = 'var(--danger)'; return; }
try {
changePassword(session.userId, cur, np);
msgEl.textContent = '\u2705 Password changed successfully!';
msgEl.style.color = '#22c55e';
document.getElementById('cpCurrent').value = '';
document.getElementById('cpNew').value = '';
document.getElementById('cpConfirm').value = '';
} catch(e) {
msgEl.textContent = e.message;
msgEl.style.color = 'var(--danger)';
}
}
function renderTeachers() {
const teachers = getTeachersForStudent(session.userId);
const container = document.getElementById('teachersList');
const noTeach = document.getElementById('noTeachers');
document.getElementById('totalTeachers').textContent = teachers.length;
const submitted = teachers.filter(t => hasSubmitted(session.userId, t.id, t._enrolledSubjectId)).length;
document.getElementById('totalSubmitted').textContent = submitted;
document.getElementById('totalPending').textContent = teachers.length - submitted;
if (!teachers.length) { container.style.display = 'none'; noTeach.style.display = ''; return; }
container.style.display = ''; noTeach.style.display = 'none';
const canSubmit = canSubmitFeedback(session.userId);
const attRecord = getStudentAttendance(session.userId);
// If student is blocked, show a banner
if (!canSubmit && attRecord !== null && !document.getElementById('attBanner')) {
const d = document.createElement('div');
d.id = 'attBanner';
d.innerHTML = `<div style="background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.3); border-radius:12px; padding:16px; margin-bottom:20px; display:flex; gap:14px; align-items:center;">
<div style="font-size:24px;">🚫</div>
<div>
<div style="font-weight:700; color:var(--danger); margin-bottom:4px;">Feedback Locked: Low Attendance</div>
<div style="font-size:13px; color:var(--text);">Your attendance is <strong>${attRecord.percentage}%</strong>. The institution requires a minimum of 75% to submit feedback.</div>
</div>
</div>`;
document.getElementById('teachersList').parentNode.insertBefore(d, document.getElementById('teachersList'));
}
container.innerHTML = teachers.map(t => {
const sub = getSubjectById(t._enrolledSubjectId);
const done = hasSubmitted(session.userId, t.id, t._enrolledSubjectId);
const initials = t.name.split(' ').map(w => w[0]).join('').substring(0, 2).toUpperCase();
let statusHtml, btnHtml;
if (!canSubmit && attRecord !== null) {
statusHtml = '<span class="badge badge-red">🔒 Locked</span>';
btnHtml = `<button class="btn btn-secondary btn-sm" disabled style="opacity:0.6; cursor:not-allowed;">Feedback Locked</button>`;
} else {
statusHtml = done ? '<span class="badge badge-green">✅ Submitted</span>' : '<span class="badge badge-orange">⏳ Pending</span>';
btnHtml = done ? '<span style="font-size:12px; color:var(--text-muted);">Already submitted</span>' : `<button class="btn btn-primary btn-sm" onclick="goToFeedback('${t.id}','${t._enrolledSubjectId || ''}')">📝 Give Feedback</button>`;
}
return `
<div class="teacher-card">
<div class="teacher-avatar-lg">${initials}</div>
<div class="teacher-name">${t.name}</div>
<div class="teacher-meta">${t.department || 'Department N/A'}${t.section ? ' · ' + t.section : ''}</div>
${sub ? `<div class="teacher-subject-tag">📚 ${sub.name}</div>` : ''}
<div style="margin-bottom:14px;">${statusHtml}</div>
${btnHtml}
</div>
`;
}).join('');
}
function renderHistory() {
const responses = getResponses().filter(r => r.studentId === session.userId);
const list = document.getElementById('historyList');
const noHist = document.getElementById('noHistory');
if (!responses.length) { list.innerHTML = ''; noHist.style.display = ''; return; }
noHist.style.display = 'none';
list.innerHTML = `<div class="table-wrap"><table>
<thead><tr><th>Teacher</th><th>Subject</th><th>Avg Score</th><th>Anonymous</th><th>Date</th></tr></thead>
<tbody>
${responses.map(r => {
const t = getUserById(r.teacherId);
const sub = getSubjectById(r.subjectId);
const all = Object.values(r.scores || {}).flat();
const avg = all.length ? (all.reduce((a, b) => a + b, 0) / all.length).toFixed(1) : 'N/A';
return `<tr>
<td>${t ? t.name : 'Unknown'}</td>
<td>${sub ? sub.name : 'N/A'}</td>
<td><span class="badge badge-purple">⭐ ${avg}/5</span></td>
<td>${r.anonymous ? '<span class="badge badge-blue">Anonymous</span>' : '<span class="badge badge-gray">Identified</span>'}</td>
<td>${new Date(r.submittedAt).toLocaleDateString()}</td>
</tr>`;
}).join('')}
</tbody>
</table></div>`;
}
function goToFeedback(teacherId, subjectId) {
const anon = document.getElementById('anonToggle').checked;
sessionStorage.setItem('sfft_feedback_teacher', teacherId);
sessionStorage.setItem('sfft_feedback_subject', subjectId || '');
sessionStorage.setItem('sfft_feedback_anon', anon ? '1' : '0');
window.location.href = 'feedback-form.html';
}
function showToast(msg, type='info') {
const c = document.getElementById('toastContainer');
const t = document.createElement('div');
t.className = `toast toast-${type}`;
t.textContent = msg;
c.appendChild(t);
setTimeout(() => t.remove(), 3800);
}
renderTeachers();
</script>
<script>
// Global chatbot functions (outside main script scope for reliability)
var chatOpen = false;
var chatHistoryGlobal = [];
function toggleChat() {
chatOpen = !chatOpen;
var widget = document.getElementById('chatWidget');
var fab = document.getElementById('chatFab');
if (widget) widget.style.display = chatOpen ? 'flex' : 'none';
if (fab) fab.style.display = chatOpen ? 'none' : 'flex';
if (chatOpen && chatHistoryGlobal.length === 0) {