#!/bin/bash

set -e

echo "🚀 Setting up HVAC Plugin in Docker Environment"

# 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: Checking Docker Environment...${NC}"

# Check if Docker is running
if ! docker info >/dev/null 2>&1; then
    echo -e "${RED}❌ Docker is not running${NC}"
    exit 1
fi

# Check if containers are up
if ! docker compose -f $DOCKER_COMPOSE_FILE ps | grep -q "Up"; then
    echo -e "${YELLOW}🔄 Starting Docker containers...${NC}"
    docker compose -f $DOCKER_COMPOSE_FILE up -d
    
    # Wait for containers to be healthy
    echo -e "${YELLOW}⏱️  Waiting for containers to be healthy...${NC}"
    timeout=120
    elapsed=0
    
    while [ $elapsed -lt $timeout ]; do
        if docker compose -f $DOCKER_COMPOSE_FILE ps | grep -q "healthy"; then
            echo -e "${GREEN}✅ Containers are healthy${NC}"
            break
        fi
        sleep 2
        elapsed=$((elapsed + 2))
        echo -n "."
    done
    
    if [ $elapsed -ge $timeout ]; then
        echo -e "${RED}❌ Containers failed to become healthy${NC}"
        exit 1
    fi
fi

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

# Copy plugin files to WordPress
echo -e "${YELLOW}📁 Copying plugin files...${NC}"
docker cp . $WP_CONTAINER:/var/www/html/wp-content/plugins/hvac-community-events/

# Ensure proper file permissions
echo -e "${YELLOW}🔐 Setting file permissions...${NC}"
docker exec $WP_CONTAINER chown -R www-data:www-data /var/www/html/wp-content/plugins/hvac-community-events/

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}"

# Wait for WordPress to be ready
echo -e "${YELLOW}⏱️  Waiting for WordPress to be ready...${NC}"
timeout=60
elapsed=0

while [ $elapsed -lt $timeout ]; do
    if curl -s http://localhost:8080 | grep -q "wordpress"; then
        echo -e "${GREEN}✅ WordPress is ready${NC}"
        break
    fi
    sleep 2
    elapsed=$((elapsed + 2))
    echo -n "."
done

# 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 Required Plugins...${NC}"

docker exec $WP_CONTAINER bash -c "
    cd /var/www/html
    
    # Activate The Events Calendar if available
    if wp plugin is-installed the-events-calendar --allow-root; then
        wp plugin activate the-events-calendar --allow-root || echo 'TEC already active or not found'
    fi
    
    # Activate HVAC Plugin
    wp plugin activate hvac-community-events --allow-root
    
    echo 'Plugin activation complete'
"

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

docker exec $WP_CONTAINER bash -c "
    cd /var/www/html
    
    # Create required user roles
    wp eval '
        if (class_exists(\"HVAC_Roles\")) {
            HVAC_Roles::create_roles();
        }
    ' --allow-root
    
    # Create required pages
    wp eval '
        if (class_exists(\"HVAC_Page_Manager\")) {
            HVAC_Page_Manager::create_required_pages();
        }
    ' --allow-root
    
    # Flush rewrite rules
    wp rewrite flush --allow-root
    
    echo 'HVAC setup complete'
"

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 'Test users created'
"

echo -e "${BLUE}📋 Step 8: Setting up Database Tables...${NC}"

docker exec $WP_CONTAINER bash -c "
    cd /var/www/html
    
    # Create contact submissions table
    wp eval '
        if (class_exists(\"HVAC_Contact_Submissions_Table\")) {
            HVAC_Contact_Submissions_Table::create_table();
            echo \"Contact submissions table created\\n\";
        } else {
            echo \"HVAC_Contact_Submissions_Table class not found\\n\";
        }
    ' --allow-root
    
    # Create any other required tables
    wp eval '
        if (class_exists(\"HVAC_Activator\")) {
            HVAC_Activator::activate();
            echo \"Plugin activation complete\\n\";
        }
    ' --allow-root
"

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

echo -e "${BLUE}📋 Testing the setup...${NC}"

# Test the training leads page
if curl -s "http://localhost:8080/trainer/profile/training-leads/" | grep -q "Training Leads"; then
    echo -e "${GREEN}✅ Training leads page is working!${NC}"
else
    echo -e "${YELLOW}⚠️  Training leads page may need authentication${NC}"
fi

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}🎉 Setup complete! You can now test the training leads functionality.${NC}"