# EdumacFlo System Changelog

All notable changes, updates, fixes, and feature additions to the EdumacFlo School Management Script are documented in this file.

## [Version 2.8.3] - 2026-08-16

### 🚀 Student Mass Onboarding & Class-Based Export Suite
- **Mass Student Import Engine (`portal/pages/import_students.php`)**:
  - Built a comprehensive bulk intake system allowing schools to onboard hundreds or thousands of students in a single upload.
  - **Multi-Class Auto-Detection**: Dynamically maps each student's class and auto-derives their corresponding academic level (`NURSERY`, `PRIMARY`, `UPPER BASIC`, `SENIOR SECTION`) directly from the `classes` database.
  - **Single Class Override Mode**: Allows forcing all rows in an uploaded file into a specific selected class.
  - **Auto-Generated Admission Numbers**: Auto-generates unique sequential admission numbers with school initials (e.g., `EDM/26/XXXXXX`) if the admission number column is left blank.
  - **Secure Password Hashing**: Implemented default initial password generation (standard PIN `1234` or lowercase surname) securely hashed with bcrypt (`PASSWORD_DEFAULT`).
  - **Duplicate & Error Resilience**: Skips duplicate admission numbers and provides an interactive real-time summary with row-by-row error diagnostics.
- **Official CSV Template Generator (`portal/download_student_template.php`)**:
  - One-click streaming download of pre-formatted UTF-8 CSV templates with pre-filled sample rows.
  - Supports generating general templates or class-specific templates (e.g. `?class=JSS+1`).
- **Class-Based Student Export Engine (`portal/pages/export_students.php`, `portal/export_students_excel.php`)**:
  - Added filterable student export supporting whole-school rosters or class-specific rosters (`Basic 1`, `JSS 1`, etc.) with gender and status filters.
  - Streams clean, Excel/Google Sheets compatible `.csv` files for offline editing, auditing, and grade collation.
  - Side summary card displaying live student enrolment counts per class.
- **Sidebar & Access Control Integration**:
  - Added **"Import Students (Mass Upload)"** and **"Export Students (By Class)"** under the **Student** treeview in `portal/sidebar.php`.
  - Registered `import_students`, `export_students`, and `download_student_template` permissions in `permissions` and assigned to Super Admin (`role_id = 11`) and School Admin (`role_id = 3`).

### 🛠️ Database Connection & Local/Live Staging Stability Fixes
- **Unified Database Connection (`public/connection.php`, `cbt/public/connection.php`)**:
  - Restored full connectivity to MySQL database `edumacflo` with UTF-8 (`utf8mb4`) character set and robust fallback path resolution.
  - Unified `$conn` and `$connection` variable aliases across root and CBT submodules.
  - Created standard `public/db_config.sample.php` template for seamless live server / cPanel database configuration.
- **Apache FastCGI 500 Internal Server Error Resolution**:
  - Resolved FastCGI crash caused by invalid Linux cPanel session path `session.save_path = "/var/cpanel/php/sessions/ea-php82"` in `.user.ini` and `php.ini`.
  - Streamlined `.htaccess` and `portal/.htaccess` URL rewriting rules by removing hardcoded legacy directory prefixes for clean local WAMP and live staging compatibility.

### 🛡️ Production Security Hardening & Deployment Cleanup
- **Comprehensive Production Artifacts Cleanup**:
  - Removed obsolete debug scripts (`test.php`, `portal/login_test.php`, `portal/auto_login.php`).
  - Purged over 5MB of historical server error logs (`error_log` in root, portal, CBT, contact).
  - Cleaned up development notes (`needed_query`, `portal/pages/needed query.txt`), legacy archives (`cbt/tcpdf.zip`), and temporary composer phar binaries.
  - Relocated manual database update scripts to `database/migrations/` under strict access denial.
