#!/bin/bash
# Create Complete Test Events with Comprehensive Data
# Creates new events with all field types populated for testing field population system

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Load environment variables
if [ -f .env ]; then
    source .env
else
    echo -e "${RED}Error: .env file not found${NC}"
    exit 1
fi

echo -e "${BLUE}=== Create Comprehensive Test Events ===${NC}"
echo "This script creates new events with full venue, organizer, category, tag, cost, and image data"
echo

# SSH connection details
SSH_USER="${UPSKILL_STAGING_SSH_USER}"
SSH_HOST="${UPSKILL_STAGING_IP}"
SITE_PATH="${UPSKILL_STAGING_PATH}"

echo -e "${YELLOW}Connecting to staging server...${NC}"

# Main event creation function
ssh ${SSH_USER}@${SSH_HOST} "cd ${SITE_PATH} && wp eval \"
echo \\\"=== CREATING COMPREHENSIVE TEST EVENTS ===\\n\\\";

// Get current user (assuming test_trainer is logged in or we'll use admin)
\\\$current_user = wp_get_current_user();
\\\$author_id = \\\$current_user->ID ? \\\$current_user->ID : 1;

// Get or create venues
\\\$venues = get_posts(array('post_type' => 'tribe_venue', 'numberposts' => 5));
if (empty(\\\$venues)) {
    echo \\\"No venues found, creating new ones...\\n\\\";
    // Create a venue if none exist
    \\\$venue_id = wp_insert_post(array(
        'post_title' => 'Comprehensive Test Venue',
        'post_content' => 'A fully equipped training facility for HVAC professionals.',
        'post_status' => 'publish',
        'post_type' => 'tribe_venue',
        'post_author' => \\\$author_id
    ));
    update_post_meta(\\\$venue_id, '_VenueAddress', '123 Test Street');
    update_post_meta(\\\$venue_id, '_VenueCity', 'Test City');
    update_post_meta(\\\$venue_id, '_VenueState', 'Test State');
    update_post_meta(\\\$venue_id, '_VenueZip', '12345');
    update_post_meta(\\\$venue_id, '_VenueCountry', 'United States');
    update_post_meta(\\\$venue_id, '_VenuePhone', '(555) 123-4567');
    update_post_meta(\\\$venue_id, '_VenueURL', 'https://testvenue.com');
    \\\$venues = array((object)array('ID' => \\\$venue_id));
}

// Get or create organizers
\\\$organizers = get_posts(array('post_type' => 'tribe_organizer', 'numberposts' => 5));
if (empty(\\\$organizers)) {
    echo \\\"No organizers found, creating new ones...\\n\\\";
    // Create an organizer if none exist
    \\\$organizer_id = wp_insert_post(array(
        'post_title' => 'Comprehensive Test Organizer',
        'post_content' => 'Professional HVAC training organization.',
        'post_status' => 'publish',
        'post_type' => 'tribe_organizer',
        'post_author' => \\\$author_id
    ));
    update_post_meta(\\\$organizer_id, '_OrganizerPhone', '(555) 987-6543');
    update_post_meta(\\\$organizer_id, '_OrganizerEmail', 'test@organizer.com');
    update_post_meta(\\\$organizer_id, '_OrganizerWebsite', 'https://testorganizer.com');
    \\\$organizers = array((object)array('ID' => \\\$organizer_id));
}

// Get or create categories
\\\$categories = get_terms(array('taxonomy' => 'tribe_events_cat', 'hide_empty' => false));
if (empty(\\\$categories)) {
    echo \\\"No categories found, creating new ones...\\n\\\";
    \\\$cat_term = wp_insert_term('Test HVAC Category', 'tribe_events_cat');
    if (!is_wp_error(\\\$cat_term)) {
        \\\$categories = array((object)array('term_id' => \\\$cat_term['term_id'], 'name' => 'Test HVAC Category'));
    }
}

