#!/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 "=== Checking Created Events on Staging Server ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "Remote user: $UPSKILL_STAGING_SSH_USER"
echo "==============================="

# Check the recently created events by ID range
echo -e "\n${YELLOW}Finding events created today (ID range 5482-5486)...${NC}"
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" \
"cd ${UPSKILL_STAGING_PATH} && for ID in 5482 5483 5484 5485 5486; do wp post get \$ID --field=post_title,post_author --format=json --allow-root 2>/dev/null && echo; done"

# Get more details about these events
echo -e "\n${YELLOW}Getting detailed info about these 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 --include=5482,5483,5484,5485,5486 --fields=ID,post_title,post_author,post_status --format=table --allow-root"

# Update these events to be owned by test_trainer
echo -e "\n${YELLOW}Updating events 5482-5486 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"

# Update events by ID
for EVENT_ID in 5482 5483 5484 5485 5486; do
    if wp post get $EVENT_ID --allow-root >/dev/null 2>&1; then
        echo "Updating event ID $EVENT_ID..."
        wp post update $EVENT_ID --post_author=$TRAINER_ID --allow-root
    else
        echo "Event ID $EVENT_ID not found"
    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}Event check completed!${NC}"