#!/bin/bash

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

echo "=== Creating Complete Test Data with Revenue ==="

# Execute PHP script directly on server
ssh $REMOTE_USER@$REMOTE_HOST << 'ENDSSH'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Create and execute the PHP script
cat << 'EOF' > create-test-data-with-revenue.php
<?php
// Load WordPress
require_once('wp-load.php');

echo "=== Creating complete test data with revenue ===\n\n";

// First, let's check what's happening with events
global $wpdb;
$events_table = $wpdb->posts;
$event_count = $wpdb->get_var("SELECT COUNT(*) FROM {$events_table} WHERE post_type = 'tribe_events'");
echo "Total events in database: {$event_count}\n";

// Check if The Events Calendar is properly set up
if (!class_exists('Tribe__Events__Main')) {
    die("The Events Calendar plugin is not active!\n");
}

// Get test trainer
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    die("test_trainer user not found.\n");
}
$trainer_id = $test_trainer->ID;
echo "Using test_trainer (ID: {$trainer_id})\n\n";

// Delete any existing test events to start fresh
$existing_events = $wpdb->get_col("
    SELECT ID FROM {$wpdb->posts} 
    WHERE post_type = 'tribe_events' 
    AND post_author = {$trainer_id}
");

if (!empty($existing_events)) {
    echo "Cleaning up " . count($existing_events) . " existing test events...\n";
    foreach ($existing_events as $event_id) {
        wp_delete_post($event_id, true);
    }
}

// Create comprehensive test events
$events_data = [
    [
        'title' => 'Advanced HVAC Diagnostics Workshop',
        'description' => 'Master advanced diagnostic techniques for modern HVAC systems including digital controls and variable speed equipment.',
        'venue_name' => 'HVAC Excellence Training Center',
        'venue_address' => '1234 Technical Drive',
        'venue_city' => 'Dallas',
        'venue_state' => 'TX',
        'venue_zip' => '75201',
        'start_date' => date('Y-m-d 09:00:00', strtotime('+1 week')),
        'end_date' => date('Y-m-d 17:00:00', strtotime('+1 week')),
        'price' => 349,
        'capacity' => 30,
        'attendees' => 25,
        'checked_in' => 22
    ],
    [
        'title' => 'Commercial Refrigeration Certification',
        'description' => 'Comprehensive certification course covering commercial refrigeration systems, EPA regulations, and best practices.',
        'venue_name' => 'Industrial Training Institute',
        'venue_address' => '5678 Commerce Park',
        'venue_city' => 'Chicago',
        'venue_state' => 'IL',
        'venue_zip' => '60601',
        'start_date' => date('Y-m-d 08:00:00', strtotime('+2 weeks')),
        'end_date' => date('Y-m-d 18:00:00', strtotime('+2 weeks +1 day')),
        'price' => 599,
        'capacity' => 25,
        'attendees' => 20,
        'checked_in' => 18
    ],
    [
        'title' => 'Heat Pump Installation & Service',
        'description' => 'Learn proper installation, commissioning, and service procedures for modern heat pump systems.',
        'venue_name' => 'Green Energy Training Lab',
        'venue_address' => '9012 Sustainability Way',
        'venue_city' => 'San Francisco',
        'venue_state' => 'CA',
        'venue_zip' => '94105',
        'start_date' => date('Y-m-d 09:00:00', strtotime('+3 weeks')),
        'end_date' => date('Y-m-d 16:00:00', strtotime('+3 weeks')),
        'price' => 299,
        'capacity' => 35,
        'attendees' => 28,
        'checked_in' => 25
    ],
    [
        'title' => 'Building Automation Systems',
        'description' => 'Introduction to BAS/BMS systems, programming, troubleshooting, and integration with HVAC equipment.',
        'venue_name' => 'Smart Building Academy',
        'venue_address' => '3456 Innovation Boulevard',
        'venue_city' => 'New York',
        'venue_state' => 'NY',
        'venue_zip' => '10001',
        'start_date' => date('Y-m-d 08:30:00', strtotime('+4 weeks')),
        'end_date' => date('Y-m-d 17:30:00', strtotime('+4 weeks +2 days')),
        'price' => 799,
        'capacity' => 20,
        'attendees' => 18,
        'checked_in' => 16
    ]
];

$created_events = [];
$total_revenue = 0;

// Names pool for attendees
$first_names = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer', 'Michael', 'Linda', 
                'William', 'Elizabeth', 'David', 'Barbara', 'Richard', 'Susan', 'Joseph', 'Jessica',
                'Thomas', 'Sarah', 'Charles', 'Karen', 'Christopher', 'Nancy', 'Daniel', 'Betty',
                'Matthew', 'Helen', 'Anthony', 'Sandra', 'Mark', 'Donna', 'Donald', 'Carol'];

