# Trainer Certification System Refactoring Plan

**Date:** August 28, 2025  
**Status:** Planning Phase  
**Scope:** Refactor single trainer certification fields to support multiple certifications per trainer

## Overview

Currently, the HVAC plugin stores trainer certifications as simple meta fields in trainer profiles:
- `certification_type` (single value)
- `certification_status` (single value)  
- `date_certified` (single date)
- `certification_color` (auto-assigned)

**Goal:** Expand to support multiple certifications per trainer with proper tracking, expiration dates, and audit trails.

## Current State Analysis

### Existing Fields (in `trainer_profile` post type):
- `certification_type`: "Certified measureQuick Champion", "Certified measureQuick Trainer"
- `certification_status`: "Active", "Expired", "Suspended"
- `date_certified`: Single certification date
- `certification_color`: Color coding based on type

### Current Usage:
- Trainer profile displays show single certification
- Find-a-trainer filtering by certification type
- Color coding in UI based on certification level

## Proposed Solution: Custom Post Type Architecture

### 1. New Custom Post Type: `trainer_certification`

```php
register_post_type('trainer_certification', [
    'public' => false,
    'show_ui' => true,
    'show_in_menu' => 'hvac-dashboard',
    'supports' => ['title', 'editor'],
    'capability_type' => 'hvac_certification',
    'labels' => [
        'name' => 'Trainer Certifications',
        'singular_name' => 'Trainer Certification',
        'menu_name' => 'Certifications'
    ]
]);
```

### 2. Meta Fields Structure

**Core Fields:**
- `_trainer_user_id` (BIGINT) - Links to trainer's WordPress user ID
- `_certification_type` (VARCHAR) - Type of certification
- `_certification_number` (VARCHAR) - Unique identifier (e.g., "MQT-2025-00123")
- `_issue_date` (DATE) - When certification was granted
- `_expiration_date` (DATE) - When certification expires (nullable)
- `_status` (ENUM) - active, expired, suspended, revoked
- `_issued_by` (BIGINT) - User ID of who granted the certification

**Administrative Fields:**
- `_renewal_date` (DATE) - Last renewal date
- `_renewal_count` (INT) - Number of times renewed
- `_revocation_reason` (TEXT) - Reason if revoked
- `_revoked_by` (BIGINT) - Who revoked it
- `_revoked_date` (DATETIME) - When revoked

**Future Expansion Fields:**
- `_certification_level` (VARCHAR) - Basic, Advanced, Master
- `_prerequisites_met` (LONGTEXT) - JSON array of prerequisite certifications
- `_continuing_education_hours` (INT) - CE hours associated
- `_certificate_file_url` (TEXT) - Link to certification document

### 3. Custom Taxonomy: `certification_category`

**Terms:**
- measureQuick (current focus)
- NATE (future)
- EPA (future)
- Manufacturer (future)
- Safety (future)

### 4. Database Schema

**Post Structure:**
- `post_title`: Descriptive name (e.g., "John Doe - measureQuick Certified Trainer")
- `post_content`: Notes about the certification
- `post_status`: draft (pending), publish (active), private (revoked)
- `post_author`: The trainer who holds the certification

## Implementation Plan

### Phase 1: Core Infrastructure (Week 1)
1. **Create Custom Post Type Registration**
   - File: `includes/certifications/class-hvac-trainer-certification-manager.php`
   - Register post type and taxonomies
   - Set up meta field definitions
   - Add admin UI customizations

2. **Database Setup**
   - No custom tables needed (using WordPress post system)
   - Add meta field validation
   - Set up proper indexing for queries

3. **Admin Interface**
   - Custom meta boxes for certification details
   - List view with certification status filters
   - Bulk actions for status changes

### Phase 2: Migration System (Week 1)
1. **Migration Script**
   - File: `includes/certifications/class-hvac-certification-migrator.php`
   - Convert existing certification fields to new post type
   - Preserve historical data
   - Create audit trail

2. **Backward Compatibility Layer**
   - Maintain old meta field getters during transition
   - Add deprecation notices
   - Gradual migration approach

### Phase 3: Integration Updates (Week 2)
1. **Trainer Profile Manager Updates**
   - Update display logic for multiple certifications
   - Modify save/update routines
   - Maintain color coding system

2. **Find-a-Trainer Integration**
   - Update filtering to work with new structure
   - Support multiple certification searches
   - Performance optimization

3. **API Endpoints**
   - REST API for certification management
   - AJAX handlers for admin interface
   - Export capabilities

### Phase 4: Advanced Features (Week 2-3)
1. **Expiration Management**
   - Automated expiration checking
   - Email notifications for expiring certifications
   - Renewal workflow

2. **Audit Trail**
   - Track all certification changes
   - Admin reporting interface
   - Export audit logs

