# TEC Community Events - Comprehensive Event Edit Field Population Fix

## Overview

**Issue**: The Events Calendar Community Events plugin has a systematic bug where both `submission_form` and `edit_event` views fail to populate core event fields (title, description, venue, organizer, categories, tags, etc.) when editing existing events.

**Solution**: Comprehensive field population system that uses WordPress/TEC APIs to properly populate ALL form fields for event editing.

## Root Cause Analysis

### TEC Plugin Bug Evidence
- **`[tribe_community_events view="submission_form"]`** ❌ Empty fields
- **`[tribe_community_events view="edit_event" id="123"]`** ❌ Empty fields  
- **Date/time meta fields** ✅ Populate correctly
- **Core post fields & meta** ❌ Always empty

### What Works vs What Doesn't
| Field Type | Status | Notes |
|------------|--------|-------|
| Event Title | ❌ Empty | Core post field |
| Event Description | ❌ Empty | Core post field |
| Start/End Date | ✅ Works | Meta field |
| Start/End Time | ✅ Works | Meta field |
| Venue | ❌ Empty | Taxonomy/Meta |
| Organizer | ❌ Empty | Taxonomy/Meta |
| Categories | ❌ Empty | Taxonomy |
| Tags | ❌ Empty | Taxonomy |
| Event Image | ❌ Empty | Featured image |
| Virtual Event | ❌ Empty | Meta field |
| Tickets/RSVP | ❌ Empty | Complex meta |

## Technical Architecture

### Current Implementation Status
- **JavaScript workaround**: Partially working (title/description only)
- **TEC edit_event view**: Confirmed broken
- **Need**: Comprehensive solution for ALL fields

### Required Data Sources
1. **Core Event Data**: `get_post($event_id)`
2. **Event Meta**: `get_post_meta($event_id, '_*')`
3. **Venues**: `tribe_get_venue_id($event_id)` + venue data
4. **Organizers**: `tribe_get_organizer_id($event_id)` + organizer data
5. **Taxonomies**: `wp_get_post_terms($event_id, 'tribe_events_cat')`
6. **Featured Image**: `get_post_thumbnail_id($event_id)`

### Implementation Strategy
1. **Server-side PHP Class**: Get all event data via WordPress/TEC APIs
2. **Client-side JavaScript**: Comprehensive field population after form load
3. **Field Detection**: Robust selectors for all TEC form fields
4. **Data Validation**: Ensure data integrity and security
5. **Performance**: Minimal overhead, only load on edit pages

## Field Population Mapping

### Core Fields
```javascript
// Title
'input[name="post_title"], #post_title' → event.post_title

// Description  
'textarea[name="post_content"], #post_content' → event.post_content
// TinyMCE: tinymce.get('post_content').setContent(content)
```

### Date/Time Fields (Working - for reference)
```javascript
'input[name="EventStartDate"]' → event._EventStartDate
'input[name="EventEndDate"]' → event._EventEndDate
'input[name="EventStartHour"]' → event._EventStartHour
'input[name="EventEndHour"]' → event._EventEndHour
```

### Venue Fields
```javascript
// Venue dropdown/search
'select[name="venue[VenueID]"], input[name="venue[Venue]"]' → venue data
// Venue creation fields
'input[name="venue[Venue]"]' → venue.post_title
'textarea[name="venue[Description]"]' → venue.post_content
'input[name="venue[Address]"]' → venue._VenueAddress
'input[name="venue[City]"]' → venue._VenueCity
'input[name="venue[State]"]' → venue._VenueState
'input[name="venue[Province]"]' → venue._VenueProvince
'input[name="venue[Zip]"]' → venue._VenueZip
'input[name="venue[Country]"]' → venue._VenueCountry
'input[name="venue[Phone]"]' → venue._VenuePhone
'input[name="venue[URL]"]' → venue._VenueURL
```

### Organizer Fields
```javascript
// Organizer dropdown/search
'select[name="organizer[OrganizerID]"], input[name="organizer[Organizer]"]' → organizer data
// Organizer creation fields
'input[name="organizer[Organizer]"]' → organizer.post_title
'textarea[name="organizer[Description]"]' → organizer.post_content
'input[name="organizer[Phone]"]' → organizer._OrganizerPhone
'input[name="organizer[Website]"]' → organizer._OrganizerWebsite
'input[name="organizer[Email]"]' → organizer._OrganizerEmail
```

### Taxonomy Fields
```javascript
// Categories (checkboxes or select)
'input[name="tax_input[tribe_events_cat][]"]' → event categories
// Tags (text input or select)
'input[name="tax_input[post_tag][]"]' → event tags
```

### Meta Fields
```javascript
// Featured Image
'input[type="file"][name="featured_image"]' → featured image ID
// Virtual Event
'input[name="is_virtual"]' → _VirtualEvent meta
// External URL
'input[name="external_url"]' → _EventURL meta
// Cost
'input[name="EventCost"]' → _EventCost meta
```

## Security Requirements