// Get or create tags
\\\$tags = get_terms(array('taxonomy' => 'post_tag', 'hide_empty' => false));
if (empty(\\\$tags)) {
    echo \\\"No tags found, creating new ones...\\n\\\";
    \\\$tag_term = wp_insert_term('comprehensive-test', 'post_tag');
    if (!is_wp_error(\\\$tag_term)) {
        \\\$tags = array((object)array('term_id' => \\\$tag_term['term_id'], 'name' => 'comprehensive-test'));
    }
}

// Event templates with comprehensive data
\\\$events_data = array(
    array(
        'title' => 'Comprehensive HVAC Field Population Test Event',
        'content' => 'This is a comprehensive test event created specifically to verify that the field population system works correctly with ALL field types including venue, organizer, categories, tags, cost, and featured image data.',
        'excerpt' => 'Complete test event for field population verification.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+1 week')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+1 week +8 hours')),
        'cost' => '149.00',
        'url' => 'https://example.com/comprehensive-test-event',
        'all_day' => false
    ),
    array(
        'title' => 'Advanced Systems Test Event with Full Data',
        'content' => 'An advanced HVAC systems training event with complete venue, organizer, taxonomy, and meta field data for comprehensive field population testing.',
        'excerpt' => 'Advanced systems training with comprehensive data.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+2 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+2 weeks +6 hours')),
        'cost' => '249.00',
        'url' => 'https://example.com/advanced-systems-test',
        'all_day' => false
    ),
    array(
        'title' => 'Full-Day Comprehensive Training Workshop',
        'content' => 'A full-day workshop designed to test all aspects of the comprehensive field population system including all-day events, multiple categories, and extensive meta data.',
        'excerpt' => 'Full-day workshop for complete system testing.',
        'start_date' => date('Y-m-d', strtotime('+3 weeks')),
        'end_date' => date('Y-m-d', strtotime('+3 weeks')),
        'cost' => '399.00',
        'url' => 'https://example.com/full-day-workshop',
        'all_day' => true
    )
);

