#!/bin/bash

echo "=== Migrating event_trainer users to hvac_trainer role ==="
echo "Date: $(date)"
echo

# SSH connection details
SERVER="146.190.76.204"
USER="roodev"

echo "🔄 Migrating legacy event_trainer roles to hvac_trainer..."

# Execute migration via SSH
ssh ${USER}@${SERVER} << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

echo "=== Event Trainer to HVAC Trainer Migration ==="

echo "🔍 Step 1: List all users with event_trainer role before migration..."
wp user list --role=event_trainer --fields=ID,user_login,user_email,roles --format=table

echo
echo "🔄 Step 2: Migrating each event_trainer user to hvac_trainer role..."

# Get all event_trainer users and migrate them
wp user list --role=event_trainer --field=user_login | while read -r username; do
    if [ -n "$username" ]; then
        echo "  🔄 Migrating user: $username"
        
        # Remove event_trainer role and add hvac_trainer role
        wp user remove-role "$username" event_trainer
        wp user add-role "$username" hvac_trainer
        
        echo "  ✅ Migrated $username from event_trainer to hvac_trainer"
    fi
done

echo
echo "🔍 Step 3: Verify migration - list all users with hvac_trainer role..."
wp user list --role=hvac_trainer --fields=ID,user_login,user_email,roles --format=table

echo
echo "🔍 Step 4: Check if any event_trainer users remain..."
REMAINING_COUNT=$(wp user list --role=event_trainer --format=count)
echo "Remaining event_trainer users: $REMAINING_COUNT"

if [ "$REMAINING_COUNT" -gt 0 ]; then
    echo "⚠️  Some event_trainer users still remain:"
    wp user list --role=event_trainer --fields=ID,user_login,user_email,roles --format=table
else
    echo "✅ All event_trainer users successfully migrated!"
fi

echo
echo "🔍 Step 5: Final verification - test master dashboard query..."
wp eval "
\$trainer_users = get_users(array(
    'role__in' => array('hvac_trainer', 'hvac_master_trainer'),
    'fields' => 'ID'
));
echo 'Total trainer users now found by master dashboard query: ' . count(\$trainer_users) . PHP_EOL;
echo 'User breakdown:' . PHP_EOL;
foreach(\$trainer_users as \$user_id) {
    \$user = get_user_by('ID', \$user_id);
    echo '  - ' . \$user->user_login . ' (' . \$user->user_email . ') - Roles: ' . implode(', ', \$user->roles) . PHP_EOL;
}
"

echo
echo "✅ Migration completed!"

EOF

echo "✅ Event trainer to HVAC trainer migration completed on staging server!"
echo
echo "Summary:"
echo "- All users with 'event_trainer' role have been migrated to 'hvac_trainer'"
echo "- Master dashboard should now show all trainer users"
echo "- Legacy 'event_trainer' role artifacts have been cleaned up"