3. **Bulk Operations**
   - Bulk certification renewal
   - Batch imports
   - Mass status changes

## Migration Strategy

### Step 1: Data Preservation
```php
// Before migration, backup existing data
$existing_certifications = [];
$trainers = get_users(['role' => 'hvac_trainer']);
foreach ($trainers as $trainer) {
    $profile = get_trainer_profile($trainer->ID);
    if ($profile) {
        $existing_certifications[$trainer->ID] = [
            'type' => get_post_meta($profile->ID, 'certification_type', true),
            'status' => get_post_meta($profile->ID, 'certification_status', true),
            'date' => get_post_meta($profile->ID, 'date_certified', true),
            'color' => get_post_meta($profile->ID, 'certification_color', true)
        ];
    }
}
```

### Step 2: Create New Certification Records
```php
foreach ($existing_certifications as $trainer_id => $cert_data) {
    if (!empty($cert_data['type'])) {
        $certification_id = wp_insert_post([
            'post_type' => 'trainer_certification',
            'post_title' => get_user_meta($trainer_id, 'display_name', true) . ' - ' . $cert_data['type'],
            'post_status' => 'publish',
            'post_author' => $trainer_id
        ]);
        
        update_post_meta($certification_id, '_trainer_user_id', $trainer_id);
        update_post_meta($certification_id, '_certification_type', $cert_data['type']);
        update_post_meta($certification_id, '_status', strtolower($cert_data['status']));
        update_post_meta($certification_id, '_issue_date', $cert_data['date']);
        update_post_meta($certification_id, '_issued_by', get_current_user_id());
    }
}
```

### Step 3: Update Display Logic
- Modify trainer profile templates to show multiple certifications
- Update find-a-trainer filters
- Maintain existing color coding where possible

## API Design

### New Manager Class: `HVAC_Trainer_Certification_Manager`

**Key Methods:**
```php
class HVAC_Trainer_Certification_Manager {
    // Core CRUD operations
    public function create_certification($trainer_id, $type, $data = []);
    public function get_trainer_certifications($trainer_id, $active_only = true);
    public function update_certification_status($cert_id, $status, $reason = '');
    public function renew_certification($cert_id, $new_expiration = null);
    
    // Queries and reporting
    public function get_expiring_certifications($days_ahead = 30);
    public function get_certification_stats();
    public function search_certifications($criteria = []);
    
    // Migration and compatibility
    public function migrate_legacy_certifications();
    public function get_primary_certification($trainer_id); // Backward compatibility
}
```

## Security Considerations

1. **Capability Management**
   - Only `hvac_master_trainer` and `administrator` can manage certifications
   - Trainers can view their own certifications (read-only)
   - Audit all certification changes

2. **Data Validation**
   - Validate all input fields
   - Prevent duplicate certifications
   - Enforce business rules (expiration dates, etc.)

3. **Access Control**
   - Nonce verification for all actions
   - User permission checks
   - Sanitize all inputs

## Testing Strategy

1. **Unit Tests**
   - Test all CRUD operations
   - Validate migration scripts
   - Test search and filter functionality

2. **Integration Tests**
   - Test trainer profile display
   - Verify find-a-trainer filtering
   - Check admin interface functionality

3. **Performance Tests**
   - Query performance with large datasets
   - Page load times with multiple certifications
   - Search performance

## Future Enhancements

### Phase 5: Advanced Certification Types (Future)
1. **NATE Certifications**
   - Multiple NATE specialty areas
   - Expiration tracking
   - CE hour requirements

2. **EPA Certifications**
   - Section 608 certifications
   - Universal, Type I, II, III tracking
   - Renewal management

3. **Manufacturer Certifications**
   - Brand-specific certifications
   - Product line specializations
   - Training completion tracking

### Phase 6: Reporting and Analytics (Future)
1. **Certification Dashboard**
   - Real-time certification status
   - Expiration alerts
   - Trainer qualification reports

2. **Compliance Reporting**
   - Export certification records
   - Audit trail reports
   - Regulatory compliance tracking

## Success Metrics

1. **Migration Success**
   - 100% data preservation during migration
   - Zero downtime during transition
   - All existing functionality maintained

2. **Performance**
   - Page load times remain under 2 seconds
   - Search performance under 500ms
   - Admin interface responsive

3. **User Experience**
   - Intuitive admin interface
   - Clear certification status displays
   - Easy bulk operations

## Timeline

**Week 1:**
- Core infrastructure implementation
- Migration system development
- Basic admin interface

**Week 2:**
- Integration with existing systems
- Testing and bug fixes
- Performance optimization

**Week 3:**
- Advanced features
- Documentation
- Production deployment

---

*This document will be updated as implementation progresses.*