-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.php
More file actions
2141 lines (1940 loc) · 130 KB
/
Copy pathadmin.php
File metadata and controls
2141 lines (1940 loc) · 130 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
declare(strict_types=1);
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/app/helpers.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/app/learners.php';
require_once __DIR__ . '/app/reports.php';
require_once __DIR__ . '/app/sections.php';
require_once __DIR__ . '/app/teachers.php';
require_once __DIR__ . '/app/announcements.php';
require_once __DIR__ . '/app/issues.php';
require_once __DIR__ . '/app/theme_settings.php';
require_once __DIR__ . '/password_resets.php';
function format_report_time(?string $value): string
{
if ($value === null || $value === '') {
return '-';
}
$timestamp = strtotime($value);
return $timestamp === false ? (string) $value : date('h:i A', $timestamp);
}
function format_report_date(string $value, string $format = 'M j, Y'): string
{
$timestamp = strtotime($value);
return $timestamp === false ? $value : date($format, $timestamp);
}
function report_filter_summary_items(array $filters, array $sections, array $learners): array
{
$items = [];
if ($filters['report_type'] === '') {
return $items;
}
$reportTypeLabels = attendance_report_type_options();
$items['Report Type'] = $reportTypeLabels[$filters['report_type']] ?? 'Attendance Report';
if (in_array($filters['report_type'], ['daily_attendance', 'section_attendance'], true) && $filters['report_date'] !== '') {
$items['Report Date'] = format_report_date($filters['report_date']);
}
if ($filters['report_type'] === 'monthly_summary' && $filters['report_month'] !== '') {
$monthStamp = strtotime($filters['report_month'] . '-01');
$items['Month'] = $monthStamp === false ? $filters['report_month'] : date('F Y', $monthStamp);
}
if ($filters['report_type'] === 'learner_history' && $filters['report_month'] !== '') {
$monthStamp = strtotime($filters['report_month'] . '-01');
$items['Month'] = $monthStamp === false ? $filters['report_month'] : date('F Y', $monthStamp);
}
if (in_array($filters['report_type'], ['late_absence', 'attendance_logs'], true)) {
$items['Date Range'] = format_report_date($filters['date_from']) . ' to ' . format_report_date($filters['date_to']);
}
if ($filters['section_id'] !== '') {
foreach ($sections as $section) {
if ((string) $section['id'] === (string) $filters['section_id']) {
$items['Section'] = ($section['grade_level'] ?? 'N/A') . ' - ' . ($section['name'] ?? 'Unknown');
break;
}
}
}
if ($filters['learner_id'] !== '') {
foreach ($learners as $learner) {
if ((string) $learner['id'] === (string) $filters['learner_id']) {
$items['Learner'] = trim($learner['last_name'] . ', ' . $learner['first_name'] . ' ' . $learner['middle_name']) . ' [' . $learner['lrn'] . ']';
break;
}
}
}
return $items;
}
function admin_percent(int $value, int $total): int
{
if ($total <= 0) {
return 0;
}
return max(0, min(100, (int) round(($value / $total) * 100)));
}
function admin_chart_color(?string $value, string $fallback = '#b45309'): string
{
$value = trim((string) $value);
return preg_match('/^#[0-9a-fA-F]{6}$/', $value) === 1 ? $value : $fallback;
}
function admin_has_learner_filters(array $filters): bool
{
foreach (['keyword', 'status', 'grade_level', 'section_id'] as $key) {
if (trim((string) ($filters[$key] ?? '')) !== '') {
return true;
}
}
return false;
}
$user = require_roles(['admin']);
$allowedModules = [
'attendance_module' => 'Attendance Module',
'learner_management' => 'Learner Management',
'sections_management' => 'Sections Management',
'teacher_management' => 'Teacher Management',
'attendance_reports' => 'Attendance Reports',
'announcements' => 'Announcements',
'reported_issues' => 'Reported Issues',
'password_resets' => 'Password Resets',
'settings' => 'Settings',
];
$module = (string) ($_GET['module'] ?? 'attendance_module');
if (!array_key_exists($module, $allowedModules)) {
$module = 'attendance_module';
}
$stats = [
'today_logs' => 0,
'today_learners' => 0,
'last_scan' => 'No scans yet',
'today_logins' => 0,
];
$attendanceCoverage = [
'total_learners' => 0,
'scanned_learners' => 0,
'not_scanned_learners' => 0,
'coverage_percent' => 0,
];
$attendanceStatusRows = [];
$attendanceHourRows = [];
$attendanceGradeRows = [];
$latestLogs = [];
$dataWarning = null;
$learnerFlash = flash_get('learner_management');
$learnerForm = learner_form_defaults();
$learnerRows = [];
$learnerFilters = learner_list_filters();
$learnerFiltersApplied = admin_has_learner_filters($learnerFilters);
$learnerSections = [];
$learnerSchoolYear = null;
$learnerEditId = isset($_GET['edit_learner_id']) ? (int) $_GET['edit_learner_id'] : null;
$reportWarning = null;
$reportFilters = attendance_report_filters();
$reportTypeOptions = attendance_report_type_options();
$reportRows = [];
$reportMeta = [
'title' => 'Attendance Reports',
'description' => 'Review attendance data using the available report views.',
];
$reportSections = [];
$reportLearners = [];
$reportSchoolYear = null;
$reportSummaryItems = [];
$reportFilterMap = attendance_report_filter_map();
$sectionFlash = flash_get('sections_management');
$sectionForm = section_form_defaults();
$sectionAdviserOptions = [];
$sectionRows = [];
$sectionEditId = isset($_GET['edit_section_id']) ? (int) $_GET['edit_section_id'] : null;
$teacherFlash = flash_get('teacher_management');
$teacherForm = teacher_form_defaults();
$teacherRows = [];
$teacherSections = [];
$teacherEditId = isset($_GET['edit_teacher_id']) ? (int) $_GET['edit_teacher_id'] : null;
$announcementFlash = flash_get('announcements_management');
$announcementForm = ['id' => null, 'title' => '', 'content' => '', 'is_published' => 0];
$announcementRows = [];
$issueFlash = flash_get('admin_issues');
$issueRows = [];
$issueForm = issue_form_defaults();
$issueEditId = isset($_GET['edit_issue_id']) ? (int) $_GET['edit_issue_id'] : null;
$announcementEditId = isset($_GET['edit_announcement_id']) ? (int) $_GET['edit_announcement_id'] : null;
$settingsFlash = flash_get('admin_settings');
$passwordResetFlash = flash_get('admin_password_resets');
$pendingPasswordResets = [];
$themeColors = [];
$activeThemeKey = 'default';
$systemLoginLogs = [];
announcements_bootstrap();
theme_settings_bootstrap();
if ($module === 'learner_management') {
try {
$learnerSchoolYear = require_current_school_year();
$learnerSections = learner_sections();
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
if ($formAction === 'save_learner') {
$learnerForm = learner_normalize_payload($_POST);
learner_save($learnerForm);
flash_set('learner_management', $learnerForm['id'] === null ? 'Learner created successfully.' : 'Learner updated successfully.');
redirect('admin.php?module=learner_management');
}
if ($formAction === 'delete_learner') {
learner_delete((int) ($_POST['learner_id'] ?? 0));
flash_set('learner_management', 'Learner deleted successfully.');
redirect('admin.php?module=learner_management');
}
if ($formAction === 'import_learners') {
$importedCount = learner_import_file($_FILES['import_file'] ?? []);
flash_set('learner_management', 'Imported ' . $importedCount . ' learner(s) successfully.');
redirect('admin.php?module=learner_management');
}
}
if ($learnerEditId !== null && $learnerForm['id'] === null) {
$existingLearner = learner_find($learnerEditId);
if ($existingLearner !== null) {
$learnerForm = $existingLearner;
}
}
$learnerRows = learner_list($learnerFilters);
} catch (Throwable $exception) {
$learnerFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
}
if ($module === 'sections_management') {
try {
require_current_school_year();
$sectionAdviserOptions = section_adviser_options($sectionForm['adviser_name']);
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
if ($formAction === 'save_section') {
$sectionForm = section_normalize_payload($_POST);
$sectionAdviserOptions = section_adviser_options($sectionForm['adviser_name']);
section_save($sectionForm);
flash_set('sections_management', $sectionForm['id'] === null ? 'Section created successfully.' : 'Section updated successfully.');
redirect('admin.php?module=sections_management');
}
if ($formAction === 'delete_section') {
section_delete((int) ($_POST['section_id'] ?? 0));
flash_set('sections_management', 'Section deleted successfully.');
redirect('admin.php?module=sections_management');
}
}
if ($sectionEditId !== null && $sectionForm['id'] === null) {
$existingSection = section_find($sectionEditId);
if ($existingSection !== null) {
$sectionForm = $existingSection;
$sectionAdviserOptions = section_adviser_options($sectionForm['adviser_name']);
}
}
$sectionRows = section_list();
} catch (Throwable $exception) {
$sectionFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
}
if ($module === 'teacher_management') {
try {
teacher_management_bootstrap();
$teacherSections = teacher_section_options();
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
if ($formAction === 'save_teacher') {
$teacherForm = teacher_normalize_payload($_POST);
teacher_save($teacherForm);
flash_set('teacher_management', $teacherForm['id'] === null ? 'Teacher account created successfully.' : 'Teacher account updated successfully.');
redirect('admin.php?module=teacher_management');
}
if ($formAction === 'delete_teacher') {
teacher_delete((int) ($_POST['teacher_id'] ?? 0));
flash_set('teacher_management', 'Teacher account deleted successfully.');
redirect('admin.php?module=teacher_management');
}
}
if ($teacherEditId !== null && $teacherForm['id'] === null) {
$existingTeacher = teacher_find($teacherEditId);
if ($existingTeacher !== null) {
$teacherForm = $existingTeacher;
}
}
$teacherRows = teacher_list();
$teacherSections = teacher_section_options();
} catch (Throwable $exception) {
$teacherFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
}
if ($module === 'announcements') {
try {
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
if ($formAction === 'save_announcement') {
announcement_save($_POST, (int) $user['id']);
flash_set('announcements_management', 'Announcement saved successfully.');
redirect('admin.php?module=announcements');
}
if ($formAction === 'delete_announcement') {
announcement_delete((int) ($_POST['announcement_id'] ?? 0));
flash_set('announcements_management', 'Announcement deleted successfully.');
redirect('admin.php?module=announcements');
}
}
if ($announcementEditId !== null) {
$existingAnnouncement = announcement_find($announcementEditId);
if ($existingAnnouncement !== null) {
$announcementForm = $existingAnnouncement;
}
}
$announcementRows = announcement_list();
} catch (Throwable $exception) {
$announcementFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
}
if ($module === 'reported_issues') {
try {
issue_bootstrap();
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
if ($formAction === 'update_issue_status') {
issue_update_status((int) ($_POST['issue_id'] ?? 0), (string) ($_POST['status'] ?? 'open'));
flash_set('admin_issues', 'Issue status updated successfully.');
redirect('admin.php?module=reported_issues');
}
}
$issueRows = issue_list_for_admin();
if ($issueEditId !== null) {
$issueForm = issue_find($issueEditId) ?? issue_form_defaults();
}
} catch (Throwable $exception) {
$issueFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
}
if ($module === 'password_resets') {
try {
password_resets_bootstrap();
if (is_post()) {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
$formAction = (string) ($_POST['form_action'] ?? '');
$requestId = (int) ($_POST['request_id'] ?? 0);
if ($formAction === 'approve_reset') {
$newPassword = approve_password_reset($requestId, (int) $user['id']);
flash_set('admin_password_resets', 'Password has been reset. The new password is: ' . $newPassword);
redirect('admin.php?module=password_resets');
}
if ($formAction === 'deny_reset') {
deny_password_reset($requestId, (int) $user['id']);
flash_set('admin_password_resets', 'Password reset request has been denied.');
redirect('admin.php?module=password_resets');
}
}
$pendingPasswordResets = get_pending_password_requests();
} catch (Throwable $exception) {
$passwordResetFlash = ['type' => 'error', 'message' => $exception->getMessage()];
}
}
if ($module === 'settings') {
try {
if (is_post() && ($_POST['form_action'] ?? '') === 'save_theme') {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
theme_colors_save((string) ($_POST['theme_key'] ?? ''));
flash_set('admin_settings', 'Portal theme saved successfully.');
redirect('admin.php?module=settings');
}
if (is_post() && ($_POST['form_action'] ?? '') === 'reset_theme') {
if (!verify_csrf_token($_POST['csrf_token'] ?? null)) {
throw new RuntimeException('Invalid form token. Please refresh the page.');
}
theme_colors_reset();
flash_set('admin_settings', 'Theme colors have been reset to default.');
redirect('admin.php?module=settings');
}
} catch (Throwable $exception) {
$settingsFlash = [
'type' => 'error',
'message' => $exception->getMessage(),
];
}
$themeColors = theme_colors();
$activeThemeKey = theme_active_key();
$stats['today_logins'] = (int) database()->query('SELECT COUNT(*) FROM auth_login_logs WHERE login_status = \'success\' AND DATE(logged_in_at) = CURDATE()')->fetchColumn();
$systemLoginLogs = auth_recent_login_logs(10);
}
if ($module === 'attendance_module') {
try {
$statsStatement = database()->query(
'SELECT
COUNT(*) AS today_logs,
COUNT(DISTINCT learner_enrollment_id) AS today_learners,
MAX(scanned_at) AS last_scan
FROM attendance_scan_logs
WHERE DATE(scanned_at) = CURDATE()'
);
$statsRow = $statsStatement->fetch() ?: [];
$stats['today_logs'] = (int) ($statsRow['today_logs'] ?? 0);
$stats['today_learners'] = (int) ($statsRow['today_learners'] ?? 0);
$stats['last_scan'] = !empty($statsRow['last_scan'])
? date('M j, Y h:i A', strtotime((string) $statsRow['last_scan']))
: 'No scans yet';
$attendanceSchoolYear = current_school_year();
if ($attendanceSchoolYear !== null) {
$coverageStatement = database()->prepare(
'SELECT
COUNT(DISTINCT le.id) AS total_learners,
COUNT(DISTINCT CASE WHEN DATE(asl.scanned_at) = CURDATE() THEN le.id END) AS scanned_learners
FROM learner_enrollments le
INNER JOIN learners l ON l.id = le.learner_id
LEFT JOIN attendance_scan_logs asl ON asl.learner_enrollment_id = le.id
WHERE le.school_year_id = :school_year_id
AND le.enrollment_status = \'enrolled\'
AND l.current_status = \'active\''
);
$coverageStatement->execute(['school_year_id' => (int) $attendanceSchoolYear['id']]);
$coverageRow = $coverageStatement->fetch() ?: [];
$totalLearners = (int) ($coverageRow['total_learners'] ?? 0);
$scannedLearners = (int) ($coverageRow['scanned_learners'] ?? 0);
$notScannedLearners = max(0, $totalLearners - $scannedLearners);
$attendanceCoverage = [
'total_learners' => $totalLearners,
'scanned_learners' => $scannedLearners,
'not_scanned_learners' => $notScannedLearners,
'coverage_percent' => admin_percent($scannedLearners, $totalLearners),
];
$stats['today_learners'] = $scannedLearners;
$statusStatement = database()->prepare(
'SELECT
al.code,
al.label,
al.color_hex,
COUNT(CASE WHEN le.id IS NOT NULL AND l.id IS NOT NULL THEN ar.id END) AS total
FROM attendance_legends al
LEFT JOIN attendance_records ar
ON ar.legend_id = al.id
AND ar.attendance_date = CURDATE()
LEFT JOIN learner_enrollments le
ON le.id = ar.learner_enrollment_id
AND le.school_year_id = :school_year_id
AND le.enrollment_status = \'enrolled\'
LEFT JOIN learners l
ON l.id = le.learner_id
AND l.current_status = \'active\'
GROUP BY al.id, al.code, al.label, al.color_hex
ORDER BY al.code ASC'
);
$statusStatement->execute(['school_year_id' => (int) $attendanceSchoolYear['id']]);
$attendanceStatusRows = $statusStatement->fetchAll();
$hourStatement = database()->prepare(
'SELECT
HOUR(asl.scanned_at) AS hour_value,
DATE_FORMAT(asl.scanned_at, \'%l %p\') AS hour_label,
COUNT(*) AS total
FROM attendance_scan_logs asl
INNER JOIN learner_enrollments le ON le.id = asl.learner_enrollment_id
INNER JOIN learners l ON l.id = le.learner_id
WHERE le.school_year_id = :school_year_id
AND le.enrollment_status = \'enrolled\'
AND l.current_status = \'active\'
AND DATE(asl.scanned_at) = CURDATE()
GROUP BY HOUR(asl.scanned_at), DATE_FORMAT(asl.scanned_at, \'%l %p\')
ORDER BY hour_value ASC'
);
$hourStatement->execute(['school_year_id' => (int) $attendanceSchoolYear['id']]);
$attendanceHourRows = $hourStatement->fetchAll();
$gradeStatement = database()->prepare(
'SELECT
le.grade_level,
COUNT(DISTINCT le.id) AS total_learners,
COUNT(DISTINCT CASE WHEN DATE(asl.scanned_at) = CURDATE() THEN le.id END) AS scanned_learners
FROM learner_enrollments le
INNER JOIN learners l ON l.id = le.learner_id
LEFT JOIN attendance_scan_logs asl ON asl.learner_enrollment_id = le.id
WHERE le.school_year_id = :school_year_id
AND le.enrollment_status = \'enrolled\'
AND l.current_status = \'active\'
GROUP BY le.grade_level
ORDER BY FIELD(le.grade_level, \'Kinder\', \'Grade 1\', \'Grade 2\', \'Grade 3\', \'Grade 4\', \'Grade 5\', \'Grade 6\', \'Grade 7\', \'Grade 8\', \'Grade 9\', \'Grade 10\', \'Grade 11\', \'Grade 12\'), le.grade_level ASC'
);
$gradeStatement->execute(['school_year_id' => (int) $attendanceSchoolYear['id']]);
$attendanceGradeRows = $gradeStatement->fetchAll();
}
$logsStatement = database()->query(
'SELECT
asl.scanned_at,
CONCAT(l.first_name, \' \', l.last_name) AS learner_name,
l.lrn,
CONCAT(le.grade_level, \' / \', COALESCE(s.name, \'Unassigned\')) AS grade_section,
CONCAT(asl.slot_label, \' recorded as \', al.label) AS log_entry
FROM attendance_scan_logs asl
INNER JOIN learner_enrollments le ON le.id = asl.learner_enrollment_id
INNER JOIN learners l ON l.id = le.learner_id
LEFT JOIN sections s ON s.id = le.section_id
INNER JOIN attendance_legends al ON al.id = asl.legend_id
ORDER BY asl.scanned_at DESC, asl.id DESC
LIMIT 8'
);
$latestLogs = $logsStatement->fetchAll();
} catch (Throwable $exception) {
$dataWarning = 'Attendance data preview is unavailable right now.';
}
}
if ($module === 'settings') {
$stats['today_logins'] = (int) database()->query('SELECT COUNT(*) FROM auth_login_logs WHERE login_status = \'success\' AND DATE(logged_in_at) = CURDATE()')->fetchColumn();
$systemLoginLogs = auth_recent_login_logs(10);
}
if ($module === 'attendance_reports') {
try {
$reportSchoolYear = require_current_school_year();
$reportSections = learner_sections();
$reportLearners = attendance_report_learner_options();
$reportMeta = attendance_report_data($reportFilters);
$reportRows = $reportMeta['rows'] ?? [];
$reportSummaryItems = report_filter_summary_items($reportFilters, $reportSections, $reportLearners);
} catch (Throwable $exception) {
$reportWarning = $exception->getMessage();
}
}
$gradeLevelOptions = learner_grade_level_options();
$statusOptions = ['active', 'inactive', 'graduated', 'transferred'];
$sexOptions = ['male', 'female'];
$attendanceStatusTotal = 0;
$attendanceMaxHourlyScans = 0;
$attendanceMaxGradeLearners = 0;
foreach ($attendanceStatusRows as $row) {
$attendanceStatusTotal += (int) ($row['total'] ?? 0);
}
foreach ($attendanceHourRows as $row) {
$attendanceMaxHourlyScans = max($attendanceMaxHourlyScans, (int) ($row['total'] ?? 0));
}
foreach ($attendanceGradeRows as $row) {
$attendanceMaxGradeLearners = max($attendanceMaxGradeLearners, (int) ($row['total_learners'] ?? 0));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php echo theme_stylesheet_markup(); ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo escape(APP_NAME); ?> Admin</title>
<link rel="stylesheet" href="<?php echo escape(asset_url('assets/css/app.css')); ?>">
</head>
<body class="dashboard-body admin-dashboard">
<button
id="sidebar-toggle"
class="sidebar-toggle-button"
type="button"
data-sidebar-label="admin menu"
aria-label="Open admin menu"
aria-controls="admin-sidebar"
aria-expanded="false"
>
<span></span>
<span></span>
<span></span>
</button>
<div id="sidebar-backdrop" class="sidebar-backdrop" hidden></div>
<main class="dashboard-shell admin-shell wide-admin-shell">
<section class="admin-layout">
<aside id="admin-sidebar" class="admin-sidebar">
<div class="sidebar-profile">
<p class="eyebrow">Admin Profile</p>
<h1>Portal Admin</h1>
<p class="sidebar-user"><?php echo escape($user['username']); ?></p>
<p class="sidebar-email"><?php echo escape($user['email']); ?></p>
</div>
<nav class="sidebar-nav" aria-label="Admin Navigation">
<div class="menu-group">
<p class="menu-group-title">Attendance</p>
<a href="<?php echo escape(route_url('admin.php?module=attendance_module')); ?>" class="submenu-link<?php echo $module === 'attendance_module' ? ' active' : ''; ?>">Attendance Module</a>
<a href="<?php echo escape(route_url('admin.php?module=learner_management')); ?>" class="submenu-link<?php echo $module === 'learner_management' ? ' active' : ''; ?>">Learner Management</a>
<a href="<?php echo escape(route_url('admin.php?module=sections_management')); ?>" class="submenu-link<?php echo $module === 'sections_management' ? ' active' : ''; ?>">Sections Management</a>
<a href="<?php echo escape(route_url('admin.php?module=teacher_management')); ?>" class="submenu-link<?php echo $module === 'teacher_management' ? ' active' : ''; ?>">Teacher Management</a>
<a href="<?php echo escape(route_url('admin.php?module=attendance_reports')); ?>" class="submenu-link<?php echo $module === 'attendance_reports' ? ' active' : ''; ?>">Attendance Reports</a>
</div>
<div class="menu-group">
<p class="menu-group-title">System</p>
<a href="<?php echo escape(route_url('admin.php?module=announcements')); ?>" class="submenu-link<?php echo $module === 'announcements' ? ' active' : ''; ?>">Announcements</a>
<a href="<?php echo escape(route_url('admin.php?module=reported_issues')); ?>" class="submenu-link<?php echo $module === 'reported_issues' ? ' active' : ''; ?>">Reported Issues</a>
<a href="<?php echo escape(route_url('admin.php?module=password_resets')); ?>" class="submenu-link<?php echo $module === 'password_resets' ? ' active' : ''; ?>">Password Resets</a>
<a href="<?php echo escape(route_url('admin.php?module=settings')); ?>" class="submenu-link<?php echo $module === 'settings' ? ' active' : ''; ?>">Settings</a>
<a href="<?php echo escape(route_url('change_password.php')); ?>" class="submenu-link">Change Password</a>
</div>
</nav>
<div class="sidebar-footer">
<a href="<?php echo escape(route_url('logout.php')); ?>" class="secondary-link full-width-link">Logout</a>
</div>
</aside>
<section class="admin-main-panel">
<?php if ($module === 'attendance_module'): ?>
<header class="admin-page-header">
<div class="admin-page-title">
<img class="school-logo header-logo" src="<?php echo escape(school_logo_url()); ?>" alt="School logo">
<div class="header-copy">
<p class="eyebrow">Attendance</p>
<h2>Attendance Module</h2>
<p>Monitor daily scan activity and launch the attendance station from here.</p>
</div>
</div>
<div class="topbar-actions">
<a href="<?php echo escape(route_url('attendance.php')); ?>" class="primary-button">Open Attendance Station</a>
<a href="<?php echo escape(route_url('face_enrollment.php')); ?>" class="secondary-link">Face Enrollment</a>
<a href="<?php echo escape(route_url('face_attendance.php')); ?>" class="ghost-button">Face Recognition Station</a>
</div>
</header>
<?php if ($dataWarning !== null): ?>
<div class="alert error"><?php echo escape($dataWarning); ?></div>
<?php endif; ?>
<section class="admin-stat-grid">
<article class="admin-stat-card">
<span class="stat-label">Today's Logs</span>
<strong><?php echo escape((string) $stats['today_logs']); ?></strong>
</article>
<article class="admin-stat-card">
<span class="stat-label">Learners Scanned Today</span>
<strong><?php echo escape((string) $stats['today_learners']); ?></strong>
</article>
<article class="admin-stat-card">
<span class="stat-label">Last Scan</span>
<strong><?php echo escape($stats['last_scan']); ?></strong>
</article>
</section>
<section class="admin-analytics-grid">
<article class="admin-module-card analytics-card">
<div class="panel-heading compact-heading">
<h2>Today's Scan Coverage</h2>
<p>Active enrolled learners scanned vs not yet scanned.</p>
</div>
<div class="coverage-chart-row">
<div class="coverage-donut" style="--coverage: <?php echo escape((string) $attendanceCoverage['coverage_percent']); ?>%;">
<strong><?php echo escape((string) $attendanceCoverage['coverage_percent']); ?>%</strong>
<span>scanned</span>
</div>
<div class="coverage-breakdown">
<div>
<span class="status-dot success-dot"></span>
<p>Scanned</p>
<strong><?php echo escape((string) $attendanceCoverage['scanned_learners']); ?></strong>
</div>
<div>
<span class="status-dot muted-dot"></span>
<p>Not Yet Scanned</p>
<strong><?php echo escape((string) $attendanceCoverage['not_scanned_learners']); ?></strong>
</div>
<div>
<span class="status-dot accent-dot"></span>
<p>Total Active Learners</p>
<strong><?php echo escape((string) $attendanceCoverage['total_learners']); ?></strong>
</div>
</div>
</div>
</article>
<article class="admin-module-card analytics-card">
<div class="panel-heading compact-heading">
<h2>Attendance Status Mix</h2>
<p>Today's attendance records by legend.</p>
</div>
<?php if ($attendanceStatusRows === []): ?>
<div class="alert neutral">No attendance legend data is available yet.</div>
<?php else: ?>
<div class="chart-bar-list">
<?php foreach ($attendanceStatusRows as $row): ?>
<?php
$statusCount = (int) ($row['total'] ?? 0);
$statusPercent = admin_percent($statusCount, $attendanceStatusTotal);
$statusColor = admin_chart_color($row['color_hex'] ?? null);
?>
<div class="chart-row">
<div class="chart-label">
<span><i style="--dot-color: <?php echo escape($statusColor); ?>;"></i><?php echo escape($row['label']); ?></span>
<strong><?php echo escape((string) $statusCount); ?></strong>
</div>
<div class="chart-track">
<span class="chart-fill" style="--bar-width: <?php echo escape((string) $statusPercent); ?>%; --bar-color: <?php echo escape($statusColor); ?>;"></span>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</article>
<article class="admin-module-card analytics-card">
<div class="panel-heading compact-heading">
<h2>Hourly Scan Volume</h2>
<p>Attendance station activity across today.</p>
</div>
<?php if ($attendanceHourRows === []): ?>
<div class="alert neutral">No scan volume is available for today yet.</div>
<?php else: ?>
<div class="chart-bar-list">
<?php foreach ($attendanceHourRows as $row): ?>
<?php
$hourCount = (int) ($row['total'] ?? 0);
$hourPercent = admin_percent($hourCount, max(1, $attendanceMaxHourlyScans));
?>
<div class="chart-row">
<div class="chart-label">
<span><?php echo escape($row['hour_label']); ?></span>
<strong><?php echo escape((string) $hourCount); ?></strong>
</div>
<div class="chart-track">
<span class="chart-fill" style="--bar-width: <?php echo escape((string) $hourPercent); ?>%; --bar-color: var(--info);"></span>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</article>
<article class="admin-module-card analytics-card">
<div class="panel-heading compact-heading">
<h2>Grade-Level Coverage</h2>
<p>Scanned learners compared with active enrollment.</p>
</div>
<?php if ($attendanceGradeRows === []): ?>
<div class="alert neutral">No active learner enrollment is available for charting.</div>
<?php else: ?>
<div class="chart-bar-list">
<?php foreach ($attendanceGradeRows as $row): ?>
<?php
$gradeTotal = (int) ($row['total_learners'] ?? 0);
$gradeScanned = (int) ($row['scanned_learners'] ?? 0);
$gradePercent = admin_percent($gradeScanned, $gradeTotal);
?>
<div class="chart-row">
<div class="chart-label">
<span><?php echo escape($row['grade_level']); ?></span>
<strong><?php echo escape($gradeScanned . '/' . $gradeTotal); ?></strong>
</div>
<div class="chart-track">
<span class="chart-fill" style="--bar-width: <?php echo escape((string) $gradePercent); ?>%; --bar-color: var(--success);"></span>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</article>
</section>
<section>
<article class="admin-module-card">
<div class="panel-heading compact-heading">
<h2>Latest Attendance Logs</h2>
<p>Recent system activity across the attendance station.</p>
</div>
<div class="table-shell">
<table class="records-table admin-log-table">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Learner</th>
<th>LRN</th>
<th>Grade / Section</th>
<th>Log Entry</th>
</tr>
</thead>
<tbody>
<?php if ($latestLogs === []): ?>
<tr>
<td colspan="6" class="empty-row">No attendance logs available yet.</td>
</tr>
<?php else: ?>
<?php foreach ($latestLogs as $log): ?>
<tr>
<td><?php echo escape(date('Y-m-d', strtotime($log['scanned_at']))); ?></td>
<td><?php echo escape(date('h:i:s A', strtotime($log['scanned_at']))); ?></td>
<td><?php echo escape($log['learner_name']); ?></td>
<td><?php echo escape($log['lrn']); ?></td>
<td><?php echo escape($log['grade_section']); ?></td>
<td><span class="table-status"><?php echo escape($log['log_entry']); ?></span></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</article>
</section>
<?php elseif ($module === 'learner_management'): ?>
<header class="admin-page-header">
<div class="admin-page-title">
<img class="school-logo header-logo" src="<?php echo escape(school_logo_url()); ?>" alt="School logo">
<div class="header-copy">
<p class="eyebrow">Attendance</p>
<h2>Learner Management</h2>
<p>Manage learners, import master lists, and maintain current school-year grade, section, and basic profile assignments.</p>
</div>
</div>
</header>
<?php if ($learnerFlash !== null): ?>
<div class="alert <?php echo escape($learnerFlash['type']); ?>"><?php echo escape($learnerFlash['message']); ?></div>
<?php endif; ?>
<section class="learner-admin-grid">
<article class="admin-module-card">
<?php if ($learnerForm['id'] !== null): ?>
<div class="teacher-profile-identity" style="margin-bottom: 1rem;">
<div class="teacher-profile-photo-frame">
<img
class="teacher-profile-photo"
src="<?php echo escape(learner_photo_url($learnerForm['lrn'])); ?>"
alt="<?php echo escape($learnerForm['first_name'] . ' ' . $learnerForm['last_name']); ?> photo"
>
</div>
<div class="teacher-profile-identity-copy">
<p class="meta-label dark">Editing Learner</p>
<div class="teacher-readonly-field"><?php echo escape(trim($learnerForm['last_name'] . ', ' . $learnerForm['first_name'])); ?></div>
</div>
</div>
<?php endif; ?>
<div class="panel-heading compact-heading">
<h2><?php echo $learnerForm['id'] === null ? 'Add Learner' : 'Edit Learner'; ?></h2>
<p>Current school year: <?php echo escape($learnerSchoolYear['label'] ?? 'Not set'); ?></p>
</div>
<form method="post" class="learner-form-grid">
<input type="hidden" name="csrf_token" value="<?php echo escape(csrf_token()); ?>">
<input type="hidden" name="form_action" value="save_learner">
<input type="hidden" name="id" value="<?php echo escape((string) ($learnerForm['id'] ?? '')); ?>">
<div>
<label for="lrn">LRN</label>
<input id="lrn" name="lrn" type="text" inputmode="numeric" minlength="12" maxlength="12" pattern="\d{12}" value="<?php echo escape($learnerForm['lrn']); ?>" required>
</div>
<div>
<label for="first_name">First Name</label>
<input id="first_name" name="first_name" type="text" value="<?php echo escape($learnerForm['first_name']); ?>" required>
</div>
<div>
<label for="middle_name">Middle Name</label>
<input id="middle_name" name="middle_name" type="text" value="<?php echo escape($learnerForm['middle_name']); ?>">
</div>
<div>
<label for="last_name">Last Name</label>
<input id="last_name" name="last_name" type="text" value="<?php echo escape($learnerForm['last_name']); ?>" required>
</div>
<div>
<label for="birthdate">Birthdate</label>
<input
id="birthdate"
name="birthdate"
type="date"
value="<?php echo escape($learnerForm['birthdate']); ?>"
data-age-target="learner_age_display"
data-age-reference-date="<?php echo escape(learner_reference_date_for_school_year($learnerSchoolYear)); ?>"
>
</div>
<div>
<label>Age as of first Friday of June</label>
<div id="learner_age_display" class="teacher-readonly-field">
<?php
$learnerAge = learner_age_for_school_year($learnerForm['birthdate'] !== '' ? $learnerForm['birthdate'] : null, $learnerSchoolYear);
echo escape($learnerAge !== null ? (string) $learnerAge : '-');
?>
</div>
</div>
<div>
<label for="mother_tongue">Mother Tongue</label>
<input id="mother_tongue" name="mother_tongue" type="text" value="<?php echo escape($learnerForm['mother_tongue']); ?>">
</div>
<div>
<label for="religion">Religion</label>
<select id="religion" name="religion">
<option value="">Select religion</option>
<?php foreach (learner_religion_options_with_selected($learnerForm['religion']) as $option): ?>
<option value="<?php echo escape($option); ?>"<?php echo $learnerForm['religion'] === $option ? ' selected' : ''; ?>><?php echo escape($option); ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="has_disability">Learner with disability</label>
<select id="has_disability" name="has_disability">
<option value="0"<?php echo (string) $learnerForm['has_disability'] !== '1' ? ' selected' : ''; ?>>No</option>
<option value="1"<?php echo (string) $learnerForm['has_disability'] === '1' ? ' selected' : ''; ?>>Yes</option>
</select>
</div>