ACI Portal - Comprehensive Technical README
===========================================

Overview
--------
This `portal` directory is a multi-role school management web application built in procedural PHP.
It combines:
- Student portal
- Teacher portal
- Super admin portal
- Payment and wallet management (Paystack integration)
- Academic records and reports
- AI-based student performance analysis

The app runs primarily on XAMPP/Apache + MySQL and uses AdminLTE-style frontend assets.


Tech Stack and Runtime
----------------------
Backend:
- PHP 8.2+ (see `composer.json`)
- Mixed MySQL access style:
  - PDO (`$dbh`)
  - MySQLi (`$con`)

Key packages:
- `vlucas/phpdotenv` for `.env` configuration
- `mpdf/mpdf` and `phpoffice/phpspreadsheet` for document/report export workflows
- `knplabs/knp-snappy` for PDF/snappy support
- PHPUnit + Eris for tests

Frontend:
- AdminLTE ecosystem in `plugins/` and `dist/`
- jQuery, DataTables, FullCalendar, Summernote, Select2, SweetAlert2


High-Level Architecture
-----------------------
This is a page-controller style PHP app (no central framework/router). Each `.php` file is often both:
- a controller (reads request, validates session, queries DB), and
- a view (renders HTML/CSS/JS).

Shared core files:
- `includes/dbconnection.php` - global DB constants and connections
- `includes/session.php` - student session guard with tab-based session model
- `includes/session1.php` - teacher session guard with tab-based session model
- `includes/session_term_helper.php` - resolves current academic session/term
- `includes/head.php`, `includes/header.php`, `includes/sidebar.php`, `includes/foot.php` - shared layout blocks

API-style endpoints:
- `api/load_sessions.php`
- `api/load_terms.php`
- `api/generate_report.php`
- `api/generate_ai_report.php`
- `api/get_teacher_ai_report.php`


Core Portal Flows
-----------------
1) Student Authentication and Portal
- Entry: `index.php`
- Login checks `students` table with active status.
- Password validation uses `password_verify`.
- On success, creates tab-scoped session in `$_SESSION['tabs'][tab_id]`.
- Redirect chooses day/boarding page based on stream (`oldstdday.php` / `oldstdboard.php`).
- Session continuity/validation is enforced by `includes/session.php`.

2) Teacher Authentication and Portal
- Entry: `teacher.php`
- Auth source: `tblusers` where permission is `Teacher`.
- Password accepted via:
  - `password_verify`,
  - legacy MD5 fallback,
  - optional env default teacher password.
- Successful login creates tab session and redirects to `teacher_dashboard.php?tab_id=...`.
- Guard and compatibility session hydration handled by `includes/session1.php`.

3) Super Admin Authentication and Portal
- Entry: `admin.php`
- Uses dedicated session name and save path (`super_admin_session` and `session_data/super`).
- Auth source: `tblusers` where permission is `Super User`.
- On success, logs activity into `userlog` and redirects to `dashboard.php`.
- `dashboard.php` validates session + permission and renders KPI widgets, calendar, analytics, and links to operational modules.


Main Functional Modules
-----------------------
A) Payments and Finance
- Fee payment initiation/verification:
  - `initiate_payment.php`
  - `callback.php`
  - `verify_payment*.php`
- Paystack asynchronous settlement:
  - `paystack_webhook.php`
  - Handles signature verification via `X-Paystack-Signature`
  - Handles two streams:
    - Wallet deposits (email tag-based student ID extraction)
    - Normal school fee payments into `payments` table
- Wallet management:
  - `wallet_*.php`, `manage_wallet.php`, wallet logs and settings pages

B) Academic Results and Assessment
- Result entry/management:
  - `add_results*.php`, `manage_results*.php`, `edit_result.php`
- Reporting/print workflows:
  - `print_broadsheet*.php`
  - `print_scoresheet*.php`
  - `view_result*.php`
- Attendance/rating:
  - `mark_attendance.php`, `attendance_report.php`
  - `rating_form.php`, `view_ratings.php`

C) Student/Staff/School Operations
- Student lifecycle:
  - application/provisional/full/graduated/demoted listings
  - many `student*.php` and `*_students.php` pages
- Teacher assignment and management:
  - `assign_teacher*.php`, `manage_teacher_subjects.php`
- Session/term/class structures:
  - `manage_session.php`, `manage_class_section.php`, related utilities


Reporting and AI Analytics
--------------------------
1) Standard Analytics API
- `api/generate_report.php` accepts filters:
  - session, term, class, section, subject
- Produces aggregate metrics such as:
  - top students
  - overall average
  - top/worst class
  - best/worst subject
  - class-section performance breakdowns
- JSON is consumed by report UI pages (notably `reports.php`).

