#!/bin/bash

# Create extensive test data for test_trainer with realistic patterns and variety

# Load configuration
source bin/deploy-config.sh

echo "=== Creating Extensive Test Data for test_trainer ==="
echo "Remote host: $REMOTE_HOST"
echo "Remote user: $REMOTE_USER"
echo "WordPress path: $REMOTE_PATH_BASE"
echo "==============================="

# Create comprehensive PHP script to run on server
cat << 'EOF' > /tmp/extensive-test-data.php
<?php
/**
 * Extensive Test Data Generator for HVAC Community Events
 * 
 * Creates realistic training event data including:
 * - Past events (6 months back) with full attendee and certificate data
 * - Current/upcoming events with various states
 * - Varied pricing, attendance patterns, and venues
 * - Complete certificate lifecycle (active, revoked, emailed)
 */

// Load WordPress
require_once('wp-load.php');

// Ensure required plugins are active
if (!class_exists('Tribe__Events__Main') || !class_exists('Tribe__Tickets__Main')) {
    die("Required plugins (The Events Calendar or Event Tickets) are not active\n");
}

echo "=== Creating Extensive Test Data for test_trainer ===\n\n";

// Get the test trainer user
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    die("test_trainer user not found. Please create this user first.\n");
}

$trainer_id = $test_trainer->ID;
echo "Found test_trainer user ID: {$trainer_id}\n\n";

// Initialize certificate manager if available
$certificate_manager = null;
if (class_exists('HVAC_Certificate_Manager')) {
    $certificate_manager = HVAC_Certificate_Manager::instance();
    echo "Certificate manager initialized\n";
} else {
    echo "Certificate manager not available - certificates will not be generated\n";
}

// Ensure certificate table exists
if ($certificate_manager) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'hvac_certificates';
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    
    if (!$table_exists && class_exists('HVAC_Certificate_Installer')) {
        echo "Creating certificate table...\n";
        $installer = HVAC_Certificate_Installer::instance();
        $installer->create_tables();
    }
}

// Create certificate storage directory
$upload_dir = wp_upload_dir();
$cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');
if (!file_exists($cert_dir)) {
    wp_mkdir_p($cert_dir);
}

// Define comprehensive event dataset
$event_categories = [
    'Basic' => [
        'price_range' => [150, 300],
        'duration_hours' => [6, 8],
        'capacity_range' => [20, 35],
        'attendance_rate' => 0.85
    ],
    'Intermediate' => [
        'price_range' => [300, 500],
        'duration_hours' => [8, 12],
        'capacity_range' => [15, 25],
        'attendance_rate' => 0.75
    ],
    'Advanced' => [
        'price_range' => [500, 800],
        'duration_hours' => [12, 16],
        'capacity_range' => [10, 20],
        'attendance_rate' => 0.65
    ],
    'Certification' => [
        'price_range' => [800, 1200],
        'duration_hours' => [16, 24],
        'capacity_range' => [8, 15],
        'attendance_rate' => 0.90
    ]
];