$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'];

$companies = ['ABC Heating & Air', 'Comfort Systems Inc', 'CoolTech HVAC', 'Premier Climate Control',
              'Elite Mechanical', 'ProAir Services', 'Quality Comfort Solutions', 'Advanced HVAC Systems'];

foreach ($events_data as $event_data) {
    echo "\nCreating event: {$event_data['title']}\n";
    
    // Create the event using Tribe__Events__API
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_data['description'],
        'post_status' => 'publish',
        'post_author' => $trainer_id,
        'EventStartDate' => $event_data['start_date'],
        'EventEndDate' => $event_data['end_date'],
        'EventCost' => $event_data['price'],
        'EventCurrencySymbol' => '$',
        'Venue' => [
            'Venue' => $event_data['venue_name'],
            'Address' => $event_data['venue_address'],
            'City' => $event_data['venue_city'],
            'State' => $event_data['venue_state'],
            'Zip' => $event_data['venue_zip'],
            'Country' => 'United States'
        ]
    ];
    
    // Use The Events Calendar API to create event
    $event_id = tribe_create_event($event_args);
    
    if (is_wp_error($event_id) || !$event_id) {
        echo "Failed to create event\n";
        continue;
    }
    
    echo "Created event ID: {$event_id}\n";
    
    // Ensure ticket provider is set
    update_post_meta($event_id, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
    
    // Create ticket
    $ticket_args = [
        'post_title' => "General Admission - {$event_data['title']}",
        'post_content' => "Access to {$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)) {
        echo "Failed to create ticket\n";
        continue;
    }
    
    // Set comprehensive ticket meta
    $ticket_meta = [
        '_tribe_tpp_for_event' => $event_id,
        '_price' => $event_data['price'],
        '_tribe_ticket_capacity' => $event_data['capacity'],
        '_capacity' => $event_data['capacity'],
        '_stock' => $event_data['capacity'] - $event_data['attendees'],
        '_manage_stock' => 'yes',
        '_tribe_ticket_show_not_going' => 'no',
        '_tribe_tpp_sold' => $event_data['attendees'],
        '_tribe_ticket_sold' => $event_data['attendees'],
        'total_sales' => $event_data['attendees']
    ];
    
    foreach ($ticket_meta as $key => $value) {
        update_post_meta($ticket_id, $key, $value);
    }
    
    echo "Created ticket ID: {$ticket_id} (Price: \${$event_data['price']})\n";
    
    // Create attendees
    echo "Creating {$event_data['attendees']} attendees...\n";
    
    for ($i = 0; $i < $event_data['attendees']; $i++) {
        // First attendee is always Ben
        if ($i === 0) {
            $first_name = 'Ben';
            $last_name = 'Reed';
            $email = 'ben@tealmaker.com';
            $company = 'TealMaker';
        } else {
            $first_name = $first_names[array_rand($first_names)];
            $last_name = $last_names[array_rand($last_names)];
            $email = strtolower($first_name . '.' . $last_name . rand(100, 999) . '@example.com');
            $company = $companies[array_rand($companies)];
        }
        
        $full_name = "{$first_name} {$last_name}";
        
        // Create attendee post
        $attendee_args = [
            'post_title' => $full_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;
        }
        
        // Generate realistic order data
        $order_id = 'PAY-' . strtoupper(substr(md5($event_id . $attendee_id . microtime()), 0, 17));
        $security_code = strtoupper(substr(md5($order_id), 0, 10));
        
        // Set comprehensive attendee meta
        $attendee_meta = [
            // Event and ticket association
            '_tribe_tpp_event' => $event_id,
            '_tribe_tpp_product' => $ticket_id,
            '_tribe_tickets_event_id' => $event_id,
            '_tribe_tickets_product_id' => $ticket_id,
            
            // Order information
            '_tribe_tpp_order' => $order_id,
            '_tribe_paypal_transaction_id' => $order_id,
            '_tribe_tpp_order_status' => 'completed',
            '_tribe_tickets_order_status' => 'completed',
            
            // Personal information
            '_tribe_tickets_full_name' => $full_name,
            '_tribe_tickets_email' => $email,
            '_tribe_tpp_full_name' => $full_name,
            '_tribe_tpp_email' => $email,
            
            // Payment information
            '_paid_price' => $event_data['price'],
            '_tribe_tpp_price' => $event_data['price'],
            
            // Security
            '_tribe_tpp_security_code' => $security_code,
            
            // Additional fields
            'company' => $company,
            '_tribe_tpp_attendee_optout' => 'no'
        ];
        
        foreach ($attendee_meta as $key => $value) {
            update_post_meta($attendee_id, $key, $value);
        }
        
        // Check in attendees based on the specified count
        if ($i < $event_data['checked_in']) {
            update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
            update_post_meta($attendee_id, 'check_in', 1);
            update_post_meta($attendee_id, '_tribe_tickets_checkin_status', 1);
        }
    }
    
    // Calculate and store event revenue
    $event_revenue = $event_data['attendees'] * $event_data['price'];
    $total_revenue += $event_revenue;
    
    // Update event meta with sales data
    update_post_meta($event_id, '_tribe_ticket_sold_count', $event_data['attendees']);
    update_post_meta($event_id, '_tribe_event_revenue', $event_revenue);
    
    $created_events[] = [
        'id' => $event_id,
        'title' => $event_data['title'],
        'attendees' => $event_data['attendees'],
        'checked_in' => $event_data['checked_in'],
        'revenue' => $event_revenue
    ];
    
    echo "Created {$event_data['attendees']} attendees, {$event_data['checked_in']} checked in\n";
    echo "Event revenue: \${$event_revenue}\n";
}

