# HVAC Template System API Documentation **Version**: 2.0 **Date**: September 25, 2025 **Status**: Production Ready --- ## ๐Ÿ“‹ Overview The HVAC Template System API provides comprehensive template management functionality for the HVAC Event Form Builder, including template creation, retrieval, preview, and application capabilities. ## ๐Ÿ—๏ธ Architecture ### Core Components 1. **HVAC_Event_Form_Builder** - Form builder with template integration 2. **HVAC_Event_Template_Manager** - Template CRUD operations 3. **HVAC_Shortcodes** - AJAX handlers for template operations 4. **JavaScript Frontend** - Template UI interactions --- ## ๐Ÿ”ง PHP API Reference ### HVAC_Event_Form_Builder Methods #### `add_template_selector(array $categories = []): self` Adds an enhanced template selector dropdown to the form. **Parameters:** - `$categories` (array) - Optional array of template categories to filter **Returns:** `self` for method chaining **Example:** ```php $form_builder->add_template_selector(['training', 'workshop', 'certification']); ``` #### `add_template_actions(): self` Adds template action buttons including "Save as Template". **Returns:** `self` for method chaining #### `add_progressive_disclosure(): self` Adds the progressive disclosure toggle for advanced options. **Returns:** `self` for method chaining #### `mark_field_as_advanced(string $field_name): self` Marks a specific field as advanced for progressive disclosure. **Parameters:** - `$field_name` (string) - Name of the field to mark as advanced **Returns:** `self` for method chaining **Example:** ```php $form_builder->mark_field_as_advanced('event_capacity') ->mark_field_as_advanced('event_cost'); ``` #### `load_template(string $template_id): bool` Loads template data into the form builder. **Parameters:** - `$template_id` (string) - Template ID to load **Returns:** `bool` - Success status ### HVAC_Shortcodes AJAX Handlers #### `ajax_get_template_preview()` **Action:** `hvac_get_template_preview` **Method:** POST **Authentication:** Required (trainer role) **Request Parameters:** - `template_id` (string) - Template ID to preview - `nonce` (string) - WordPress nonce for security **Response:** ```json { "success": true, "data": { "id": "template_123", "name": "Basic Training Template", "description": "Standard template for training events", "category": "training", "field_data": { "event_title": "Sample Training Event", "event_description": "...", "event_capacity": "50" }, "created_by": 1, "created_at": "2025-09-25 12:00:00" } } ``` #### `ajax_load_template_data()` **Action:** `hvac_load_template_data` **Method:** POST **Authentication:** Required (trainer role) **Request Parameters:** - `template_id` (string) - Template ID to load - `nonce` (string) - WordPress nonce for security **Response:** ```json { "success": true, "data": { "event_title": "Sample Training Event", "event_description": "Comprehensive training session", "event_capacity": "50", "event_cost": "299.00" } } ``` #### `ajax_save_template()` **Action:** `hvac_save_template` **Method:** POST **Authentication:** Required (trainer role) **Request Parameters:** - `template_name` (string) - Template name - `template_description` (string) - Template description - `template_category` (string) - Template category - `is_public` (bool) - Whether template is public - `field_data` (object) - Form field data to save - `nonce` (string) - WordPress nonce for security **Response:** ```json { "success": true, "data": { "message": "Template saved successfully", "template_id": "template_456" } } ``` --- ## ๐ŸŽจ JavaScript API Reference ### Template Preview Functions #### `hvacShowTemplatePreview(templateId)` Shows the template preview modal for the specified template. **Parameters:** - `templateId` (string) - Template ID to preview **Example:** ```javascript hvacShowTemplatePreview('template_123'); ``` #### `hvacCloseTemplatePreview()` Closes the template preview modal. #### `hvacApplyTemplate()` Applies the currently previewed template to the form. ### Save Template Functions #### `hvacShowSaveTemplateDialog(event)` Shows the save template dialog. **Parameters:** - `event` (Event) - Click event to prevent default #### `hvacCloseSaveDialog()` Closes the save template dialog. #### `hvacSaveAsTemplate()` Saves the current form as a new template. ### Progressive Disclosure Functions #### `hvacToggleAdvancedOptions()` Toggles the visibility of advanced form options with animations. ### Auto-save Functions #### `performAutoSave()` Performs an auto-save of the current form state. #### `attemptDraftRecovery()` Attempts to recover draft data on page load. #### `updateAutoSaveStatus(status, message)` Updates the auto-save status indicator. **Parameters:** - `status` (string) - Status type: 'saving', 'saved', 'error', 'draft-loaded' - `message` (string) - Optional custom message --- ## ๐Ÿ—„๏ธ Data Structures ### Template Object Structure ```javascript { id: "template_123", name: "Training Template", description: "Standard training event template", category: "training", is_public: true, field_data: { event_title: "Sample Title", event_description: "Sample Description", event_capacity: "50", event_cost: "299.00" }, meta_data: { source: "event_form", created_at: "2025-09-25T12:00:00Z", user_ip: "192.168.1.1" }, created_by: 1, created_at: "2025-09-25 12:00:00" } ``` ### Auto-save Data Structure ```javascript { formData: { event_title: "Event Title", event_description: "Event Description", // ... other form fields }, timestamp: "2025-09-25T12:00:00.000Z", url: "https://example.com/trainer/events/create/", version: "2.0" } ``` --- ## ๐Ÿ”’ Security Implementation ### Authentication & Authorization - **Required Role:** `hvac_trainer` or `hvac_master_trainer` - **Nonce Verification:** All AJAX requests require valid WordPress nonce - **Permission Checks:** Role validation on all template operations ### Input Sanitization ```php // Template data sanitization $template_name = sanitize_text_field($_POST['template_name']); $template_description = sanitize_textarea_field($_POST['template_description']); $template_category = sanitize_text_field($_POST['template_category']); // Field data sanitization foreach ($field_data as $key => $value) { $sanitized_key = sanitize_key($key); if (is_array($value)) { $sanitized_field_data[$sanitized_key] = array_map('sanitize_text_field', $value); } else { $sanitized_field_data[$sanitized_key] = sanitize_text_field($value); } } ``` ### Error Handling - **Template Not Found:** Returns appropriate error messages - **Permission Denied:** Blocks unauthorized access attempts - **Validation Failures:** Provides specific validation error messages - **Storage Limits:** Handles localStorage quota exceeded gracefully --- ## ๐ŸŽฏ Usage Examples ### Creating a Form with Template Support ```php // Initialize form builder with template support $form_builder = new HVAC_Event_Form_Builder('hvac_event_form', true); // Create form with all template features $form_builder->create_event_form([ 'include_template_selector' => true, 'include_venue_fields' => true, 'include_organizer_fields' => true, 'include_cost_fields' => true, 'include_capacity_fields' => true, 'include_datetime_fields' => true, 'template_categories' => ['general', 'training', 'workshop', 'certification'] ]); // Render the form echo $form_builder->render(); ``` ### JavaScript Template Integration ```javascript jQuery(document).ready(function($) { // Initialize template selector functionality $(document).on('change', '[name="event_template"]', function() { const templateId = $(this).val(); if (templateId && templateId !== '0') { hvacShowTemplatePreview(templateId); } }); // Initialize auto-save createAutoSaveIndicator(); setTimeout(attemptDraftRecovery, 500); // Initialize progressive disclosure if ($('.advanced-field').length > 0) { setupAdvancedFieldGroups(); } }); ``` ### Custom Template Categories ```php // Define custom template categories $custom_categories = [ 'certification' => 'Certification Events', 'webinar' => 'Online Webinars', 'conference' => 'Conference Sessions', 'workshop' => 'Hands-on Workshops' ]; // Add template selector with custom categories $form_builder->add_template_selector(array_keys($custom_categories)); ``` --- ## ๐Ÿ“Š Performance Considerations ### Auto-save Optimization - **Debounce Timing:** 1-3 seconds based on field type - **Selective Storage:** Only saves fields with meaningful content - **Quota Management:** Falls back to essential fields if storage full - **Background Operation:** Uses `visibilitychange` for tab switching ### Template Loading - **Cached Results:** Template lists cached for performance - **AJAX Optimization:** Minimal data transfer for preview/apply operations - **Progressive Loading:** Templates loaded on demand ### Animation Performance - **CSS Transitions:** Hardware-accelerated transforms - **Staggered Reveals:** 50ms delays prevent janky animations - **Efficient Selectors:** Optimized jQuery selectors --- ## ๐Ÿงช Testing Guidelines ### Unit Testing ```php // Test template creation $template_data = [ 'name' => 'Test Template', 'category' => 'testing', 'field_data' => ['event_title' => 'Test Event'] ]; $result = $template_manager->create_template($template_data); $this->assertTrue($result['success']); ``` ### Integration Testing ```javascript // Test template preview functionality QUnit.test('Template Preview', function(assert) { const done = assert.async(); hvacShowTemplatePreview('test_template_123'); setTimeout(function() { assert.ok($('#hvac-template-preview').is(':visible'), 'Preview modal shown'); done(); }, 500); }); ``` ### Auto-save Testing ```javascript // Test auto-save functionality QUnit.test('Auto-save Operation', function(assert) { $('#event-title').val('Test Event').trigger('input'); setTimeout(function() { const draftData = localStorage.getItem('hvac_event_draft'); assert.ok(draftData, 'Draft data saved'); const parsed = JSON.parse(draftData); assert.equal(parsed.formData.event_title, 'Test Event', 'Title saved correctly'); }, 3500); }); ``` --- ## ๐Ÿš€ Deployment Notes ### Dependencies - WordPress 5.0+ - jQuery 3.0+ - HVAC Event Template Manager - TEC Core (for event creation) ### File Structure ``` includes/ โ”œโ”€โ”€ class-hvac-event-form-builder.php โ”œโ”€โ”€ class-hvac-shortcodes.php โ””โ”€โ”€ class-hvac-event-template-manager.php templates/ โ””โ”€โ”€ page-tec-create-event.php assets/ โ”œโ”€โ”€ css/ (inline styles in template) โ””โ”€โ”€ js/ (inline scripts in template) ``` ### Configuration ```php // Enable template mode in form builder $form_builder = new HVAC_Event_Form_Builder('form_id', true); // true enables templates // Configure auto-save timing (optional) define('HVAC_AUTOSAVE_DELAY_TEXT', 3000); // 3 seconds for text fields define('HVAC_AUTOSAVE_DELAY_SELECT', 1000); // 1 second for dropdowns ``` --- ## ๐Ÿ“š Related Documentation - **[PHASE-2B-TEMPLATE-SYSTEM-FEATURES.md](PHASE-2B-TEMPLATE-SYSTEM-FEATURES.md)** - Complete feature documentation - **[PHASE-2-TEC-INTEGRATION-ANALYSIS.md](PHASE-2-TEC-INTEGRATION-ANALYSIS.md)** - Integration analysis - **[ARCHITECTURE.md](ARCHITECTURE.md)** - System architecture - **[TROUBLESHOOTING.md](TROUBLESHOOTING.md)** - Common issues and solutions --- ## ๐Ÿ› Troubleshooting ### Common Issues #### Template Preview Not Loading ```javascript // Check AJAX URL and nonce console.log('AJAX URL:', ajaxurl); console.log('Nonce:', $('[name="hvac_event_form_nonce"]').val()); // Verify template ID is valid console.log('Template ID:', templateId); ``` #### Auto-save Not Working ```javascript // Check localStorage availability if (typeof(Storage) !== "undefined") { console.log('localStorage available'); } else { console.log('localStorage not supported'); } // Check for quota exceeded errors try { localStorage.setItem('test', 'data'); console.log('Storage working'); } catch(e) { console.log('Storage error:', e); } ``` #### Progressive Disclosure Issues ```javascript // Check advanced field detection console.log('Advanced fields found:', $('.advanced-field').length); // Verify localStorage state console.log('Advanced options state:', localStorage.getItem('hvac_advanced_options_visible')); ``` --- *API Documentation generated for HVAC Template System v2.0* *๐Ÿค– Generated with [Claude Code](https://claude.ai/code)*