#!/bin/bash

echo "📄 Creating Event Management Pages (Fixed Version)..."
echo "====================================================="

# Check SSH connection first
echo "🔍 Testing SSH connection..."
if ! ssh -o ConnectTimeout=10 wp@upskill-staging.measurequick.com 'echo "Connection successful"' 2>/dev/null; then
    echo "❌ SSH connection failed"
    echo "This script requires SSH access to upskill-staging.measurequick.com"
    echo "You may need to run the deployment script instead."
    exit 1
fi

echo "✅ SSH connection successful"

# Connect to staging without suppressing errors
ssh wp@upskill-staging.measurequick.com << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

echo "🔧 Checking for trainer parent page..."
TRAINER_ID=$(wp post list --post_type=page --name=trainer --field=ID)
if [ -z "$TRAINER_ID" ]; then
    echo "❌ Trainer parent page not found!"
    exit 1
fi
echo "✅ Trainer parent page found: ID $TRAINER_ID"

echo "🔧 Creating Create Event page..."
CREATE_EVENT_ID=$(wp post create \
    --post_type=page \
    --post_title='Create Event' \
    --post_content='[hvac_create_event]' \
    --post_status=publish \
    --post_author=1 \
    --post_parent=$TRAINER_ID \
    --post_name='create-event' \
    --meta_input='{"_wp_page_template":"templates/page-create-event.php"}' \
    --porcelain)

if [ $? -eq 0 ] && [ ! -z "$CREATE_EVENT_ID" ]; then
    echo "✅ Create Event page created with ID: $CREATE_EVENT_ID"
else
    echo "❌ Failed to create Create Event page"
    exit 1
fi

echo "🔧 Creating Edit Event page..."
EDIT_EVENT_ID=$(wp post create \
    --post_type=page \
    --post_title='Edit Event' \
    --post_content='[hvac_edit_event]' \
    --post_status=publish \
    --post_author=1 \
    --post_parent=$TRAINER_ID \
    --post_name='edit-event' \
    --meta_input='{"_wp_page_template":"templates/page-edit-event.php"}' \
    --porcelain)

if [ $? -eq 0 ] && [ ! -z "$EDIT_EVENT_ID" ]; then
    echo "✅ Edit Event page created with ID: $EDIT_EVENT_ID"
else
    echo "❌ Failed to create Edit Event page"
    exit 1
fi

echo "🔄 Flushing rewrite rules..."
wp rewrite flush

echo "📋 Verifying created pages:"
wp post list --post_type=page --name='create-event' --fields=ID,post_title,post_name,post_status,post_parent
wp post list --post_type=page --name='edit-event' --fields=ID,post_title,post_name,post_status,post_parent

echo "🔧 Testing page URLs..."
echo "Create Event: https://upskill-staging.measurequick.com/trainer/create-event/"
echo "Edit Event: https://upskill-staging.measurequick.com/trainer/edit-event/"

EOF

if [ $? -eq 0 ]; then
    echo -e "\n✅ Event pages created successfully!"
    echo "URLs:"
    echo "  Create: https://upskill-staging.measurequick.com/trainer/create-event/"
    echo "  Edit: https://upskill-staging.measurequick.com/trainer/edit-event/"
else
    echo -e "\n❌ Failed to create event pages"
    exit 1
fi