#!/bin/bash
set -e

# Fix TEC Template Installation Script
# Resolves theme detection and template override placement issues

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

# Load environment variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

if [ -f "$PROJECT_ROOT/.env" ]; then
    export $(cat "$PROJECT_ROOT/.env" | sed 's/#.*//g' | xargs)
fi

ENVIRONMENT="${1:-staging}"

if [ "$ENVIRONMENT" = "staging" ]; then
    SERVER_IP=$UPSKILL_STAGING_IP
    SSH_USER=$UPSKILL_STAGING_SSH_USER
    SSH_PASS=$UPSKILL_STAGING_PASS
    SERVER_PATH=$UPSKILL_STAGING_PATH
    SITE_URL=$UPSKILL_STAGING_URL
else
    SERVER_IP=$UPSKILL_PROD_IP
    SSH_USER=$UPSKILL_PROD_SSH_USER
    SSH_PASS=$UPSKILL_PROD_SSH_PASS
    SERVER_PATH=$UPSKILL_PROD_PATH
    SITE_URL=$UPSKILL_PROD_URL
fi

echo -e "${YELLOW}=== Fixing TEC Template Installation ===${NC}"
echo "Environment: $ENVIRONMENT"
echo "Server: $SERVER_IP"
echo ""

echo -e "${GREEN}Step 1: Detecting active theme and installing template override...${NC}"

sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
cd $SERVER_PATH

# Get active theme using WordPress database query
ACTIVE_THEME=\$(wp eval 'echo wp_get_theme()->get_stylesheet();' 2>/dev/null | tr -d '\n')

if [ -z \"\$ACTIVE_THEME\" ]; then
    echo 'Failed to detect active theme via WP-CLI, trying alternative method...'
    ACTIVE_THEME=\$(wp option get stylesheet 2>/dev/null | tr -d '\n')
fi

if [ -z \"\$ACTIVE_THEME\" ]; then
    echo 'Using fallback theme detection...'
    ACTIVE_THEME='astra'
fi

echo \"Detected active theme: \$ACTIVE_THEME\"

# Create theme template directories
THEME_PATH=\"wp-content/themes/\$ACTIVE_THEME\"
echo \"Creating template directories in: \$THEME_PATH\"

mkdir -p \"\$THEME_PATH/tribe-events/community\"
mkdir -p \"\$THEME_PATH/tribe-events/community/partials\"

# Copy enhanced template files
if [ -f \"wp-content/plugins/hvac-community-events/templates/community-edit-event-enhanced.php\" ]; then
    cp wp-content/plugins/hvac-community-events/templates/community-edit-event-enhanced.php \"\$THEME_PATH/tribe-events/community/edit-event.php\"
    echo '✅ Enhanced template copied to theme'
else
    echo '❌ Enhanced template source file not found'
    exit 1
fi

# Copy template partials
if [ -d \"wp-content/plugins/hvac-community-events/templates/partials\" ]; then
    cp -r wp-content/plugins/hvac-community-events/templates/partials/* \"\$THEME_PATH/tribe-events/community/partials/\"
    echo '✅ Template partials copied'
else
    echo '❌ Template partials directory not found'
fi

# Set proper permissions
chmod -R 755 \"\$THEME_PATH/tribe-events\"

echo \"Template installation completed for theme: \$ACTIVE_THEME\"

# Verify installation
if [ -f \"\$THEME_PATH/tribe-events/community/edit-event.php\" ]; then
    echo '✅ Template override verified in place'
    ls -la \"\$THEME_PATH/tribe-events/community/\"
else
    echo '❌ Template override installation failed'
    exit 1
fi
"

echo ""
echo -e "${GREEN}Step 2: Testing template override accessibility...${NC}"

# Test if the template is accessible via HTTP
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
cd $SERVER_PATH

# Check if TEC Community Events plugin is active
if wp plugin list --name='the-events-calendar-community-events' --status=active --format=count | grep -q '1'; then
    echo '✅ TEC Community Events plugin is active'
else
    echo '⚠️ TEC Community Events plugin may not be active'
    wp plugin list --status=active | grep -i 'events'
fi

# Test basic WordPress functionality
echo 'Testing WordPress functionality...'
wp eval 'echo \"WordPress loaded successfully\";' || echo 'WordPress eval failed'

# Check if we can access the theme
ACTIVE_THEME=\$(wp option get stylesheet 2>/dev/null | tr -d '\n')
echo \"Active theme: \$ACTIVE_THEME\"

# List theme contents to verify template is there
echo 'Theme template structure:'
find wp-content/themes/\$ACTIVE_THEME/tribe-events -type f 2>/dev/null | head -10 || echo 'No tribe-events templates found'
"

echo ""
echo -e "${GREEN}Step 3: Clearing all caches...${NC}"

sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
cd $SERVER_PATH

# Clear WordPress caches
wp cache flush 2>/dev/null && echo 'WordPress cache cleared' || echo 'WordPress cache flush failed'

# Clear object cache if available
wp cache flush 2>/dev/null && echo 'Object cache cleared' || echo 'Object cache not available'

# Clear Breeze cache if available
wp breeze purge --cache=all 2>/dev/null && echo 'Breeze cache cleared' || echo 'Breeze cache not available'

# Clear OPcache if available
wp eval 'if (function_exists(\"opcache_reset\")) { opcache_reset(); echo \"OPcache cleared\"; } else { echo \"OPcache not available\"; }'

# Flush rewrite rules to ensure proper URL routing
wp rewrite flush && echo 'Rewrite rules flushed' || echo 'Rewrite flush failed'
"

echo ""
echo -e "${GREEN}✅ TEC Template Installation Fix Complete!${NC}"
echo ""
echo -e "${YELLOW}Test the enhanced template at:${NC}"
echo "1. Event Creation: $SITE_URL/events/community/add/"
echo "2. Alternative URL: $SITE_URL/community/events/add/"
echo ""
echo -e "${YELLOW}Manual verification steps:${NC}"
echo "1. Login to: $SITE_URL/training-login/"
echo "2. Navigate to event creation"
echo "3. Look for 'Enhanced HVAC Template Active' indicator"
echo "4. Verify excerpt, categories, featured image, and tags fields are present"