# HVAC Community Events - Plugin Architecture

## Overview

The HVAC Community Events plugin follows a modular, single-responsibility architecture designed for maintainability and extensibility.

## Core Architecture Components

### 1. HVAC_Plugin (Main Controller)
- **Location**: `/includes/class-hvac-plugin.php`
- **Purpose**: Main plugin initialization and coordination
- **Responsibilities**:
  - Plugin activation/deactivation
  - Loading dependencies
  - Initializing core components
  - Hook registration

### 2. HVAC_Shortcodes
- **Location**: `/includes/class-hvac-shortcodes.php`
- **Purpose**: Centralized shortcode management
- **Responsibilities**:
  - Register all plugin shortcodes
  - Handle shortcode callbacks
  - Manage shortcode attributes
- **Key Shortcodes**:
  - `[hvac_dashboard]` - Trainer dashboard
  - `[hvac_master_dashboard]` - Master trainer dashboard
  - `[hvac_trainer_registration]` - Registration form
  - `[hvac_community_login]` - Login form
  - `[hvac_manage_event]` - Event management
  - `[hvac_certificate_reports]` - Certificate reports

### 3. HVAC_Scripts_Styles
- **Location**: `/includes/class-hvac-scripts-styles.php`
- **Purpose**: Asset management
- **Responsibilities**:
  - Frontend script/style enqueuing
  - Admin script/style enqueuing
  - Script localization
  - Cache busting

### 4. HVAC_Route_Manager
- **Location**: `/includes/class-hvac-route-manager.php`
- **Purpose**: URL routing and redirects
- **Responsibilities**:
  - Legacy URL redirects
  - Parent page redirects
  - Custom rewrite rules
  - Query var registration

### 5. HVAC_Template_Loader
- **Location**: `/includes/class-hvac-template-loader.php`
- **Purpose**: Template handling
- **Responsibilities**:
  - Load custom templates
  - Template hierarchy
  - Theme compatibility

### 6. HVAC_Page_Manager
- **Location**: `/includes/class-hvac-page-manager.php`
- **Purpose**: WordPress page management
- **Responsibilities**:
  - Create plugin pages
  - Manage page hierarchy
  - Set page templates

## Feature Components

### Authentication & Access Control
- **HVAC_Access_Control**: Page access restrictions
- **HVAC_Roles**: User role management
- **HVAC_Trainer_Status**: Trainer approval status

### Event Management
- **HVAC_Manage_Event**: Event creation/editing
- **HVAC_Event_Summary**: Event details display
- **Event_Form_Handler**: Form processing

### Dashboards
- **HVAC_Dashboard**: Trainer dashboard
- **HVAC_Master_Dashboard**: Master trainer dashboard
- **HVAC_Dashboard_Data**: Dashboard data processing

### Certificate System
- **HVAC_Certificate_Manager**: Certificate generation
- **HVAC_Certificate_Security**: Security measures
- **HVAC_Certificate_URL_Handler**: URL processing

### Venue Management
- **HVAC_Venues**: Venue CRUD operations (Singleton)
- **Venue Database**: TEC venue post type integration
- **Venue Shortcodes**: Display and management interfaces
- **AJAX Handlers**: Real-time venue operations

### Organizer Management  
- **HVAC_Organizers**: Organization profiles (Singleton)
- **Logo Upload**: Media library integration
- **Organizer Database**: TEC organizer post type
- **Company Profiles**: Business information management

### Training Leads System
- **HVAC_Training_Leads**: Lead tracking (Singleton)
- **Lead Forms**: Contact request handling
- **Status Management**: Lead lifecycle tracking
- **Reply Tracking**: Communication history

### Communication
- **HVAC_Communication_Templates**: Email templates
- **HVAC_Communication_Scheduler**: Automated emails
- **HVAC_Announcements**: System-wide notifications
- **HVAC_Master_Content_Injector**: Dynamic content injection

## Design Patterns

### Singleton Pattern
Used for classes that should have only one instance:
- HVAC_Plugin
- HVAC_Shortcodes
- HVAC_Scripts_Styles
- HVAC_Route_Manager
- HVAC_Help_System
- HVAC_Certificate_Security
- HVAC_Venues
- HVAC_Organizers
- HVAC_Training_Leads
- HVAC_Breadcrumbs
- HVAC_Master_Layout_Standardizer

