#!/bin/bash

echo "=== Updating Joe Users with Master Trainer Roles ==="
echo "Date: $(date)"
echo

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

echo "🔧 Updating user roles on staging server..."

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

echo "=== Updating Joe Users with Master Trainer Roles ==="

# Update joe@measurequick.com
echo "🔧 Updating joe@measurequick.com..."
wp user list --field=user_email | grep -q "joe@measurequick.com"
if [ $? -eq 0 ]; then
    echo "✅ Found joe@measurequick.com user"
    
    # Get user ID
    USER_ID=$(wp user get joe@measurequick.com --field=ID 2>/dev/null)
    echo "📋 User ID: $USER_ID"
    
    # Add hvac_master_trainer role (keeping existing roles)
    wp user add-role joe@measurequick.com hvac_master_trainer
    echo "✅ Added hvac_master_trainer role"
    
    # Verify roles
    ROLES=$(wp user get joe@measurequick.com --field=roles)
    echo "📋 Current roles: $ROLES"
else
    echo "⚠️ joe@measurequick.com user not found, creating..."
    wp user create joe@measurequick.com joe@measurequick.com --role=hvac_trainer --user_pass=JoeTrainer2025@ --first_name=Joe --last_name=MeasureQuick
    wp user add-role joe@measurequick.com hvac_master_trainer
    echo "✅ Created and configured joe@measurequick.com"
fi

echo

# Update joe@upskillhvac.com
echo "🔧 Updating joe@upskillhvac.com..."
wp user list --field=user_email | grep -q "joe@upskillhvac.com"
if [ $? -eq 0 ]; then
    echo "✅ Found joe@upskillhvac.com user"
    
    # Get user ID
    USER_ID=$(wp user get joe@upskillhvac.com --field=ID 2>/dev/null)
    echo "📋 User ID: $USER_ID"
    
    # Add hvac_trainer role if not present
    wp user add-role joe@upskillhvac.com hvac_trainer
    
    # Add hvac_master_trainer role
    wp user add-role joe@upskillhvac.com hvac_master_trainer
    echo "✅ Added hvac_master_trainer role"
    
    # Verify roles
    ROLES=$(wp user get joe@upskillhvac.com --field=roles)
    echo "📋 Current roles: $ROLES"
else
    echo "⚠️ joe@upskillhvac.com user not found, creating..."
    wp user create joe@upskillhvac.com joe@upskillhvac.com --role=hvac_trainer --user_pass=JoeTrainer2025@ --first_name=Joe --last_name=UpskillHVAC
    wp user add-role joe@upskillhvac.com hvac_master_trainer
    echo "✅ Created and configured joe@upskillhvac.com"
fi

echo
echo "=== Final Verification ==="

# List all users with HVAC roles
echo "📋 All users with HVAC trainer roles:"
wp user list --role=hvac_trainer --fields=ID,user_login,user_email,roles

echo
echo "📋 All users with HVAC master trainer roles:"
wp user list --role=hvac_master_trainer --fields=ID,user_login,user_email,roles

echo
echo "✅ User role updates completed!"

EOF

echo "✅ User role updates completed on staging server!"
echo
echo "Updated users:"
echo "- joe@measurequick.com: hvac_trainer + hvac_master_trainer roles"
echo "- joe@upskillhvac.com: hvac_trainer + hvac_master_trainer roles"