foreach (\\\$events_data as \\\$index => \\\$event_data) {
    echo \\\"\\nCreating event: \\\" . \\\$event_data['title'] . \\\"\\n\\\";
    
    // Create the event
    \\\$event_id = wp_insert_post(array(
        'post_title' => \\\$event_data['title'],
        'post_content' => \\\$event_data['content'],
        'post_excerpt' => \\\$event_data['excerpt'],
        'post_status' => 'pending',
        'post_type' => 'tribe_events',
        'post_author' => \\\$author_id
    ));
    
    if (\\\$event_id) {
        echo \\\"  ✓ Event created with ID: \\\$event_id\\n\\\";
        
        // Set event date/time
        update_post_meta(\\\$event_id, '_EventStartDate', \\\$event_data['start_date']);
        update_post_meta(\\\$event_id, '_EventEndDate', \\\$event_data['end_date']);
        update_post_meta(\\\$event_id, '_EventAllDay', \\\$event_data['all_day'] ? 'yes' : 'no');
        update_post_meta(\\\$event_id, '_EventTimezone', 'America/Denver');
        echo \\\"  ✓ Date/time set\\n\\\";
        
        // Assign venue
        \\\$venue = \\\$venues[\\\$index % count(\\\$venues)];
        update_post_meta(\\\$event_id, '_EventVenueID', \\\$venue->ID);
        echo \\\"  ✓ Venue assigned (ID: \\\" . \\\$venue->ID . \\\")\\n\\\";
        
        // Assign organizer
        \\\$organizer = \\\$organizers[\\\$index % count(\\\$organizers)];
        update_post_meta(\\\$event_id, '_EventOrganizerID', \\\$organizer->ID);
        echo \\\"  ✓ Organizer assigned (ID: \\\" . \\\$organizer->ID . \\\")\\n\\\";
        
        // Assign categories (2-3 categories per event)
        if (!empty(\\\$categories)) {
            \\\$event_categories = array_slice(\\\$categories, 0, 2 + (\\\$index % 2));
            \\\$category_ids = array_map(function(\\\$cat) { return \\\$cat->term_id; }, \\\$event_categories);
            wp_set_post_terms(\\\$event_id, \\\$category_ids, 'tribe_events_cat');
            echo \\\"  ✓ Categories assigned: \\\" . implode(', ', \\\$category_ids) . \\\"\\n\\\";
        }
        
        // Assign tags (3-4 tags per event)
        if (!empty(\\\$tags)) {
            \\\$event_tags = array_slice(\\\$tags, 0, 3 + (\\\$index % 2));
            \\\$tag_ids = array_map(function(\\\$tag) { return \\\$tag->term_id; }, \\\$event_tags);
            wp_set_post_terms(\\\$event_id, \\\$tag_ids, 'post_tag');
            echo \\\"  ✓ Tags assigned: \\\" . implode(', ', \\\$tag_ids) . \\\"\\n\\\";
        }
        
        // Set cost and currency
        update_post_meta(\\\$event_id, '_EventCost', \\\$event_data['cost']);
        update_post_meta(\\\$event_id, '_EventCurrencySymbol', '$');
        update_post_meta(\\\$event_id, '_EventCurrencyPosition', 'prefix');
        echo \\\"  ✓ Cost set: $\\\" . \\\$event_data['cost'] . \\\"\\n\\\";
        
        // Set external URL
        update_post_meta(\\\$event_id, '_EventURL', \\\$event_data['url']);
        echo \\\"  ✓ External URL set\\n\\\";
        
        // Set additional meta fields for comprehensive testing
        update_post_meta(\\\$event_id, '_EventShowMap', '1');
        update_post_meta(\\\$event_id, '_EventShowMapLink', '1');
        
        // Create and assign featured image
        \\\$image_url = 'https://via.placeholder.com/1200x800/2196F3/FFFFFF?text=Comprehensive+Test+Event+' . (\\\$index + 1);
        \\\$image_id = media_sideload_image(\\\$image_url, \\\$event_id, 'Comprehensive Test Event Featured Image', 'id');
        if (!is_wp_error(\\\$image_id)) {
            set_post_thumbnail(\\\$event_id, \\\$image_id);
            echo \\\"  ✓ Featured image set (ID: \\\$image_id)\\n\\\";
        }
        
        // For first event, also mark it as virtual for virtual event testing
        if (\\\$index === 0) {
            update_post_meta(\\\$event_id, '_VirtualEvent', 'yes');
            update_post_meta(\\\$event_id, '_VirtualURL', 'https://example.com/virtual-meeting');
            echo \\\"  ✓ Virtual event settings applied\\n\\\";
        }
        
        echo \\\"  ✓ Event \\\" . \\\$event_data['title'] . \\\" created successfully!\\n\\\";
    } else {
        echo \\\"  ✗ Failed to create event: \\\" . \\\$event_data['title'] . \\\"\\n\\\";
    }
}

echo \\\"\\n=== COMPREHENSIVE TEST EVENTS CREATED ===\\n\\\";
echo \\\"All events have been created with complete data for testing:\\n\\\";
echo \\\"- Venues assigned\\n\\\";
echo \\\"- Organizers assigned\\n\\\";
echo \\\"- Categories and tags assigned\\n\\\";
echo \\\"- Cost information set\\n\\\";
echo \\\"- External URLs configured\\n\\\";
echo \\\"- Featured images attached\\n\\\";
echo \\\"- Virtual event settings (for first event)\\n\\\";
echo \\\"\\nThese events can now be used to test comprehensive field population!\\n\\\";
\""

echo
echo -e "${GREEN}✓ Comprehensive test events created successfully!${NC}"
echo
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Log in to staging as a trainer user"
echo "2. Navigate to the trainer dashboard to see the new events"
echo "3. Click 'Edit' on any of the new comprehensive test events"
echo "4. Verify that ALL fields are populated by the comprehensive system"