-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
1691 lines (1580 loc) · 74 KB
/
Copy pathscripts.js
File metadata and controls
1691 lines (1580 loc) · 74 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
document.addEventListener('DOMContentLoaded', () => {
// ... (existing variable declarations) ...
const authContainer = document.getElementById('auth-container');
const appContainer = document.getElementById('app-container');
const loginContainer = document.getElementById('login-container');
const signupContainer = document.getElementById('signup-container');
const showSignup = document.getElementById('show-signup');
const showLogin = document.getElementById('show-login');
const signoutBtn = document.getElementById('signout-btn');
const sidebarMenu = document.querySelector('.sidebar-menu');
// Exam-related elements
const createExamForm = document.getElementById('create-exam-form');
const examList = document.getElementById('exam-list');
const examSubjectDropdown = document.getElementById('exam-subject');
const studentExamList = document.getElementById('student-exam-list');
const examInterface = document.getElementById('exam-interface');
const examTitleDisplay = document.getElementById('exam-title-display');
const examTimer = document.getElementById('exam-timer');
const examQuestionsContainer = document.getElementById('exam-questions-container');
const submitExamBtn = document.getElementById('submit-exam-btn');
const studentResultsList = document.getElementById('student-results-list');
const submittedExamsList = document.getElementById('submitted-exams-list');
const examScoresList = document.getElementById('exam-scores-list');
const scoreExamFilter = document.getElementById('score-exam-filter');
const exportScoresBtn = document.getElementById('export-scores-btn');
// Question-related elements
const createQuestionForm = document.getElementById('create-question-form');
const questionList = document.getElementById('question-list');
const questionSubjectDropdown = document.getElementById('question-subject');
const questionTypeDropdown = document.getElementById('question-type');
const optionsContainer = document.getElementById('options-container');
// Token Generation elements
const generateTokenForm = document.getElementById('generate-token-form');
const tokenExamDropdown = document.getElementById('token-exam');
const tokenStudentDropdown = document.getElementById('token-student');
const generatedTokensList = document.getElementById('generated-tokens-list');
// Admin elements
const userList = document.getElementById('user-list');
const editUserModal = document.getElementById('edit-user-modal');
const editUserForm = document.getElementById('edit-user-form');
// System Settings elements
const createCourseForm = document.getElementById('create-course-form');
const createSubjectForm = document.getElementById('create-subject-form');
const courseList = document.getElementById('course-list');
const subjectList = document.getElementById('subject-list');
const subjectCourseDropdown = document.getElementById('subject-course');
// Modal elements
const gradeExamModal = document.getElementById('grade-exam-modal');
const gradeExamQuestionsContainer = document.getElementById('grade-exam-questions-container');
const finishGradingBtn = document.getElementById('finish-grading-btn');
const editExamModal = document.getElementById('edit-exam-modal');
const editExamForm = document.getElementById('edit-exam-form');
const editQuestionModal = document.getElementById('edit-question-modal');
const editQuestionForm = document.getElementById('edit-question-form');
const confirmationModal = document.getElementById('confirmation-modal');
const manageExamQuestionsModal = document.getElementById('manage-exam-questions-modal');
const closeModalButtons = document.querySelectorAll('.close-modal');
const confirmYesBtn = document.getElementById('confirm-yes-btn');
const confirmNoBtn = document.getElementById('confirm-no-btn');
const availableQuestionsList = document.getElementById('available-questions-list');
const examQuestionsList = document.getElementById('exam-questions-list');
const loginForm = document.getElementById('login-form');
const signupForm = document.getElementById('signup-form');
const signupPassword = document.getElementById('signup-password');
const repeatPassword = document.getElementById('signup-repeat-password');
const strengthIndicator = document.getElementById('password-strength-indicator');
const notification = document.getElementById('notification');
let currentExamId = null; // To store the ID of the exam being managed
let currentAttemptId = null; // To store the ID of the exam attempt being graded
let examTimerInterval = null;
// --- Custom Notification Function ---
const showNotification = (message, isSuccess) => {
notification.textContent = message;
notification.className = 'notification-bar'; // Reset classes
if (isSuccess) {
notification.classList.add('notification-success');
} else {
notification.classList.add('notification-error');
}
notification.classList.add('show');
// Hide the notification after 3 seconds
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
};
// --- Custom Confirmation Modal Logic ---
let confirmCallback = null;
const showConfirmation = (title, message, callback) => {
document.getElementById('confirmation-title').textContent = title;
document.getElementById('confirmation-message').textContent = message;
confirmationModal.style.display = 'flex';
confirmCallback = callback;
};
if(confirmYesBtn) {
confirmYesBtn.addEventListener('click', () => {
if (confirmCallback) {
confirmCallback();
}
confirmationModal.style.display = 'none';
});
}
if(confirmNoBtn) {
confirmNoBtn.addEventListener('click', () => {
confirmationModal.style.display = 'none';
});
}
// --- UI Update Functions ---
const setupDashboardUI = (role) => {
authContainer.style.display = 'none';
appContainer.style.display = 'flex';
document.body.style.justifyContent = 'flex-start';
document.body.style.alignItems = 'flex-start';
const navLinks = {
student: [
{ text: 'Dashboard', section: 'student-dashboard' },
{ text: 'My Exams', section: 'student-my-exams' },
{ text: 'Results', section: 'student-results' }
],
examiner: [
{ text: 'Dashboard', section: 'examiner-dashboard' },
{ text: 'Manage Exams', section: 'examiner-manage-exams' },
{ text: 'Question Bank', section: 'examiner-question-bank' },
{ text: 'Grade Exams', section: 'examiner-grade-exams' },
{ text: 'Exam Scores', section: 'examiner-exam-scores' }
],
admin: [
{ text: 'Dashboard', section: 'admin-dashboard' },
{ text: 'Manage Users', section: 'admin-manage-users' },
{ text: 'System Settings', section: 'admin-settings' }
]
};
sidebarMenu.innerHTML = '';
const userLinks = navLinks[role] || [];
userLinks.forEach(link => {
const li = document.createElement('li');
li.innerHTML = `<a href="#" data-section="${link.section}">${link.text}</a>`;
sidebarMenu.appendChild(li);
});
document.querySelectorAll('.dashboard-section').forEach(section => {
section.style.display = 'none';
});
const dashboard = document.getElementById(`${role}-dashboard`);
if (dashboard) {
dashboard.style.display = 'block';
}
// Pre-fetch data for forms
if (role === 'examiner') {
fetchAndPopulateExamsForTokenDropdown();
fetchAndPopulateStudents();
fetchAndDisplayGeneratedTokens();
}
if (role === 'admin') {
fetchAndDisplayUsers();
}
};
const showLoginScreen = () => {
appContainer.style.display = 'none';
authContainer.style.display = 'block';
document.body.style.justifyContent = 'center';
document.body.style.alignItems = 'center';
};
// --- Event Listeners ---
if (showSignup) {
showSignup.addEventListener('click', (e) => {
e.preventDefault();
loginContainer.style.display = 'none';
signupContainer.style.display = 'block';
});
}
if (showLogin) {
showLogin.addEventListener('click', (e) => {
e.preventDefault();
signupContainer.style.display = 'none';
loginContainer.style.display = 'block';
});
}
sidebarMenu.addEventListener('click', (e) => {
e.preventDefault();
const target = e.target;
if (target.tagName === 'A' && target.dataset.section) {
const sectionId = target.dataset.section;
document.querySelectorAll('.dashboard-section').forEach(section => {
section.style.display = 'none';
});
const sectionToShow = document.getElementById(sectionId);
if (sectionToShow) {
sectionToShow.style.display = 'block';
}
if (sectionId === 'examiner-manage-exams') {
fetchAndDisplayExams();
fetchAndPopulateSubjects(examSubjectDropdown);
}
if (sectionId === 'examiner-question-bank') {
fetchAndDisplayQuestions();
fetchAndPopulateSubjects(questionSubjectDropdown);
// Render the default options for the initially selected question type
if (questionTypeDropdown) {
questionTypeDropdown.dispatchEvent(new Event('change'));
}
}
if (sectionId === 'student-my-exams') {
fetchAndDisplayStudentExams();
}
if (sectionId === 'admin-manage-users') {
fetchAndDisplayUsers();
}
if (sectionId === 'admin-settings') {
fetchAndDisplayCourses();
fetchAndDisplaySubjects();
fetchAndPopulateCoursesForSubjectDropdown();
}
if (sectionId === 'examiner-grade-exams') {
fetchAndDisplaySubmittedExams();
}
if (sectionId === 'examiner-exam-scores') {
fetchAndDisplayExamScores();
fetchAndPopulateExamsForScoreFilter();
}
if (sectionId === 'student-results') {
fetchAndDisplayStudentResults();
}
}
});
// --- Question Bank Specific Logic ---
const renderMcqOptions = () => {
optionsContainer.innerHTML = `
<label>Options</label>
<div class="option-group">
<input type="radio" name="correct_option" value="0" checked>
<input type="text" name="options[]" placeholder="Option 1" required>
</div>
<div class="option-group">
<input type="radio" name="correct_option" value="1">
<input type="text" name="options[]" placeholder="Option 2" required>
</div>
<button type="button" id="add-option-btn" class="btn-secondary">Add Another Option</button>
`;
};
const renderTrueFalseOptions = () => {
optionsContainer.innerHTML = `
<label>Correct Answer</label>
<div class="option-group">
<input type="radio" name="correct_tf_option" value="True" checked> True
</div>
<div class="option-group">
<input type="radio" name="correct_tf_option" value="False"> False
</div>
`;
};
const renderFillBlankOptions = () => {
optionsContainer.innerHTML = `
<label>Correct Answer</label>
<div class="form-group">
<input type="text" name="fill_blank_answer" placeholder="Enter the exact answer" required>
</div>
`;
};
if (questionTypeDropdown) {
questionTypeDropdown.addEventListener('change', () => {
const questionType = questionTypeDropdown.value;
if (questionType === 'mcq') {
renderMcqOptions();
} else if (questionType === 'true_false') {
renderTrueFalseOptions();
} else if (questionType === 'fill_blank') {
renderFillBlankOptions();
} else {
optionsContainer.innerHTML = '';
}
});
}
document.addEventListener('click', (e) => {
if (e.target && e.target.id === 'add-option-btn') {
const optionCount = optionsContainer.querySelectorAll('.option-group').length;
const newOption = document.createElement('div');
newOption.className = 'option-group';
newOption.innerHTML = `
<input type="radio" name="correct_option" value="${optionCount}">
<input type="text" name="options[]" placeholder="Option ${optionCount + 1}" required>
`;
e.target.before(newOption);
}
});
// --- Password Strength Checker ---
const checkPasswordStrength = (password) => {
let score = 0;
if (password.length > 8) score++;
if (password.match(/[a-z]/)) score++;
if (password.match(/[A-Z]/)) score++;
if (password.match(/[0-9]/)) score++;
if (password.match(/[^a-zA-Z0-9]/)) score++;
const strengthMap = [
{ text: 'Weak', className: 'strength-weak' },
{ text: 'Weak', className: 'strength-weak' },
{ text: 'Weak', className: 'strength-weak' },
{ text: 'Medium', className: 'strength-medium' },
{ text: 'Strong', className: 'strength-strong' },
{ text: 'Strong', className: 'strength-strong' }
];
return strengthMap[score] || { text: '', className: '' };
};
if (signupPassword) {
signupPassword.addEventListener('input', () => {
const password = signupPassword.value;
const strength = checkPasswordStrength(password);
strengthIndicator.textContent = password ? `Strength: ${strength.text}` : '';
strengthIndicator.className = strength.className;
});
}
// --- Form Submission and Auth Logic ---
if (loginForm) {
loginForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(loginForm);
try {
const response = await fetch('api/signin.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Login successful!', true);
await checkAuthState();
} else {
showNotification(`Login failed: ${result.message || 'Invalid credentials.'}`, false);
}
} catch (error) {
console.error('Error during login:', error);
showNotification('An error occurred. Please try again.', false);
}
});
}
if (signupForm) {
signupForm.addEventListener('submit', async (event) => {
event.preventDefault();
if (signupPassword.value !== repeatPassword.value) {
showNotification("Passwords do not match.", false);
return;
}
const formData = new FormData(signupForm);
try {
const response = await fetch('api/signup.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Sign up successful! Please log in.', true);
signupContainer.style.display = 'none';
loginContainer.style.display = 'block';
} else {
showNotification(`Sign up failed: ${result.message}`, false);
}
} catch (error) {
console.error('Error during signup:', error);
showNotification('An error occurred. Please try again.', false);
}
});
}
if (createExamForm) {
createExamForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(createExamForm);
try {
const response = await fetch('api/create_exam.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Exam created successfully!', true);
createExamForm.reset();
fetchAndDisplayExams();
} else {
showNotification(`Error: ${result.message}`, false);
}
} catch (error) {
console.error('Error creating exam:', error);
showNotification('An error occurred. Please try again.', false);
}
});
}
if (createQuestionForm) {
createQuestionForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(createQuestionForm);
const data = Object.fromEntries(formData);
const questionType = data.question_type;
data.options = []; // Initialize options array
if (questionType === 'mcq') {
const options = Array.from(document.querySelectorAll('input[name="options[]"]')).map(input => input.value);
const checkedRadio = document.querySelector('input[name="correct_option"]:checked');
if (!checkedRadio) {
showNotification('Please select a correct answer for the multiple-choice question.', false);
return;
}
const correctOptionIndex = checkedRadio.value;
data.options = options.map((option, index) => ({
option_text: option,
is_correct: index == correctOptionIndex
}));
} else if (questionType === 'true_false') {
const checkedRadio = document.querySelector('input[name="correct_tf_option"]:checked');
if (!checkedRadio) {
showNotification('Please select a correct answer for the true/false question.', false);
return;
}
const correctAnswer = checkedRadio.value;
data.options.push({ option_text: 'True', is_correct: correctAnswer === 'True' });
data.options.push({ option_text: 'False', is_correct: correctAnswer === 'False' });
} else if (questionType === 'fill_blank') {
const correctAnswer = document.querySelector('input[name="fill_blank_answer"]').value;
if (correctAnswer) {
data.options.push({ option_text: correctAnswer, is_correct: true });
} else {
showNotification('Please provide the correct answer for the fill in the blank question.', false);
return;
}
}
try {
const response = await fetch('api/create_question.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Question added successfully!', true);
createQuestionForm.reset();
optionsContainer.innerHTML = '';
fetchAndDisplayQuestions();
} else {
showNotification(`Error: ${result.message}`, false);
}
} catch (error) {
console.error('Error creating question:', error);
showNotification('An error occurred. Please try again.', false);
}
});
}
if (generateTokenForm) {
generateTokenForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(generateTokenForm);
const data = Object.fromEntries(formData);
try {
const response = await fetch('api/generate_token.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
showNotification(`Token generated: ${result.token}`, true);
generateTokenForm.reset();
fetchAndDisplayGeneratedTokens(); // Refresh the list
} else {
showNotification(`Error: ${result.message}`, false);
}
} catch (error) {
console.error('Error generating token:', error);
showNotification('An error occurred. Please try again.', false);
}
});
}
if (signoutBtn) {
signoutBtn.addEventListener('click', async () => {
await fetch('api/signout.php');
showNotification('You have been signed out.', true);
showLoginScreen();
});
}
// --- Data Fetching ---
const fetchAndDisplayExams = async () => {
try {
const response = await fetch('api/get_exams.php');
const exams = await response.json();
examList.innerHTML = '';
if (exams.length > 0) {
exams.forEach(exam => {
const examElement = document.createElement('div');
examElement.className = 'exam-item';
examElement.innerHTML = `
<div>
<h4>${exam.title}</h4>
<p>${exam.description}</p>
<div class="exam-meta">
<span>Marks: ${exam.total_marks}</span>
<span>Time: ${exam.time_limit} mins</span>
</div>
</div>
<div class="item-actions">
<button class="edit-exam-btn" data-exam-id="${exam.exam_id}">Edit</button>
<button class="manage-questions-btn" data-exam-id="${exam.exam_id}" data-exam-title="${exam.title}">Manage Questions</button>
<button class="delete-exam-btn" data-exam-id="${exam.exam_id}">Delete</button>
</div>
`;
examList.appendChild(examElement);
});
} else {
examList.innerHTML = '<p>No exams found.</p>';
}
} catch (error) {
console.error('Error fetching exams:', error);
}
};
const fetchAndDisplayGeneratedTokens = async () => {
try {
const response = await fetch('api/get_generated_tokens.php');
const tokens = await response.json();
generatedTokensList.innerHTML = '';
if (tokens.length > 0) {
tokens.forEach(token => {
const tokenElement = document.createElement('div');
tokenElement.className = 'exam-item';
tokenElement.innerHTML = `
<div>
<h4>Token: ${token.token}</h4>
<div class="exam-meta">
<span>Exam: ${token.exam_title}</span>
<span>Student: ${token.student_name}</span>
</div>
</div>
`;
generatedTokensList.appendChild(tokenElement);
});
} else {
generatedTokensList.innerHTML = '<p>No tokens generated yet.</p>';
}
} catch (error) {
console.error('Error fetching tokens:', error);
}
};
const fetchAndPopulateExamsForTokenDropdown = async () => {
try {
const response = await fetch('api/get_exams.php');
const exams = await response.json();
tokenExamDropdown.innerHTML = '<option value="">Select an Exam</option>';
if (exams.length > 0) {
exams.forEach(exam => {
const option = document.createElement('option');
option.value = exam.exam_id;
option.textContent = exam.title;
tokenExamDropdown.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching exams for token:', error);
}
};
const fetchAndPopulateStudents = async () => {
try {
const response = await fetch('api/get_students.php');
const students = await response.json();
tokenStudentDropdown.innerHTML = '<option value="">Select a Student</option>';
if (students.length > 0) {
students.forEach(student => {
const option = document.createElement('option');
option.value = student.id;
option.textContent = `${student.username} (${student.email})`;
tokenStudentDropdown.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching students:', error);
}
};
const fetchAndDisplayStudentExams = async () => {
try {
const response = await fetch('api/get_student_exams.php');
const exams = await response.json();
studentExamList.innerHTML = '';
if (exams.length > 0) {
exams.forEach(exam => {
const examElement = document.createElement('div');
examElement.className = 'exam-item';
examElement.innerHTML = `
<div>
<h4>${exam.title} (${exam.subject_name})</h4>
<p>${exam.description}</p>
<div class="exam-meta">
<span>Marks: ${exam.total_marks}</span>
<span>Time: ${exam.time_limit} mins</span>
</div>
</div>
<div class="item-actions">
<input type="text" class="token-input" placeholder="Enter Exam Token" data-exam-id="${exam.exam_id}">
<button class="start-exam-btn" data-exam-id="${exam.exam_id}">Start Exam</button>
</div>
`;
studentExamList.appendChild(examElement);
});
} else {
studentExamList.innerHTML = '<p>No exams assigned to you yet.</p>';
}
} catch (error) {
console.error('Error fetching student exams:', error);
}
};
const fetchAndDisplayStudentResults = async () => {
try {
const response = await fetch('api/get_student_results.php');
const results = await response.json();
const studentResultsList = document.getElementById('student-results-list');
studentResultsList.innerHTML = '';
if (results.length > 0) {
results.forEach(result => {
const resultElement = document.createElement('div');
resultElement.className = 'exam-item';
resultElement.innerHTML = `
<div>
<h4>${result.exam_title}</h4>
<div class="exam-meta">
<span>Subject: ${result.subject_name}</span>
<span>Score: ${result.score}</span>
<span>Completed: ${new Date(result.end_time).toLocaleString()}</span>
</div>
</div>
`;
studentResultsList.appendChild(resultElement);
});
} else {
studentResultsList.innerHTML = '<p>No results found.</p>';
}
} catch (error) {
console.error('Error fetching student results:', error);
}
};
const fetchAndDisplayQuestions = async () => {
try {
const response = await fetch('api/get_questions.php');
const questions = await response.json();
questionList.innerHTML = '';
if (questions.length > 0) {
questions.forEach(q => {
const qElement = document.createElement('div');
qElement.className = 'question-item';
qElement.innerHTML = `
<div>
<h4>${q.question_text}</h4>
<div class="question-meta">
<span>Subject: ${q.subject_name}</span>
<span>Type: ${q.question_type}</span>
<span>Marks: ${q.marks}</span>
</div>
</div>
<div class="item-actions">
<button class="edit-btn" data-id="${q.question_id}" data-text="${q.question_text}" data-marks="${q.marks}">Edit</button>
<button class="delete-btn" data-id="${q.question_id}">Delete</button>
</div>
`;
questionList.appendChild(qElement);
});
} else {
questionList.innerHTML = '<p>No questions found.</p>';
}
} catch (error) {
console.error('Error fetching questions:', error);
}
};
const fetchAndDisplayUsers = async () => {
try {
const response = await fetch('api/get_users.php');
const users = await response.json();
userList.innerHTML = '';
if (users.length > 0) {
users.forEach(user => {
const userElement = document.createElement('div');
userElement.className = 'exam-item'; // Re-using styles
userElement.innerHTML = `
<div>
<h4>${user.username} (${user.email})</h4>
<div class="exam-meta">
<span>Role: ${user.role}</span>
<span>Status: ${user.status}</span>
<span>Joined: ${new Date(user.created_at).toLocaleDateString()}</span>
</div>
</div>
<div class="item-actions">
<button class="edit-user-btn" data-id="${user.id}" data-username="${user.username}" data-email="${user.email}" data-role="${user.role}">Edit</button>
<button class="deactivate-user-btn" data-id="${user.id}" data-status="${user.status}">${user.status === 'active' ? 'Ban' : 'Unban'}</button>
<button class="delete-user-btn" data-id="${user.id}">Delete</button>
</div>
`;
userList.appendChild(userElement);
});
} else {
userList.innerHTML = '<p>No users found.</p>';
}
} catch (error) {
console.error('Error fetching users:', error);
}
};
const fetchAndDisplaySubmittedExams = async () => {
try {
const response = await fetch('api/get_submitted_exams.php');
const attempts = await response.json();
submittedExamsList.innerHTML = '';
if (attempts.length > 0) {
attempts.forEach(attempt => {
const attemptElement = document.createElement('div');
attemptElement.className = 'exam-item';
attemptElement.innerHTML = `
<div>
<h4>${attempt.exam_title}</h4>
<div class="exam-meta">
<span>Student: ${attempt.student_name}</span>
<span>Submitted: ${new Date(attempt.end_time).toLocaleString()}</span>
</div>
</div>
<div class="item-actions">
<button class="grade-exam-btn" data-attempt-id="${attempt.attempt_id}">Grade</button>
</div>
`;
submittedExamsList.appendChild(attemptElement);
});
} else {
submittedExamsList.innerHTML = '<p>No exams to grade.</p>';
}
} catch (error) {
console.error('Error fetching submitted exams:', error);
}
};
const fetchAndDisplayExamScores = async (examId = '') => {
try {
const response = await fetch(`api/get_exam_scores.php?exam_id=${examId}`);
const scores = await response.json();
examScoresList.innerHTML = '';
if (scores.length > 0) {
scores.forEach(score => {
const scoreElement = document.createElement('div');
scoreElement.className = 'exam-item';
scoreElement.innerHTML = `
<div>
<h4>${score.exam_title}</h4>
<div class="exam-meta">
<span>Student: ${score.student_name}</span>
<span>Score: ${score.score} / ${score.total_marks}</span>
<span>Graded on: ${new Date(score.end_time).toLocaleString()}</span>
</div>
</div>
`;
examScoresList.appendChild(scoreElement);
});
} else {
examScoresList.innerHTML = '<p>No scores found.</p>';
}
} catch (error) {
console.error('Error fetching exam scores:', error);
}
};
const fetchAndPopulateExamsForScoreFilter = async () => {
try {
const response = await fetch('api/get_exams.php');
const exams = await response.json();
scoreExamFilter.innerHTML = '<option value="">Filter by Exam</option>';
if (exams.length > 0) {
exams.forEach(exam => {
const option = document.createElement('option');
option.value = exam.exam_id;
option.textContent = exam.title;
scoreExamFilter.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching exams for filter:', error);
}
};
const fetchAndPopulateSubjects = async (dropdownElement) => {
if (!dropdownElement) return;
try {
const response = await fetch('api/get_subjects.php');
const subjects = await response.json();
dropdownElement.innerHTML = '<option value="">Select a Subject</option>';
if (subjects.length > 0) {
subjects.forEach(subject => {
const option = document.createElement('option');
option.value = subject.subject_id;
option.textContent = subject.name;
dropdownElement.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching subjects:', error);
}
};
const fetchAndDisplayCourses = async () => {
try {
const response = await fetch('api/get_courses.php');
const courses = await response.json();
courseList.innerHTML = '';
if (courses.length > 0) {
courses.forEach(course => {
const courseElement = document.createElement('div');
courseElement.className = 'exam-item';
courseElement.innerHTML = `
<div>
<h4>${course.name}</h4>
<p>${course.description}</p>
</div>
<div class="item-actions">
<button class="delete-course-btn" data-id="${course.course_id}">Delete</button>
</div>
`;
courseList.appendChild(courseElement);
});
} else {
courseList.innerHTML = '<p>No courses found.</p>';
}
} catch (error) {
console.error('Error fetching courses:', error);
}
};
const fetchAndDisplaySubjects = async () => {
try {
const response = await fetch('api/get_subjects.php');
const subjects = await response.json();
subjectList.innerHTML = '';
if (subjects.length > 0) {
subjects.forEach(subject => {
const subjectElement = document.createElement('div');
subjectElement.className = 'exam-item';
subjectElement.innerHTML = `
<div>
<h4>${subject.name}</h4>
<div class="exam-meta">
<span>Course: ${subject.course_name}</span>
</div>
</div>
<div class="item-actions">
<button class="delete-subject-btn" data-id="${subject.subject_id}">Delete</button>
</div>
`;
subjectList.appendChild(subjectElement);
});
} else {
subjectList.innerHTML = '<p>No subjects found.</p>';
}
} catch (error) {
console.error('Error fetching subjects:', error);
}
};
const fetchAndPopulateCoursesForSubjectDropdown = async () => {
try {
const response = await fetch('api/get_courses.php');
const courses = await response.json();
subjectCourseDropdown.innerHTML = '<option value="">Select a Course</option>';
if (courses.length > 0) {
courses.forEach(course => {
const option = document.createElement('option');
option.value = course.course_id;
option.textContent = course.name;
subjectCourseDropdown.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching courses for dropdown:', error);
}
};
// --- Edit/Delete Question Logic ---
questionList.addEventListener('click', (e) => {
const target = e.target;
if (target.classList.contains('delete-btn')) {
const questionId = target.dataset.id;
showConfirmation('Delete Question', 'Are you sure you want to delete this question?', async () => {
try {
const response = await fetch('api/delete_question.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question_id: questionId })
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Question deleted successfully!', true);
fetchAndDisplayQuestions();
} else {
showNotification(`Error: ${result.message}`, false);
}
} catch (error) {
console.error('Error deleting question:', error);
showNotification('An error occurred.', false);
}
});
}
if (target.classList.contains('edit-btn')) {
document.getElementById('edit-question-id').value = target.dataset.id;
document.getElementById('edit-question-text').value = target.dataset.text;
document.getElementById('edit-question-marks').value = target.dataset.marks;
editQuestionModal.style.display = 'flex';
}
});
closeModalButtons.forEach(btn => {
btn.addEventListener('click', () => {
const modalId = btn.dataset.modalId;
document.getElementById(modalId).style.display = 'none';
});
});
if(editQuestionForm) {
editQuestionForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(editQuestionForm);
const data = Object.fromEntries(formData);
try {
const response = await fetch('api/update_question.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
showNotification('Question updated successfully!', true);
editQuestionModal.style.display = 'none';
fetchAndDisplayQuestions();
} else {
showNotification(`Error: ${result.message}`, false);
}
} catch (error) {
console.error('Error updating question:', error);
showNotification('An error occurred.', false);
}
});
}
// --- Manage Exam Questions Logic ---
examList.addEventListener('click', async (e) => {
const target = e.target;
if (target.classList.contains('edit-exam-btn')) {
const examId = target.dataset.examId;
// Fetch the exam details to populate the modal
try {
const response = await fetch(`api/get_exam.php?exam_id=${examId}`);
const exam = await response.json();
if (response.ok) {
document.getElementById('edit-exam-id').value = exam.exam_id;
document.getElementById('edit-exam-title').value = exam.title;
document.getElementById('edit-exam-description').value = exam.description;
document.getElementById('edit-exam-marks').value = exam.total_marks;