# CUSTOM TEC TEMPLATE IMPLEMENTATION PLAN
## Achieving 100% Field Control for HVAC Event Editing

**Document Version**: 1.0  
**Date**: August 12, 2025  
**Status**: Implementation Ready  
**Priority**: High  

---

## EXECUTIVE SUMMARY

**Current Status**: 81% field population success rate using JavaScript workarounds  
**Target Goal**: 100% field control via custom TEC Community Events template  
**Strategic Approach**: Template override system using official TEC/WordPress best practices  

**Key Decision Factors**:
- TEC REST API adds unnecessary complexity for in-WordPress context
- Template override is officially supported by TEC 6.0+
- Provides direct access to all WordPress core fields (excerpt, categories, featured images)
- Maintains security and upgrade compatibility

---

## TECHNICAL APPROACH ANALYSIS

### Approaches Evaluated

**Option 1: TEC REST API** ❌
- Pros: Complete programmatic control, decoupled architecture
- Cons: Authentication complexity, must build entire UI, unnecessary HTTP overhead
- Verdict: Overkill for in-WordPress template context

**Option 2: Enhanced JavaScript Workarounds** ⚠️ 
- Pros: Minimal disruption to existing system
- Cons: Limited by TEC shortcode constraints, fragile across updates
- Verdict: Current 81% success hits TEC plugin limitations

**Option 3: Custom Template Override** ✅ **SELECTED**
- Pros: 100% field access, upgrade-safe, TEC officially supported, security inherited
- Cons: Must understand TEC template structure, maintenance across updates
- Verdict: Optimal balance of control, compatibility, and maintainability

---

## IMPLEMENTATION PHASES

```
Phase 1: Discovery      Phase 2: Prototype      Phase 3: Implementation     Phase 4: Deployment
[Investigation] ------> [Basic Override] ------> [Full Features] ---------> [Testing & Launch]
    Steps 1-2               Steps 3-4               Steps 5-7                   Step 8
      |                       |                       |                         |
 TEC Analysis          Template Setup         Field Implementation      E2E Testing
 Gap Documentation     Minimal Test           Security & Processing     Staging Deploy
```

---

## DETAILED IMPLEMENTATION STEPS

### PHASE 1: DISCOVERY AND SETUP

#### Step 1: TEC Template Investigation and Analysis
**Objectives**:
- Locate actual `edit-event.php` file in TEC Community Events plugin
- Analyze template structure, form fields, and processing mechanisms  
- Document current field mappings and identify gaps
- Create backup and fallback strategy

**Expected Location**: `/wp-content/plugins/the-events-calendar-community-events/src/views/community/edit-event.php`

**Key Analysis Points**:
- Form field structure and naming conventions
- Processing hooks and validation mechanisms  
- TEC-specific functionality that must be preserved
- Integration points with venue/organizer selection

**Deliverables**:
- Template structure documentation
- Field gap analysis report
- Processing mechanism mapping
- Compatibility requirements

#### Step 2: Minimal Prototype Implementation
**Objectives**:
- Create basic template override with one additional field (excerpt)
- Test template override system works correctly
- Verify form processing and validation
- Establish baseline for further development

**Implementation**:
- Create `/wp-content/themes/[theme]/tribe/community/edit-event.php`
- Add excerpt field with proper WordPress integration
- Test form submission and data persistence
- Validate template override hierarchy

**Success Criteria**:
- Template override loads without errors
- Excerpt field renders and saves correctly
- Original TEC functionality remains intact
- No security or validation issues

### PHASE 2: STRUCTURE AND FOUNDATION

#### Step 3: Template Override Setup and Structure Creation
**Objectives**:
- Create proper theme directory structure
- Copy edit-event.php to theme with permissions and backup
- Add version tracking and compatibility comments  
- Test basic template override functionality