// Event templates with variety
$event_templates = [
    // Basic Level Events
    [
        'title' => 'HVAC Fundamentals Workshop',
        'description' => 'Essential HVAC principles for new technicians entering the field.',
        'category' => 'Basic',
        'venue_type' => 'Training Center'
    ],
    [
        'title' => 'Residential HVAC Basics',
        'description' => 'Introduction to residential HVAC systems, components, and basic maintenance.',
        'category' => 'Basic',
        'venue_type' => 'Community College'
    ],
    [
        'title' => 'Safety in HVAC Work',
        'description' => 'Comprehensive safety training for HVAC professionals.',
        'category' => 'Basic',
        'venue_type' => 'Safety Training Center'
    ],
    
    // Intermediate Level Events
    [
        'title' => 'HVAC System Diagnostics',
        'description' => 'Advanced troubleshooting techniques for complex HVAC issues.',
        'category' => 'Intermediate',
        'venue_type' => 'Technical Institute'
    ],
    [
        'title' => 'Commercial HVAC Systems',
        'description' => 'Understanding large-scale commercial HVAC installations and maintenance.',
        'category' => 'Intermediate',
        'venue_type' => 'Industry Training Facility'
    ],
    [
        'title' => 'Heat Pump Technology Workshop',
        'description' => 'Modern heat pump systems, installation, and troubleshooting.',
        'category' => 'Intermediate',
        'venue_type' => 'Manufacturer Training Center'
    ],
    [
        'title' => 'Ductwork Design and Installation',
        'description' => 'Proper ductwork sizing, installation, and air balancing techniques.',
        'category' => 'Intermediate',
        'venue_type' => 'Construction Training Center'
    ],
    
    // Advanced Level Events
    [
        'title' => 'Building Automation Systems',
        'description' => 'Integration of HVAC with smart building control systems.',
        'category' => 'Advanced',
        'venue_type' => 'Technology Center'
    ],
    [
        'title' => 'Variable Refrigerant Flow (VRF) Systems',
        'description' => 'Advanced VRF system design, installation, and maintenance.',
        'category' => 'Advanced',
        'venue_type' => 'Manufacturer Facility'
    ],
    [
        'title' => 'Geothermal HVAC Systems',
        'description' => 'Ground-source heat pump systems and installation techniques.',
        'category' => 'Advanced',
        'venue_type' => 'Green Energy Institute'
    ],
    [
        'title' => 'Advanced Refrigeration Controls',
        'description' => 'Complex refrigeration control systems and electronic diagnostics.',
        'category' => 'Advanced',
        'venue_type' => 'Refrigeration Lab'
    ],
    
    // Certification Level Events
    [
        'title' => 'EPA 608 Certification Prep',
        'description' => 'Comprehensive preparation for EPA Section 608 certification exam.',
        'category' => 'Certification',
        'venue_type' => 'Certification Center'
    ],
    [
        'title' => 'NATE Certification Workshop',
        'description' => 'Preparation for North American Technician Excellence certification.',
        'category' => 'Certification',
        'venue_type' => 'Testing Center'
    ],
    [
        'title' => 'Commercial Refrigeration Certification',
        'description' => 'Professional certification in commercial refrigeration systems.',
        'category' => 'Certification',
        'venue_type' => 'Industry Association'
    ]
];

// Venue locations across different regions
$venues = [
    'Training Center' => [
        'addresses' => [
            '123 Industrial Blvd, Phoenix, AZ 85001',
            '456 Tech Park Way, Denver, CO 80202',
            '789 Training Ave, Atlanta, GA 30303'
        ]
    ],
    'Community College' => [
        'addresses' => [
            '321 College Dr, Orlando, FL 32801',
            '654 Education Rd, Austin, TX 78701',
            '987 Campus Blvd, Sacramento, CA 95814'
        ]
    ],
    'Technical Institute' => [
        'addresses' => [
            '111 Technical Way, Cleveland, OH 44101',
            '222 Institute Dr, Milwaukee, WI 53201',
            '333 Vocational St, Kansas City, MO 64101'
        ]
    ],
    'Manufacturer Training Center' => [
        'addresses' => [
            '444 Industrial Park, Charlotte, NC 28201',
            '555 Manufacturing Dr, Indianapolis, IN 46201',
            '666 Factory Rd, Nashville, TN 37201'
        ]
    ],
    'Technology Center' => [
        'addresses' => [
            '777 Innovation Blvd, Seattle, WA 98101',
            '888 Tech Valley Dr, San Jose, CA 95101',
            '999 Digital Way, Raleigh, NC 27601'
        ]
    ],
    'Safety Training Center' => [
        'addresses' => [
            '147 Safety First St, Houston, TX 77001',
            '258 Protection Ave, Detroit, MI 48201',
            '369 Secure Blvd, Las Vegas, NV 89101'
        ]
    ],
    'Industry Training Facility' => [
        'addresses' => [
            '159 Industry Dr, Pittsburgh, PA 15201',
            '267 Commerce Way, Memphis, TN 38101',
            '375 Trade Center Rd, Oklahoma City, OK 73101'
        ]
    ],
    'Construction Training Center' => [
        'addresses' => [
            '483 Builder St, Louisville, KY 40201',
            '591 Construction Ave, Richmond, VA 23220',
            '627 Contractor Blvd, Salt Lake City, UT 84101'
        ]
    ],
    'Green Energy Institute' => [
        'addresses' => [
            '735 Renewable Dr, Portland, OR 97201',
            '841 Sustainable Way, Burlington, VT 05401',
            '957 Eco-Friendly St, Madison, WI 53701'
        ]
    ],
    'Refrigeration Lab' => [
        'addresses' => [
            '163 Cooling Blvd, Minneapolis, MN 55401',
            '279 Freezer Ave, Buffalo, NY 14201',
            '385 Chiller Dr, Des Moines, IA 50301'
        ]
    ],
    'Certification Center' => [
        'addresses' => [
            '491 Testing Pkwy, Jacksonville, FL 32201',
            '537 Exam Center Dr, Albuquerque, NM 87101',
            '683 Credential Ave, Boise, ID 83701'
        ]
    ],
    'Testing Center' => [
        'addresses' => [
            '729 Assessment St, Fresno, CA 93701',
            '845 Evaluation Way, Tucson, AZ 85701',
            '961 Certification Rd, Spokane, WA 99201'
        ]
    ],
    'Industry Association' => [
        'addresses' => [
            '187 Professional Blvd, Omaha, NE 68101',
            '293 Association Dr, Little Rock, AR 72201',
            '349 Guild Way, Hartford, CT 06101'
        ]
    ]
];