- **Web Server Protection & Security Headers**:
  - Hardened root, portal, CBT, public, database, and uploads `.htaccess` files.
  - Disabled directory browsing (`Options -Indexes`) project-wide.
  - Added HTTP security headers (`X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, `X-XSS-Protection: 1; mode=block`).
  - Disabled PHP script execution inside upload directories (`uploads/` and `cbt/uploads/`) to prevent remote code execution.
  - Blocked direct HTTP browser access to internal server include files in `public/` (HTTP 403 Forbidden).
- **Session & Routing Protection**:
  - Implemented `session_regenerate_id(true)` upon successful authentication in `public/auth.php` to prevent session fixation attacks.
  - Added strict alphanumeric/dash sanitization on the `$page` routing parameter in `portal/index.php` to eliminate directory traversal risks.
- **Live Deployment Guide**:
  - Created comprehensive step-by-step staging and client demo deployment guide in `docs/LIVE_DEPLOYMENT_GUIDE.md`.

---

## [Version 2.8.2] - 2026-08-16

### 🎓 Academic Results Formulation (Basic 3 - 2025/2026)
- **Comprehensive Score Formulation Engine**:
  - Successfully generated Continuous Assessment (CA 1 & CA 2) and Terminal Examination results for all 14 students in **Basic 3** across 14 standard subjects.
  - Formulated full academic performance records for **First Term**, **Second Term**, and **Third Term** (588 subject records).
  - Computed subject rankings (`subject_rank`) dynamically across classmates.
  - Calculated terminal totals, terminal averages, and overall class positions with customized teacher and headmaster remarks in `positions`.
  - Compiled cumulative annual results and broadsheets with promotion remarks ("PROMOTED TO BASIC 4") in `annual_result` and `annual_result_summary`.
  - Generated behavioral assessments (Punctuality, Neatness, Initiative, Honesty, Attitude) for all students in `behavioral`.
  - Provisioned fresh scratch PINs in `pin1`, `pin2`, and `pin3` for seamless result checking via `result.php`.

## [Version 2.8.1] - 2026-08-16

### 📅 Session & Term Management Suite Upgrade
- **Exam Results Checker UI/UX Redesign (`result.php`)**:
  - Rebuilt the layout into a modern 2-column responsive design (Instruction Guide & Support + High-accessibility Form).
  - Added real-time student lookup indicator with live spinner, checkmark confirmation, and automatic class selection.
  - Implemented smart default selection for the active academic session (`2025/2026`) and active term.
  - Added scratch PIN show/hide toggle and dynamic school identity loading from the database.
  - Fixed `require_once` relative include path resolution that caused a fatal stream opening error when accessed through portal routing.
- **Synchronization Hub Fix (`portal/pages/sync_manager.php`, `db_update_sync.php`)**:
  - Added `remote_sync_url` and `sync_api_key` columns to `administratives` table and `is_synced` columns to all syncable data tables.
  - Added self-healing schema guards to `portal/pages/sync_manager.php` preventing database column exceptions.
- **Academic Year & Term Configuration (`portal/pages/session_term.php`)**:
  - Configured active academic session for **2025/2026**.
  - Built an interactive **1-Click Term Switcher** allowing instant switching between **First Term**, **Second Term**, and **Third Term**.
  - Added live gradient KPI overview cards for Active Session, Active Term, and Term Ending/Resumption calendar dates.
  - Added automatic pre-selection of active term and active session in form dropdowns.
  - Added registered academic sessions management table with direct 1-click "Make Active" quick actions.

---

## [Version 2.8.0] - 2026-08-15

### 📱 Full Progressive Web App (PWA) Suite & Offline Resilience
- **Upgraded Web App Manifest (`manifest.json`)**:
  - Configured standalone app display, theme palette, and high-resolution icons (192x192, 512x512 maskable).
  - Added native quick-access shortcuts: **CBT Exam Portal**, **Class Broadsheet**, **QR Attendance**, and **Defaulters Tracker**.
- **Enhanced Service Worker Engine (`sw.js` - v3.0)**:
  - Pre-caches core application shell, font icons, Google Fonts, and offline templates.
  - Implemented **Network-First** strategy for dynamic PHP documents with automatic fallback to offline view.
  - Implemented **Stale-While-Revalidate** strategy for static assets (CSS, JS, images, webfonts) for lightning-fast loads.
  - Automatically purges outdated caches on activation and claims active clients.
- **Redesigned Premium Offline Fallback Page (`offline.html`)**:
  - Modern glassmorphism UI with live connectivity status indicators.
  - **Auto-Reconnection Listener**: Automatically detects when internet is restored and reloads the previous page seamlessly.
  - Interactive "Check Connection & Retry" action with immediate visual feedback.
- **System-Wide Install App Integration**:
  - Added global install prompt handler (`triggerPwaInstall()`) in `portal/footer.php` with cross-platform instructions (Chrome, Edge, Android, iOS).
  - Added permanent **"📱 Install EdumacFlo App"** link in `portal/sidebar.php`.
  - Registered PWA manifest and Service Worker in root landing page (`index.php`), main portal (`portal/header.php`), and CBT student panel (`cbt/student/partials/`).

---

## [Version 2.7.0] - 2026-08-15

### 🗄️ Automated Database Backup, Maintenance & Disaster Recovery Engine
- **Created Automated Backup & Scheduled Cron Script (`portal/backup_cron.php`)**:
  - Automatically dumps complete database schema and records.
  - Automatically creates compressed `.zip` archives (with `.sql` fallback) to save server storage.
  - Implemented automatic **30-day snapshot rotation and auto-pruning** to prevent disk bloat.
  - Supports CLI execution (Windows Task Scheduler, Linux cron) and token-secured HTTP webhook triggers.
- **Upgraded Database Management Hub (`portal/pages/db_management.php`)**:
  - **KPI Metrics Overview**: Live cards for Database Size (MB), Total Tables, Total Records, Reclaimable Overhead Space, and Latest Snapshot.
  - **4 Interactive Tabs**:
    1. 🗄️ **Backups & Snapshots**: 1-click live backup download (.zip/.sql), on-demand server snapshot creation, and local snapshot management table (Download, Restore, Delete).
    2. ⚙️ **Table Health & Optimization**: Full MySQL table diagnostics matrix with 1-click **Optimize All Tables**, **Repair All Tables**, and **Analyze Tables**.
    3. 🔄 **Disaster Recovery Restore Point**: Secure file uploader for `.sql` and `.zip` backups with safety confirmation and foreign key integrity handling.
    4. ⏰ **Automated Scheduler Guide**: Copy-paste commands for Windows Task Scheduler, Linux Cron, and Webhook URL.
- **Hardened Backups Directory Security (`portal/backups/`)**:
  - Protected storage directory with `.htaccess` (`Deny from all`) and blank `index.html` preventing public web discovery.

---

## [Version 2.6.0] - 2026-08-15

### 📊 Class Broadsheet Suite: 1-Click Excel / CSV & PDF Export + Live Ranking
- **Created Dedicated Excel / CSV Broadsheet Exporter (`portal/export_broadsheet_excel.php`)**:
  - Automatically aggregates student scores across all subjects (`CA1`, `CA2`, `EXAM`, `Total`).
  - Computes Grand Totals, Class Averages, and Class Positions (1st, 2nd, 3rd, etc.).
  - Includes institutional header metadata and class summary statistics (Total Students, Computed Subjects, Highest Avg, Lowest Avg, Class Mean).
- **Upgraded Broadsheet Viewers (`portal/pages/view_class_broadsheet.php` & `portal/pages/teacher_view_broadsheet.php`)**:
  - Implemented automatic on-screen **Dense Ordinal Rank Computation** (1st, 2nd, 3rd, etc.) with gold, silver, bronze position badges.
  - Added modern action toolbar with direct 1-click **Export Excel (.CSV)**, **Download Official PDF**, and **Print Broadsheet** buttons.
  - Added real-time **Class Performance KPI Summary Cards** (Total Students, Subjects Computed, Highest Class Avg, Class Mean Avg).
  - Form value retention so selected Class, Term, and Session persist across actions.
- **Fixed Teacher Dashboard Routing (`portal/pages/teacher_dashboard.php`)**:
  - Fixed route matching for `teacher_view_class_broadsheet` and `teacher_view_broadsheet` to load `teacher_view_broadsheet.php` without broken file includes.

---

## [Version 2.5.0] - 2026-08-15

### 🔒 Permission Matrix Audit, Auto-Seeding & Session Inactivity Security
- **Hardened Permission Verification (`portal/check_permission.php`)**:
  - Implemented automatic **30-minute idle session timeout** (`$_SESSION['last_activity']`) to secure accounts on shared devices.
  - Added query-parameter-aware permission checks for pages routed via `modules.php` and `teacher_dashboard.php`.
  - Added smart role-aware redirects to prevent access looping (`teacher_dashboard.php` for teachers, `dashboard.php` for admin).
- **Auto-Seeded Permissions Database (`db_update_permissions.php`)**:
  - Registered and mapped permission keys (`excel_result_upload`, `teacher_excel_result_upload`, `mailbox`, `defaulters_tracker`, `elibrary`, `qr_attendance`, `view_class_broadsheet`, `teacher_view_broadsheet`) across all roles (Super Admin, School Admin, Class Teacher, Subject Teacher, Accountant, Exam Officer, Student).

---

## [Version 2.4.0] - 2026-08-14

### 🚀 Excel / CSV Spreadsheet Result Upload & Export Suite
- **Added Dual-Format Spreadsheet Support**:
  - **Single Subject Format**: Enables individual subject teachers to export and import scores for a single specific subject.
  - **Subject Combination / Master Class Format**: Enables form teachers and administrators to export and import all subjects offered by a class in a single batch spreadsheet (`★ All Subjects Combination`).
- **Added Dedicated Upload & Export Hubs**:
  - Created `portal/pages/excel_result_upload.php` for Admin and Principal dashboards with dual export/import panels and CSV format guidelines.
  - Upgraded `portal/pages/teacher_excel_result_upload.php` for Teachers with teacher-class scoping and active season defaults.
- **Upgraded Spreadsheet Generators**:
  - `portal/pages/PHPExcel.php` and `portal/pages/teacher_PHPExcel.php` now generate genuine, standards-compliant CSV files (`text/csv`) with pre-filled student registration numbers, names, class, term, session, and pre-existing scores.
- **Upgraded Batch CSV Importers**:
  - `portal/pages/result_upload_excel.php` and `portal/pages/teacher_result_upload_excel.php` updated with robust CSV row parsing, automatic score totaling (`ca1 + ca2 + exam`), upsert database operations (`INSERT` or `UPDATE`), and automatic multi-subject ranking re-calculation.
- **Direct UI Action Buttons**:
  - Added a green **"Excel / CSV Result Upload & Export"** button at the top of all CA and Exam score upload 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`, `upload_ca.php`, `upload_exam.php`).
