#!/bin/bash

# Load environment variables
if [ ! -f ../.env ]; then
    echo "Error: .env file not found!"
    exit 1
fi

source ../.env

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

# Default values
SETUP_MODE="local"
SKIP_CONFIRM=false

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo "Options:"
    echo "  -m, --mode MODE     Setup mode: 'local' or 'production' (default: local)"
    echo "  -y, --yes          Skip confirmation prompts"
    echo "  -h, --help         Show this help message"
    echo ""
    echo "Modes:"
    echo "  local              Set up a fresh WordPress installation with test data"
    echo "  production         Sync data from production environment"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        -m|--mode)
            SETUP_MODE="$2"
            shift 2
            ;;
        -y|--yes)
            SKIP_CONFIRM=true
            shift
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_usage
            exit 1
            ;;
    esac
done

# Validate setup mode
if [[ "$SETUP_MODE" != "local" && "$SETUP_MODE" != "production" ]]; then
    echo -e "${RED}Error: Invalid setup mode. Use 'local' or 'production'${NC}"
    exit 1
fi

# Function to confirm action
confirm_action() {
    if [ "$SKIP_CONFIRM" = true ]; then
        return 0
    fi
    
    read -p "$1 [y/N] " response
    case "$response" in
        [yY][eE][sS]|[yY]) 
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

# Stop and remove existing containers
echo "Stopping existing containers..."
docker-compose down -v
check_status "Container cleanup"

# Start fresh containers
echo "Starting containers..."
docker-compose up -d
check_status "Container startup"

# Wait for MySQL to be ready
echo "Waiting for MySQL to be ready..."
sleep 10

if [ "$SETUP_MODE" = "production" ]; then
    # Check if backup exists
    if [ ! -d "../backups/latest" ]; then
        echo -e "${RED}Error: No backup found. Please run sync-production.sh first.${NC}"
        exit 1
    fi

    # Import database from backup
    echo "Importing production database..."
    cat "../backups/latest/database.sql" | docker-compose exec -T db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" "$DEV_DB_NAME"
    check_status "Database import"

    # Copy WordPress files
    echo "Copying WordPress files..."
    cp -r ../backups/latest/wordpress/* ../wordpress/
    check_status "WordPress files copy"
else
    # Local setup mode
    echo "Setting up fresh WordPress installation..."
    
    # Create database
    echo "Creating database..."
    docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS $DEV_DB_NAME;"
    check_status "Database creation"

    # Install WordPress
    echo "Installing WordPress..."
    docker-compose exec wordpress wp core download --version=6.7.2 --allow-root
    check_status "WordPress core download"

    docker-compose exec wordpress wp core install \
        --url=http://localhost:8080 \
        --title="HVAC Training Events" \
        --admin_user="$WP_ADMIN_USER" \
        --admin_password="$WP_ADMIN_PASS" \
        --admin_email="admin@example.com" \
        --allow-root
    check_status "WordPress installation"

    # Install and activate required plugins
    echo "Installing required plugins..."
    REQUIRED_PLUGINS=(
        "the-events-calendar"
        "events-calendar-pro"
        "event-tickets"
        "event-tickets-plus"
        "tribe-community-events"
    )

    for plugin in "${REQUIRED_PLUGINS[@]}"; do
        echo "Installing plugin: $plugin"
        docker-compose exec wordpress wp plugin install "$plugin" --allow-root
        docker-compose exec wordpress wp plugin activate "$plugin" --allow-root
        check_status "Plugin $plugin installation"
    done

    # Generate test data
    echo "Generating test data..."
    docker-compose exec wordpress wp user create test_trainer test.trainer@example.com --role=author --user_pass=SecurePass123! --allow-root
    check_status "Test trainer creation"
fi

# Update wp-config.php
echo "Updating wp-config.php..."
cat > ../wordpress/wp-config.php << EOF
<?php
define('DB_NAME', '$DEV_DB_NAME');
define('DB_USER', '$DEV_DB_USER');
define('DB_PASSWORD', '$DEV_DB_PASSWORD');
define('DB_HOST', 'db');
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

\$table_prefix = 'wp_';

if ( ! defined('ABSPATH') ) {
    define('ABSPATH', dirname(__FILE__) . '/');
}

require_once ABSPATH . 'wp-settings.php';
EOF
check_status "wp-config.php creation"

# Update site URL
echo "Updating WordPress URLs..."
docker-compose exec wordpress wp option update home "http://localhost:8080" --allow-root
docker-compose exec wordpress wp option update siteurl "http://localhost:8080" --allow-root
check_status "URL updates"

# Clear cache
echo "Clearing caches..."
docker-compose exec wordpress wp cache flush --allow-root
docker-compose exec wordpress rm -rf wp-content/cache/*
check_status "Cache clearing"

# Set correct permissions
echo "Setting file permissions..."
docker-compose exec wordpress chown -R www-data:www-data /var/www/html
check_status "Permission updates"

echo -e "${GREEN}Development environment setup completed!${NC}"
echo -e "${YELLOW}Mode: $SETUP_MODE${NC}"
echo -e "${YELLOW}Access your site at: http://localhost:8080${NC}"
echo -e "${YELLOW}Access phpMyAdmin at: http://localhost:8081${NC}"

if [ "$SETUP_MODE" = "local" ]; then
    echo -e "\n${YELLOW}Test Credentials:${NC}"
    echo "Admin User: $WP_ADMIN_USER"
    echo "Admin Password: $WP_ADMIN_PASS"
    echo "Test Trainer Email: test.trainer@example.com"
    echo "Test Trainer Password: SecurePass123!"
fi 