#!/bin/bash

# Create Test Attendees Script
# Creates proper Event Tickets attendee records with correct post_parent relationships

source .env

echo "=== Creating Test Attendees for Certificate Testing ==="
echo "Target: $UPSKILL_STAGING_IP"
echo "======================================="

# Upload and execute PHP script to create attendees
sshpass -p "$UPSKILL_STAGING_PASS" scp -o StrictHostKeyChecking=no /dev/stdin $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:tmp/create-attendees.php << 'PHPEOF'
<?php
require_once('wp-load.php');

echo "=== Creating Test Attendees for Events ===\n";

// Get recent test events created by test_trainer
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    die("test_trainer user not found. Run comprehensive test data script first.\n");
}

$trainer_id = $test_trainer->ID;
echo "Using trainer ID: {$trainer_id}\n";

// Get the trainer's events
$events = get_posts([
    'post_type' => 'tribe_events',
    'post_status' => 'publish',
    'author' => $trainer_id,
    'numberposts' => 5,
    'orderby' => 'date',
    'order' => 'DESC'
]);

if (empty($events)) {
    die("No events found for test_trainer. Run comprehensive test data script first.\n");
}

echo "Found " . count($events) . " events for test_trainer\n";

foreach ($events as $event) {
    echo "\nCreating attendees for event: {$event->post_title} (ID: {$event->ID})\n";
    
    // Create 5 attendees for each event
    for ($i = 1; $i <= 5; $i++) {
        $attendee_args = [
            'post_title' => "Test Attendee {$i} for {$event->post_title}",
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'tribe_tpp_attendees',
            'post_author' => $trainer_id,
            'post_parent' => $event->ID  // CRITICAL: Link to event
        ];
        
        $attendee_id = wp_insert_post($attendee_args);
        
        if (!is_wp_error($attendee_id)) {
            echo "Created attendee ID: {$attendee_id}\n";
            
            // Add all required meta fields
            update_post_meta($attendee_id, '_tribe_tpp_event', $event->ID);
            update_post_meta($attendee_id, '_tribe_tpp_full_name', "Test Attendee {$i}");
            update_post_meta($attendee_id, '_tribe_tickets_full_name', "Test Attendee {$i}");
            update_post_meta($attendee_id, '_tribe_tpp_email', "test.attendee.{$i}.{$event->ID}@example.com");
            update_post_meta($attendee_id, '_tribe_tickets_email', "test.attendee.{$i}.{$event->ID}@example.com");
            update_post_meta($attendee_id, '_tribe_tpp_attendee_email', "test.attendee.{$i}.{$event->ID}@example.com");
            update_post_meta($attendee_id, '_tribe_tpp_order', "ORDER-{$event->ID}-{$i}");
            update_post_meta($attendee_id, '_tribe_tpp_product', 0); // No specific ticket product
            
            // Check in first 3 attendees, leave 2 unchecked
            if ($i <= 3) {
                update_post_meta($attendee_id, '_tribe_tickets_attendee_checked_in', '1');
                update_post_meta($attendee_id, '_tribe_tpp_checkin', '1');
                update_post_meta($attendee_id, 'check_in', '1');
                echo "  - Checked in attendee {$i}\n";
            } else {
                update_post_meta($attendee_id, '_tribe_tickets_attendee_checked_in', '0');
                update_post_meta($attendee_id, '_tribe_tpp_checkin', '0');
                update_post_meta($attendee_id, 'check_in', '0');
                echo "  - Left attendee {$i} not checked in\n";
            }
        } else {
            echo "Failed to create attendee {$i}: " . $attendee_id->get_error_message() . "\n";
        }
    }
}

echo "\n=== Verification Query ===\n";
echo "Running same query as certificate template...\n";

// Run the exact same query that the certificate template uses
global $wpdb;

foreach ($events as $event) {
    echo "\nEvent: {$event->post_title} (ID: {$event->ID})\n";
    
    $attendees = $wpdb->get_results($wpdb->prepare(
        "SELECT 
            p.ID as attendee_id,
            p.post_parent as event_id,
            COALESCE(tec_full_name.meta_value, tpp_full_name.meta_value, tickets_full_name.meta_value, 'Unknown Attendee') as holder_name,
            COALESCE(tec_email.meta_value, tpp_email.meta_value, tickets_email.meta_value, tpp_attendee_email.meta_value, 'no-email@example.com') as holder_email,
            COALESCE(checked_in.meta_value, '0') as check_in
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} tec_full_name ON p.ID = tec_full_name.post_id AND tec_full_name.meta_key = '_tec_tickets_commerce_full_name'
        LEFT JOIN {$wpdb->postmeta} tpp_full_name ON p.ID = tpp_full_name.post_id AND tpp_full_name.meta_key = '_tribe_tpp_full_name'
        LEFT JOIN {$wpdb->postmeta} tickets_full_name ON p.ID = tickets_full_name.post_id AND tickets_full_name.meta_key = '_tribe_tickets_full_name'
        LEFT JOIN {$wpdb->postmeta} tec_email ON p.ID = tec_email.post_id AND tec_email.meta_key = '_tec_tickets_commerce_email'
        LEFT JOIN {$wpdb->postmeta} tpp_email ON p.ID = tpp_email.post_id AND tpp_email.meta_key = '_tribe_tpp_email'
        LEFT JOIN {$wpdb->postmeta} tickets_email ON p.ID = tickets_email.post_id AND tickets_email.meta_key = '_tribe_tickets_email'
        LEFT JOIN {$wpdb->postmeta} tpp_attendee_email ON p.ID = tpp_attendee_email.post_id AND tpp_attendee_email.meta_key = '_tribe_tpp_attendee_email'
        LEFT JOIN {$wpdb->postmeta} checked_in ON p.ID = checked_in.post_id AND checked_in.meta_key = '_tribe_tickets_attendee_checked_in'
        WHERE p.post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees') 
        AND p.post_parent = %d
        ORDER BY p.ID ASC",
        $event->ID
    ));
    
    echo "Found " . count($attendees) . " attendees:\n";
    foreach ($attendees as $attendee) {
        $status = $attendee->check_in ? 'Checked In' : 'Not Checked In';
        echo "  - ID: {$attendee->attendee_id}, Name: {$attendee->holder_name}, Email: {$attendee->holder_email}, Status: {$status}\n";
    }
}

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

# Execute the script on the server
echo "Executing attendee creation script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP "cd $UPSKILL_STAGING_PATH && php ../tmp/create-attendees.php && rm ../tmp/create-attendees.php"

echo ""
echo "✅ Test attendee creation completed!"
echo ""
echo "Next steps:"
echo "1. Login to staging as test_trainer (Test123!)"
echo "2. Go to Generate Certificates page"
echo "3. Select any event - should now show 5 attendees"
echo "4. Verify certificate generation works"