#!/bin/bash

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

echo "=== Creating Complete Test Data on Staging Server ==="

# 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-complete-test-data.php
<?php
// Load WordPress
require_once('wp-load.php');

echo "=== Creating complete test data ===\n\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";

// Check if tribe_events post type exists
if (!post_type_exists('tribe_events')) {
    die("The Events Calendar is not properly initialized. Post type 'tribe_events' not found.\n");
}

// Create 3 test events with complete data
$events_data = [
    [
        'title' => 'HVAC System Diagnostics Workshop',
        'description' => 'Learn advanced diagnostic techniques for modern HVAC systems.',
        'venue_name' => 'Technical Training Center',
        'venue_address' => '123 Tech Drive',
        'venue_city' => 'New York',
        'venue_state' => 'NY',
        'venue_zip' => '10001',
        'start_offset' => '+7 days',
        'price' => 299
    ],
    [
        'title' => 'Commercial Refrigeration Basics',
        'description' => 'Comprehensive introduction to commercial refrigeration systems.',
        'venue_name' => 'Industrial Learning Center',
        'venue_address' => '456 Industry Blvd',
        'venue_city' => 'Chicago',
        'venue_state' => 'IL',
        'venue_zip' => '60601',
        'start_offset' => '+14 days',
        'price' => 349
    ],
    [
        'title' => 'Energy Efficient HVAC Design',
        'description' => 'Master the latest in energy-efficient HVAC system design.',
        'venue_name' => 'Green Tech Institute',
        'venue_address' => '789 Eco Way',
        'venue_city' => 'San Francisco',
        'venue_state' => 'CA',
        'venue_zip' => '94105',
        'start_offset' => '+21 days',
        'price' => 399
    ]
];

$created_events = [];

foreach ($events_data as $data) {
    echo "Creating event: {$data['title']}\n";
    
    // Calculate dates
    $start_date = date('Y-m-d 09:00:00', strtotime($data['start_offset']));
    $end_date = date('Y-m-d 17:00:00', strtotime($data['start_offset']));
    
    // Create the event
    $event_args = [
        'post_title' => $data['title'],
        'post_content' => $data['description'],
        'post_status' => 'publish',
        'post_type' => 'tribe_events',
        'post_author' => $trainer_id,
        'meta_input' => [
            '_EventStartDate' => $start_date,
            '_EventEndDate' => $end_date,
            '_EventStartDateUTC' => get_gmt_from_date($start_date),
            '_EventEndDateUTC' => get_gmt_from_date($end_date),
            '_EventCost' => $data['price'],
            '_EventCurrencySymbol' => '$'
        ]
    ];
    
    $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;
    }
    
    echo "Created event ID: {$event_id}\n";
    
    // Create venue
    $venue_args = [
        'post_title' => $data['venue_name'],
        'post_status' => 'publish',
        'post_type' => 'tribe_venue',
        'post_author' => $trainer_id,
        'meta_input' => [
            '_VenueAddress' => $data['venue_address'],
            '_VenueCity' => $data['venue_city'],
            '_VenueState' => $data['venue_state'],
            '_VenueZip' => $data['venue_zip'],
            '_VenueCountry' => 'United States'
        ]
    ];
    
    $venue_id = wp_insert_post($venue_args);
    
    if (!is_wp_error($venue_id)) {
        update_post_meta($event_id, '_EventVenueID', $venue_id);
        echo "Created venue ID: {$venue_id}\n";
    }
    
    // Create ticket
    $ticket_args = [
        'post_title' => "General Admission",
        'post_content' => '',
        '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)) {
        // Set ticket provider first
        update_post_meta($event_id, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
        
        // Set ticket meta
        update_post_meta($ticket_id, '_tribe_tpp_for_event', $event_id);
        update_post_meta($ticket_id, '_price', $data['price']);
        update_post_meta($ticket_id, '_tribe_ticket_capacity', 30);
        update_post_meta($ticket_id, '_capacity', 30);
        update_post_meta($ticket_id, '_stock', 20);
        update_post_meta($ticket_id, '_manage_stock', 'yes');
        update_post_meta($ticket_id, '_tribe_ticket_show_not_going', 'no');
        update_post_meta($ticket_id, 'total_sales', 10);
        
        echo "Created ticket ID: {$ticket_id}\n";
        
        // Create 10 attendees
        $names = [
            ['Ben', 'Reed', 'ben@tealmaker.com'],
            ['John', 'Smith', 'john.smith@example.com'],
            ['Sarah', 'Johnson', 'sarah.j@example.com'],
            ['Mike', 'Davis', 'mike.davis@example.com'],
            ['Emma', 'Wilson', 'emma.w@example.com'],
            ['David', 'Brown', 'david.brown@example.com'],
            ['Lisa', 'Garcia', 'lisa.g@example.com'],
            ['James', 'Miller', 'james.m@example.com'],
            ['Mary', 'Jones', 'mary.jones@example.com'],
            ['Robert', 'Taylor', 'robert.t@example.com']
        ];
        
        $attendees_created = 0;
        $attendees_checked_in = 0;
        
        foreach ($names as $i => $name_data) {
            list($first_name, $last_name, $email) = $name_data;
            $full_name = "{$first_name} {$last_name}";
            
            // Create attendee
            $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)) {
                // Order ID
                $order_id = 'TEST-' . $event_id . '-' . ($i + 1) . '-' . time();
                
                // Set all required attendee meta
                $attendee_meta = [
                    '_tribe_tpp_event' => $event_id,
                    '_tribe_tpp_product' => $ticket_id,
                    '_tribe_tpp_order' => $order_id,
                    '_tribe_tickets_full_name' => $full_name,
                    '_tribe_tickets_email' => $email,
                    '_tribe_tpp_full_name' => $full_name,
                    '_tribe_tpp_email' => $email,
                    '_tribe_tpp_security_code' => substr(md5($order_id), 0, 10),
                    '_paid_price' => $data['price'],
                    '_tribe_tickets_order_status' => 'completed',
                    '_tribe_tpp_order_status' => 'completed'
                ];
                
                foreach ($attendee_meta as $key => $value) {
                    update_post_meta($attendee_id, $key, $value);
                }
                
                // Check in first 8 attendees
                if ($i < 8) {
                    update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
                    update_post_meta($attendee_id, 'check_in', 1);
                    $attendees_checked_in++;
                }
                
                $attendees_created++;
            }
        }
        
        // Update ticket sales
        update_post_meta($ticket_id, '_tribe_tpp_sold', $attendees_created);
        update_post_meta($ticket_id, '_stock', 30 - $attendees_created);
        
        echo "Created {$attendees_created} attendees, checked in {$attendees_checked_in}\n";
    }
    
    $created_events[] = [
        'id' => $event_id,
        'title' => $data['title']
    ];
    
    echo "----------------------------\n";
}

