#!/bin/bash

# Add test attendees with check-ins to existing events for certificate testing

echo "=== Adding Test Attendees with Check-ins on Staging Server ==="
echo "Remote host: 146.190.76.204"
echo "Remote user: roodev"
echo "==============================="

# Create PHP script to run on server
cat << 'EOF' > add-attendees.php
<?php
// Load WordPress
require_once 'wp-load.php';

// Ensure TEC and ET 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");
}

echo "Adding test attendees to existing events...\n";

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

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

// Use existing events
$event_data = [
    5484 => [ // HVAC Installation Best Practices
        'price' => 150,
        'attendees' => 12,
        'checkins' => 8
    ],
    5485 => [ // Commercial HVAC Systems Overview
        'price' => 250,
        'attendees' => 15,
        'checkins' => 10
    ],
    5486 => [ // HVAC Energy Efficiency Certification
        'price' => 350,
        'attendees' => 20,
        'checkins' => 15
    ]
];

foreach ($event_data as $event_id => $data) {
    // Get event post
    $event = get_post($event_id);
    if (!$event) {
        echo "Event ID {$event_id} not found, skipping\n";
        continue;
    }
    
    echo "Processing event: {$event->post_title} (ID: {$event_id})\n";
    
    // Create ticket if needed or use existing
    $existing_tickets = get_posts([
        'post_type' => 'tribe_tpp_tickets',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_for_event',
                'value' => $event_id,
            ]
        ],
        'posts_per_page' => 1
    ]);
    
    if (!empty($existing_tickets)) {
        $ticket_id = $existing_tickets[0]->ID;
        echo "Using existing ticket ID: {$ticket_id}\n";
        
        // Update ticket price and capacity if needed
        update_post_meta($ticket_id, '_price', $data['price']);
        update_post_meta($ticket_id, '_capacity', $data['attendees'] + 5); // Add buffer
    } else {
        // Create new ticket using PayPal provider
        if (class_exists('Tribe__Tickets_Plus__Commerce__PayPal__Main')) {
            $provider = Tribe__Tickets_Plus__Commerce__PayPal__Main::get_instance();
            
            $ticket_args = [
                'post_title' => "General Admission - {$event->post_title}",
                'post_content' => "Ticket for {$event->post_title}",
                'post_status' => 'publish',
                'post_type' => 'tribe_tpp_tickets',
            ];
            
            $ticket_id = wp_insert_post($ticket_args);
            
            if (is_wp_error($ticket_id)) {
                echo "Failed to create ticket for event {$event_id}: " . $ticket_id->get_error_message() . "\n";
                continue;
            }
            
            // 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'] + 5); // Add buffer
            update_post_meta($ticket_id, '_stock', $data['attendees'] + 5);
            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 new ticket ID: {$ticket_id}\n";
        } else {
            echo "Event Tickets Plus PayPal provider not available, skipping ticket creation\n";
            continue;
        }
    }
    
    // Clear any existing attendees (optional - comment out if you want to keep existing ones)
    $existing_attendees = get_posts([
        'post_type' => 'tribe_tpp_attendees',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_event',
                'value' => $event_id,
            ]
        ],
        'posts_per_page' => -1
    ]);
    
    if (!empty($existing_attendees)) {
        echo "Removing " . count($existing_attendees) . " existing attendees...\n";
        foreach ($existing_attendees as $attendee) {
            wp_delete_post($attendee->ID, true);
        }
    }
    
    // Create attendees with check-ins
    $attendee_ids = [];
    for ($i = 1; $i <= $data['attendees']; $i++) {
        $attendee_first_name = "Attendee" . $i;
        $attendee_last_name = "Event" . $event_id;
        $attendee_email = "attendee{$i}_event{$event_id}@example.com";
        
        // 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 (for certificate testing)
        if ($i <= $data['checkins']) {
            // Multiple check-in meta fields for compatibility with different providers
            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 "Checked in attendee {$attendee_id} for event {$event_id}\n";
        }
    }
    
    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']);
    
    echo "----------------------------\n";
}

echo "Test attendee creation completed!\n";
?>
EOF

# Copy PHP script to server and execute
echo "[1;33mCopying script to server...[0m"
scp add-attendees.php roodev@146.190.76.204:/home/974670.cloudwaysapps.com/uberrxmprk/public_html/

echo "[1;33mExecuting script on server...[0m"
ssh roodev@146.190.76.204 "cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html/ && php add-attendees.php"

# Clean up
rm add-attendees.php
ssh roodev@146.190.76.204 "rm /home/974670.cloudwaysapps.com/uberrxmprk/public_html/add-attendees.php"

echo "[0;32mTest data creation completed![0m"
echo "1. Added attendees to existing events on staging"
echo "2. Some attendees are marked as checked-in"
echo "3. One attendee for each event has email: ben@tealmaker.com"
echo "4. Checked-in attendees are ready for certificate generation"