#!/bin/bash

set -e

echo "🚀 Setting up HVAC Plugin in Docker Environment (Focused)"

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

# Configuration
DOCKER_COMPOSE_FILE="tests/docker-compose.test.yml"
WP_CONTAINER="hvac-wordpress-test"

echo -e "${BLUE}📋 Step 1: Preparing Plugin Files...${NC}"

# Create temporary directory with just the plugin files
TEMP_DIR=$(mktemp -d)
PLUGIN_DIR="$TEMP_DIR/hvac-community-events"

mkdir -p "$PLUGIN_DIR"

# Copy essential plugin files
echo -e "${YELLOW}📁 Copying essential plugin files...${NC}"

# Main plugin file
cp hvac-community-events.php "$PLUGIN_DIR/"

# Core directories
cp -r includes "$PLUGIN_DIR/"
cp -r templates "$PLUGIN_DIR/"
cp -r assets "$PLUGIN_DIR/" 2>/dev/null || echo "No assets directory found"

# Cleanup unwanted files
find "$PLUGIN_DIR" -name "*.log" -delete 2>/dev/null || true
find "$PLUGIN_DIR" -name "*.tmp" -delete 2>/dev/null || true

echo -e "${BLUE}📋 Step 2: Installing Plugin in WordPress...${NC}"

# Copy plugin files to WordPress
docker cp "$PLUGIN_DIR" $WP_CONTAINER:/var/www/html/wp-content/plugins/

# Ensure proper file permissions
docker exec $WP_CONTAINER chown -R www-data:www-data /var/www/html/wp-content/plugins/hvac-community-events/

# Cleanup temp directory
rm -rf "$TEMP_DIR"

echo -e "${BLUE}📋 Step 3: Installing WordPress CLI...${NC}"

# Install WP-CLI if not present
docker exec $WP_CONTAINER bash -c '
    if ! command -v wp &> /dev/null; then
        echo "Installing WP-CLI..."
        curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
        chmod +x wp-cli.phar
        mv wp-cli.phar /usr/local/bin/wp
    fi
'

echo -e "${BLUE}📋 Step 4: Configuring WordPress...${NC}"

# Install WordPress if not installed
docker exec $WP_CONTAINER bash -c '
    cd /var/www/html
    
    # Check if WordPress is installed
    if ! wp core is-installed --allow-root 2>/dev/null; then
        echo "Installing WordPress..."
        wp core install \
            --url="http://localhost:8080" \
            --title="HVAC Test Site" \
            --admin_user="admin" \
            --admin_password="admin" \
            --admin_email="admin@test.com" \
            --skip-email \
            --allow-root
    fi
'

echo -e "${BLUE}📋 Step 5: Activating HVAC Plugin...${NC}"

docker exec $WP_CONTAINER bash -c '
    cd /var/www/html
    
    # Activate HVAC Plugin
    wp plugin activate hvac-community-events --allow-root
    echo "HVAC Plugin activated"
'

echo -e "${BLUE}📋 Step 6: Setting up HVAC Plugin Components...${NC}"

docker exec $WP_CONTAINER bash -c '
    cd /var/www/html
    
    # Initialize plugin and create database tables
    wp eval "
        // Force plugin initialization
        do_action(\"plugins_loaded\");
        
        // Create roles
        if (class_exists(\"HVAC_Roles\")) {
            echo \"Creating HVAC roles...\\n\";
            HVAC_Roles::create_roles();
        }
        
        // Create pages
        if (class_exists(\"HVAC_Page_Manager\")) {
            echo \"Creating HVAC pages...\\n\"; 
            HVAC_Page_Manager::create_required_pages();
        }
        
        // Create database tables
        if (class_exists(\"HVAC_Contact_Submissions_Table\")) {
            echo \"Creating contact submissions table...\\n\";
            HVAC_Contact_Submissions_Table::create_table();
        }
        
        // Run plugin activation
        if (class_exists(\"HVAC_Activator\")) {
            echo \"Running plugin activation...\\n\";
            HVAC_Activator::activate();
        }
        
        echo \"Plugin setup complete\\n\";
    " --allow-root
    
    # Flush rewrite rules
    wp rewrite flush --allow-root
    echo "Rewrite rules flushed"
'

echo -e "${BLUE}📋 Step 7: Creating Test Users...${NC}"

docker exec $WP_CONTAINER bash -c '
    cd /var/www/html
    
    # Create test trainer user
    if ! wp user get trainer1 --allow-root 2>/dev/null; then
        wp user create trainer1 trainer1@test.com --user_pass=password123 --role=hvac_trainer --allow-root
        echo "Created trainer1 user"
    fi
    
    # Create test master trainer user  
    if ! wp user get master1 --allow-root 2>/dev/null; then
        wp user create master1 master1@test.com --user_pass=password123 --role=hvac_master_trainer --allow-root
        echo "Created master1 user"
    fi
'

echo -e "${BLUE}📋 Step 8: Testing Setup...${NC}"

# Test basic WordPress functionality
if curl -s "http://localhost:8080" | grep -q "HVAC Test Site"; then
    echo -e "${GREEN}✅ WordPress is working${NC}"
else
    echo -e "${YELLOW}⚠️  WordPress may need more time to start${NC}"
fi

# Test trainer routes
if curl -s "http://localhost:8080/trainer/" | grep -q -v "Not Found"; then
    echo -e "${GREEN}✅ HVAC trainer routes are working${NC}"
else
    echo -e "${YELLOW}⚠️  HVAC routes may need authentication or more setup time${NC}"
fi

echo -e "${GREEN}✅ HVAC Plugin setup complete!${NC}"

echo -e "${BLUE}🔗 Access URLs:${NC}"
echo "WordPress: http://localhost:8080"
echo "Admin: http://localhost:8080/wp-admin/ (admin/admin)"  
echo "Training Leads: http://localhost:8080/trainer/profile/training-leads/"
echo "MailHog: http://localhost:8025"

echo -e "${GREEN}🎉 You can now test the training leads functionality!${NC}"