### Data Validation
```php
// Always verify user can edit event
if (!current_user_can('edit_post', $event_id) && get_post($event_id)->post_author !== get_current_user_id()) {
    wp_die('Permission denied');
}

// Sanitize all output
$event_data = array(
    'title' => sanitize_text_field($post->post_title),
    'content' => wp_kses_post($post->post_content),
    // ... etc
);
```

### Nonce Security
```php
// Include nonce for AJAX security
wp_localize_script('hvac-event-fix', 'hvac_event_data', array(
    'event_data' => $event_data,
    'nonce' => wp_create_nonce('hvac_event_edit_' . $event_id),
    'event_id' => $event_id
));
```

## Implementation Files

### PHP Files to Create/Modify
1. **`includes/class-hvac-event-edit-comprehensive.php`** - Main fix class
2. **`includes/class-hvac-event-data-provider.php`** - Data retrieval class
3. **`assets/js/hvac-event-edit-comprehensive.js`** - Client-side population
4. **`assets/css/hvac-event-edit-fixes.css`** - Visual feedback styles

### WordPress/TEC API Usage
```php
// Core event data
$event = get_post($event_id);
$event_meta = get_post_meta($event_id);

// TEC-specific data
$venue_id = tribe_get_venue_id($event_id);
$venue_data = $venue_id ? get_post($venue_id) : null;
$organizer_id = tribe_get_organizer_id($event_id);
$organizer_data = $organizer_id ? get_post($organizer_id) : null;

// Taxonomies
$categories = wp_get_post_terms($event_id, 'tribe_events_cat');
$tags = wp_get_post_terms($event_id, 'post_tag');

// Featured image
$featured_image_id = get_post_thumbnail_id($event_id);
```

## WordPress CLI Integration

### Test Data Creation
```bash
# Create test events with full data
wp eval '
$event_id = tribe_create_event(array(
    "post_title" => "Test Event with Full Data",
    "post_content" => "Complete event description",
    "_EventStartDate" => "2025-08-15",
    "_EventVenueID" => 123,
    "_EventOrganizerID" => 456
));
echo "Created event: " . $event_id;
'

# Verify event data
wp eval 'var_dump(tribe_get_event(6078));'
```

### Data Verification
```bash
# Check event meta fields
wp post meta list 6078

# Check venue association
wp eval 'echo "Venue ID: " . tribe_get_venue_id(6078);'

# Check organizer association  
wp eval 'echo "Organizer ID: " . tribe_get_organizer_id(6078);'
```

## Testing Strategy

### Test Cases
1. **Empty Form Fix** - Verify all fields populate from existing event data
2. **Partial Data** - Handle events with missing venue/organizer gracefully
3. **Security** - Ensure only authorized users can edit events
4. **Performance** - Minimal impact on page load times
5. **Cross-browser** - Test in Safari, Chrome, Firefox
6. **Mobile** - Responsive design for mobile editing

### Test Events Required
```bash
# Complete event (all fields)
wp eval 'echo tribe_create_event(array("post_title" => "Complete Test Event"));'

# Minimal event (title only)
wp eval 'echo tribe_create_event(array("post_title" => "Minimal Test Event"));'

# Event with venue/organizer
wp eval 'echo tribe_create_event(array("post_title" => "Event with Associations"));'
```

## User Experience

### Visual Feedback
- **Green borders** on successfully populated fields
- **Success notification** showing field count populated
- **Loading indicator** during population process
- **Error handling** for failed field population

### Fallback Behavior
- If field population fails, form remains functional
- Console logging for debugging
- Graceful degradation for missing data

## Deployment Steps

1. **Create comprehensive PHP class** with all TEC API calls
2. **Build robust JavaScript** with field detection and population
3. **Add security validation** and error handling
4. **Deploy to staging** and test with real event data
5. **Verify all field types** populate correctly
6. **Test user permissions** and security
7. **Performance test** page load times
8. **Deploy to production** after full verification

## Success Criteria

### Functional Requirements
- ✅ All event fields populate correctly when editing
- ✅ Works with all TEC event types (standard, virtual, recurring)
- ✅ Handles missing data gracefully
- ✅ Security validated (user permissions, nonces)
- ✅ Performance impact < 100ms additional load time

### User Experience
- ✅ Visual confirmation of field population
- ✅ No JavaScript errors in console
- ✅ Form remains fully functional
- ✅ Works across all supported browsers
- ✅ Mobile-responsive

## Environment Variables

From `.env` file:
```bash
# WordPress/TEC access for testing
UPSKILL_STAGING_IP=146.190.76.204
UPSKILL_STAGING_SSH_USER=roodev
UPSKILL_STAGING_PATH=/home/974670.cloudwaysapps.com/uberrxmprk/public_html
```

## Known Limitations

1. **TEC Plugin Dependency** - Requires TEC Community Events to be active
2. **JavaScript Dependency** - Won't work with JS disabled (acceptable trade-off)
3. **Complex Fields** - Some advanced TEC fields may require special handling
4. **Performance** - Additional API calls on edit page load

## Maintenance Notes

- **Monitor TEC updates** - Plugin updates may fix or break field population
- **Test after WordPress updates** - Core WP changes may affect field selectors
- **Performance monitoring** - Watch for increased page load times
- **User feedback** - Monitor for issues with specific event types or browsers