/**
 * HVAC Venues JavaScript
 *
 * @package HVAC_Community_Events
 * @version 2.0.0
 */

jQuery(document).ready(function($) {
    // Cache DOM elements
    const $venueForm = $('#hvac-venue-form');
    const $deleteButton = $('#hvac-delete-venue');
    const $filterForm = $('.hvac-filter-form');
    
    // Form validation
    function validateVenueForm() {
        let isValid = true;
        const errors = [];
        
        // Clear previous errors
        $('.hvac-form-error').removeClass('hvac-form-error');
        $('.hvac-error-message').remove();
        
        // Required fields
        const requiredFields = [
            { id: 'venue_name', label: 'Venue Name' },
            { id: 'venue_address', label: 'Street Address' },
            { id: 'venue_city', label: 'City' },
            { id: 'venue_state', label: 'State/Province' },
            { id: 'venue_zip', label: 'Zip/Postal Code' },
            { id: 'venue_country', label: 'Country' }
        ];
        
        requiredFields.forEach(field => {
            const $field = $('#' + field.id);
            const value = $field.val();
            
            if (!value || value.trim() === '') {
                isValid = false;
                errors.push(field.label + ' is required');
                $field.addClass('hvac-form-error');
                $field.after('<span class="hvac-error-message">' + field.label + ' is required</span>');
            }
        });
        
        // Validate phone format if provided
        const phone = $('#venue_phone').val();
        if (phone && !isValidPhone(phone)) {
            isValid = false;
            errors.push('Please enter a valid phone number');
            $('#venue_phone').addClass('hvac-form-error');
            $('#venue_phone').after('<span class="hvac-error-message">Please enter a valid phone number</span>');
        }
        
        // Validate website URL if provided
        const website = $('#venue_website').val();
        if (website && !isValidURL(website)) {
            isValid = false;
            errors.push('Please enter a valid website URL');
            $('#venue_website').addClass('hvac-form-error');
            $('#venue_website').after('<span class="hvac-error-message">Please enter a valid website URL</span>');
        }
        
        return isValid;
    }
    
    // Phone validation
    function isValidPhone(phone) {
        // Remove all non-digits
        const digits = phone.replace(/\D/g, '');
        // Check if it's 10 or 11 digits (US/Canada)
        return digits.length >= 10 && digits.length <= 15;
    }
    
    // URL validation
    function isValidURL(url) {
        try {
            new URL(url);
            return true;
        } catch (_) {
            return false;
        }
    }
    
    // Show success message
    function showMessage(message, type = 'success') {
        const messageClass = type === 'success' ? 'hvac-message-success' : 'hvac-message-error';
        const $message = $('<div class="hvac-message ' + messageClass + '">' + message + '</div>');
        
        // Remove any existing messages
        $('.hvac-message').remove();
        
        // Add new message
        $('.hvac-page-header').after($message);
        
        // Auto-hide success messages after 5 seconds
        if (type === 'success') {
            setTimeout(function() {
                $message.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
        
        // Scroll to top
        $('html, body').animate({
            scrollTop: $('.hvac-page-header').offset().top - 100
        }, 300);
    }
    
    // Handle venue form submission
    if ($venueForm.length) {
        $venueForm.on('submit', function(e) {
            e.preventDefault();
            
            // Validate form
            if (!validateVenueForm()) {
                return false;
            }
            
            // Disable submit button
            const $submitButton = $venueForm.find('button[type="submit"]');
            const originalText = $submitButton.text();
            $submitButton.prop('disabled', true).text('Saving...');
            
            // Gather form data
            const formData = {
                action: 'hvac_save_venue',
                nonce: hvacVenues.nonce,
                venue_id: $('input[name="venue_id"]').val(),
                venue_name: $('#venue_name').val(),
                venue_description: $('#venue_description').val(),
                venue_address: $('#venue_address').val(),
                venue_city: $('#venue_city').val(),
                venue_state: $('#venue_state').val(),
                venue_zip: $('#venue_zip').val(),
                venue_country: $('#venue_country').val(),
                venue_phone: $('#venue_phone').val(),
                venue_website: $('#venue_website').val()
            };
            
            // Send AJAX request
            $.ajax({
                url: hvacVenues.ajax_url,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        showMessage(response.data.message, 'success');
                        
                        // If creating new venue, update form to edit mode
                        if (!formData.venue_id && response.data.venue_id) {
                            $('input[name="venue_id"]').val(response.data.venue_id);
                            $('.hvac-page-header h1').text('Edit Venue');
                            $('.hvac-breadcrumb').html('<a href="/trainer/dashboard/">Trainer</a> &gt; <a href="/trainer/venue/list/">Venues</a> &gt; Edit');
                            
                            // Add delete button if not present
                            if (!$('#hvac-delete-venue').length) {
                                const deleteButton = '<button type="button" id="hvac-delete-venue" class="hvac-button hvac-button-danger" data-venue-id="' + response.data.venue_id + '">Delete Venue</button>';
                                $('.hvac-form-actions').append(deleteButton);
                            }
                        }
                        
                        // Update button text
                        $submitButton.text('Update Venue');
                    } else {
                        showMessage(response.data || 'An error occurred while saving the venue.', 'error');
                    }
                },
                error: function() {
                    showMessage('An error occurred. Please try again.', 'error');
                },
                complete: function() {
                    // Re-enable submit button
                    $submitButton.prop('disabled', false).text(originalText);
                }
            });
        });
    }
    
    // Handle venue deletion
    $(document).on('click', '#hvac-delete-venue', function(e) {
        e.preventDefault();
        
        const $deleteButton = $(this);
        const venueId = $deleteButton.data('venue-id');
        
        if (!venueId) {
            showMessage('Invalid venue ID', 'error');
            return;
        }
        
        // Confirm deletion
        if (!confirm('Are you sure you want to delete this venue? This action cannot be undone.')) {
            return;
        }
        
        // Disable button
        $deleteButton.prop('disabled', true).text('Deleting...');
        
        // Send delete request
        $.ajax({
            url: hvacVenues.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_delete_venue',
                nonce: hvacVenues.nonce,
                venue_id: venueId
            },
            success: function(response) {
                if (response.success) {
                    showMessage(response.data || 'Venue deleted successfully.', 'success');
                    
                    // Redirect to venues list after 2 seconds
                    setTimeout(function() {
                        window.location.href = '/trainer/venue/list/';
                    }, 2000);
                } else {
                    showMessage(response.data || 'Failed to delete venue.', 'error');
                    // Re-enable button
                    $deleteButton.prop('disabled', false).text('Delete Venue');
                }
            },
            error: function() {
                showMessage('An error occurred. Please try again.', 'error');
                // Re-enable button
                $deleteButton.prop('disabled', false).text('Delete Venue');
            }
        });
    });
    
    // Handle filter form submission
    if ($filterForm.length) {
        // Prevent form submission on enter in search field
        $filterForm.find('input[name="search"]').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $filterForm.find('button[type="submit"]').click();
            }
        });
    }
    
    // Real-time validation
    $('#venue_phone').on('blur', function() {
        const phone = $(this).val();
        $('.hvac-error-message', $(this).parent()).remove();
        $(this).removeClass('hvac-form-error');
        
        if (phone && !isValidPhone(phone)) {
            $(this).addClass('hvac-form-error');
            $(this).after('<span class="hvac-error-message">Please enter a valid phone number</span>');
        }
    });
    
    $('#venue_website').on('blur', function() {
        const website = $(this).val();
        $('.hvac-error-message', $(this).parent()).remove();
        $(this).removeClass('hvac-form-error');
        
        if (website && !isValidURL(website)) {
            $(this).addClass('hvac-form-error');
            $(this).after('<span class="hvac-error-message">Please enter a valid website URL</span>');
        }
    });
    
    // Auto-format phone number
    $('#venue_phone').on('input', function() {
        let value = $(this).val().replace(/\D/g, '');
        
        if (value.length > 0) {
            if (value.length <= 3) {
                value = value;
            } else if (value.length <= 6) {
                value = value.slice(0, 3) + '-' + value.slice(3);
            } else if (value.length <= 10) {
                value = value.slice(0, 3) + '-' + value.slice(3, 6) + '-' + value.slice(6);
            } else {
                value = value.slice(0, 3) + '-' + value.slice(3, 6) + '-' + value.slice(6, 10);
            }
        }
        
        $(this).val(value);
    });
});