2) AI-Powered Performance Layer
- Engine: `includes/AIEngine.php`
- Endpoint: `api/generate_ai_report.php`
- Access control: requires active super admin session and `Super User` permission.
- Processing model:
  - computes base score from exam/test/class performance/weekly assessment
  - applies trend scoring (weighted linear regression over terms)
  - computes bounded performance score
  - assigns band by class level (SS/JSS/Primary-aware grading rules)
  - derives risk levels and recommendations (student/teacher/parent/admin angles)
- Persistence:
  - stores generated records in `ai_performance_reports`
  - migration file: `db/migrations/create_ai_performance_reports.sql`


Session and Security Model
--------------------------
Session model differs by role:
- Student: `student_portal`
- Teacher: `teacher_portal`
- Super admin: `super_admin_session` with explicit custom save path/cookie settings

Notable design detail:
- Student/teacher flows use "tab IDs" to hold multiple per-tab session states in `$_SESSION['tabs']`.
- Session include files copy selected tab data into legacy global session keys for backward compatibility with older pages.


Data and Database Notes
-----------------------
Database bootstrap:
- Configured in `includes/dbconnection.php`
- Default constants point to local DB (`sms`) with root/no password (development-oriented default)
- Timezone is set in PHP and MySQL sessions.

Frequently used tables (observed):
- `students`
- `tblusers`
- `results`
- `payment` / `payments`
- `wallets`
- `wallet_transactions`
- `school_sessions`
- `school_terms`
- `userlog`
- `feedback`
- `message`
- `ai_performance_reports` (AI module)


Folder Map (Important Paths)
----------------------------
- `includes/` -> shared configuration, session guards, components, helper classes
- `api/` -> JSON endpoints for reports and dependent filters
- `db/migrations/` -> SQL migration scripts
- `plugins/`, `dist/` -> frontend assets
- `vendor/` -> Composer dependencies
- `phpmailer/` -> SMTP mailing implementation
- `tests/` -> PHPUnit and property-style tests


Setup Instructions (Local Development)
--------------------------------------
1. Place project in your web root (`htdocs`) and open `portal` folder.
2. Start Apache + MySQL (XAMPP).
3. Create/import database schema and data.
4. Run AI migration:
   - Execute `db/migrations/create_ai_performance_reports.sql` once.
5. Install PHP dependencies in `portal`:
   - `composer install`
6. Configure environment:
   - Ensure `.env` has correct values (school branding, payment keys, SMTP, defaults).
7. Verify database connection details in:
   - `includes/dbconnection.php`
8. Access key entry points:
   - Student: `/portal/index.php`
   - Teacher: `/portal/teacher.php`
   - Super admin: `/portal/admin.php`


How Pages and APIs Work Together
--------------------------------
Typical pattern:
1. User opens role-specific page.
2. Role page validates session and permission.
3. UI loads dynamic filters/options (sessions/terms via API).
4. Frontend sends AJAX requests to `api/*.php`.
5. API performs SQL aggregations and returns JSON.
6. Page renders charts/tables/cards and optional exports.

Payment pattern:
1. Payment initiated on portal.
2. User completes checkout on Paystack.
3. Paystack redirects/callback may be used for immediate confirmation.
4. Webhook (`paystack_webhook.php`) is authoritative for asynchronous updates.
5. Payment/wallet tables are updated idempotently by reference checks.


Testing
-------
- Test files are available under `tests/`.
- Run tests with Composer script:
  - `composer test`
- Test coverage includes wallet rules, transfer validation/completion behavior, badge/session-term helpers, and regression-style bug-condition checks.


Operational Considerations and Risks
------------------------------------
1) Configuration/secret handling
- This project depends heavily on `.env` values. Keep production secrets out of source control.

2) Legacy compatibility in authentication
- Teacher/admin login still supports MD5 fallback paths for older password records.
- Plan migration to strict modern password hashing only.

3) Mixed DB style
- Both PDO and MySQLi are used. Future refactor should standardize DB access and query patterns.

4) Large procedural surface
- Many pages contain intertwined query + render logic and duplicate variants (`*1.php`, etc.), so changes should be tested carefully by role/module.


Maintenance Notes
-----------------
- When adding new report logic, prefer placing computation in API endpoints (`api/`) and keeping UI pages focused on rendering.
- Keep session checks consistent with role and session name to avoid cross-portal leakage.
- Keep migration SQL scripts in `db/migrations` for reproducible database changes.


Quick Entry Index
-----------------
- Student login: `index.php`
- Teacher login: `teacher.php`
- Admin login: `admin.php`
- Admin dashboard: `dashboard.php`
- Reports UI: `reports.php`
- Standard report API: `api/generate_report.php`
- AI report API: `api/generate_ai_report.php`
- AI engine: `includes/AIEngine.php`
- Paystack webhook: `paystack_webhook.php`
- DB config: `includes/dbconnection.php`
