#!/bin/bash

echo "=== Debugging Master Dashboard Trainer Users Issue ==="
echo "Date: $(date)"
echo

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

echo "🔍 Investigating trainer users in database..."

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

echo "=== Master Dashboard Trainer Users Debug ==="

echo "🔍 Step 1: 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 2: List ALL users with hvac_master_trainer role..."
wp user list --role=hvac_master_trainer --fields=ID,user_login,user_email,roles --format=table

echo
echo "🔍 Step 3: Count total users with each role..."
echo "HVAC Trainers:"
wp user list --role=hvac_trainer --format=count

echo "HVAC Master Trainers:"
wp user list --role=hvac_master_trainer --format=count

echo
echo "🔍 Step 4: Check if there are users with 'HVAC Trainer' role (capitalized)..."
wp db query "SELECT u.ID, u.user_login, u.user_email, um.meta_value as roles 
            FROM wp_users u 
            JOIN wp_usermeta um ON u.ID = um.user_id 
            WHERE um.meta_key = 'wp_capabilities' 
            AND (um.meta_value LIKE '%hvac_trainer%' OR um.meta_value LIKE '%HVAC%')"

echo
echo "🔍 Step 5: Check for any role variations or case issues..."
wp db query "SELECT DISTINCT meta_value FROM wp_usermeta WHERE meta_key = 'wp_capabilities' AND meta_value LIKE '%hvac%'"

echo
echo "🔍 Step 6: Test the master dashboard query directly..."
wp eval "
\$trainer_users = get_users(array(
    'role__in' => array('hvac_trainer', 'hvac_master_trainer'),
    'fields' => 'ID'
));
echo 'Trainer users found by role__in query: ' . count(\$trainer_users) . PHP_EOL;
foreach(\$trainer_users as \$user_id) {
    \$user = get_user_by('ID', \$user_id);
    echo 'User: ' . \$user->user_login . ' (' . \$user->user_email . ') - Roles: ' . implode(', ', \$user->roles) . PHP_EOL;
}
"

echo
echo "🔍 Step 7: Check actual events created by trainer users..."
wp db query "SELECT p.post_author, u.user_login, u.user_email, COUNT(*) as event_count
            FROM wp_posts p 
            JOIN wp_users u ON p.post_author = u.ID 
            WHERE p.post_type = 'tribe_events' 
            GROUP BY p.post_author 
            ORDER BY event_count DESC"

EOF

echo "✅ Trainer users debugging completed!"