**Directory Structure**:
```
/wp-content/themes/[theme]/
└── tribe/
    └── community/
        ├── edit-event.php          # Main template override
        ├── backup/
        │   └── original-edit-event.php  # TEC original backup
        └── modules/                # Custom field modules
            ├── excerpt-field.php
            ├── categories-field.php
            └── featured-image-field.php
```

**Version Tracking**:
```php
<?php
/**
 * Custom HVAC Event Edit Template
 * 
 * Overrides: /plugins/the-events-calendar-community-events/src/views/community/edit-event.php
 * TEC Version Compatibility: 6.0+
 * Last Updated: August 12, 2025
 * Changes: Added excerpt, categories, featured image fields
 */
```

#### Step 4: Field Analysis and Integration Planning
**Objectives**:
- Document all existing TEC form fields and processing mechanisms
- Identify specific WordPress functions needed for missing fields
- Map out form field placement and styling requirements
- Plan integration with existing HVAC comprehensive field population system

**Field Mapping**:
| Field Type | Current Status | WordPress Function | Integration Method |
|------------|----------------|-------------------|-------------------|
| Title | ✅ Working | `post_title` | Native TEC |
| Description | ✅ Working (TinyMCE) | `post_content` | Native TEC |
| Excerpt | ❌ Missing | `wp_update_post()` | **Custom Addition** |
| Categories | ❌ Limited | `wp_set_post_categories()` | **Custom Addition** |
| Featured Image | ❌ Missing | `set_post_thumbnail()` | **Custom Addition** |
| Venue/Organizer | ✅ Working | TEC Functions | Native TEC |
| Date/Time | ✅ Working | TEC Functions | Native TEC |

### PHASE 3: FULL IMPLEMENTATION

#### Step 5: Custom Field Implementation and Form Enhancement
**Objectives**:
- Add excerpt field with proper WordPress integration
- Implement WordPress categories with autocomplete/selection
- Add featured image upload capability
- Create custom meta field handlers
- Style new fields to match TEC design

**Excerpt Field Implementation**:
```php
<div class="tribe-section tribe-section-excerpt">
    <div class="tribe-section-header">
        <h3><?php esc_html_e('Event Excerpt', 'tribe-events-community'); ?></h3>
        <p><?php esc_html_e('Brief summary of the event for search results and previews.', 'tribe-events-community'); ?></p>
    </div>
    <div class="tribe-section-content">
        <textarea 
            name="post_excerpt" 
            id="post_excerpt" 
            rows="3" 
            class="tribe-common-form-control-text__input"
        ><?php echo esc_textarea($event->post_excerpt); ?></textarea>
    </div>
</div>
```

**Categories Field Implementation**:
```php
<div class="tribe-section tribe-section-categories">
    <div class="tribe-section-header">
        <h3><?php esc_html_e('Event Categories', 'tribe-events-community'); ?></h3>
    </div>
    <div class="tribe-section-content">
        <?php 
        wp_dropdown_categories(array(
            'taxonomy' => 'tribe_events_cat',
            'name' => 'tax_input[tribe_events_cat][]',
            'selected' => wp_get_post_categories($event->ID, array('fields' => 'ids')),
            'show_option_none' => __('Select Categories...', 'tribe-events-community'),
            'class' => 'tribe-dropdown tribe-common-form-control-text__input',
            'multiple' => true
        ));
        ?>
    </div>
</div>
```

#### Step 6: Form Processing and Security Implementation
**Objectives**:
- Create secure form processing hooks using TEC's action points
- Add nonce verification and user capability checks
- Implement sanitization and validation
- Add AJAX handlers for dynamic interactions
- Test form submission and data persistence