### Implementation Example:
```php
class HVAC_Component {
    private static $instance = null;
    
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Initialize component
        add_action('init', array($this, 'init'));
    }
}

### Hook-Based Architecture
WordPress actions and filters are used extensively:
- `init` - Component initialization
- `wp_enqueue_scripts` - Frontend assets
- `admin_enqueue_scripts` - Admin assets
- `template_redirect` - Access control

## File Structure

```
hvac-community-events/
├── hvac-community-events.php              # Main plugin file
├── includes/
│   ├── class-hvac-plugin.php             # Main controller (Singleton)
│   ├── class-hvac-shortcodes.php         # Shortcode manager (Singleton)
│   ├── class-hvac-scripts-styles.php     # Asset manager (Singleton)
│   ├── class-hvac-route-manager.php      # URL routing (Singleton)
│   ├── class-hvac-template-loader.php    # Templates
│   ├── class-hvac-template-router.php    # Template routing
│   ├── class-hvac-template-security.php  # Template security
│   ├── class-hvac-page-manager.php       # Page creation
│   ├── class-hvac-page-manager-v2.php    # Enhanced page management
│   ├── class-hvac-page-content-manager.php # Content injection
│   ├── class-hvac-access-control.php     # Access control
│   ├── class-hvac-venues.php             # Venue management (Singleton)
│   ├── class-hvac-organizers.php         # Organizer management (Singleton)
│   ├── class-hvac-training-leads.php     # Lead tracking (Singleton)
│   ├── class-hvac-help-system.php        # Help system (Singleton)
│   ├── class-hvac-menu-system.php        # Menu management
│   ├── class-hvac-master-*               # Master trainer components
│   ├── admin/                            # Admin classes
│   ├── certificates/                     # Certificate system
│   ├── communication/                    # Email system
│   └── find-trainer/                     # Public trainer directory
├── templates/
│   ├── page-*.php                        # Page templates
│   ├── template-*.php                    # Layout templates
│   └── status/                           # Status templates
├── assets/
│   ├── css/                              # Stylesheets
│   ├── js/                               # JavaScript
│   └── images/                           # Image assets
├── tests/
│   ├── docker-compose.test.yml           # Docker test environment
│   ├── fixtures/                         # Test data
│   └── e2e/                              # End-to-end tests
├── scripts/                               # Deployment & maintenance
├── lib/                                  # Third-party libraries
└── docs/                                  # Documentation
```

## Initialization Flow

1. `hvac-community-events.php` loads
2. `HVAC_Plugin::instance()` singleton created
3. Core components initialized:
   - HVAC_Shortcodes
   - HVAC_Scripts_Styles
   - HVAC_Route_Manager
   - HVAC_Template_Loader
4. Feature components loaded
5. Hooks registered
6. Ready for requests

## Database Schema

### Custom Tables

#### hvac_certificates
```sql
CREATE TABLE {prefix}_hvac_certificates (
    id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    certificate_number varchar(50) NOT NULL,
    trainer_id bigint(20) unsigned NOT NULL,
    event_id bigint(20) unsigned NOT NULL,
    attendee_name varchar(255) NOT NULL,
    attendee_email varchar(255) NOT NULL,
    completion_date datetime NOT NULL,
    created_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY certificate_number (certificate_number),
    KEY trainer_id (trainer_id),
    KEY event_id (event_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

#### hvac_training_leads
```sql
-- Training leads are stored in wp_posts with post_type='hvac_training_lead'
-- Meta data stored in wp_postmeta
```

### WordPress Tables Used
- `{prefix}_posts` - Events, venues, organizers, pages
- `{prefix}_postmeta` - Event/venue/organizer metadata
- `{prefix}_users` - Trainer accounts
- `{prefix}_usermeta` - Trainer profile data
- `{prefix}_options` - Plugin settings

## Key URLs

### Trainer Pages
- `/trainer/dashboard/` - Main dashboard
- `/trainer/registration/` - Registration form
- `/trainer/event/manage/` - Create/edit events
- `/trainer/certificate-reports/` - View certificates

### Master Trainer Pages
- `/master-trainer/dashboard/` - Master dashboard
- `/master-trainer/google-sheets/` - Google Sheets integration

### Public Pages
- `/training-login/` - Login page
- `/trainer/registration/` - Public registration

## CSS Architecture

### Stylesheet Organization
- **hvac-dashboard.css** - Base dashboard styles, stat cards, tables
- **hvac-dashboard-enhanced.css** - Advanced dashboard features
- **hvac-event-manage.css** - Event creation/editing form styles
- **hvac-layout.css** - Layout containers and responsive grids
- **hvac-common.css** - Shared components and utilities
- **hvac-page-templates.css** - Page-specific template styles

### CSS Methodology
- **Scoped Selectors**: All styles scoped to prevent theme conflicts
  - Example: `.hvac-event-manage-wrapper .tribe-section`
- **CSS Variables**: Used for consistent theming
  - `--hvac-primary`, `--hvac-spacing-*`, `--hvac-radius-*`
- **Mobile-First**: Responsive breakpoints at 768px
- **BEM-like Naming**: Component-based class naming

### Theme Compatibility
- Styles use high specificity to override theme defaults
- Container max-width enforced at 1200px
- Consistent 20px padding on all pages
- Theme layout constraints overridden where necessary

## Security Architecture

### Access Control
- **Role-Based**: Uses WordPress roles (hvac_trainer, hvac_master_trainer)
- **Capability Checks**: Fine-grained permission system
- **Page Templates**: Security flag `HVAC_IN_PAGE_TEMPLATE`
- **AJAX Security**: Nonce verification on all AJAX calls

### Data Protection
```php
// Input sanitization
$trainer_id = absint($_POST['trainer_id']);
$email = sanitize_email($_POST['email']);
$text = sanitize_text_field($_POST['text']);

// Output escaping
echo esc_html($trainer_name);
echo esc_url($profile_url);
echo esc_attr($css_class);

// Nonce verification
if (!wp_verify_nonce($_POST['nonce'], 'hvac_action')) {
    wp_die('Security check failed');
}

// SQL injection prevention
$wpdb->prepare("SELECT * FROM table WHERE id = %d", $id);
```

### Security Headers
- Content Security Policy
- X-Frame-Options: SAMEORIGIN
- X-Content-Type-Options: nosniff
- Strict-Transport-Security

## Performance Optimizations

- Singleton patterns prevent duplicate initialization
- Assets loaded only on relevant pages
- Database queries optimized
- Caching implemented where appropriate

## Testing Infrastructure

### Docker Test Environment
```yaml
Services:
  - WordPress 6.4 (PHP 8.2) on port 8080
  - MySQL 8.0 on port 3307  
  - Redis 7 on port 6380
  - Mailhog on port 8025
  - PhpMyAdmin on port 8081
```

### Test Framework
- **Architecture**: Page Object Model (POM)
- **Coverage**: 146 E2E tests migrated
- **Efficiency**: 90% code reduction through shared patterns
- **Browser Support**: Headless and headed modes
- **Test Data**: Comprehensive fixtures and seeders

### Running Tests
```bash
# Start Docker environment
docker compose -f tests/docker-compose.test.yml up -d

# Run E2E tests (headless)
HEADLESS=true BASE_URL=http://localhost:8080 node test-master-trainer-e2e.js

# Run with browser (requires display)
DISPLAY=:0 node test-comprehensive-validation.js
```

## Integration Points

### The Events Calendar (TEC)
- **Version**: 5.0+ required
- **Post Types**: tribe_events, tribe_venues, tribe_organizers
- **Custom Fields**: CE credits, certification types
- **Template Override**: Custom event display templates

### Third-Party Services
- **Google Sheets API**: Data export/sync
- **SMTP Services**: Email delivery
- **PDF Generation**: TCPDF for certificates
- **Maps Integration**: Venue location display

## Performance Considerations

### Optimization Strategies
- **Singleton Pattern**: Prevents duplicate initialization
- **Lazy Loading**: Components loaded on demand
- **Asset Optimization**: Conditional script/style loading
- **Database Indexes**: Optimized query performance
- **Object Caching**: Redis/Memcached support
- **CDN Integration**: Static asset delivery

### Caching Layers
```
┌─────────────────┐
│   Browser Cache │
└────────┬────────┘
         │
┌────────▼────────┐
│   CDN Cache     │
└────────┬────────┘
         │  
┌────────▼────────┐
│  Page Cache     │
└────────┬────────┘
         │
┌────────▼────────┐
│ Object Cache    │
└────────┬────────┘
         │
┌────────▼────────┐
│   Database      │
└─────────────────┘
```

## Deployment Architecture

### Environments
- **Development**: Local Docker containers
- **Staging**: Mirror of production
- **Production**: Live environment

### CI/CD Pipeline
```yaml
Stages:
  1. Code Quality Checks
  2. Security Scanning
  3. Unit Tests
  4. E2E Tests
  5. Staging Deployment
  6. Smoke Tests
  7. Production Deployment
```

## Future Roadmap

### Phase 1 (Q3 2025)
- REST API v2 implementation
- GraphQL endpoint
- Webhook system expansion

### Phase 2 (Q4 2025)
- Microservices architecture
- Event streaming (Kafka/RabbitMQ)
- Advanced analytics dashboard

### Phase 3 (Q1 2026)
- Machine learning integration
- Predictive analytics
- Mobile application API