# EdumacFlo Script Working Document & Technical Architecture

## 1. Executive Summary
This document serves as the master operational and architectural reference for the customizations, modules, and enhancements applied to the **EdumacFlo School Management System**.

---

## 2. Security, Authentication & Role-Based Access Control (RBAC)
* **Permission Engine**: `portal/check_permission.php`
  - Enforces page-level and query-route permission validation for every request.
  - Automatically exempts Super Administrators, School Admins, Proprietors, and Directors from granular permission blocks.
  - **Inactivity Session Timeout**: Automatically terminates idle user sessions after 30 minutes of inactivity and safely redirects to login (`index.php?timeout=1`).
  - **Query-Route Resolution**: Inspects query actions for routed URLs (e.g. `modules.php?excel_result_upload`, `teacher_dashboard.php?teacher_excel_result_upload`) ensuring deep permission checks.
* **Auto-Seeding & Synchronization**: `db_update_permissions.php`
  - Automated migration tool mapping new module permissions to system roles (`School admin`, `class teacher`, `subject teacher`, `Accountant`, `Exam Officer`, `student`).

---

## 3. Core Functional Modules & File References

### A. Result Management & Spreadsheet (Excel/CSV) Suite
* **Purpose**: Allows teachers and administrators to enter scores manually online or perform batch exports and imports using CSV spreadsheets.
* **Supported Formats**:
  1. **Single Subject Sheet**: Downloads or uploads scores for a single chosen subject.
  2. **All Subjects Combination Sheet**: Downloads or uploads all registered subjects and students for a selected class in one master sheet.
* **Key Files**:
  - `portal/pages/excel_result_upload.php`: Admin & Principal dual-panel interface (Export & Import).
  - `portal/pages/teacher_excel_result_upload.php`: Teacher dual-panel interface scoped by assigned classes.
  - `portal/pages/PHPExcel.php` & `portal/pages/teacher_PHPExcel.php`: Export processors outputting pre-populated CSV files.
  - `portal/pages/result_upload_excel.php` & `portal/pages/teacher_result_upload_excel.php`: Batch CSV import processors handling row parsing, total calculations (`ca1 + ca2 + exam`), upsert operations, and multi-subject rank recalculation.
  - `portal/pages/admin_upload_ca.php`, `admin_upload_exam.php`, `vp_upload_ca.php`, `vp_upload_exam.php`, `teacher_upload_ca.php`, `teacher_upload_exam.php`, `subject_teacher_upload_ca.php`, `subject_teacher_upload_exam.php`: Manual score entry pages fitted with direct **"Excel / CSV Result Upload & Export"** action buttons.
* **Database Tables**:
  - `results1` (`id`, `class`, `term`, `session`, `reg_number`, `name`, `subjects`, `ca1`, `ca2`, `exam`, `subject_total`, `subject_rank`, `date_of_upload`).
  - `subjects` (`id`, `class`, `term`, `session`, `reg_number`, `name`, `subjects`).

---

### B. Class Broadsheet & Performance Reporting Suite
* **Purpose**: Computes comprehensive termly score broadsheets for classes with on-screen live ranking, PDF generation, and Excel/CSV data exports.
* **Features**:
  - **1-Click Excel / CSV Export**: `portal/export_broadsheet_excel.php` generates hierarchical multi-subject CSV files with student grand totals, averages, and ordinal ranks.
  - **1-Click Official PDF Generation**: `portal/generate.php` outputs landscape PDF documents complete with teacher and principal signature lines.
  - **Live Position & Ranking**: On-screen computation of dense ordinal ranks (`1st`, `2nd`, `3rd`, etc.) with gold/silver/bronze highlight badges.
  - **Class Performance KPI Metrics**: Summary cards for Total Students, Computed Subjects, Highest Class Average, and Class Mean Average.
* **Key Files**:
  - `portal/pages/view_class_broadsheet.php`: Admin & Principal broadsheet dashboard.
  - `portal/pages/teacher_view_broadsheet.php`: Teacher broadsheet dashboard with teacher class filtering.
  - `portal/export_broadsheet_excel.php`: Dedicated streaming CSV export engine.
  - `portal/generate.php`: TCPDF landscape broadsheet report generator.

---

### B. Smart QR-Code & Manual Attendance Suite
* **Purpose**: Provides real-time attendance roll call via device camera QR scanner, offline CSV synchronization, and historical attendance log tracking.
* **Key Files**:
  - `portal/pages/qr_attendance.php`: Live camera QR scanner using HTML5-QRCode for students and staff.
  - `portal/pages/class_attendance.php`: Manual daily roll call sheet with integrated CSV import/export tools.
  - `portal/pages/import_attendance.php` & `export_attendance.php`: Batch CSV attendance processors.
  - `portal/pages/view_attendance_records.php` & `teacher_view_attendance.php`: Comprehensive attendance log viewers.
* **Database Tables**:
  - `attendance` (`id`, `reg_number`, `name`, `class`, `term`, `session`, `date`, `status`).
  - `staff_attendance` (`id`, `username`, `name`, `term`, `session`, `date`, `time`, `status`).

---

