# Training System Documentation

## Overview

The NordSafe EHS Training System has been refactored to support a hierarchical structure:

**Course → Modules → Lessons (Videos) + Quizzes**

This allows for comprehensive training programs with multiple modules, video lessons, and assessments.

## Database Structure

### Tables

1. **TrainingCourses** - Top-level courses
   - Contains: title, description, category, standard (e.g., OSHA 1926), level, duration
   
2. **TrainingModules** - Sections within a course
   - Each module contains multiple lessons and a quiz
   
3. **TrainingLessons** - Video lessons within modules
   - Supports uploaded videos (MP4/WebM) or YouTube
   - Tracks watch progress (must watch 80% to unlock quiz)
   
4. **TrainingQuizzes** - Quiz questions per module
   - Multiple choice questions with explanations
   - Passing score: 80%
   
5. **TrainingCourseEnrollments** - User enrollment per course
   - Tracks overall progress and certificate
   
6. **TrainingModuleProgress** - User progress per module
   - Tracks quiz scores and completion
   
7. **TrainingLessonProgress** - User watch progress per lesson
   - Tracks video watch percentage

### Migration

Run the migration to create tables:

```bash
# Execute the SQL file in your MySQL database
mysql -u username -p database_name < backend/migrations/create-training-courses-modules.sql
```

Or run it through phpMyAdmin/cPanel.

## API Endpoints

### User Endpoints

#### GET /api/training-courses
Get all active courses with enrollment status

**Response:**
```json
[
  {
    "id": 1,
    "title": "Trenching & Excavation Safety",
    "description": "...",
    "category": "Construction Safety",
    "standard": "OSHA 1926 Subpart P",
    "level": "foundation",
    "moduleCount": 3,
    "lessonCount": 4,
    "quizCount": 10,
    "enrollment": {
      "status": "in-progress",
      "overallScore": null,
      "certificateId": null
    }
  }
]
```

#### GET /api/training-courses/:courseId
Get detailed course with modules, lessons, quizzes, and user progress

**Response:**
```json
{
  "id": 1,
  "title": "Trenching & Excavation Safety",
  "enrollment": {
    "status": "in-progress",
    "overallScore": null
  },
  "modules": [
    {
      "id": 1,
      "title": "Introduction to Trenching Safety",
      "progress": {
        "status": "not-started"
      },
      "lessons": [
        {
          "id": 1,
          "title": "Understanding Trench Hazards",
          "videoFileName": "trench-hazards.mp4",
          "duration": 5,
          "watchUnlockPercent": 80,
          "progress": {
            "watchProgressPercent": 0,
            "completed": false
          }
        }
      ],
      "quizzes": [
        {
          "id": 1,
          "question": "What is the most common cause...",
          "options": ["...", "..."]
        }
      ]
    }
  ]
}
```

#### POST /api/training-courses/:courseId/modules/:moduleId/lessons/:lessonId/progress
Update lesson watch progress

**Request Body:**
```json
{
  "watchProgressPercent": 85
}
```

**Response:**
```json
{
  "watchProgressPercent": 85,
  "completed": true
}
```

#### POST /api/training-courses/:courseId/modules/:moduleId/complete
Submit module quiz

**Request Body:**
```json
{
  "answers": [1, 2, 0, 1, 2]  // Array of answer indices
}
```

**Response:**
```json
{
  "status": "completed",
  "quizScore": 100,
  "courseCompleted": true,
  "certificateId": "CERT-A1B2C3D4",
  "overallScore": 95
}
```

#### GET /api/training-courses/certificates
Get user's certificates

**Response:**
```json
[
  {
    "certificateId": "CERT-A1B2C3D4",
    "completedAt": "2024-01-15T10:30:00Z",
    "overallScore": 95,
    "courseTitle": "Trenching & Excavation Safety",
    "category": "Construction Safety",
    "standard": "OSHA 1926 Subpart P"
  }
]
```

### Admin Endpoints

#### POST /api/training-courses/admin/course
Create a new course with modules, lessons, and quizzes

