#!/bin/bash

# Comprehensive Test Data Creation Script
# Creates users, events, attendees, and certificates for staging environment
# Includes both regular trainers and master trainers

source .env

echo "=== Creating Comprehensive Test Data on Staging Server ==="
echo "Target: $UPSKILL_STAGING_IP"
echo "==============================="

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

echo "=== Creating comprehensive test data ===\n";

// Create or update test_trainer user
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    echo "Creating test_trainer user...\n";
    $user_id = wp_create_user('test_trainer', 'Test123!', 'test@example.com');
    if (!is_wp_error($user_id)) {
        $user = new WP_User($user_id);
        $user->set_role('hvac_trainer');
        update_user_meta($user_id, 'first_name', 'Test');
        update_user_meta($user_id, 'last_name', 'Trainer');
        $test_trainer = get_user_by('ID', $user_id);
        echo "Created test_trainer user (ID: {$user_id})\n";
    }
} else {
    echo "Found existing test_trainer user (ID: {$test_trainer->ID})\n";
}

// Create or update Joe Medosch as master trainer
$joe_user = get_user_by('email', 'JoeMedosch@gmail.com');
if (!$joe_user) {
    echo "Creating JoeMedosch@gmail.com master trainer...\n";
    $joe_id = wp_create_user('joemedosch', 'JoeTrainer2025@', 'JoeMedosch@gmail.com');
    if (!is_wp_error($joe_id)) {
        $user = new WP_User($joe_id);
        $user->set_role('hvac_master_trainer');
        update_user_meta($joe_id, 'first_name', 'Joe');
        update_user_meta($joe_id, 'last_name', 'Medosch');
        update_user_meta($joe_id, 'display_name', 'Joe Medosch');
        $joe_user = get_user_by('ID', $joe_id);
        echo "Created Joe Medosch master trainer (ID: {$joe_id})\n";
    }
} else {
    echo "Found existing Joe Medosch user (ID: {$joe_user->ID})\n";
    // Ensure they have master trainer role
    $user = new WP_User($joe_user->ID);
    $user->set_role('hvac_master_trainer');
    echo "Updated Joe Medosch to master trainer role\n";
}

// Assign roles to joe@measurequick.com if user exists
$joe_mq_user = get_user_by('email', 'joe@measurequick.com');
if ($joe_mq_user) {
    echo "Found joe@measurequick.com user (ID: {$joe_mq_user->ID})\n";
    echo "Assigning trainer and master trainer roles...\n";
    
    // Add both HVAC roles (keeping existing roles)
    $user = new WP_User($joe_mq_user->ID);
    $user->add_role('hvac_trainer');
    $user->add_role('hvac_master_trainer');
    
    echo "Added hvac_trainer and hvac_master_trainer roles to joe@measurequick.com\n";
} else {
    echo "joe@measurequick.com user not found (may not exist in staging)\n";
}

if (!$test_trainer) {
    die("Failed to create/find test_trainer user\n");
}

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

// Create 3 test events
$events = [
    [
        'title' => 'HVAC System Diagnostics',
        'description' => 'Advanced diagnostic techniques for HVAC systems',
        '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' => 299
    ],
    [
        'title' => 'Commercial Refrigeration',
        'description' => 'Commercial refrigeration systems training',
        'start_date' => date('Y-m-d 09:00:00', strtotime('+2 weeks')),
        'end_date' => date('Y-m-d 17:00:00', strtotime('+2 weeks')),
        'price' => 349
    ],
    [
        'title' => 'Energy Efficient HVAC',
        'description' => 'Energy efficiency in HVAC design',
        'start_date' => date('Y-m-d 09:00:00', strtotime('+3 weeks')),
        'end_date' => date('Y-m-d 17:00:00', strtotime('+3 weeks')),
        'price' => 399
    ]
];

$events_created = 0;
foreach ($events as $event_data) {
    echo "Creating event: {$event_data['title']}\n";
    
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_data['description'],
        'post_status' => 'publish',
        'post_type' => 'tribe_events',
        'post_author' => $trainer_id,
        'meta_input' => [
            '_EventStartDate' => $event_data['start_date'],
            '_EventEndDate' => $event_data['end_date'],
            '_EventCost' => $event_data['price']
        ]
    ];
    
    $event_id = wp_insert_post($event_args);
    
    if (!is_wp_error($event_id)) {
        echo "Created event ID: {$event_id}\n";
        
        // Create ticket
        $ticket_args = [
            'post_title' => 'General Admission',
            '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)) {
            update_post_meta($ticket_id, '_tribe_tpp_for_event', $event_id);
            update_post_meta($ticket_id, '_price', $event_data['price']);
            update_post_meta($ticket_id, '_capacity', 30);
            update_post_meta($ticket_id, '_stock', 25);
            
            // Create 5 attendees
            for ($i = 1; $i <= 5; $i++) {
                $attendee_args = [
                    'post_title' => "Test Attendee {$i}",
                    '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)) {
                    update_post_meta($attendee_id, '_tribe_tpp_event', $event_id);
                    update_post_meta($attendee_id, '_tribe_tpp_product', $ticket_id);
                    update_post_meta($attendee_id, '_tribe_tickets_full_name', "Test Attendee {$i}");
                    update_post_meta($attendee_id, '_tribe_tickets_email', "test{$i}@example.com");
                    update_post_meta($attendee_id, '_tribe_tpp_order', "ORDER-{$event_id}-{$i}");
                    
                    // Check in first 3 attendees
                    if ($i <= 3) {
                        update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
                        update_post_meta($attendee_id, 'check_in', 1);
                    }
                }
            }
            
            echo "Created 5 attendees (3 checked in)\n";
        }
        $events_created++;
    }
}

echo "\n=== Test Data Creation Complete ===\n";
echo "Created users:\n";
echo "- test_trainer (hvac_trainer role)\n";
echo "- JoeMedosch@gmail.com (hvac_master_trainer role)\n";
echo "Created {$events_created} events with attendees\n";
echo "\nLogin credentials:\n";
echo "test_trainer: Test123!\n";
echo "JoeMedosch@gmail.com: JoeTrainer2025@\n";
?>
PHPEOF

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

echo ""
echo "✅ Comprehensive test data creation completed!"
echo ""
echo "Users created:"
echo "- test_trainer (Trainer): Test123!"
echo "- JoeMedosch@gmail.com (Master Trainer): JoeTrainer2025@"
echo ""
echo "Test URLs:"
echo "- Login: https://upskill-staging.measurequick.com/training-login/"
echo "- Trainer Dashboard: https://upskill-staging.measurequick.com/trainer/dashboard/"
echo "- Master Dashboard: https://upskill-staging.measurequick.com/master-trainer/dashboard/"