#!/bin/bash

# Create comprehensive test data using RSVP tickets

echo "=== Creating Test Data with RSVP Tickets on Staging Server ==="
echo "Remote host: 146.190.76.204"
echo "Remote user: roodev"
echo "==============================="

# Create the PHP script
cat > rsvp-test-data.php << 'EOL'
<?php
/**
 * Test Data Generator with RSVP Tickets
 * 
 * Creates events, RSVP tickets, attendees, check-ins, and certificates for testing
 */

// 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");
}

// Certificate manager is required for certificate generation
if (!class_exists('HVAC_Certificate_Manager')) {
    die("HVAC Certificate Manager class not found. Please activate the HVAC Community Events plugin.");
}

echo "=== Creating test data with RSVP tickets ===\n\n";

// Initialize certificate manager
$certificate_manager = HVAC_Certificate_Manager::instance();

// Check for certificate table and create if needed
global $wpdb;
$table_name = $wpdb->prefix . 'hvac_certificates';
$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;

if (!$table_exists) {
    echo "Certificate table does not exist. Creating it now...\n";
    
    if (class_exists('HVAC_Certificate_Installer')) {
        $installer = HVAC_Certificate_Installer::instance();
        $installer->create_tables();
        
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        if (!$table_exists) {
            die("Failed to create certificate table. Exiting.\n");
        }
        
        echo "Certificate table created successfully.\n";
    } else {
        die("Error: HVAC_Certificate_Installer class not found. Exiting.\n");
    }
}

// Create certificate storage directory if it doesn't exist
$upload_dir = wp_upload_dir();
$cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');

if (!file_exists($cert_dir)) {
    echo "Certificate directory does not exist. Creating it now...\n";
    $result = wp_mkdir_p($cert_dir);
    if (!$result) {
        die("Failed to create certificate directory at: {$cert_dir}\n");
    }
    echo "Certificate directory created at: {$cert_dir}\n";
}

// Get or create test trainer user
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    echo "test_trainer user not found, creating one...\n";
    
    $user_id = wp_create_user('test_trainer', wp_generate_password(12, false), 'test_trainer@example.com');
    
    if (is_wp_error($user_id)) {
        die("Failed to create test_trainer user: " . $user_id->get_error_message() . "\n");
    }
    
    // Set role and update user meta
    $user = new WP_User($user_id);
    $user->set_role('hvac_trainer');
    
    update_user_meta($user_id, 'first_name', 'Test');
    update_user_meta($user_id, 'last_name', 'Trainer');
    
    $test_trainer = get_user_by('ID', $user_id);
    echo "Created test_trainer user (ID: {$user_id})\n";
} else {
    echo "Found existing test_trainer user (ID: {$test_trainer->ID})\n";
}

$trainer_id = $test_trainer->ID;

// Create test events
$event_data = [
    [
        'title' => 'Advanced HVAC Troubleshooting',
        'description' => 'Learn advanced techniques for diagnosing and fixing complex HVAC system issues.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+2 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+2 weeks +8 hours')),
        'venue' => 'HVAC Training Center',
        'address' => '123 Main St, New York, NY 10001',
        'price' => 299,
        'capacity' => 30,
        'attendees' => 20,
        'checkins' => 18
    ],
    [
        'title' => 'HVAC Energy Efficiency Workshop',
        'description' => 'Master the latest energy efficiency techniques and technologies in HVAC systems.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+1 month')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+1 month +6 hours')),
        'venue' => 'Green Energy Training Facility',
        'address' => '456 Eco Blvd, Chicago, IL 60601',
        'price' => 349,
        'capacity' => 25,
        'attendees' => 15,
        'checkins' => 12
    ],
    [
        'title' => 'Commercial Refrigeration Systems',
        'description' => 'Comprehensive training on installation and maintenance of commercial refrigeration systems.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+6 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+6 weeks +16 hours')),
        'venue' => 'Industrial Training Complex',
        'address' => '789 Commerce Lane, Dallas, TX 75201',
        'price' => 499,
        'capacity' => 40,
        'attendees' => 25,
        'checkins' => 22
    ]
];