// Generate certificates for checked-in attendees
if (class_exists('HVAC_Certificate_Manager')) {
    echo "\n=== Generating certificates ===\n";
    
    $certificate_manager = HVAC_Certificate_Manager::instance();
    $total_certificates = 0;
    
    foreach ($created_events as $event_info) {
        echo "\nGenerating certificates for: {$event_info['title']}\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_info['id']
                ],
                [
                    'key' => '_tribe_tpp_checkin',
                    'value' => 1
                ]
            ],
            'posts_per_page' => -1
        ]);
        
        $event_certificates = 0;
        
        foreach ($checked_in_attendees as $attendee) {
            if (!$certificate_manager->certificate_exists($event_info['id'], $attendee->ID)) {
                $cert_filename = 'certificate-' . $event_info['id'] . '-' . $attendee->ID . '-' . time() . rand(100, 999) . '.pdf';
                $cert_path = 'hvac-certificates/' . date('Y/m/') . $cert_filename;
                
                $cert_id = $certificate_manager->create_certificate(
                    $event_info['id'],
                    $attendee->ID,
                    0,
                    $cert_path,
                    $trainer_id
                );
                
                if ($cert_id) {
                    $event_certificates++;
                    $total_certificates++;
                    
                    // Create dummy PDF
                    $upload_dir = wp_upload_dir();
                    $full_path = $upload_dir['basedir'] . '/' . $cert_path;
                    $dir = dirname($full_path);
                    if (!file_exists($dir)) {
                        wp_mkdir_p($dir);
                    }
                    
                    $attendee_name = get_post_meta($attendee->ID, '_tribe_tickets_full_name', true);
                    $pdf_content = "%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n";
                    $pdf_content .= "2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n";
                    $pdf_content .= "3 0 obj<</Type/Page/MediaBox[0 0 612 792]/Parent 2 0 R/Resources<<>>>>endobj\n";
                    $pdf_content .= "%%EOF\n";
                    file_put_contents($full_path, $pdf_content);
                }
            }
        }
        
        echo "Generated {$event_certificates} certificates\n";
    }
    
    echo "\nTotal certificates generated: {$total_certificates}\n";
}

// Final summary
echo "\n=== TEST DATA CREATION COMPLETE ===\n";
echo "Created " . count($created_events) . " events:\n\n";

foreach ($created_events as $event) {
    echo "- {$event['title']}\n";
    echo "  Attendees: {$event['attendees']} | Checked in: {$event['checked_in']} | Revenue: \${$event['revenue']}\n";
}

echo "\nTotal Revenue: \${$total_revenue}\n";
echo "\nAll test data has been created successfully!\n";
?>
EOF

# Execute the PHP script
php create-test-data-with-revenue.php

# Clean up
rm create-test-data-with-revenue.php
ENDSSH

echo ""
echo "[0;32mComplete test data with revenue created![0m"
echo ""
echo "You can now test all features:"
echo ""
echo "1. Enhanced Dashboard: https://upskill-staging.measurequick.com/hvac-dashboard/"
echo "   - Search for events (try 'Workshop' or 'Certification')"
echo "   - Filter by date range"
echo "   - Change items per page (10/25/50/100)"
echo "   - Sort by clicking column headers"
echo "   - View revenue numbers for each event"
echo ""
echo "2. Certificate Generation: https://upskill-staging.measurequick.com/generate-certificates/"
echo "   - Select any event to see attendees"
echo "   - Generate certificates for checked-in attendees"
echo ""
echo "3. Certificate Reports: https://upskill-staging.measurequick.com/certificate-reports/"
echo "   - View all generated certificates"
echo "   - Filter by event or attendee name"
echo "   - Download certificates"
echo ""
echo "Login as: test_trainer"