#!/bin/bash

# Create comprehensive test data including events, attendees, and certificates

# Load configuration
source wordpress-dev/bin/hvac-plugin-deploy.conf

echo "=== Creating Comprehensive Test Data on Staging Server ==="
echo "Remote host: $REMOTE_HOST"
echo "Remote user: $REMOTE_USER"
echo "WordPress path: $REMOTE_PATH_BASE"
echo "==============================="

# Create the comprehensive PHP script
cat << 'EOF' > comprehensive-test-data.php
<?php
/**
 * Comprehensive Test Data Generator
 * 
 * Creates events, attendees, check-ins, and certificates for thorough 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 comprehensive test data ===\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 or update Joe Medosch as master trainer
$joe_user = get_user_by('email', 'JoeMedosch@gmail.com');
if (!$joe_user) {
    echo "JoeMedosch@gmail.com user not found, creating master trainer...\n";
    
    $joe_id = wp_create_user('joemedosch', 'JoeTrainer2025@', 'JoeMedosch@gmail.com');
    
    if (is_wp_error($joe_id)) {
        echo "Failed to create JoeMedosch user: " . $joe_id->get_error_message() . "\n";
    } else {
        // Set role and update user meta
        $user = new WP_User($joe_id);
        $user->set_role('hvac_master_trainer');
        
        update_user_meta($joe_id, 'first_name', 'Joe');
        update_user_meta($joe_id, 'last_name', 'Medosch');
        update_user_meta($joe_id, 'display_name', 'Joe Medosch');
        
        $joe_user = get_user_by('ID', $joe_id);
        echo "Created JoeMedosch master trainer user (ID: {$joe_id})\n";
    }
} else {
    echo "Found existing JoeMedosch user (ID: {$joe_user->ID})\n";
    // Ensure they have master trainer role
    $user = new WP_User($joe_user->ID);
    $user->set_role('hvac_master_trainer');
    echo "Updated JoeMedosch to master trainer role\n";
}

// Assign roles to joe@measurequick.com if user exists
$joe_mq_user = get_user_by('email', 'joe@measurequick.com');
if ($joe_mq_user) {
    echo "Found joe@measurequick.com user (ID: {$joe_mq_user->ID})\n";
    echo "Assigning trainer and master trainer roles...\n";
    
    // Add both HVAC roles (keeping existing roles like administrator)
    $user = new WP_User($joe_mq_user->ID);
    $user->add_role('hvac_trainer');
    $user->add_role('hvac_master_trainer');
    
    echo "Added hvac_trainer and hvac_master_trainer roles to joe@measurequick.com\n";
} else {
    echo "joe@measurequick.com user not found (may not exist in staging)\n";
}

// Create events with a variety of data
$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,
        'attendees' => 20,
        'checkins' => 18,
        'create_certificates' => true
    ],
    [
        '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,
        'attendees' => 15,
        'checkins' => 12,
        'create_certificates' => true
    ],
    [
        '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')), // 2-day workshop
        'venue' => 'Industrial Training Complex',
        'address' => '789 Commerce Lane, Dallas, TX 75201',
        'price' => 499,
        'attendees' => 25,
        'checkins' => 22,
        'create_certificates' => true
    ],
    [
        'title' => 'Residential HVAC Installation Best Practices',
        'description' => 'Learn industry best practices for residential HVAC installation and customer service.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+2 months')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+2 months +8 hours')),
        'venue' => 'Residential Skills Center',
        'address' => '321 Homestead Road, Atlanta, GA 30301',
        'price' => 249,
        'attendees' => 30,
        'checkins' => 26,
        'create_certificates' => true
    ],
    [
        'title' => 'HVAC Controls and Automation',
        'description' => 'Advanced training on modern HVAC control systems, automation, and smart building integration.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+3 months')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+3 months +12 hours')),
        'venue' => 'Smart Technology Institute',
        'address' => '555 Innovation Way, San Francisco, CA 94105',
        'price' => 399,
        'attendees' => 18,
        'checkins' => 15,
        'create_certificates' => true
    ]
];

// Track created events
$created_event_ids = [];

// Create test events
foreach ($event_data as $index => $data) {
    echo "Creating event: {$data['title']}\n";
    
    // Create the event post
    $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;
    }
    
    // Add 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, '_EventVenueID', 0); // Default venue
    update_post_meta($event_id, '_EventCost', $data['price']);
    
    // Create or use existing 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
        update_post_meta($venue_id, '_VenueAddress', $data['address']);
        update_post_meta($venue_id, '_VenueCity', explode(', ', $data['address'])[1]);
        update_post_meta($venue_id, '_VenueState', explode(' ', explode(', ', $data['address'])[2])[0]);
        update_post_meta($venue_id, '_VenueZip', explode(' ', explode(', ', $data['address'])[2])[1]);
        
        // Link venue to event
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    // Create PayPal ticket
    if (class_exists('Tribe__Tickets_Plus__Commerce__PayPal__Main')) {
        $ticket_args = [
            'post_title' => "Admission - {$data['title']}",
            'post_content' => "Ticket for {$data['title']}",
            'post_status' => 'publish',
            'post_type' => 'tribe_tpp_tickets',
        ];
        
        $ticket_id = wp_insert_post($ticket_args);
        
        if (!is_wp_error($ticket_id)) {
            // Add ticket meta
            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', $data['price']);
            update_post_meta($ticket_id, '_capacity', $data['attendees'] + 10);
            update_post_meta($ticket_id, '_stock', $data['attendees'] + 10);
            update_post_meta($ticket_id, '_manage_stock', 'yes');
            
            // Associate ticket with event
            update_post_meta($event_id, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
            
            echo "Created ticket for event: {$event_id}\n";
            
            // Generate varied attendee names and emails
            $first_names = ['John', 'Sarah', 'Michael', 'Emma', 'David', 'Olivia', 'James', 'Sophia', 
                           'William', 'Ava', 'Robert', 'Isabella', 'Thomas', 'Mia', 'Daniel', 'Charlotte',
                           'Joseph', 'Amelia', 'Christopher', 'Harper', 'Samuel', 'Evelyn', 'Edward', 'Abigail',
                           'Anthony', 'Emily', 'Matthew', 'Elizabeth', 'Richard', 'Sofia'];
            
            $last_names = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', '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'];
            
            $email_domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'aol.com', 
                             'icloud.com', 'protonmail.com', 'example.com', 'hvacpro.com', 'techjobs.com'];
            
            // Create attendees
            $attendee_ids = [];
            
            for ($i = 1; $i <= $data['attendees']; $i++) {
                $first_name_index = array_rand($first_names);
                $last_name_index = array_rand($last_names);
                $domain_index = array_rand($email_domains);
                
                $attendee_first_name = $first_names[$first_name_index];
                $attendee_last_name = $last_names[$last_name_index];
                $email_domain = $email_domains[$domain_index];
                
                // Generate unique email
                $attendee_email = strtolower($attendee_first_name . '.' . $attendee_last_name . '.' . rand(100, 999) . '@' . $email_domain);
                
                // Special email for the first attendee of each event
                if ($i === 1) {
                    $attendee_email = "ben@tealmaker.com";
                    $attendee_first_name = "Ben";
                    $attendee_last_name = "Tester";
                }
                
                // Create attendee post
                $attendee_args = [
                    'post_title' => "{$attendee_first_name} {$attendee_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)) {
                    echo "Failed to create attendee for event {$event_id}: " . $attendee_id->get_error_message() . "\n";
                    continue;
                }
                
                $attendee_ids[] = $attendee_id;
                
                // Generate a unique order ID
                $order_id = 'ORDER-' . $event_id . '-' . $i . '-' . uniqid();
                
                // Add attendee meta
                $meta_fields = [
                    '_tribe_tickets_full_name' => "{$attendee_first_name} {$attendee_last_name}",
                    '_tribe_tickets_email' => $attendee_email,
                    '_tribe_tpp_full_name' => "{$attendee_first_name} {$attendee_last_name}",
                    '_tribe_tpp_email' => $attendee_email,
                    '_tribe_tpp_event' => $event_id,
                    '_tribe_tpp_product' => $ticket_id,
                    '_tribe_tpp_order' => $order_id,
                    '_tribe_tpp_security_code' => wp_generate_password(10, false),
                    '_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 some attendees
                if ($i <= $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);
                }
            }
            
            echo "Created {$data['attendees']} attendees for event {$event_id}\n";
            echo "Checked in {$data['checkins']} attendees for event {$event_id}\n";
            
            // Update ticket stock and sales counts
            update_post_meta($ticket_id, '_tribe_tpp_sold', $data['attendees']);
            update_post_meta($ticket_id, '_stock', intval(get_post_meta($ticket_id, '_capacity', true)) - $data['attendees']);
            update_post_meta($ticket_id, '_tribe_ticket_sold', $data['attendees']);
            
            // Update event attendance meta
            update_post_meta($event_id, '_tribe_ticket_sold_count', $data['attendees']);
            
            // Store the created event ID
            $created_event_ids[] = $event_id;
            
            // Generate certificates if requested
            if ($data['create_certificates'] && $data['checkins'] > 0) {
                echo "Generating certificates for event {$event_id}\n";
                
                // Get checked-in attendees for this event
                $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;
                    $attendee_name = get_post_meta($attendee_id, '_tribe_tickets_full_name', true);
                    
                    // Skip if a certificate already exists
                    if ($certificate_manager->certificate_exists($event_id, $attendee_id)) {
                        echo " - Certificate already exists for attendee {$attendee_name}. Skipping.\n";
                        continue;
                    }
                    
                    // Create certificate file path
                    $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 
                        $certificate_relative_path,
                        $trainer_id
                    );
                    
                    if ($certificate_id) {
                        $certificates_created++;
                        
                        // 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)");
                        
                        // For testing, randomly mark some certificates as revoked or emailed
                        $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"
                            );
                            $certificates_revoked++;
                        }
                        
                        // Mark about 70% as emailed
                        if ($random <= 7) {
                            $certificate_manager->mark_certificate_emailed($certificate_id);
                            $certificates_emailed++;
                        }
                    }
                }
                
                echo "Created {$certificates_created} certificates for event {$event_id}\n";
                echo "Revoked {$certificates_revoked} certificates\n";
                echo "Marked {$certificates_emailed} certificates as emailed\n";
            }
        }
    } else {
        echo "Event Tickets Plus or PayPal provider not available\n";
    }
    
    echo "----------------------------\n";
}

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

// Get certificate statistics
if (class_exists('HVAC_Certificate_Manager')) {
    $stats = $certificate_manager->get_certificate_stats();
    
    echo "\nCertificate Statistics:\n";
    echo "Total certificates: {$stats['total_certificates']}\n";
    echo "Total events with certificates: {$stats['total_events']}\n";
    echo "Total trainees with certificates: {$stats['total_trainees']}\n";
    echo "Total revoked certificates: {$stats['total_revoked']}\n";
    echo "Total emailed certificates: {$stats['total_emailed']}\n";
}

echo "\nTest data creation completed!\n";
?>
EOF

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

echo "[1;33mMoving script to web directory and executing...[0m"
ssh $REMOTE_USER@$REMOTE_HOST "mv ~/comprehensive-test-data.php $REMOTE_PATH_BASE/ && cd $REMOTE_PATH_BASE && php comprehensive-test-data.php"

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

echo "[0;32mComprehensive test data creation completed![0m"
echo "The script has created:"
echo "1. Multiple test events with different dates, venues, and prices"
echo "2. Varied attendee data with realistic names and emails"
echo "3. Check-ins for most attendees"
echo "4. Certificates with varied states (active, revoked, emailed)"
echo ""
echo "You can test the system at:"
echo "- Event listing: https://upskill-staging.measurequick.com/events/"
echo "- Certificate reports: https://upskill-staging.measurequick.com/certificate-reports/"
echo ""
echo "Features to test with this data:"
echo "1. Event filtering and searching"
echo "2. Certificate filtering by event name"
echo "3. Certificate filtering by attendee name/email"
echo "4. Certificate filtering by status (active/revoked)"
echo "5. Certificate email functionality"
echo "6. Certificate download functionality"