-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_dashboard.php
More file actions
3500 lines (3181 loc) · 191 KB
/
Copy pathadmin_dashboard.php
File metadata and controls
3500 lines (3181 loc) · 191 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
<?php
include 'includes/db.php';
include 'includes/header.php';
// Check if user is logged in as admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
header('Location: login.php?type=admin');
exit();
}
// Check for session messages
if (isset($_SESSION['success_message'])) {
$success_message = $_SESSION['success_message'];
unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
$error_message = $_SESSION['error_message'];
unset($_SESSION['error_message']);
}
// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);
// ====== NEW: Set HOD ======
if (isset($_POST['set_hod'])) {
$selectedId = isset($_POST['hod_faculty_id']) && $_POST['hod_faculty_id'] !== 'none' ? intval($_POST['hod_faculty_id']) : null;
try {
// Clear existing HOD
$pdo->beginTransaction();
$pdo->exec("UPDATE faculty SET is_hod = 0");
if ($selectedId) {
$stmt = $pdo->prepare("UPDATE faculty SET is_hod = 1 WHERE id = ?");
$stmt->execute([$selectedId]);
}
$pdo->commit();
$_SESSION['success_message'] = "HOD updated successfully.";
} catch (Exception $e) {
$pdo->rollBack();
$_SESSION['error_message'] = "Failed to update HOD.";
error_log("Set HOD error: " . $e->getMessage());
}
header("Location: admin_dashboard.php#manage-hod");
exit();
}
// ====== NEW: Set Counsellor ======
if (isset($_POST['set_counsellor'])) {
$selectedId = isset($_POST['counsellor_faculty_id']) && $_POST['counsellor_faculty_id'] !== 'none' ? intval($_POST['counsellor_faculty_id']) : null;
try {
// Clear existing Counsellor
$pdo->beginTransaction();
$pdo->exec("UPDATE faculty SET is_counsellor = 0");
if ($selectedId) {
$stmt = $pdo->prepare("UPDATE faculty SET is_counsellor = 1 WHERE id = ?");
$stmt->execute([$selectedId]);
}
$pdo->commit();
$_SESSION['success_message'] = "Counsellor updated successfully.";
} catch (Exception $e) {
$pdo->rollBack();
$_SESSION['error_message'] = "Failed to update Counsellor.";
error_log("Set Counsellor error: " . $e->getMessage());
}
header("Location: admin_dashboard.php#manage-counsellor");
exit();
}
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Add Announcement
if (isset($_POST['add_announcement'])) {
$title = $_POST['title'];
$message = $_POST['message'];
$stmt = $pdo->prepare("INSERT INTO announcements (title, message) VALUES (?, ?)");
$stmt->execute([$title, $message]);
$success_message = "Announcement added successfully.";
}
// Update Announcement
if (isset($_POST['update_announcement'])) {
$announcement_id = $_POST['announcement_id'];
$title = $_POST['title'];
$message = $_POST['message'];
$stmt = $pdo->prepare("UPDATE announcements SET title=?, message=? WHERE id=?");
$stmt->execute([$title, $message, $announcement_id]);
$success_message = "Announcement updated successfully.";
header("Location: admin_dashboard.php#manage-announcements");
exit();
}
// Add Achievement image
if (isset($_POST['add_achievement'])) {
if (isset($_FILES['achievement_image']) && $_FILES['achievement_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/achievements/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
$original = $_FILES['achievement_image']['name'];
$ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type for achievement image. Allowed: " . implode(', ', $allowed);
} else {
$filename = uniqid('ach_') . '.' . $ext;
$target = $upload_dir . $filename;
if (move_uploaded_file($_FILES['achievement_image']['tmp_name'], $target)) {
// Create table if not exists then insert record
$pdo->exec("CREATE TABLE IF NOT EXISTS achievements (
id INT AUTO_INCREMENT PRIMARY KEY,
file_path VARCHAR(255) NOT NULL,
alt_text VARCHAR(255) DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$stmt = $pdo->prepare("INSERT INTO achievements (file_path, alt_text) VALUES (?, ?)");
$stmt->execute([$target, trim($_POST['alt_text'] ?? '')]);
$success_message = "Achievement image uploaded successfully.";
} else {
$error_message = "Failed to move uploaded achievement image.";
}
}
} else {
$error_message = "No achievement image uploaded or upload error.";
}
}
// Add Faculty
if (isset($_POST['add_faculty'])) {
$full_name = $_POST['full_name'];
$subject = $_POST['subject'];
$qualification = $_POST['qualification'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$is_hod = isset($_POST['is_hod']) ? 1 : 0;
$is_counsellor = isset($_POST['is_counsellor']) ? 1 : 0;
$profile_image = 'default.jpg';
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/images/faculty/';
$file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
$profile_image = uniqid() . '.' . $file_extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $upload_dir . $profile_image);
}
$stmt = $pdo->prepare("INSERT INTO faculty (full_name, subject, qualification, email, phone, profile_image, is_hod, is_counsellor) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$full_name, $subject, $qualification, $email, $phone, $profile_image, $is_hod, $is_counsellor]);
$success_message = "Faculty added successfully.";
}
// Update Faculty
if (isset($_POST['update_faculty'])) {
$faculty_id = $_POST['faculty_id'];
$full_name = $_POST['full_name'];
$subject = $_POST['subject'];
$qualification = $_POST['qualification'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$is_hod = isset($_POST['is_hod']) ? 1 : 0;
$is_counsellor = isset($_POST['is_counsellor']) ? 1 : 0;
$existing_profile_image = $_POST['existing_profile_image'];
$profile_image = $existing_profile_image;
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/images/faculty/';
$file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
$profile_image = uniqid() . '.' . $file_extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $upload_dir . $profile_image);
}
$stmt = $pdo->prepare("UPDATE faculty SET full_name=?, subject=?, qualification=?, email=?, phone=?, profile_image=?, is_hod=?, is_counsellor=? WHERE id=?");
$stmt->execute([$full_name, $subject, $qualification, $email, $phone, $profile_image, $is_hod, $is_counsellor, $faculty_id]);
$success_message = "Faculty updated successfully.";
header("Location: admin_dashboard.php#manage-faculty");
exit();
}
// Add Student
if (isset($_POST['add_student'])) {
$roll_number = $_POST['roll_number'];
$full_name = $_POST['full_name'];
$date_of_birth = $_POST['date_of_birth'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$is_admin_profile = isset($_POST['is_admin_profile']) ? 1 : 0;
$hashed_password = password_hash($date_of_birth, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, 'student')");
$stmt->execute([$roll_number, $hashed_password]);
$user_id = $pdo->lastInsertId();
$profile_image = 'default.jpg';
$is_cr = isset($_POST['is_cr']) ? 1 : 0;
$is_lr = isset($_POST['is_lr']) ? 1 : 0;
$is_acr = isset($_POST['is_acr']) ? 1 : 0;
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/images/students/';
$file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
$profile_image = uniqid() . '.' . $file_extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $upload_dir . $profile_image);
}
$stmt = $pdo->prepare("INSERT INTO students (user_id, roll_number, full_name, date_of_birth, email, phone, address, profile_image, year, semester, is_admin_profile, is_cr, is_lr, is_acr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$user_id, $roll_number, $full_name, $date_of_birth, $email, $phone, $address, $profile_image, $year, $semester, $is_admin_profile, $is_cr, $is_lr, $is_acr]);
$success_message = "Student added successfully.";
}
// Update Student
if (isset($_POST['update_student'])) {
$student_id = $_POST['student_id'];
$roll_number = $_POST['roll_number'];
$full_name = $_POST['full_name'];
$date_of_birth = $_POST['date_of_birth'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$is_admin_profile = isset($_POST['is_admin_profile']) ? 1 : 0;
$existing_profile_image = $_POST['existing_profile_image'];
$profile_image = $existing_profile_image;
$is_cr = isset($_POST['is_cr']) ? 1 : 0;
$is_lr = isset($_POST['is_lr']) ? 1 : 0;
$is_acr = isset($_POST['is_acr']) ? 1 : 0;
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/images/students/';
$file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
$profile_image = uniqid() . '.' . $file_extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $upload_dir . $profile_image);
}
$stmt = $pdo->prepare("UPDATE students SET roll_number=?, full_name=?, date_of_birth=?, email=?, phone=?, address=?, profile_image=?, year=?, semester=?, is_admin_profile=?, is_cr=?, is_lr=?, is_acr=? WHERE id=?");
$stmt->execute([$roll_number, $full_name, $date_of_birth, $email, $phone, $address, $profile_image, $year, $semester, $is_admin_profile, $is_cr, $is_lr, $is_acr, $student_id]);
$stmt = $pdo->prepare("SELECT user_id FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$user_id = $row['user_id'];
$stmt = $pdo->prepare("UPDATE users SET username=? WHERE id=?");
$stmt->execute([$roll_number, $user_id]);
}
$success_message = "Student updated successfully.";
header("Location: admin_dashboard.php#manage-students");
exit();
}
// Add Attendance
if (isset($_POST['add_attendance'])) {
$student_id = $_POST['student_id'];
$date = $_POST['date'];
$attendance_data = [];
for ($i = 1; $i <= 8; $i++) {
$attendance_data["period$i"] = isset($_POST["period$i"]) ? 1 : 0;
}
$stmt = $pdo->prepare("SELECT id FROM students WHERE id = ?");
$stmt->execute([$student_id]);
if ($stmt->fetchColumn()) {
$stmt = $pdo->prepare("SELECT id FROM attendance WHERE student_id = ? AND date = ?");
$stmt->execute([$student_id, $date]);
$existing_attendance = $stmt->fetch(PDO::FETCH_ASSOC);
if ($existing_attendance) {
$stmt = $pdo->prepare("UPDATE attendance SET period1=?, period2=?, period3=?, period4=?, period5=?, period6=?, period7=?, period8=? WHERE id=?");
$stmt->execute([
$attendance_data['period1'],
$attendance_data['period2'],
$attendance_data['period3'],
$attendance_data['period4'],
$attendance_data['period5'],
$attendance_data['period6'],
$attendance_data['period7'],
$attendance_data['period8'],
$existing_attendance['id']
]);
$success_message = "Attendance updated successfully.";
} else {
$stmt = $pdo->prepare("INSERT INTO attendance (student_id, date, period1, period2, period3, period4, period5, period6, period7, period8) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
$student_id,
$date,
$attendance_data['period1'],
$attendance_data['period2'],
$attendance_data['period3'],
$attendance_data['period4'],
$attendance_data['period5'],
$attendance_data['period6'],
$attendance_data['period7'],
$attendance_data['period8']
]);
$success_message = "Attendance added successfully.";
}
} else {
$error_message = "Invalid student selected for attendance.";
}
}
// Bulk Attendance Upload
if (isset($_POST['bulk_attendance'])) {
$date = $_POST['bulk_date'];
$year = $_POST['bulk_year'];
$semester = $_POST['bulk_semester'];
$stmt = $pdo->prepare("SELECT id FROM students WHERE year = ? AND semester = ?");
$stmt->execute([$year, $semester]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
$success_count = 0;
$error_count = 0;
foreach ($students as $student) {
$student_id = $student['id'];
$stmt = $pdo->prepare("SELECT id FROM attendance WHERE student_id = ? AND date = ?");
$stmt->execute([$student_id, $date]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$existing) {
$stmt = $pdo->prepare("INSERT INTO attendance (student_id, date, period1, period2, period3, period4, period5, period6, period7, period8) VALUES (?, ?, 0, 0, 0, 0, 0, 0, 0, 0)");
if ($stmt->execute([$student_id, $date])) {
$success_count++;
} else {
$error_count++;
}
}
}
$success_message = "Bulk attendance created. $success_count records added, $error_count errors.";
}
}
// Add Timetable
if (isset($_POST['upload_timetable_image'])) {
if (isset($_FILES['timetable_image']) && $_FILES['timetable_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/timetable/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
$allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$originalName = $_FILES['timetable_image']['name'];
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed_ext)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed_ext);
} else {
// Remove any previous timetable_current.* files
foreach (glob($upload_dir . 'timetable_current.*') as $old) {
@unlink($old);
}
$target = $upload_dir . 'timetable_current.' . $ext;
if (move_uploaded_file($_FILES['timetable_image']['tmp_name'], $target)) {
// Optional: set secure permissions
@chmod($target, 0644);
$_SESSION['success_message'] = "Timetable image uploaded successfully.";
header("Location: admin_dashboard.php#manage-timetable");
exit();
} else {
$error_message = "Failed to move uploaded file.";
}
}
} else {
$error_message = "No file uploaded or upload error.";
}
}
// Add Syllabus
if (isset($_POST['add_syllabus'])) {
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$syllabus_content = $_POST['syllabus_content'];
$file_path = '';
if (isset($_FILES['syllabus_file']) && $_FILES['syllabus_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/syllabus/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['syllabus_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt', 'zip', 'rar', '7z'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('syll_') . '.' . $ext;
move_uploaded_file($_FILES['syllabus_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("INSERT INTO syllabus (year, semester, subject, syllabus_content, file_path) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$year, $semester, $subject, $syllabus_content, $file_path]);
$success_message = "Syllabus added successfully.";
}
// Update Syllabus
if (isset($_POST['update_syllabus'])) {
$syllabus_id = $_POST['syllabus_id'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$syllabus_content = $_POST['syllabus_content'];
$existing_file_path = $_POST['existing_file_path'];
$file_path = $existing_file_path;
if (isset($_FILES['syllabus_file']) && $_FILES['syllabus_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/syllabus/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['syllabus_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt', 'zip', 'rar', '7z'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('syll_') . '.' . $ext;
move_uploaded_file($_FILES['syllabus_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("UPDATE syllabus SET year=?, semester=?, subject=?, syllabus_content=?, file_path=? WHERE id=?");
$stmt->execute([$year, $semester, $subject, $syllabus_content, $file_path, $syllabus_id]);
$success_message = "Syllabus updated successfully.";
header("Location: admin_dashboard.php#manage-syllabus");
exit();
}
// Add Study Material
if (isset($_POST['add_material'])) {
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$file_path = '';
if (isset($_FILES['material_file']) && $_FILES['material_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/materials/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['material_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt', 'zip', 'rar', '7z'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('mat_') . '.' . $ext;
move_uploaded_file($_FILES['material_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("INSERT INTO study_materials (year, semester, subject, file_path) VALUES (?, ?, ?, ?)");
$stmt->execute([$year, $semester, $subject, $file_path]);
$success_message = "Question Bank added successfully.";
}
// Update Study Material
if (isset($_POST['update_material'])) {
$material_id = $_POST['material_id'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$existing_file_path = $_POST['existing_file_path'];
$file_path = $existing_file_path;
if (isset($_FILES['material_file']) && $_FILES['material_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/materials/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['material_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt', 'zip', 'rar', '7z'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('mat_') . '.' . $ext;
move_uploaded_file($_FILES['material_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("UPDATE study_materials SET year=?, semester=?, subject=?, file_path=? WHERE id=?");
$stmt->execute([$year, $semester, $subject, $file_path, $material_id]);
$success_message = "Question Bank updated successfully.";
header("Location: admin_dashboard.php#manage-materials");
exit();
}
// Add Bit Bank
if (isset($_POST['add_bit_bank'])) {
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$file_path = '';
if (isset($_FILES['bit_bank_file']) && $_FILES['bit_bank_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/bit_bank/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['bit_bank_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('bit_') . '.' . $ext;
move_uploaded_file($_FILES['bit_bank_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("INSERT INTO bit_bank (year, semester, subject, file_path) VALUES (?, ?, ?, ?)");
$stmt->execute([$year, $semester, $subject, $file_path]);
$success_message = "Bit Bank added successfully.";
}
// Update Bit Bank
if (isset($_POST['update_bit_bank'])) {
$bit_bank_id = $_POST['bit_bank_id'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$existing_file_path = $_POST['existing_file_path'];
$file_path = $existing_file_path;
if (isset($_FILES['bit_bank_file']) && $_FILES['bit_bank_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/bit_bank/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['bit_bank_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('bit_') . '.' . $ext;
move_uploaded_file($_FILES['bit_bank_file']['tmp_name'], $upload_dir . $safe_name);
$file_path = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("UPDATE bit_bank SET year=?, semester=?, subject=?, file_path=? WHERE id=?");
$stmt->execute([$year, $semester, $subject, $file_path, $bit_bank_id]);
$success_message = "Bit Bank updated successfully.";
header("Location: admin_dashboard.php#manage-bit-bank");
exit();
}
// Add Question Bank
if (isset($_POST['add_question_bank'])) {
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$question_file = '';
if (isset($_FILES['question_file']) && $_FILES['question_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/question_bank/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['question_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('qbank_') . '.' . $ext;
move_uploaded_file($_FILES['question_file']['tmp_name'], $upload_dir . $safe_name);
$question_file = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("INSERT INTO question_bank (year, semester, subject, question_file) VALUES (?, ?, ?, ?)");
$stmt->execute([$year, $semester, $subject, $question_file]);
$success_message = "Question Bank added successfully.";
}
// Update Question Bank
if (isset($_POST['update_question_bank'])) {
$question_bank_id = $_POST['question_bank_id'];
$year = $_POST['year'];
$semester = $_POST['semester'];
$subject = $_POST['subject'];
$existing_question_file = $_POST['existing_question_file'];
$question_file = $existing_question_file;
if (isset($_FILES['question_file']) && $_FILES['question_file']['error'] === UPLOAD_ERR_OK) {
$upload_dir = 'assets/uploads/question_bank/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
$file_name = $_FILES['question_file']['name'];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'docm', 'odt'];
if (!in_array($ext, $allowed)) {
$error_message = "Invalid file type. Allowed: " . implode(', ', $allowed);
} else {
$safe_name = uniqid('qbank_') . '.' . $ext;
move_uploaded_file($_FILES['question_file']['tmp_name'], $upload_dir . $safe_name);
$question_file = $upload_dir . $safe_name;
}
}
$stmt = $pdo->prepare("UPDATE question_bank SET year=?, semester=?, subject=?, question_file=? WHERE id=?");
$stmt->execute([$year, $semester, $subject, $question_file, $question_bank_id]);
$success_message = "Question Bank updated successfully.";
header("Location: admin_dashboard.php#manage-question-bank");
exit();
}
// Handle delete actions
if (isset($_GET['delete'])) {
if ($_GET['type'] === 'announcement' && isset($_GET['id'])) {
$stmt = $pdo->prepare("DELETE FROM announcements WHERE id = ?");
$stmt->execute([$_GET['id']]);
echo '<script>alert("Announcement deleted successfully");</script>';
header("Location: admin_dashboard.php#manage-announcements");
exit();
}
$type = $_GET['type'];
$id = $_GET['id'];
// Special case for achievement to handle file deletion
$type = $_GET['type'];
$id = $_GET['id'] ?? null;
if ($type === 'achievement' && $id) {
// remove DB record and unlink file if exists
$stmt = $pdo->prepare("SELECT file_path FROM achievements WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
if (!empty($row['file_path']) && file_exists($row['file_path'])) {
@unlink($row['file_path']);
}
$stmt = $pdo->prepare("DELETE FROM achievements WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Achievement image deleted successfully");</script>';
}
header("Location: admin_dashboard.php#manage-achievements");
exit();
}
switch ($type) {
case 'contact_message':
$stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Contact message deleted successfully");</script>';
header("Location: admin_dashboard.php#contact-messages");
exit();
case 'faculty':
$stmt = $pdo->prepare("DELETE FROM faculty WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Faculty deleted successfully");</script>';
break;
case 'student':
// First get user_id to delete from users table
$stmt = $pdo->prepare("SELECT user_id FROM students WHERE id = ?");
$stmt->execute([$id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if ($student) {
$stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
$stmt->execute([$id]);
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$student['user_id']]);
echo '<script>alert("Student deleted successfully");</script>';
}
break;
case 'syllabus':
$stmt = $pdo->prepare("DELETE FROM syllabus WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Syllabus deleted successfully");</script>';
break;
case 'timetable':
$stmt = $pdo->prepare("DELETE FROM timetable WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Timetable deleted successfully");</script>';
break;
case 'material':
$stmt = $pdo->prepare("DELETE FROM study_materials WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Study material deleted successfully");</script>';
break;
case 'attendance':
$stmt = $pdo->prepare("DELETE FROM attendance WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Attendance record deleted successfully");</script>';
break;
case 'bit_bank':
$stmt = $pdo->prepare("DELETE FROM bit_bank WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Bit Bank deleted successfully");</script>';
break;
case 'question_bank':
$stmt = $pdo->prepare("DELETE FROM question_bank WHERE id = ?");
$stmt->execute([$id]);
echo '<script>alert("Question Bank deleted successfully");</script>';
break;
}
header("Location: admin_dashboard.php");
exit();
}
// =============================================
// CORRECTED AJAX HANDLERS SECTION
// =============================================
// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
// Clear any previous output
if (ob_get_length())
ob_clean();
header('Content-Type: application/json');
$action = $_POST['ajax_action'];
$response = ['status' => 'error', 'message' => 'Unknown action'];
try {
switch ($action) {
// 🔹 CHECK ROLL NUMBER EXISTS IN DATABASE - CORRECTED
case 'check_roll_number':
$roll_number = trim($_POST['user_roll_number'] ?? '');
if (empty($roll_number)) {
$response = ['status' => 'error', 'message' => 'Roll number is required', 'exists' => false];
break;
}
// DIRECT QUERY - Check if roll number exists in students table
$stmt = $pdo->prepare("
SELECT s.id, s.roll_number, s.full_name, s.email, u.id as user_id
FROM students s
LEFT JOIN users u ON s.user_id = u.id
WHERE s.roll_number = ?
");
$stmt->execute([$roll_number]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if ($student && !empty($student['id'])) {
$response = [
'status' => 'success',
'exists' => true,
'message' => 'Roll number found',
'user_data' => [
'full_name' => $student['full_name'] ?? 'Name not set',
'email' => $student['email'] ?? 'Email not set',
'user_id' => $student['user_id']
]
];
} else {
$response = [
'status' => 'success',
'exists' => false,
'message' => 'Roll number not found in system'
];
}
break;
// 🔹 SEND OTP TO USER'S EMAIL - CORRECTED
case 'send_otp':
$roll_number = trim($_POST['user_roll_number'] ?? '');
if (empty($roll_number)) {
$response = ['status' => 'error', 'message' => 'Roll number is required'];
break;
}
// Get student details directly from students table
$stmt = $pdo->prepare("
SELECT s.id, s.email, s.full_name, u.id as user_id
FROM students s
LEFT JOIN users u ON s.user_id = u.id
WHERE s.roll_number = ?
");
$stmt->execute([$roll_number]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$student) {
$response = ['status' => 'error', 'message' => 'Invalid roll number - student not found'];
break;
}
if (empty($student['email'])) {
$response = ['status' => 'error', 'message' => 'No email found for this student'];
break;
}
// Generate OTP
$otp = rand(100000, 999999);
// Store OTP in session with expiration
$_SESSION['password_change_otp'] = [
'user_id' => $student['user_id'],
'roll_number' => $roll_number,
'otp' => $otp,
'expires' => time() + 600, // 10 minutes
'user_email' => $student['email'],
'user_name' => $student['full_name']
];
// Send OTP via email
$mail_sent = sendOtpEmail($student['email'], $student['full_name'], $otp);
if ($mail_sent) {
$response = [
'status' => 'success',
'message' => 'OTP sent successfully to your registered email',
'otp_expires' => 10 // minutes
];
} else {
// Clear OTP if email failed
unset($_SESSION['password_change_otp']);
$response = ['status' => 'error', 'message' => 'Failed to send OTP email. Please try again.'];
}
break;
// 🔹 CHANGE USER PASSWORD - CORRECTED
case 'change_password':
$roll_number = trim($_POST['user_roll_number'] ?? '');
$new_password = $_POST['new_password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';
$otp = $_POST['otp'] ?? '';
// Validation checks
if (empty($roll_number) || empty($new_password) || empty($confirm_password) || empty($otp)) {
$response = ['status' => 'error', 'message' => 'All fields are required'];
break;
}
if ($new_password !== $confirm_password) {
$response = ['status' => 'error', 'message' => 'Passwords do not match'];
break;
}
if (strlen($new_password) < 6) {
$response = ['status' => 'error', 'message' => 'Password must be at least 6 characters'];
break;
}
// Verify OTP session exists and is valid
if (!isset($_SESSION['password_change_otp']) || !is_array($_SESSION['password_change_otp'])) {
$response = ['status' => 'error', 'message' => 'OTP session expired. Please request a new OTP.'];
break;
}
$otp_data = $_SESSION['password_change_otp'];
// Verify OTP matches and hasn't expired
if ($otp_data['roll_number'] !== $roll_number) {
$response = ['status' => 'error', 'message' => 'Roll number mismatch with OTP session'];
break;
}
if ($otp_data['otp'] != $otp) { // Loose comparison for string vs int
$response = ['status' => 'error', 'message' => 'Invalid OTP'];
break;
}
if ($otp_data['expires'] < time()) {
$response = ['status' => 'error', 'message' => 'OTP has expired. Please request a new one.'];
break;
}
// Get user data from session
$user_id = $otp_data['user_id'];
$user_email = $otp_data['user_email'];
$user_name = $otp_data['user_name'];
// Hash new password
$hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
// Update password in database
$stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$update_result = $stmt->execute([$hashed_password, $user_id]);
if ($update_result && $stmt->rowCount() > 0) {
// Send confirmation email
sendPasswordChangeConfirmationEmail($user_email, $user_name);
// 🔥 FIX: Clear OTP session AND reset cooldown
unset($_SESSION['password_change_otp']);
$response = [
'status' => 'success',
'message' => 'Password changed successfully!',
'reset_cooldown' => true // Signal to reset cooldown in JavaScript
];
} else {
$response = ['status' => 'error', 'message' => 'Failed to update password in database'];
}
break;
// 🔹 CHECK PASSWORD STRENGTH (Optional enhancement)
case 'check_password_strength':
$password = $_POST['password'] ?? '';
if (empty($password)) {
$response = ['status' => 'error', 'message' => 'Password is empty'];
break;
}
$strength = calculatePasswordStrength($password);
$response = [
'status' => 'success',
'strength' => $strength['level'],
'score' => $strength['score'],
'message' => $strength['message']
];
break;
default:
$response = ['status' => 'error', 'message' => 'Invalid action'];
break;
}
} catch (PDOException $e) {
error_log("Database error in AJAX handler {$action}: " . $e->getMessage());
$response = ['status' => 'error', 'message' => 'Database error occurred'];
} catch (Exception $e) {
error_log("General error in AJAX handler {$action}: " . $e->getMessage());
$response = ['status' => 'error', 'message' => 'An unexpected error occurred'];
}
echo json_encode($response);
exit;
}
// =============================================
// SUPPORTING FUNCTIONS (Keep your existing ones)
// =============================================
/**
* Send OTP email to user
*/
function sendOtpEmail($email, $name, $otp)
{
try {
require_once 'includes/PHPMailer/PHPMailer.php';
require_once 'includes/PHPMailer/SMTP.php';
require_once 'includes/PHPMailer/Exception.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->isSMTP();
$mail->Host = env('SMTP_HOST', 'smtp.gmail.com');
$mail->SMTPAuth = true;
$mail->Username = env('SMTP_USERNAME', '');
$mail->Password = env('SMTP_PASSWORD', '');
$mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = (int) env('SMTP_PORT', 587);
$mail->setFrom(env('SMTP_FROM', env('SMTP_USERNAME', '')), env('SMTP_FROM_NAME', 'CAI Admin'));
$mail->addAddress($email, $name);
$mail->Subject = 'Password Change OTP - CAI System';
$mail->Body = "
Dear {$name},
You have requested to change your password. Please use the following OTP to proceed:
🔐 OTP: {$otp}
This OTP is valid for 10 minutes only.
If you did not request this password change, please contact the administration immediately.
Best regards,
CAI Admin System
";
$mail->isHTML(false);
return $mail->send();
} catch (Exception $e) {
error_log("Email sending failed: " . $e->getMessage());
return false;
}
}
/**
* Send password change confirmation email
*/
function sendPasswordChangeConfirmationEmail($email, $name)
{
try {
require_once 'includes/PHPMailer/PHPMailer.php';
require_once 'includes/PHPMailer/SMTP.php';
require_once 'includes/PHPMailer/Exception.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->isSMTP();
$mail->Host = env('SMTP_HOST', 'smtp.gmail.com');
$mail->SMTPAuth = true;
$mail->Username = env('SMTP_USERNAME', '');
$mail->Password = env('SMTP_PASSWORD', '');
$mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = (int) env('SMTP_PORT', 587);
$mail->setFrom(env('SMTP_FROM', env('SMTP_USERNAME', '')), env('SMTP_FROM_NAME', 'CAI Admin'));
$mail->addAddress($email, $name);
$mail->Subject = 'Password Changed Successfully - CAI System';
$mail->Body = "
Dear {$name},
Your password has been changed successfully.
If you did not make this change, please contact the administration immediately.