/**
 * HVAC TEC Form Fields Injector
 * 
 * This script manually injects form fields when TEC Community Events
 * fails to render them properly. This is a workaround for the TEC bug
 * where forms render with only hidden fields.
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

(function($) {
    'use strict';
    
    const HVACFormInjector = {
        
        /**
         * Initialize the form field injector
         */
        init: function() {
            console.log('[HVAC Form Injector] Initializing...');
            
            // Wait for document ready
            $(document).ready(() => {
                // Check if we're on a page with TEC form
                if ($('form[data-datepicker_format]').length > 0) {
                    this.checkAndInjectFields();
                }
            });
        },
        
        /**
         * Check if form fields exist and inject if missing
         */
        checkAndInjectFields: function() {
            const $form = $('form[data-datepicker_format]');
            
            if (!$form.length) {
                console.log('[HVAC Form Injector] No TEC form found');
                return;
            }
            
            // Check if form has visible fields
            const visibleInputs = $form.find('input:visible:not([type="hidden"])').length;
            const textareas = $form.find('textarea:visible').length;
            
            if (visibleInputs === 0 && textareas === 0) {
                console.log('[HVAC Form Injector] Form has no visible fields, injecting...');
                this.injectFormFields($form);
            } else {
                console.log('[HVAC Form Injector] Form already has fields');
            }
        },
        
        /**
         * Inject the missing form fields
         */
        injectFormFields: function($form) {
            // Create form HTML structure matching TEC's expected layout
            const formHTML = `
                <div class="tribe-section tribe-section-title">
                    <div class="tribe-section-header">
                        <h3>Event Title <span class="required">*</span></h3>
                    </div>
                    <div class="tribe-section-content">
                        <input type="text" 
                               id="EventTitle" 
                               name="post_title" 
                               class="tribe-common-form-control-text__input" 
                               required 
                               placeholder="Enter the event title">
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-content">
                    <div class="tribe-section-header">
                        <h3>Event Description <span class="required">*</span></h3>
                    </div>
                    <div class="tribe-section-content">
                        <textarea id="EventDescription" 
                                  name="post_content" 
                                  rows="8" 
                                  class="tribe-common-form-control-text__input"
                                  required
                                  placeholder="Describe your event in detail"></textarea>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-excerpt">
                    <div class="tribe-section-header">
                        <h3>Event Summary (Excerpt)</h3>
                        <p class="tribe-section-description">
                            Brief summary for search results and previews
                        </p>
                    </div>
                    <div class="tribe-section-content">
                        <textarea id="event_excerpt" 
                                  name="excerpt" 
                                  rows="3" 
                                  class="tribe-common-form-control-text__input"
                                  placeholder="Enter a brief summary of your event..."></textarea>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-datetime">
                    <div class="tribe-section-header">
                        <h3>Event Date & Time <span class="required">*</span></h3>
                    </div>
                    <div class="tribe-section-content">
                        <div class="tribe-datetime-block">
                            <label for="EventStartDate">Start Date/Time:</label>
                            <input type="datetime-local" 
                                   id="EventStartDate" 
                                   name="EventStartDate" 
                                   class="tribe-common-form-control-text__input"
                                   required>
                        </div>
                        <div class="tribe-datetime-block">
                            <label for="EventEndDate">End Date/Time:</label>
                            <input type="datetime-local" 
                                   id="EventEndDate" 
                                   name="EventEndDate" 
                                   class="tribe-common-form-control-text__input"
                                   required>
                        </div>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-venue">
                    <div class="tribe-section-header">
                        <h3>Venue</h3>
                    </div>
                    <div class="tribe-section-content">
                        <select id="EventVenueID" 
                                name="EventVenueID" 
                                class="tribe-common-form-control-select__input">
                            <option value="">Select a venue...</option>
                            <option value="new">+ Create New Venue</option>
                        </select>
                        
                        <div id="new-venue-fields" style="display:none; margin-top: 15px;">
                            <input type="text" 
                                   name="venue[Venue]" 
                                   placeholder="Venue Name"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="text" 
                                   name="venue[Address]" 
                                   placeholder="Address"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="text" 
                                   name="venue[City]" 
                                   placeholder="City"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="text" 
                                   name="venue[State]" 
                                   placeholder="State/Province"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="text" 
                                   name="venue[Zip]" 
                                   placeholder="Zip/Postal Code"
                                   class="tribe-common-form-control-text__input">
                        </div>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-organizer">
                    <div class="tribe-section-header">
                        <h3>Organizer</h3>
                    </div>
                    <div class="tribe-section-content">
                        <select id="EventOrganizerID" 
                                name="EventOrganizerID" 
                                class="tribe-common-form-control-select__input">
                            <option value="">Select an organizer...</option>
                            <option value="new">+ Create New Organizer</option>
                        </select>
                        
                        <div id="new-organizer-fields" style="display:none; margin-top: 15px;">
                            <input type="text" 
                                   name="organizer[Organizer]" 
                                   placeholder="Organizer Name"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="email" 
                                   name="organizer[Email]" 
                                   placeholder="Organizer Email"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="tel" 
                                   name="organizer[Phone]" 
                                   placeholder="Organizer Phone"
                                   class="tribe-common-form-control-text__input"
                                   style="margin-bottom: 10px;">
                            <input type="url" 
                                   name="organizer[Website]" 
                                   placeholder="Organizer Website"
                                   class="tribe-common-form-control-text__input">
                        </div>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-categories">
                    <div class="tribe-section-header">
                        <h3>Event Categories</h3>
                    </div>
                    <div class="tribe-section-content">
                        <div class="tribe-event-categories">
                            <label><input type="checkbox" name="tax_input[tribe_events_cat][]" value="training"> Training</label>
                            <label><input type="checkbox" name="tax_input[tribe_events_cat][]" value="certification"> Certification</label>
                            <label><input type="checkbox" name="tax_input[tribe_events_cat][]" value="workshop"> Workshop</label>
                            <label><input type="checkbox" name="tax_input[tribe_events_cat][]" value="seminar"> Seminar</label>
                        </div>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-tags">
                    <div class="tribe-section-header">
                        <h3>Event Tags</h3>
                        <p class="tribe-section-description">
                            Separate tags with commas
                        </p>
                    </div>
                    <div class="tribe-section-content">
                        <input type="text" 
                               id="EventTags" 
                               name="tax_input[post_tag]" 
                               class="tribe-common-form-control-text__input"
                               placeholder="hvac, training, certification, etc.">
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-image">
                    <div class="tribe-section-header">
                        <h3>Featured Image</h3>
                    </div>
                    <div class="tribe-section-content">
                        <input type="file" 
                               id="EventImage" 
                               name="event_image" 
                               accept="image/*"
                               class="tribe-common-form-control-file__input">
                        <p class="description">Upload an image for your event (JPG, PNG, GIF)</p>
                    </div>
                </div>
                
                <div class="tribe-section tribe-section-submit">
                    <div class="tribe-section-content">
                        <input type="submit" 
                               class="tribe-common-c-btn tribe-common-c-btn--style-primary" 
                               value="Submit Event"
                               style="background: #0073aa; color: white; padding: 10px 20px; font-size: 16px; border: none; border-radius: 4px; cursor: pointer;">
                    </div>
                </div>
            `;
            
            // Insert the fields into the form
            $form.append(formHTML);
            
            // Load existing venues and organizers via AJAX
            this.loadVenuesAndOrganizers();
            
            // Set up event handlers
            this.setupEventHandlers();
            
            console.log('[HVAC Form Injector] Form fields injected successfully');
        },
        
        /**
         * Load venues and organizers via AJAX
         */
        loadVenuesAndOrganizers: function() {
            // Load venues
            if (typeof hvac_ajax !== 'undefined') {
                $.post(hvac_ajax.ajax_url, {
                    action: 'hvac_get_venues',
                    nonce: hvac_ajax.nonce
                }, function(response) {
                    if (response.success && response.data) {
                        const $select = $('#EventVenueID');
                        response.data.forEach(venue => {
                            $select.append(`<option value="${venue.id}">${venue.name}</option>`);
                        });
                    }
                });
                
                // Load organizers
                $.post(hvac_ajax.ajax_url, {
                    action: 'hvac_get_organizers',
                    nonce: hvac_ajax.nonce
                }, function(response) {
                    if (response.success && response.data) {
                        const $select = $('#EventOrganizerID');
                        response.data.forEach(organizer => {
                            $select.append(`<option value="${organizer.id}">${organizer.name}</option>`);
                        });
                    }
                });
            }
        },
        
        /**
         * Set up event handlers for dynamic fields
         */
        setupEventHandlers: function() {
            // Show/hide new venue fields
            $('#EventVenueID').on('change', function() {
                if ($(this).val() === 'new') {
                    $('#new-venue-fields').slideDown();
                } else {
                    $('#new-venue-fields').slideUp();
                }
            });
            
            // Show/hide new organizer fields
            $('#EventOrganizerID').on('change', function() {
                if ($(this).val() === 'new') {
                    $('#new-organizer-fields').slideDown();
                } else {
                    $('#new-organizer-fields').slideUp();
                }
            });
            
            // Form submission handler
            $('form[data-datepicker_format]').on('submit', function(e) {
                console.log('[HVAC Form Injector] Form submitted');
                
                // Validate required fields
                const title = $('#EventTitle').val();
                const description = $('#EventDescription').val();
                const startDate = $('#EventStartDate').val();
                const endDate = $('#EventEndDate').val();
                
                if (!title || !description || !startDate || !endDate) {
                    e.preventDefault();
                    alert('Please fill in all required fields');
                    return false;
                }
                
                // If REST API is available, use it for submission
                if (typeof HVACRestEventSubmission !== 'undefined') {
                    e.preventDefault();
                    HVACRestEventSubmission.submitForm(this);
                    return false;
                }
                
                // Otherwise let the form submit normally
                return true;
            });
        }
    };
    
    // Initialize when document is ready
    $(document).ready(function() {
        HVACFormInjector.init();
    });
    
    // Also try to initialize on window load
    $(window).on('load', function() {
        HVACFormInjector.checkAndInjectFields();
    });
    
})(jQuery);