- **Sidebar Menus**:
  - Added **"Excel / CSV Result Upload"** under `Result Management` in both `portal/pages/modules.php` (Admin) and `portal/pages/teacher_dashboard.php` (Teacher).

### 🐛 Attendance Term Selection Fix
- Updated `portal/pages/qr_attendance.php`, `portal/pages/class_attendance.php`, `portal/pages/view_attendance_records.php`, and `portal/pages/teacher_view_attendance.php` to render all 3 academic terms (`First Term`, `Second Term`, `Third Term`) with the active session term pre-selected by default.

---

## [Version 2.3.0] - 2026-04-15

### 🛠️ Attendance Module Fixes & PWA Polish
- **Attendance CSV Fix**:
  - Removed deprecated PHPExcel include dependencies in `portal/pages/export_attendance.php`.
  - Added UTF-8 BOM headers so CSV exports render properly across Microsoft Excel and LibreOffice.
- **Self-Contained Attendance Form**:
  - Updated `portal/pages/class_attendance.php` with self-contained Class and Date selectors for CSV import and export.
- **PWA & UI Modernization**:
  - Added progressive web app install prompt banner in `portal/footer.php`.
  - Added mobile responsive breakpoints, custom theme cards, and badge indicators in `assets/css/custom-theme.css`.