// Diverse attendee names and demographics
$first_names = [
    'James', 'Robert', 'John', 'Michael', 'David', 'William', 'Richard', 'Joseph', 'Christopher', 'Matthew',
    'Mary', 'Patricia', 'Jennifer', 'Linda', 'Elizabeth', 'Barbara', 'Susan', 'Jessica', 'Sarah', 'Karen',
    'Anthony', 'Mark', 'Donald', 'Steven', 'Paul', 'Andrew', 'Joshua', 'Kenneth', 'Kevin', 'Brian',
    'Nancy', 'Lisa', 'Betty', 'Helen', 'Sandra', 'Donna', 'Carol', 'Ruth', 'Sharon', 'Michelle',
    'Daniel', 'Thomas', 'Jose', 'Charles', 'Benjamin', 'Jonathan', 'Frank', 'Gregory', 'Raymond', 'Alexander',
    'Emily', 'Kimberly', 'Deborah', 'Dorothy', 'Amy', 'Angela', 'Ashley', 'Virginia', 'Kathleen', 'Pamela'
];

$last_names = [
    'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez',
    'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson', 'Thomas', 'Taylor', 'Moore', 'Jackson', 'Martin',
    'Lee', 'Perez', 'Thompson', 'White', 'Harris', 'Sanchez', 'Clark', 'Ramirez', 'Lewis', 'Robinson',
    'Walker', 'Young', 'Allen', 'King', 'Wright', 'Scott', 'Torres', 'Nguyen', 'Hill', 'Flores',
    'Green', 'Adams', 'Nelson', 'Baker', 'Hall', 'Rivera', 'Campbell', 'Mitchell', 'Carter', 'Roberts'
];

$email_domains = [
    'gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'aol.com', 'icloud.com',
    'hvactech.com', 'contractormail.com', 'servicepro.net', 'fieldtech.org'
];

// Generate event schedule (6 months past to 6 months future)
$events_to_create = [];
$start_date = new DateTime('-6 months');
$end_date = new DateTime('+6 months');

// Create events throughout the timeline
for ($month = 0; $month < 12; $month++) {
    $current_month = clone $start_date;
    $current_month->add(new DateInterval('P' . $month . 'M'));
    
    // 2-4 events per month with seasonal variation
    $events_this_month = rand(2, 4);
    if ($current_month->format('n') >= 6 && $current_month->format('n') <= 8) {
        $events_this_month = rand(3, 5); // Summer training season
    }
    
    for ($event_num = 0; $event_num < $events_this_month; $event_num++) {
        $template = $event_templates[array_rand($event_templates)];
        $category = $event_categories[$template['category']];
        
        // Random day within the month (avoid weekends for most events)
        $day = rand(1, 28);
        $event_date = clone $current_month;
        $event_date->setDate($current_month->format('Y'), $current_month->format('n'), $day);
        
        // Adjust to weekday
        while ($event_date->format('N') >= 6) { // Weekend
            $event_date->modify('+1 day');
        }
        
        // Random start time (8 AM to 10 AM)
        $start_hour = rand(8, 10);
        $event_date->setTime($start_hour, 0, 0);
        
        // Calculate end date based on duration
        $duration = rand($category['duration_hours'][0], $category['duration_hours'][1]);
        $end_date_obj = clone $event_date;
        $end_date_obj->add(new DateInterval('PT' . $duration . 'H'));
        
        // Generate pricing
        $price = rand($category['price_range'][0], $category['price_range'][1]);
        $capacity = rand($category['capacity_range'][0], $category['capacity_range'][1]);
        
        // Calculate realistic attendance
        $attendance_rate = $category['attendance_rate'] + (rand(-10, 10) / 100); // ±10% variation
        $attendees = max(1, min($capacity, round($capacity * $attendance_rate)));
        
        // Check-in rate varies by event type and timing
        $checkin_rate = 0.85; // Base rate
        if ($template['category'] === 'Certification') {
            $checkin_rate = 0.95; // Higher for certification events
        }
        if ($event_date < new DateTime('-1 month')) {
            $checkin_rate += 0.05; // Slightly higher for past events
        }
        
        $checkins = round($attendees * ($checkin_rate + (rand(-5, 5) / 100)));
        $checkins = max(0, min($attendees, $checkins));
        
        // Select venue
        $venue_addresses = $venues[$template['venue_type']]['addresses'];
        $venue_address = $venue_addresses[array_rand($venue_addresses)];
        
        $events_to_create[] = [
            'title' => $template['title'],
            'description' => $template['description'],
            'category' => $template['category'],
            'venue_type' => $template['venue_type'],
            'venue_address' => $venue_address,
            'start_date' => $event_date->format('Y-m-d H:i:s'),
            'end_date' => $end_date_obj->format('Y-m-d H:i:s'),
            'price' => $price,
            'capacity' => $capacity,
            'attendees' => $attendees,
            'checkins' => $checkins,
            'is_past' => $event_date < new DateTime()
        ];
    }
}

