# System Architecture

## Overview

This LMS is a multi-tenant educational platform built on Laravel 11 with Filament v3 admin panels. It manages educational programs (tenants), teachers, students, courses, assessments, competitions, and a comprehensive subscription/plan system.

## Architecture Style

**Modular Monolith** — The system is deployed as a single Laravel application but organized into distinct business modules with clear boundaries. Each module has its own models, Filament resources, and services while sharing common infrastructure (NotificationEngine, FeatureEntitlement, Participation system).

## Key Architectural Decisions

### 1. Two Filament Panels
The application uses two separate Filament panels:
- **Admin Panel** (`/admin`) — System-level administration for super-admins/managers
- **Program Panel** (`/program`) — Tenant-level interface for program admins, teachers, and students

### 2. Custom Notification Engine
Instead of relying solely on Laravel's built-in notification system, the application implements a **pipeline-based notification engine** (`app/NotificationEngine/`) with 16 configurable stages. This provides:
- Global enable/disable toggles
- Per-program notification overrides
- User preference resolution
- Channel resolution (database, mail, WhatsApp)
- Quiet hours enforcement
- Rate limiting / throttling
- Deduplication
- Template rendering
- Queue management
- Retry logic
- Audit logging

### 3. Polymorphic Participation System
Events (marathons, competitions) share a unified participation architecture with polymorphic relationships:
- `EventParticipation` — Tracks teacher participation in events
- `StudentEnrollment` — Tracks student enrollment in events
- `EventEligibility` — Defines eligibility criteria
- `SeatAllocation` — Manages seat limits per participant
- `ParticipationAudit` — Audit trail for participation actions
- `PaymentSubmission` — Tracks payment submissions for events

### 4. Three-Tier Subscription System
Separate subscription models for each subscriber type:
- `ProgramSubscription` — Program-level features/capacity
- `TeacherSubscription` — Teacher-level features/limits
- `StudentSubscription` — Student-level features/limits

### 5. Feature Entitlement Engine
A centralized `FeatureGate` service (`app/Services/FeatureEntitlement/`) that:
- Reads feature definitions from `config/features.php`
- Resolves the correct subscription for any subscriber type
- Checks feature limits (numeric, boolean, storage, rate, seats)
- Tracks usage consumption/release via `SubscriptionUsageObserver`
- Supports soft and hard limits with notification thresholds

### 6. Polymorphic Morph Map
Uses Laravel's `Relation::morphMap()` to provide short type names in the database:
- `'program'` → `Program`
- `'marathon'` → `Marathon`, `'competition'` → `Assessment`
- `'marathon_participation'` / `'competition_participation'` → `EventParticipation`
- `'marathon_enrollment'` / `'competition_enrollment'` → `StudentEnrollment`

## Module Relationships

```
Program (Tenant)
  ├── Users (Admins, Managers)
  ├── Teachers → Courses → Lessons
  │              └── Teams → Students (via TeamUser pivot)
  ├── Students → Assessments (attempts)
  ├── Marathons → Competitions (child Assessments)
  ├── Assessments (exams, competitions, trainings, assignments)
  ├── Announcements
  ├── Videos (teacher-owned)
  ├── Certificates
  ├── Level Classifications
  ├── Ranking Titles
  ├── Attendance Records
  └── Subscription (ProgramSubscription)
       └── Features (via FeatureGate)
            ├── Teachers → TeacherSubscription
            └── Students → StudentSubscription
```

## Data Flow Patterns

### Create Resource with Feature Check
1. User creates a resource (e.g., Course)
2. `SubscriptionUsageObserver@created` fires
3. Resolves subscriber from `config/subscription-resources.php`
4. Calls `FeatureGate::consume()` to check and increment usage
5. If limit exceeded → throws `FeatureLimitExceededException`

### Dispatch Notification
1. Model event or system action triggers `NotificationEngine::dispatch()`
2. Pipeline processes through 16 stages (enable/disable, settings, preferences, channels, etc.)
3. Final stage dispatches to appropriate channels (database, mail, WhatsApp)
4. History and audit records created

### Participation Workflow
1. Teacher requests to participate in an event (marathon/competition)
2. Eligibility checked via `EligibilityService`
3. Request approved/rejected by authority (system/program scoped)
4. Seat allocated via `SeatAllocationService`
5. Students enrolled via `StudentEnrollmentService`
6. Payments processed via `PaymentService`
7. Audit trail recorded via `ParticipationAuditService`

## Cross-Cutting Concerns

- **Authorization:** Spatie permissions with custom `ParticipationPolicy` for scope-aware access
- **Audit:** Fatal error logging on shutdown, slow request detection (>5s), participation audit trail
- **Localization:** Spatie Translatable on models, 80+ translation files (EN/AR), Filament language switcher
- **Storage:** File uploads via Filament's file handling, video streaming endpoint, custom `storage.serve` route
- **Real-time:** Chatify messaging with Pusher, database notifications with 30s/3s polling
