#!/bin/bash
set -e

# Fix Production Issues Script
# Addresses: Missing edit event page, jQuery compatibility errors

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

echo -e "${YELLOW}=== Fixing Production Issues ===${NC}"
echo "Date: $(date)"
echo ""

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

# Set production variables
SERVER_IP=$UPSKILL_PROD_IP
SSH_USER=$UPSKILL_PROD_SSH_USER
SSH_PASS=$UPSKILL_PROD_PASS
SERVER_PATH=$UPSKILL_PROD_PATH
SITE_URL=$UPSKILL_PROD_URL

echo -e "${YELLOW}Target:${NC} $SITE_URL"
echo -e "${YELLOW}Server:${NC} $SERVER_IP"
echo ""

# Function to run WordPress CLI commands
run_wp_cli() {
    local cmd="$1"
    echo -e "${GREEN}Running WP-CLI:${NC} $cmd"
    sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" \
        "cd $SERVER_PATH && wp $cmd"
}

echo -e "${YELLOW}Step 1: Creating missing Edit Event page...${NC}"

# Check if edit event page exists
PAGE_EXISTS=$(run_wp_cli "post list --post_type=page --name='edit-event' --format=count" 2>/dev/null || echo "0")

if [ "$PAGE_EXISTS" = "0" ]; then
    echo "Creating Edit Event page..."
    
    # Create the edit event page
    PAGE_ID=$(run_wp_cli "post create --post_type=page --post_title='Edit Event' --post_name='edit-event' --post_status=publish --post_parent=6177 --porcelain")
    
    if [ ! -z "$PAGE_ID" ]; then
        echo -e "${GREEN}✅ Edit Event page created with ID: $PAGE_ID${NC}"
        
        # Set the page template
        run_wp_cli "post meta update $PAGE_ID _wp_page_template 'templates/page-edit-event-custom.php'"
        echo -e "${GREEN}✅ Page template assigned${NC}"
        
        # Update page content if needed
        run_wp_cli "post update $PAGE_ID --post_content='[hvac_edit_event_form]'"
        echo -e "${GREEN}✅ Page content updated with shortcode${NC}"
    else
        echo -e "${RED}❌ Failed to create Edit Event page${NC}"
    fi
else
    echo -e "${GREEN}✅ Edit Event page already exists${NC}"
fi

echo ""
echo -e "${YELLOW}Step 2: Updating jQuery compatibility...${NC}"

# Clear all caches to ensure jQuery fixes are loaded
echo "Clearing caches..."
run_wp_cli "cache flush"
echo -e "${GREEN}✅ WordPress cache cleared${NC}"

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

# Clear any object cache
run_wp_cli "eval 'if (function_exists(\"wp_cache_flush\")) { wp_cache_flush(); echo \"Object cache cleared\"; }'"

echo ""
echo -e "${YELLOW}Step 3: Flushing rewrite rules...${NC}"
run_wp_cli "rewrite flush --hard"
echo -e "${GREEN}✅ Rewrite rules flushed${NC}"

echo ""
echo -e "${YELLOW}Step 4: Re-activating plugin to ensure all hooks are registered...${NC}"
run_wp_cli "plugin deactivate hvac-community-events"
run_wp_cli "plugin activate hvac-community-events"
echo -e "${GREEN}✅ Plugin re-activated${NC}"

echo ""
echo -e "${GREEN}=== Production fixes completed! ===${NC}"
echo ""
echo -e "${YELLOW}Verification URLs:${NC}"
echo "1. Login: $SITE_URL/training-login/"
echo "2. Dashboard: $SITE_URL/trainer/dashboard/"
echo "3. Edit Event: $SITE_URL/trainer/event/edit/"
echo ""
echo -e "${YELLOW}Please test the site functionality after these fixes.${NC}"