#!/bin/bash

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

# Load environment variables
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=== Fixing Test Events on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "==============================="

# Check the recently created events
echo -e "\n${YELLOW}Finding recently created events...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && wp post list --post_type=tribe_events --orderby=ID --order=DESC --fields=ID,post_title,post_author --number=10 --format=table --allow-root"

# Update the events to be owned by test_trainer
echo -e "\n${YELLOW}Updating events to be owned by test_trainer...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Get trainer user ID
TRAINER_ID=$(wp user get test_trainer --field=ID --allow-root)
echo "Trainer ID: $TRAINER_ID"

# Find our test events by title and update their author
EVENT_TITLES=(
    "HVAC System Maintenance Workshop"
    "Advanced HVAC Diagnostics Training"
    "HVAC Installation Best Practices"
    "Commercial HVAC Systems Overview"
    "HVAC Energy Efficiency Certification"
)

for TITLE in "${EVENT_TITLES[@]}"; do
    echo "Updating event: $TITLE"
    EVENT_ID=$(wp post list --post_type=tribe_events --title="$TITLE" --field=ID --allow-root)
    if [ -n "$EVENT_ID" ]; then
        wp post update $EVENT_ID --post_author=$TRAINER_ID --allow-root
        echo "Updated event ID $EVENT_ID"
    else
        echo "Event not found: $TITLE"
    fi
done

# Verify the updates
echo -e "\nVerifying updates..."
wp post list --post_type=tribe_events --author=$TRAINER_ID --fields=ID,post_title,post_author --format=table --allow-root
EOF

echo -e "\n${GREEN}Test events fixed!${NC}"