$created_event_ids = [];
$total_certificates = 0;

// First name and last name options for test data
$first_names = ['John', 'Sarah', 'Michael', 'Emma', 'David', 'Olivia', 'James', 'Sophia', 
               'William', 'Ava', 'Robert', 'Isabella', 'Thomas', 'Mia', 'Daniel', 'Charlotte'];
$last_names = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Garcia', 'Miller', 'Davis',
              'Rodriguez', 'Martinez', 'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson'];
$email_domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'example.com'];

// Process each event
foreach ($event_data as $data) {
    echo "Creating event: {$data['title']}\n";
    
    // Create the event
    $event_args = [
        'post_title' => $data['title'],
        'post_content' => $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 "Failed to create event: " . $event_id->get_error_message() . "\n";
        continue;
    }
    
    // Set event meta
    update_post_meta($event_id, '_EventStartDate', $data['start_date']);
    update_post_meta($event_id, '_EventEndDate', $data['end_date']);
    update_post_meta($event_id, '_EventCost', $data['price']);
    
    // Create venue
    $venue_args = [
        'post_title' => $data['venue'],
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Venue::POSTTYPE,
        'post_author' => $trainer_id
    ];
    
    $venue_id = wp_insert_post($venue_args);
    
    if (!is_wp_error($venue_id)) {
        // Add venue meta
        $address_parts = explode(', ', $data['address']);
        $city = isset($address_parts[1]) ? $address_parts[1] : '';
        $state_zip = isset($address_parts[2]) ? explode(' ', $address_parts[2]) : ['', ''];
        
        update_post_meta($venue_id, '_VenueAddress', $address_parts[0]);
        update_post_meta($venue_id, '_VenueCity', $city);
        update_post_meta($venue_id, '_VenueStateProvince', $state_zip[0]);
        update_post_meta($venue_id, '_VenueZip', isset($state_zip[1]) ? $state_zip[1] : '');
        
        // Link venue to event
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    // Create RSVP ticket
    if (class_exists('Tribe__Tickets__RSVP')) {
        $rsvp_provider = tribe('tickets.rsvp');
        
        $ticket_args = [
            'post_title' => 'RSVP',
            'post_content' => "RSVP for {$data['title']}",
            'post_status' => 'publish',
            'post_parent' => $event_id,
            'meta_input' => [
                '_capacity' => $data['capacity'],
                '_tribe_ticket_capacity' => $data['capacity'],
                '_tribe_ticket_going_count' => 0,
                '_tribe_ticket_not_going_count' => 0,
                '_tribe_rsvp_for_event' => $event_id,
            ]
        ];
        
        // Create the ticket post
        $ticket_id = tribe_tickets_create_ticket($event_id, 'rsvp', $ticket_args);
        
        if (!is_wp_error($ticket_id) && $ticket_id) {
            echo "Created RSVP ticket for event {$event_id} (Ticket ID: {$ticket_id})\n";
            
            // Create attendees
            $attendees_created = 0;
            $attendees_checked_in = 0;
            $certificates_created = 0;
            
            for ($i = 1; $i <= $data['attendees']; $i++) {
                // Generate attendee data
                $first_name = ($i === 1) ? 'Ben' : $first_names[array_rand($first_names)];
                $last_name = ($i === 1) ? 'Tester' : $last_names[array_rand($last_names)];
                $email = ($i === 1) ? 'ben@tealmaker.com' : 
                    strtolower($first_name . '.' . $last_name . rand(100, 999) . '@' . $email_domains[array_rand($email_domains)]);
                
                $full_name = $first_name . ' ' . $last_name;
                
                // Create attendee data
                $attendee_data = [
                    'full_name' => $full_name,
                    'email' => $email,
                    'ticket_id' => $ticket_id,
                    'order_status' => 'yes',
                    'order_id' => md5($email . time() . rand(1, 1000)),
                    'user_id' => 0,
                    'attendee_status' => 'yes',
                    'event_id' => $event_id,
                    'optout' => 'no',
                ];
                
                // Create the attendee
                $attendee_id = tribe_tickets_rsvp_attendees_create($attendee_data, $ticket_id);
                
                if ($attendee_id) {
                    $attendees_created++;
                    
                    // Check in some attendees
                    if ($i <= $data['checkins']) {
                        update_post_meta($attendee_id, '_tribe_rsvp_checkin', 1);
                        update_post_meta($attendee_id, '_tribe_tickets_checkin_status', 1);
                        $attendees_checked_in++;
                        
                        // Create certificate for checked-in attendee
                        $year = date('Y');
                        $month = date('m');
                        $certificate_filename = "certificate-{$event_id}-{$attendee_id}-" . time() . ".pdf";
                        $certificate_relative_path = "hvac-certificates/{$year}/{$month}/{$certificate_filename}";
                        
                        // Create year/month directory structure if needed
                        $year_month_dir = $cert_dir . "/{$year}/{$month}";
                        if (!file_exists($year_month_dir)) {
                            wp_mkdir_p($year_month_dir);
                        }
                        
                        // Create the certificate record
                        $certificate_id = $certificate_manager->create_certificate(
                            $event_id,
                            $attendee_id,
                            0, // user_id (not associated with a user)
                            $certificate_relative_path,
                            $trainer_id // generated by (trainer)
                        );
                        
                        if ($certificate_id) {
                            $certificates_created++;
                            $total_certificates++;
                            
                            // Create dummy 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 mark as revoked or emailed for testing
                            $random = mt_rand(1, 10);
                            
                            // Revoke about 10% of certificates
                            if ($random == 1) {
                                $certificate_manager->revoke_certificate(
                                    $certificate_id,
                                    $trainer_id,
                                    "Test revocation for certificate testing"
                                );
                            }
                            
                            // Mark about 70% as emailed
                            if ($random <= 7) {
                                $certificate_manager->mark_certificate_emailed($certificate_id);
                            }
                        }
                    }
                }
            }
            
            // Update counts
            update_post_meta($ticket_id, '_tribe_ticket_going_count', $attendees_created);
            
            echo "Created {$attendees_created} attendees for event {$event_id}\n";
            echo "Checked in {$attendees_checked_in} attendees\n";
            echo "Generated {$certificates_created} certificates\n";
            
            $created_event_ids[] = $event_id;
        } else {
            echo "Failed to create RSVP ticket\n";
        }
    } else {
        echo "Tribe__Tickets__RSVP class not found. Skipping ticket creation.\n";
    }
    
    echo "----------------------------\n";
}

// Summary
echo "\n=== Test Data Creation Summary ===\n";
echo "Created " . count($created_event_ids) . " events\n";
echo "Generated " . $total_certificates . " certificates\n";

// Get certificate statistics
if (class_exists('HVAC_Certificate_Manager')) {
    $stats = $certificate_manager->get_certificate_stats();
    
    echo "\nCertificate Statistics:\n";
    echo "Total certificates in database: {$stats['total_certificates']}\n";
    echo "Total events with certificates: {$stats['total_events']}\n";
    echo "Total trainees with certificates: {$stats['total_trainees']}\n";
    
    echo "\nTest data creation completed!\n";
}
?>
EOL

# Copy PHP script to server and execute
echo "[1;33mCopying script to server...[0m"
scp rsvp-test-data.php roodev@146.190.76.204:~/public_html/

echo "[1;33mExecuting script on server...[0m"
ssh roodev@146.190.76.204 "cd ~/public_html/ && php rsvp-test-data.php"

# Clean up
rm rsvp-test-data.php
ssh roodev@146.190.76.204 "rm ~/public_html/rsvp-test-data.php"

echo "[0;32mRSVP Test data creation completed![0m"
echo "The script has created:"
echo "1. Test events with RSVP tickets"
echo "2. Varied attendee data with realistic names and emails"
echo "3. Check-ins for most attendees"
echo "4. Certificates for checked-in attendees"
echo ""
echo "You can test the system at:"
echo "- Event listing: https://wordpress-974670-5399585.cloudwaysapps.com/events/"
echo "- Certificate reports: https://wordpress-974670-5399585.cloudwaysapps.com/certificate-reports/"