#!/bin/bash

# Create test events, tickets, attendees with check-ins for certificate testing

# Load configuration
source bin/deploy-config.sh

echo "=== Creating Test Data with Check-ins on Staging Server ==="
echo "Remote host: $REMOTE_HOST"
echo "Remote user: $REMOTE_USER"
echo "WordPress path: $REMOTE_PATH_BASE"
echo "==============================="

# Create PHP script to run on server
cat << 'EOF' > create-test-data.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 "Creating test data for certificate testing...\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";

// Event data
$events = [
    [
        'title' => 'HVAC Certification Workshop',
        'description' => 'A comprehensive workshop for HVAC professionals seeking certification.',
        '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')),
        'price' => 250,
        'capacity' => 30,
        'attendees' => 20,
        'checkins' => 15 // Number of attendees to check in
    ],
    [
        'title' => 'Advanced HVAC Troubleshooting',
        'description' => 'Master advanced techniques for diagnosing and fixing complex HVAC issues.',
        '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')),
        'price' => 350,
        'capacity' => 20,
        'attendees' => 15,
        'checkins' => 10
    ],
    [
        'title' => 'Commercial HVAC Systems',
        'description' => 'Specialized training for commercial HVAC installation and maintenance.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+6 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+6 weeks +8 hours')),
        'price' => 400,
        'capacity' => 25,
        'attendees' => 18,
        'checkins' => 12
    ]
];

// Create events and related data
foreach ($events as $event_data) {
    // Create event
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_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;
    }
    
    echo "Created event: {$event_data['title']} (ID: {$event_id})\n";
    
    // 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' => "HVAC Training Center - {$event_data['title']}",
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::VENUE_POST_TYPE,
        '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($venue_id, '_VenuePhone', '555-123-4567');
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    // Create organizer
    $organizer_args = [
        'post_title' => "HVAC Trainers Organization",
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::ORGANIZER_POST_TYPE,
        'post_author' => $trainer_id
    ];
    
    $organizer_id = wp_insert_post($organizer_args);
    
    if (!is_wp_error($organizer_id)) {
        update_post_meta($organizer_id, '_OrganizerEmail', 'trainer@example.com');
        update_post_meta($organizer_id, '_OrganizerPhone', '555-987-6543');
        update_post_meta($organizer_id, '_OrganizerWebsite', 'https://hvactrainers.example.com');
        update_post_meta($event_id, '_EventOrganizerID', $organizer_id);
    }
    
    // Create ticket for the event (using PayPal provider from Event Tickets Plus)
    if (class_exists('Tribe__Tickets_Plus__Commerce__PayPal__Main')) {
        $provider = Tribe__Tickets_Plus__Commerce__PayPal__Main::get_instance();
        $ticket_id = $provider->ticket_add($event_id, [
            'ticket_name' => "General Admission - {$event_data['title']}",
            'ticket_description' => "Ticket for {$event_data['title']}",
            'ticket_price' => $event_data['price'],
            'ticket_show_description' => 'yes',
            'ticket_start_date' => date('Y-m-d H:i:s'),
            'ticket_end_date' => $event_data['start_date'],
            'ticket_capacity' => $event_data['capacity']
        ]);
        
        if ($ticket_id) {
            echo "Created ticket ID: {$ticket_id} for event ID: {$event_id}\n";
            
            // Create test attendees with email addresses
            $attendee_ids = [];
            for ($i = 1; $i <= $event_data['attendees']; $i++) {
                $attendee_first_name = "Attendee" . $i;
                $attendee_last_name = "Event" . $event_id;
                $attendee_email = "attendee{$i}_event{$event_id}@example.com";
                
                // Check if we should use a specific email for one attendee per 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;
                
                // Add attendee meta
                $meta = [
                    '_tribe_tpp_full_name' => "{$attendee_first_name} {$attendee_last_name}",
                    '_tribe_tpp_email' => $attendee_email,
                    '_tribe_tickets_full_name' => "{$attendee_first_name} {$attendee_last_name}",
                    '_tribe_tickets_email' => $attendee_email,
                    '_tribe_tpp_event' => $event_id,
                    '_tribe_tpp_product' => $ticket_id,
                    '_tribe_tpp_order' => uniqid('ORDER-'),
                    '_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 as $key => $value) {
                    update_post_meta($attendee_id, $key, $value);
                }
                
                // Check in some attendees (for certificate testing)
                if ($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);
                    echo "Checked in attendee {$attendee_id} for event {$event_id}\n";
                }
            }
            
            echo "Created {$event_data['attendees']} attendees for event {$event_id}\n";
            echo "Checked in {$event_data['checkins']} attendees for event {$event_id}\n";
            
            // Update event attendance count
            update_post_meta($event_id, '_tribe_ticket_sold_count', $event_data['attendees']);
            update_post_meta($ticket_id, '_tribe_ticket_sold', $event_data['attendees']);
            update_post_meta($ticket_id, '_stock', $event_data['capacity'] - $event_data['attendees']);
        } else {
            echo "Failed to create ticket for event {$event_id}\n";
        }
    } else {
        echo "Event Tickets Plus PayPal provider not available, skipping ticket creation\n";
    }
    
    echo "----------------------------\n";
}

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

# Copy PHP script to server and execute
echo "[1;33mCopying script to server...[0m"
scp create-test-data.php $REMOTE_USER@$REMOTE_HOST:/home/974670.cloudwaysapps.com/uberrxmprk/public_html/

echo "[1;33mExecuting script on server...[0m"
ssh $REMOTE_USER@$REMOTE_HOST "cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html/ && php create-test-data.php"

# Clean up
rm create-test-data.php
ssh $REMOTE_USER@$REMOTE_HOST "rm /home/974670.cloudwaysapps.com/uberrxmprk/public_html/create-test-data.php"

echo "[0;32mTest data creation completed![0m"
echo "1. Created events, tickets, and attendees on staging"
echo "2. Added check-in status for some attendees"
echo "3. Events are assigned to test_trainer user"
echo "4. One attendee for each event has email: ben@tealmaker.com"
echo "5. Checked-in attendees are ready for certificate generation"