// Summary
echo "\n=== Test Data Creation Summary ===\n";
echo "Created " . count($created_events) . " events:\n";
foreach ($created_events as $event) {
    echo "- {$event['title']} (ID: {$event['id']})\n";
}

// Create certificates for checked-in attendees if HVAC plugin is available
if (class_exists('HVAC_Certificate_Manager')) {
    echo "\nGenerating certificates...\n";
    
    $certificate_manager = HVAC_Certificate_Manager::instance();
    $certs_created = 0;
    
    foreach ($created_events as $event_data) {
        $event_id = $event_data['id'];
        
        // Get checked-in attendees
        $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
        ]);
        
        foreach ($attendees as $attendee) {
            if (!$certificate_manager->certificate_exists($event_id, $attendee->ID)) {
                $cert_path = 'hvac-certificates/' . date('Y/m/') . 'cert-' . $event_id . '-' . $attendee->ID . '.pdf';
                $cert_id = $certificate_manager->create_certificate(
                    $event_id,
                    $attendee->ID,
                    0,
                    $cert_path,
                    $trainer_id
                );
                if ($cert_id) {
                    $certs_created++;
                }
            }
        }
    }
    
    echo "Created {$certs_created} certificates\n";
}

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

# Execute the PHP script
php create-complete-test-data.php

# Clean up
rm create-complete-test-data.php
ENDSSH

echo ""
echo "[0;32mComplete test data creation finished![0m"
echo ""
echo "Test the enhanced dashboard features at:"
echo "- Dashboard: https://upskill-staging.measurequick.com/hvac-dashboard/"
echo "  - Use the search box to filter events"
echo "  - Use date range filters"
echo "  - Change items per page (10/25/50/100)"
echo "  - Sort columns by clicking headers"
echo ""
echo "Other pages to test:"
echo "- Create Event: https://upskill-staging.measurequick.com/manage-event/"
echo "- Generate Certificates: https://upskill-staging.measurequick.com/generate-certificates/"
echo "- Certificate Reports: https://upskill-staging.measurequick.com/certificate-reports/"