#!/bin/bash

# Create comprehensive test data for test_trainer - Working Version

# Load configuration
source bin/deploy-config.sh

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

# Create the script on the server directly using SSH
ssh $REMOTE_USER@$REMOTE_HOST << 'ENDSSH'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Create comprehensive test data inline
cat << 'ENDPHP' > create-data-inline.php
<?php
// Load WordPress
require_once 'wp-load.php';

echo "=== Creating comprehensive test data for test_trainer ===\n";

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

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

// Initialize certificate manager if available
$certificate_manager = null;
if (class_exists('HVAC_Certificate_Manager')) {
    $certificate_manager = HVAC_Certificate_Manager::instance();
    echo "Certificate manager available\n";
}

// Event data with past and future events
$events_data = [
    // Past events (for certificates and statistics)
    [
        'title' => 'HVAC Fundamentals Workshop - October 2024',
        'description' => 'Basic HVAC principles and troubleshooting techniques.',
        'start_date' => '2024-10-15 09:00:00',
        'end_date' => '2024-10-15 17:00:00',
        'price' => 250,
        'capacity' => 25,
        'attendees' => 22,
        'checkins' => 20,
        'past_event' => true
    ],
    [
        'title' => 'Commercial HVAC Systems Training - November 2024',
        'description' => 'Advanced commercial HVAC installation and maintenance.',
        'start_date' => '2024-11-20 08:00:00',
        'end_date' => '2024-11-20 18:00:00',
        'price' => 450,
        'capacity' => 20,
        'attendees' => 18,
        'checkins' => 16,
        'past_event' => true
    ],
    [
        'title' => 'Energy Efficiency Certification - December 2024',
        'description' => 'Green HVAC technologies and energy-saving strategies.',
        'start_date' => '2024-12-10 09:00:00',
        'end_date' => '2024-12-10 16:00:00',
        'price' => 350,
        'capacity' => 30,
        'attendees' => 28,
        'checkins' => 25,
        'past_event' => true
    ],
    [
        'title' => 'Heat Pump Technology Workshop - January 2025',
        'description' => 'Modern heat pump systems and troubleshooting.',
        'start_date' => '2025-01-15 10:00:00',
        'end_date' => '2025-01-15 18:00:00',
        'price' => 300,
        'capacity' => 25,
        'attendees' => 23,
        'checkins' => 21,
        'past_event' => true
    ],
    
    // Future events (for upcoming dashboard display)
    [
        'title' => 'Advanced Refrigeration Systems - June 2025',
        'description' => 'Complex refrigeration system design and maintenance.',
        'start_date' => '2025-06-15 09:00:00',
        'end_date' => '2025-06-15 17:00:00',
        'price' => 500,
        'capacity' => 15,
        'attendees' => 12,
        'checkins' => 0,
        'past_event' => false
    ],
    [
        'title' => 'Smart HVAC Controls Workshop - July 2025',
        'description' => 'Building automation and smart HVAC control systems.',
        'start_date' => '2025-07-20 08:30:00',
        'end_date' => '2025-07-20 17:30:00',
        'price' => 400,
        'capacity' => 20,
        'attendees' => 15,
        'checkins' => 0,
        'past_event' => false
    ],
    [
        'title' => 'HVAC Business Management Seminar - August 2025',
        'description' => 'Business strategies for HVAC contractors and trainers.',
        'start_date' => '2025-08-10 09:00:00',
        'end_date' => '2025-08-10 16:00:00',
        'price' => 200,
        'capacity' => 50,
        'attendees' => 35,
        'checkins' => 0,
        'past_event' => false
    ]
];

$total_events_created = 0;
$total_attendees_created = 0;
$total_certificates_created = 0;