### C. Digital E-Library & Learning Resources
* **Purpose**: Digital repository for class notes, past questions, assignments, and e-books.
* **Key Files**:
  - `portal/pages/elibrary.php`: Admin & Staff management portal with category filters and upload manager.
  - `portal/pages/student_elibrary.php`: Student-facing view filtered automatically to the student's registered class.
* **Database Tables**:
  - `curriculum` (`id`, `title`, `class`, `subject`, `category`, `description`, `file_name`, `date_uploaded`).

---

### D. Inbuilt Mailing System (Mailbox)
* **Purpose**: Internal communication network connecting administrators, teachers, and students.
* **Key Files**:
  - `portal/pages/mailbox.php`: Full mail client (Inbox, Sent, Read View, Compose modal with role-based broadcasting).
  - `portal/sidebar.php`: Navigation link featuring dynamic unread count badge.
* **Database Tables**:
  - `internal_mail` (`id`, `sender_id`, `sender_role`, `recipient_id`, `recipient_role`, `subject`, `message`, `is_read`, `created_at`).

---

### E. Financial Defaulters Tracker & Invoicing Suite
* **Purpose**: Identifies students with unpaid school fee balances, computes collection rates, and enables targeted billing reminders.
* **Key Files**:
  - `portal/pages/defaulters_tracker.php`: Defaulters dashboard with class filters, debt distribution metrics, and CSV export.
  - `portal/pages/create_invoice.php`, `view_invoice.php`, `fee_payment.php`: Billing lifecycle managers.
* **Database Tables**:
  - `invoice` (`id`, `reg_number`, `name`, `class`, `term`, `session`, `total_fee`, `amount_paid`, `balance`, `status`, `date_created`).
  - `fee_payment` (`id`, `reg_number`, `amount`, `payment_method`, `date_paid`).

---

### F. Database Management, Automated Backups & Maintenance Suite
* **Purpose**: Protects school institutional records with automated scheduled snapshots, table health diagnostics, defragmentation, and disaster recovery points.
* **Features**:
  - **Automated Daily Backups**: `portal/backup_cron.php` creates compressed `.zip` database dumps and auto-prunes snapshots older than 30 days.
  - **Live Backups & Snapshot Management**: `portal/pages/db_management.php` supports 1-click live downloads, server snapshot storage, and 1-click restore/delete.
  - **Database Diagnostics & Optimization**: Table-level inspection of row counts, data size, index size, and fragmentation overhead with 1-click `OPTIMIZE TABLE`, `REPAIR TABLE`, and `ANALYZE TABLE` utilities.
  - **Disaster Recovery Restore Point**: Multi-query execution handler with foreign key suspension and query buffer flush.
* **Key Files**:
  - `portal/backup_cron.php`: Scheduled cron & CLI backup processor.
  - `portal/pages/db_management.php`: Comprehensive 4-tab database administration hub.
  - `portal/backups/`: Protected archive directory secured via `.htaccess` (`Deny from all`).

---

### G. Progressive Web App (PWA) & Offline Resilience Suite
* **Purpose**: Allows EdumacFlo to be installed as a native desktop or mobile application with offline fallback and asset caching.
* **Features**:
  - **Installable Web App**: Configured `manifest.json` with standalone mode, branded theme color, responsive icons, and quick-action shortcuts (CBT, Broadsheet, Attendance, Defaulters).
  - **Service Worker Caching**: `sw.js` (v3.0) implements Network-First for dynamic PHP requests and Stale-While-Revalidate for static resources.
  - **Offline Fallback UI**: `offline.html` displays connection status with automatic reconnection reload listener.
  - **Global 1-Click Install**: Permanent `triggerPwaInstall()` button integrated in the sidebar and header.
* **Key Files**:
  - `manifest.json`: Web App Manifest.
  - `sw.js`: Service Worker.
  - `offline.html`: Offline fallback page.
  - `portal/footer.php` & `portal/sidebar.php`: Install triggers and lifecycle listeners.

---

## 3. CSV Format Standard for Score Sheet Import

When creating or editing spreadsheets for batch upload, ensure the following column layout:

| Col Index | Column Header | Description | Example |
|---|---|---|---|
| **0 (A)** | `S/N` | Serial Number | `1` |
| **1 (B)** | `Class` | Class Name | `JSS 1A` |
| **2 (C)** | `Term` | Academic Term | `First Term` |
| **3 (D)** | `Session` | Academic Session | `2024/2025` |
| **4 (E)** | `Reg No` | Student Registration Number | `EDF/2024/001` |
| **5 (F)** | `Name` | Student Full Name | `John Doe` |
| **6 (G)** | `Subject` | Subject Name | `Mathematics` |
| **7 (H)** | `1ST CA` | Continuous Assessment 1 (Max 20) | `18` |
| **8 (I)** | `2ND CA` | Continuous Assessment 2 (Max 20) | `17` |
| **9 (J)** | `Exam Score`| Examination Score (Max 60) | `54` |

---

## 4. Verification & Maintenance Commands

To verify syntax integrity across all PHP files in the portal:
```powershell
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\modules.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\teacher_dashboard.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\excel_result_upload.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\teacher_excel_result_upload.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\result_upload_excel.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\teacher_result_upload_excel.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\PHPExcel.php"
php -l "c:\wamp64\www\Edumacflow\eduflow\portal\pages\teacher_PHPExcel.php"
```