echo "Planning to create " . count($events_to_create) . " events\n\n";

// Create events
$created_events = 0;
$total_attendees = 0;
$total_checkins = 0;
$total_certificates = 0;

foreach ($events_to_create as $event_data) {
    echo "Creating: {$event_data['title']} ({$event_data['start_date']})\n";
    
    // Create event post
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_data['description'],
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::POSTTYPE,
        'post_author' => $trainer_id
    ];
    
    $event_id = wp_insert_post($event_args);
    
    if (is_wp_error($event_id)) {
        echo "  ERROR: Failed to create event: " . $event_id->get_error_message() . "\n";
        continue;
    }
    
    // Add event meta
    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, '_EventStartDateUTC', $event_data['start_date']);
    update_post_meta($event_id, '_EventEndDateUTC', $event_data['end_date']);
    update_post_meta($event_id, '_EventTimezone', 'America/New_York');
    update_post_meta($event_id, '_EventCost', $event_data['price']);
    
    // Create venue
    $venue_name = $event_data['venue_type'] . " - " . explode(',', $event_data['venue_address'])[1];
    $venue_args = [
        'post_title' => trim($venue_name),
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::VENUE_POST_TYPE,
        'post_author' => $trainer_id
    ];
    
    $venue_id = wp_insert_post($venue_args);
    
    if (!is_wp_error($venue_id)) {
        $address_parts = explode(', ', $event_data['venue_address']);
        $city_state = explode(', ', $address_parts[1] ?? '');
        $state_zip = explode(' ', $city_state[1] ?? '');
        
        update_post_meta($venue_id, '_VenueAddress', $address_parts[0] ?? '');
        update_post_meta($venue_id, '_VenueCity', $city_state[0] ?? '');
        update_post_meta($venue_id, '_VenueState', $state_zip[0] ?? '');
        update_post_meta($venue_id, '_VenueZip', $state_zip[1] ?? '');
        update_post_meta($venue_id, '_VenueCountry', 'USA');
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    // Create organizer
    $organizer_args = [
        'post_title' => "HVAC Training Professional",
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::ORGANIZER_POST_TYPE,
        'post_author' => $trainer_id
    ];
    
    $organizer_id = wp_insert_post($organizer_args);
    
    if (!is_wp_error($organizer_id)) {
        update_post_meta($organizer_id, '_OrganizerEmail', 'trainer@hvactraining.com');
        update_post_meta($organizer_id, '_OrganizerPhone', '555-HVAC-PRO');
        update_post_meta($organizer_id, '_OrganizerWebsite', 'https://hvactraining.com');
        update_post_meta($event_id, '_EventOrganizerID', $organizer_id);
    }
    
    // Create ticket (using PayPal provider from Event Tickets Plus)
    $ticket_id = null;
    if (class_exists('Tribe__Tickets_Plus__Commerce__PayPal__Main')) {
        $ticket_args = [
            'post_title' => "Registration - {$event_data['title']}",
            'post_content' => "Ticket for {$event_data['title']}",
            'post_status' => 'publish',
            'post_type' => 'tribe_tpp_tickets',
        ];
        
        $ticket_id = wp_insert_post($ticket_args);
        
        if (!is_wp_error($ticket_id)) {
            update_post_meta($ticket_id, '_tribe_tpp_for_event', $event_id);
            update_post_meta($ticket_id, '_tribe_tpp_enabled', 'yes');
            update_post_meta($ticket_id, '_price', $event_data['price']);
            update_post_meta($ticket_id, '_capacity', $event_data['capacity']);
            update_post_meta($ticket_id, '_stock', max(0, $event_data['capacity'] - $event_data['attendees']));
            update_post_meta($ticket_id, '_manage_stock', 'yes');
            update_post_meta($event_id, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
        }
    }
    
    // Create attendees
    if ($ticket_id && $event_data['attendees'] > 0) {
        $attendee_ids = [];
        
        for ($i = 1; $i <= $event_data['attendees']; $i++) {
            // Generate realistic attendee data
            $first_name = $first_names[array_rand($first_names)];
            $last_name = $last_names[array_rand($last_names)];
            $domain = $email_domains[array_rand($email_domains)];
            $email = strtolower($first_name . '.' . $last_name . '.' . rand(100, 999) . '@' . $domain);
            
            // Special case for first attendee
            if ($i === 1) {
                $first_name = "Ben";
                $last_name = "Tester";
                $email = "ben@tealmaker.com";
            }
            
            // Create attendee post
            $attendee_args = [
                'post_title' => "{$first_name} {$last_name}",
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'tribe_tpp_attendees',
            ];
            
            $attendee_id = wp_insert_post($attendee_args);
            
            if (is_wp_error($attendee_id)) {
                continue;
            }
            
            $attendee_ids[] = $attendee_id;
            
            // Add attendee meta
            $order_id = 'ORDER-' . $event_id . '-' . str_pad($i, 3, '0', STR_PAD_LEFT) . '-' . uniqid();
            $security_code = wp_generate_password(10, false);
            
            $meta_fields = [
                '_tribe_tickets_full_name' => "{$first_name} {$last_name}",
                '_tribe_tickets_email' => $email,
                '_tribe_tpp_full_name' => "{$first_name} {$last_name}",
                '_tribe_tpp_email' => $email,
                '_tribe_tpp_event' => $event_id,
                '_tribe_tpp_product' => $ticket_id,
                '_tribe_tpp_order' => $order_id,
                '_tribe_tpp_security_code' => $security_code,
                '_tribe_tickets_order_status' => 'complete',
                '_tribe_tpp_attendee_optout' => 'no',
                '_tribe_tickets_attendee_user_id' => 0,
            ];
            
            foreach ($meta_fields as $key => $value) {
                update_post_meta($attendee_id, $key, $value);
            }
            
            // Check in attendees based on calculated rate
            if ($i <= $event_data['checkins']) {
                update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
                update_post_meta($attendee_id, '_tribe_tpp_checked_in', 1);
                update_post_meta($attendee_id, '_tribe_tickets_checkin_status', 1);
                update_post_meta($attendee_id, 'check_in', 1);
                update_post_meta($attendee_id, '_tribe_tpp_checkin_status', 1);
            }
        }
        
        // Update ticket and event counts
        update_post_meta($ticket_id, '_tribe_tpp_sold', $event_data['attendees']);
        update_post_meta($ticket_id, '_tribe_ticket_sold', $event_data['attendees']);
        update_post_meta($event_id, '_tribe_ticket_sold_count', $event_data['attendees']);
        
        $total_attendees += $event_data['attendees'];
        $total_checkins += $event_data['checkins'];
    }
    
    // Generate certificates for past events with check-ins
    if ($certificate_manager && $event_data['is_past'] && $event_data['checkins'] > 0) {
        $checked_in_attendees = get_posts([
            'post_type' => 'tribe_tpp_attendees',
            'meta_query' => [
                'relation' => 'AND',
                [
                    'key' => '_tribe_tpp_event',
                    'value' => $event_id,
                ],
                [
                    'key' => '_tribe_tpp_checkin',
                    'value' => 1,
                ]
            ],
            'posts_per_page' => -1
        ]);
        
        $certificates_created = 0;
        $certificates_revoked = 0;
        $certificates_emailed = 0;
        
        foreach ($checked_in_attendees as $attendee) {
            $attendee_id = $attendee->ID;
            
            // Skip if certificate already exists
            if ($certificate_manager->certificate_exists($event_id, $attendee_id)) {
                continue;
            }
            
            // Create certificate file path
            $year = date('Y', strtotime($event_data['start_date']));
            $month = date('m', strtotime($event_data['start_date']));
            $certificate_filename = "certificate-{$event_id}-{$attendee_id}-" . time() . ".pdf";
            $certificate_relative_path = "hvac-certificates/{$year}/{$month}/{$certificate_filename}";
            
            // Create directory structure
            $year_month_dir = $cert_dir . "/{$year}/{$month}";
            if (!file_exists($year_month_dir)) {
                wp_mkdir_p($year_month_dir);
            }
            
            // Create certificate record
            $certificate_id = $certificate_manager->create_certificate(
                $event_id,
                $attendee_id,
                0, // user_id
                $certificate_relative_path,
                $trainer_id
            );
            
            if ($certificate_id) {
                $certificates_created++;
                $total_certificates++;
                
                // Create placeholder certificate file
                $certificate_full_path = $upload_dir['basedir'] . '/' . $certificate_relative_path;
                file_put_contents($certificate_full_path, "Placeholder for certificate PDF (Generated for testing)");
                
                // Randomly vary certificate states for testing
                $random = mt_rand(1, 100);
                
                // Revoke ~5% of certificates
                if ($random <= 5) {
                    $certificate_manager->revoke_certificate(
                        $certificate_id,
                        $trainer_id,
                        "Test revocation for data variety"
                    );
                    $certificates_revoked++;
                }
                
                // Mark ~80% as emailed
                if ($random <= 80) {
                    $certificate_manager->mark_certificate_emailed($certificate_id);
                    $certificates_emailed++;
                }
            }
        }
        
        if ($certificates_created > 0) {
            echo "  Generated {$certificates_created} certificates ({$certificates_revoked} revoked, {$certificates_emailed} emailed)\n";
        }
    }
    
    $created_events++;
    echo "  Event created successfully (ID: {$event_id})\n";
}

echo "\n=== Test Data Creation Summary ===\n";
echo "Events created: {$created_events}\n";
echo "Total attendees: {$total_attendees}\n";
echo "Total check-ins: {$total_checkins}\n";
echo "Total certificates: {$total_certificates}\n";

// Get certificate statistics if available
if ($certificate_manager && class_exists('HVAC_Certificate_Manager')) {
    try {
        $stats = $certificate_manager->get_certificate_stats();
        echo "\nFinal Certificate Statistics:\n";
        echo "Total certificates in system: {$stats['total_certificates']}\n";
        echo "Events with certificates: {$stats['total_events']}\n";
        echo "Trainees with certificates: {$stats['total_trainees']}\n";
        echo "Revoked certificates: {$stats['total_revoked']}\n";
        echo "Emailed certificates: {$stats['total_emailed']}\n";
    } catch (Exception $e) {
        echo "Could not retrieve certificate statistics: " . $e->getMessage() . "\n";
    }
}

echo "\nExtensive test data creation completed!\n";
echo "The system now contains realistic training data spanning 12 months\n";
echo "with varied events, pricing, attendance patterns, and certificate states.\n";
?>
EOF

# Copy PHP script to server and execute
echo "[1;33mCopying extensive test data script to server...[0m"
scp /tmp/extensive-test-data.php $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH_BASE/

echo "[1;33mExecuting extensive test data creation on server...[0m"
ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH_BASE && php extensive-test-data.php"

# Clean up
rm /tmp/extensive-test-data.php
ssh $REMOTE_USER@$REMOTE_HOST "rm $REMOTE_PATH_BASE/extensive-test-data.php"

echo "[0;32mExtensive test data creation completed![0m"
echo ""
echo "=== Created Comprehensive Test Data ==="
echo "✓ 25-40 events spanning 12 months (past and future)"
echo "✓ Varied event types: Basic, Intermediate, Advanced, Certification"
echo "✓ Realistic pricing: \$150-\$1200 based on event complexity"
echo "✓ Diverse venues across multiple states"
echo "✓ Realistic attendance patterns (65-95% capacity)"
echo "✓ Variable check-in rates (80-95%)"
echo "✓ Complete certificate lifecycle for past events"
echo "✓ Varied attendee demographics and email domains"
echo "✓ Comprehensive ticket sales data"
echo ""
echo "Test Features Available:"
echo "• Dashboard analytics with real data trends"
echo "• Event filtering across multiple time periods"
echo "• Certificate reports with various states"
echo "• Revenue tracking across different price points"
echo "• Attendance pattern analysis"
echo "• Geographic distribution of training venues"