foreach ($events_data as $event_data) {
    echo "\nCreating event: {$event_data['title']}\n";
    
    // Create event post
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_data['description'],
        'post_status' => 'publish',
        'post_type' => 'tribe_events',
        'post_author' => $trainer_id,
        'post_date' => $event_data['start_date']
    ];
    
    $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', $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_args = [
        'post_title' => "Training Center - " . substr($event_data['title'], 0, 30),
        'post_status' => 'publish',
        'post_type' => 'tribe_venue',
        'post_author' => $trainer_id
    ];
    
    $venue_id = wp_insert_post($venue_args);
    
    if (!is_wp_error($venue_id)) {
        update_post_meta($venue_id, '_VenueAddress', '123 Training Street');
        update_post_meta($venue_id, '_VenueCity', 'New York');
        update_post_meta($venue_id, '_VenueState', 'NY');
        update_post_meta($venue_id, '_VenueZip', '10001');
        update_post_meta($venue_id, '_VenueCountry', 'USA');
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    // Create organizer
    $organizer_args = [
        'post_title' => "Test Trainer Organization",
        'post_status' => 'publish',
        'post_type' => 'tribe_organizer',
        'post_author' => $trainer_id
    ];
    
    $organizer_id = wp_insert_post($organizer_args);
    
    if (!is_wp_error($organizer_id)) {
        update_post_meta($organizer_id, '_OrganizerEmail', 'test_trainer@example.com');
        update_post_meta($organizer_id, '_OrganizerPhone', '555-TEST-123');
        update_post_meta($event_id, '_EventOrganizerID', $organizer_id);
    }
    
    // Create PayPal ticket
    $ticket_args = [
        'post_title' => "Registration - {$event_data['title']}",
        'post_content' => "Ticket for {$event_data['title']}",
        'post_status' => 'publish',
        'post_type' => 'tribe_tpp_tickets',
        'post_author' => $trainer_id
    ];
    
    $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', $event_data['price']);
        update_post_meta($ticket_id, '_regular_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($ticket_id, '_tribe_tpp_sold', $event_data['attendees']);
        
        // Associate ticket with event
        update_post_meta($event_id, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
        
        echo "  Created ticket (ID: {$ticket_id})\n";
        
        // Create attendees
        $attendee_ids = [];
        for ($i = 1; $i <= $event_data['attendees']; $i++) {
            $first_names = ['John', 'Sarah', 'Michael', 'Emma', 'David', 'Lisa', 'Robert', 'Jessica', 'William', 'Ashley'];
            $last_names = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Wilson'];
            
            $first_name = $first_names[array_rand($first_names)];
            $last_name = $last_names[array_rand($last_names)];
            
            // Special case for first attendee
            if ($i === 1) {
                $first_name = "Ben";
                $last_name = "Tester";
                $email = "ben@tealmaker.com";
            } else {
                $email = strtolower($first_name . '.' . $last_name . '.' . rand(100, 999) . '@example.com');
            }
            
            // Create attendee post
            $attendee_args = [
                'post_title' => "{$first_name} {$last_name}",
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'tribe_tpp_attendees',
                'post_author' => $trainer_id
            ];
            
            $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) . '-' . time();
            
            $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' => 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 attendees for past events
            if ($event_data['past_event'] && $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);
            }
            
            $total_attendees_created++;
        }
        
        // Update event and ticket counts
        update_post_meta($event_id, '_tribe_ticket_sold_count', $event_data['attendees']);
        update_post_meta($ticket_id, '_tribe_ticket_sold', $event_data['attendees']);
        
        echo "  Created {$event_data['attendees']} attendees\n";
        if ($event_data['past_event']) {
            echo "  Checked in {$event_data['checkins']} attendees\n";
        }
        
        // Generate certificates for past events with check-ins
        if ($certificate_manager && $event_data['past_event'] && $event_data['checkins'] > 0) {
            echo "  Generating certificates...\n";
            
            // Get checked-in attendees
            $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;
            
            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
                $upload_dir = wp_upload_dir();
                $year_month_dir = $upload_dir['basedir'] . "/hvac-certificates/{$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_created++;
                    
                    // Create placeholder certificate file
                    $certificate_full_path = $upload_dir['basedir'] . '/' . $certificate_relative_path;
                    file_put_contents($certificate_full_path, "Test Certificate PDF for Event {$event_id}, Attendee {$attendee_id}");
                    
                    // Randomly mark some as emailed (80% chance)
                    if (rand(1, 100) <= 80) {
                        $certificate_manager->mark_certificate_emailed($certificate_id);
                    }
                    
                    // Rarely revoke certificates (5% chance)
                    if (rand(1, 100) <= 5) {
                        $certificate_manager->revoke_certificate(
                            $certificate_id,
                            $trainer_id,
                            "Test revocation for data variety"
                        );
                    }
                }
            }
            
            echo "  Created {$certificates_created} certificates\n";
        }
    }
    
    $total_events_created++;
    echo "  Event created successfully (ID: {$event_id})\n";
}

echo "\n=== Test Data Creation Summary ===\n";
echo "Events created: {$total_events_created}\n";
echo "Total attendees: {$total_attendees_created}\n";
echo "Total certificates: {$total_certificates_created}\n";
echo "\nTest data creation completed successfully!\n";
?>
ENDPHP

# Execute the PHP script
echo "Executing test data creation script..."
php create-data-inline.php

# Clean up
rm create-data-inline.php

echo "Test data creation completed!"
ENDSSH

echo "[0;32mComprehensive test data creation completed![0m"
echo ""
echo "=== Created Test Data for test_trainer ==="
echo "✓ 7 events (4 past, 3 future)"
echo "✓ Varied pricing (\$200-\$500)"
echo "✓ 150+ attendees across all events"
echo "✓ 80+ check-ins for past events"
echo "✓ Certificates for checked-in attendees"
echo "✓ Revenue and attendance statistics"
echo ""
echo "Dashboard should now show:"
echo "• Total events, past/upcoming counts"
echo "• Total revenue and ticket sales"
echo "• Recent activity and statistics"
echo "• Certificate generation capabilities"