**Request Body:**
```json
{
  "title": "Trenching & Excavation Safety",
  "description": "...",
  "category": "Construction Safety",
  "standard": "OSHA 1926 Subpart P",
  "level": "foundation",
  "estimatedDuration": 45,
  "order": 1,
  "modules": [
    {
      "title": "Introduction to Trenching Safety",
      "description": "...",
      "order": 1,
      "lessons": [
        {
          "title": "Understanding Trench Hazards",
          "description": "...",
          "duration": 5,
          "watchUnlockPercent": 80,
          "order": 1
        }
      ],
      "quizzes": [
        {
          "question": "What is the most common cause...",
          "options": ["Option 1", "Option 2", "Option 3", "Option 4"],
          "correctAnswer": 1,
          "explanation": "...",
          "order": 1
        }
      ]
    }
  ]
}
```

#### POST /api/training-courses/admin/course/:courseId/module/:moduleId/lesson/:lessonId/upload
Upload video for a lesson

**Form Data:**
- `video`: Video file (MP4/WebM, max 150MB)

#### GET /api/training-courses/admin/courses
Get all courses (admin view)

#### DELETE /api/training-courses/admin/course/:courseId
Delete a course and all related data

## Frontend Integration

### Course List View
- Display all available courses
- Show enrollment status and progress
- Filter by category, level, standard

### Course Detail View
- Show course information
- List all modules with lessons
- Display progress indicators
- Lock/unlock modules based on completion

### Lesson Player
- HTML5 video player with progress tracking
- Auto-save watch progress every 2 seconds
- Show progress bar (must reach 80% to unlock quiz)

### Quiz Interface
- One question at a time
- Navigation between questions
- Submit all answers at once
- Show score and pass/fail status
- Display explanations after submission

### Certificate Generation
- Auto-generate PDF certificate on course completion
- Include: student name, course title, completion date, score, certificate ID

## Sample Data

See `add-sample-training-course.js` for a complete example course with:
- 3 modules
- 4 video lessons
- 10 quiz questions
- OSHA-compliant content

## Testing

### Manual Testing Steps

1. **Create a course** (Admin)
   ```bash
   POST /api/training-courses/admin/course
   # Use sample data from add-sample-training-course.js
   ```

2. **Upload videos** (Admin)
   ```bash
   POST /api/training-courses/admin/course/1/module/1/lesson/1/upload
   # Upload MP4/WebM file
   ```

3. **Enroll in course** (User)
   ```bash
   GET /api/training-courses/1
   # Automatically creates enrollment
   ```

4. **Watch lesson** (User)
   ```bash
   POST /api/training-courses/1/modules/1/lessons/1/progress
   { "watchProgressPercent": 85 }
   ```

5. **Take quiz** (User)
   ```bash
   POST /api/training-courses/1/modules/1/complete
   { "answers": [1, 1, 1, 1, 1] }
   ```

6. **Get certificate** (User)
   ```bash
   GET /api/training-courses/certificates
   ```

## Migration from Old System

The old `TrainingVideos` and `TrainingEnrollments` tables are still supported for backward compatibility. To migrate:

1. Create new courses using the new structure
2. Notify users of the new training portal
3. Optionally migrate old video data to new structure
4. Deprecate old endpoints after migration period

## Security Considerations

- Quiz correct answers are NOT sent to frontend (only question and options)
- Video files are served from protected directory
- Watch progress is validated server-side
- Certificate IDs are cryptographically random
- Admin endpoints require admin role

## Performance Optimization

- Use eager loading for nested relations
- Index on foreign keys and status fields
- Cache course catalog for anonymous users
- Paginate admin course list for large datasets

## Future Enhancements

- [ ] Course prerequisites
- [ ] Expiration dates for certificates
- [ ] Recurring training requirements
- [ ] Video streaming optimization
- [ ] Mobile app support
- [ ] Offline video download
- [ ] Multi-language support
- [ ] SCORM compliance
- [ ] Integration with HR systems
- [ ] Advanced analytics dashboard