---

## [Version 2.2.0] - 2026-04-11

### 📷 Smart QR Attendance System
- **QR Code Scanner**:
  - Created `portal/pages/qr_attendance.php` integrating HTML5-QRCode device camera scanning for instant roll call.
- **CSV Attendance Synchronization**:
  - Created `portal/pages/import_attendance.php` and `portal/pages/export_attendance.php` for offline attendance tracking.
- **Sidebar Integration**:
  - Added QR-Code Scanner navigation link under Attendance in `portal/sidebar.php`.

---

## [Version 2.1.0] - 2026-04-07

### 📬 Inbuilt Mailing System & Defaulters Tracker
- **Internal Messaging (Mailbox)**:
  - Created `db_update_mail.php` migration creating `internal_mail` table.
  - Created `portal/pages/mailbox.php` with Inbox, Sent Box, Read View, Compose Modal, and broadcast options.
- **Smart Defaulters Tracker**:
  - Created `portal/pages/defaulters_tracker.php` calculating live balances from `invoice` and `fee_payment` tables with CSV export and reminder triggers.

---

## [Version 2.0.0] - 2026-04-07

### 📚 Digital E-Library Suite
- **E-Library Management**:
  - Created `db_update_elibrary.php` migration adding category and description to `curriculum`.
  - Created `portal/pages/elibrary.php` for staff material uploads (E-Books, Notes, Assignments).
  - Created `portal/pages/student_elibrary.php` for student material downloads.

---

## [Version 1.1.0] - 2026-04-07

### 🔄 Offline-Online Synchronization Hub
- Created `db_update_sync.php` migration adding sync tracking columns (`is_synced`, `remote_sync_url`, `sync_api_key`).
- Created `portal/pages/sync_manager.php` for bidirectional data synchronization.
- Created `sync_receiver.php` as the remote data ingestion listener.

---

## [Version 1.0.0] - 2026-04-07

### 💾 Self-Service Database Utilities
- Created `portal/pages/db_management.php` featuring Full SQL Backup, Database Optimization/Compression, and SQL Restore tools.
