#!/bin/bash

# Create test users on staging server using expect
source .env

echo "=== Creating Test Users on Staging Server ==="

# Get SSH password
read -sp "Enter SSH password for $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP: " SSH_PASS
echo ""

# Create PHP script
cat << 'EOF' > /tmp/create-test-users.php
<?php
require_once('wp-load.php');

echo "Creating test users...\n";

// Create test_trainer
$user_id = wp_create_user('test_trainer', 'TestTrainer123!', 'test_trainer@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');
    update_user_meta($user_id, 'hvac_account_status', 'active');
    echo "Created test_trainer (password: TestTrainer123!)\n";
} else {
    echo "test_trainer may already exist: " . $user_id->get_error_message() . "\n";
}

// Create test_master
$user_id = wp_create_user('test_master', 'TestMaster123!', 'test_master@example.com');
if (!is_wp_error($user_id)) {
    $user = new WP_User($user_id);
    $user->set_role('hvac_master_trainer');
    update_user_meta($user_id, 'first_name', 'Test');
    update_user_meta($user_id, 'last_name', 'Master');
    update_user_meta($user_id, 'hvac_account_status', 'active');
    echo "Created test_master (password: TestMaster123!)\n";
} else {
    echo "test_master may already exist: " . $user_id->get_error_message() . "\n";
}

echo "Done!\n";
EOF

# Upload and execute using expect
expect << EXPECT_SCRIPT
set timeout 30

# Upload file
spawn scp -o StrictHostKeyChecking=no /tmp/create-test-users.php $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:/tmp/
expect "password:"
send "$SSH_PASS\r"
expect eof

# Execute on server
spawn ssh -o StrictHostKeyChecking=no $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP
expect "password:"
send "$SSH_PASS\r"
expect -re {.*[\$#] }
send "cd $UPSKILL_STAGING_PATH\r"
expect -re {.*[\$#] }
send "cp /tmp/create-test-users.php ./\r"
expect -re {.*[\$#] }
send "wp eval-file create-test-users.php\r"
expect -re {.*[\$#] }
send "rm create-test-users.php\r"
expect -re {.*[\$#] }
send "rm /tmp/create-test-users.php\r"
expect -re {.*[\$#] }
send "exit\r"
expect eof
EXPECT_SCRIPT

echo ""
echo "=== Test Users Created ==="
echo "Login credentials:"
echo "1. test_trainer / TestTrainer123!"
echo "2. test_master / TestMaster123!"
echo ""
echo "Login URL: https://upskill-staging.measurequick.com/training-login/"