**Security Implementation**:
```php
// Hook into TEC's form processing
add_action('tribe_events_community_before_event_save', 'hvac_process_custom_fields');

function hvac_process_custom_fields($event_id) {
    // Verify nonce and user capabilities
    if (!wp_verify_nonce($_POST['tribe_community_events_nonce'], 'tribe-community-events')) {
        wp_die(__('Security check failed', 'tribe-events-community'));
    }
    
    if (!current_user_can('edit_tribe_events')) {
        wp_die(__('Insufficient permissions', 'tribe-events-community'));
    }
    
    // Process excerpt
    if (isset($_POST['post_excerpt'])) {
        wp_update_post(array(
            'ID' => $event_id,
            'post_excerpt' => sanitize_textarea_field($_POST['post_excerpt'])
        ));
    }
    
    // Process categories
    if (isset($_POST['tax_input']['tribe_events_cat'])) {
        $categories = array_map('intval', $_POST['tax_input']['tribe_events_cat']);
        wp_set_post_categories($event_id, $categories, false);
    }
    
    // Process featured image
    if (isset($_POST['_thumbnail_id']) && !empty($_POST['_thumbnail_id'])) {
        set_post_thumbnail($event_id, intval($_POST['_thumbnail_id']));
    }
}
```

#### Step 7: Integration with HVAC Field Population System
**Objectives**:
- Modify existing HVAC comprehensive field population for new template
- Update field selectors to target custom fields  
- Test JavaScript population compatibility
- Add fallback mechanisms
- Verify 100% field population success rate

**JavaScript Integration Updates**:
```javascript
// Update comprehensive field population selectors
const fieldSelectors = {
    excerpt: [
        '#post_excerpt',
        'textarea[name="post_excerpt"]'
    ],
    categories: [
        'select[name="tax_input[tribe_events_cat][]"]',
        '.tribe-events-cat-dropdown'
    ],
    featured_image: [
        '#set-post-thumbnail',
        'input[name="_thumbnail_id"]'
    ]
};

// Enhanced population function
function populateCustomFields(eventData) {
    // Excerpt population
    if (eventData.core.excerpt) {
        populateField(fieldSelectors.excerpt, eventData.core.excerpt, 'Excerpt');
    }
    
    // Category selection
    if (eventData.taxonomies.categories.length > 0) {
        populateCategoryField(fieldSelectors.categories, eventData.taxonomies.categories);
    }
    
    // Featured image handling
    if (eventData.featured_image.id) {
        populateFeaturedImage(eventData.featured_image);
    }
}
```

### PHASE 4: TESTING AND DEPLOYMENT

#### Step 8: Comprehensive Testing and Deployment
**Objectives**:
- Run E2E tests with Playwright to verify all fields populate correctly
- Test form submission workflow end-to-end
- Validate security implementation and user permissions
- Deploy to staging server for user acceptance testing
- Create rollback plan and deploy to production

**E2E Testing Script**:
```javascript
// test-custom-template-fields.js
const testFields = [
    { name: 'Event Title', selector: '#post_title', type: 'text' },
    { name: 'Event Description', selector: '#tcepostcontent', type: 'tinymce' },
    { name: 'Event Excerpt', selector: '#post_excerpt', type: 'textarea' },
    { name: 'Categories', selector: 'select[name="tax_input[tribe_events_cat][]"]', type: 'select' },
    { name: 'Featured Image', selector: '#set-post-thumbnail', type: 'media' },
    // ... all other fields
];

async function testCustomTemplateFields() {
    // Test field population
    // Test form submission
    // Test data persistence
    // Validate 100% success rate
}
```

---

## CRITICAL SUCCESS FACTORS

### Technical Requirements

**Template Override Structure**:
- File location: `/wp-content/themes/[theme]/tribe/community/edit-event.php`
- Version compatibility tracking in template header
- Proper WordPress/TEC hook integration
- Backup of original TEC template

**Security Implementation**:
- WordPress nonce verification for all custom fields
- User capability checks (`edit_tribe_events` permission)
- Input sanitization using WordPress sanitization functions
- Form validation matching TEC standards

**Field Integration Strategy**:
```
Original TEC Fields          New WordPress Fields
┌─────────────────┐         ┌──────────────────┐
│ Title           │         │ Excerpt          │
│ Description     │    +    │ Categories       │
│ Venue/Organizer │         │ Featured Image   │
│ Date/Time/Cost  │         │ Custom Meta      │
└─────────────────┘         └──────────────────┘
           ↓                           ↓
    [Existing 81% Success]    [Target 19% Gap]
           ↓                           ↓
         [Combined 100% Success Rate]
```

### Compatibility Considerations

**Plugin Dependencies**:
- TEC Community Events plugin (6.0+)
- The Events Calendar core plugin
- WordPress 5.8+ for template override support

**Update Resilience**:
- Template override system protects against plugin updates
- Version tracking enables compatibility monitoring
- Hooks provide upgrade-safe extension points
- Fallback to original template if customization fails

**Theme Integration**:
- Astra theme compatibility maintained
- CSS styling matches existing TEC form design
- Responsive design for mobile devices
- HVAC plugin integration preserved

---

## RISK MITIGATION STRATEGY

### Early Validation Points

**Step 2 Checkpoint**: 
- Template override system functional verification
- Excerpt field implementation success
- No breaking changes to existing functionality

**Step 4 Checkpoint**:
- Field analysis completeness validation
- WordPress integration approach verification
- Processing mechanism compatibility confirmed

**Step 6 Checkpoint**:
- Security implementation tested
- Form processing workflow validated  
- Data persistence confirmed

### Fallback Strategy

**If Template Override Fails**:
- Fallback to enhanced JavaScript approach (current 81% success)
- Original shortcode-based system remains intact
- No disruption to existing HVAC functionality

**Rollback Mechanism**:
- Git version control for safe development
- Backup of original TEC template maintained
- Staging deployment before production
- Quick revert capability via file system

### Monitoring and Maintenance

**Version Compatibility**:
- TEC plugin update monitoring
- Template compatibility testing
- Automated regression testing
- Documentation of breaking changes

**Performance Monitoring**:
- E2E test success rate tracking
- Form submission performance metrics
- User experience feedback collection
- Error logging and monitoring

---

## EXPECTED OUTCOMES

### Immediate Benefits

**Field Control Achievement**:
- 100% field population success rate (improvement from 81%)
- Complete control over excerpt, categories, featured images
- Direct WordPress field access without API overhead

**User Experience Enhancement**:
- Single, integrated form interface
- Native WordPress field interactions
- Consistent styling with TEC design
- Mobile-responsive field layout

### Long-term Advantages

**Maintainability**:
- Upgrade-safe customization using TEC's official template system
- Clear separation of custom vs. core functionality
- Documented customization approach
- Extensible architecture for future enhancements

**Technical Foundation**:
- Foundation for additional HVAC-specific event features
- Proven approach for future TEC customizations
- Enhanced debugging and development capabilities
- Improved system reliability and performance

---

## IMPLEMENTATION READINESS

### Prerequisites Confirmed

✅ **Strategic Decision**: Template override approach selected over REST API  
✅ **Technical Research**: TEC template system and hooks documented  
✅ **Current System**: 81% success baseline established  
✅ **Requirements**: 100% field control specifications defined  

### Ready for Deployment

This comprehensive plan addresses all technical, security, and compatibility requirements while following WordPress and TEC best practices. The phased approach enables early validation and risk mitigation while building toward the goal of 100% field control.

**Next Steps**: Deploy specialized agents to execute implementation phases with access to this documentation and sequential thinking capabilities.

---

## APPENDICES

### A. Field Mapping Reference
[Detailed field mapping table with WordPress functions]

### B. Security Requirements Checklist  
[Complete security validation checklist]

### C. Testing Scenarios
[Comprehensive E2E testing scenarios]

### D. Deployment Procedures
[Step-by-step deployment and rollback procedures]

---

**Document Control**:
- Author: Claude Code AI Assistant
- Review Required: Development Team Lead
- Implementation Authorization: Project Owner  
- Last Updated: August 12, 2025