#!/bin/bash

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

source .env

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

# 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 confirm action
confirm_action() {
    read -p "$1 [y/N] " response
    case "$response" in
        [yY][eE][sS]|[yY]) 
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

# Show script header
echo -e "${BLUE}=========================================================${NC}"
echo -e "${BLUE}   Production to Development Sync and Setup Script       ${NC}"
echo -e "${BLUE}=========================================================${NC}"
echo ""
echo -e "${YELLOW}This script will:${NC}"
echo "1. Sync WordPress files and database from production"
echo "2. Import the database into the local development environment"
echo "3. Update site URLs to point to localhost:8080"
echo "4. Verify that everything is working correctly"
echo ""

# Confirm before proceeding
if ! confirm_action "Do you want to proceed?"; then
    echo "Operation cancelled."
    exit 1
fi

# Step 1: Sync from production
echo -e "\n${BLUE}Step 1: Syncing from production...${NC}"

# Create backup directory
BACKUP_DIR="backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
echo -e "${YELLOW}Creating backup in: $BACKUP_DIR${NC}"

# Test SSH connection
echo "Testing SSH connection..."
if ! ssh -q "$PROD_SSH_USER@$PROD_HOST" exit; then
    echo -e "${RED}Error: Cannot connect to production server${NC}"
    exit 1
fi
check_status "SSH connection test"

# Download WordPress files
echo "Downloading WordPress files..."
rsync -avz --exclude='wp-config.php' \
    --exclude='.git/' \
    --exclude='node_modules/' \
    --exclude='*.log' \
    --exclude='wp-content/cache/' \
    --exclude='wp-content/uploads/cache/' \
    "$PROD_SSH_USER@$PROD_HOST:$PROD_PATH/" "$BACKUP_DIR/wordpress/"
check_status "WordPress files download" || exit 1

# Export and download database
echo "Exporting production database..."
ssh "$PROD_SSH_USER@$PROD_HOST" "cd $PROD_PATH && wp db export - --add-drop-table" > "$BACKUP_DIR/database.sql"
check_status "Database export" || exit 1

# Download wp-config.php (for reference)
echo "Downloading wp-config.php..."
scp "$PROD_SSH_USER@$PROD_HOST:$PROD_PATH/wp-config.php" "$BACKUP_DIR/wp-config.php.prod" || true

# Create manifest file
echo "Creating backup manifest..."
cat > "$BACKUP_DIR/manifest.txt" <<EOF
Production Backup Manifest
========================
Date: $(date)
Server: $PROD_HOST
WordPress Path: $PROD_PATH
Database: $PROD_DB_NAME

Environment Details:
- WordPress Version: $(ssh "$PROD_SSH_USER@$PROD_HOST" "cd $PROD_PATH && wp core version")
- PHP Version: $(ssh "$PROD_SSH_USER@$PROD_HOST" "php -v | head -n 1")
- MySQL Version: $(ssh "$PROD_SSH_USER@$PROD_HOST" "mysql -V")

Backup Contents:
- WordPress files (excluding wp-config.php, cache, etc.)
- Database dump (database.sql)
- Production wp-config.php (for reference)
EOF

# Create latest symlink
rm -f backups/latest
ln -s "$BACKUP_DIR" backups/latest

echo -e "${GREEN}Production sync completed successfully!${NC}"
echo "Backup stored in: $BACKUP_DIR"

# Step 2: Stop and restart containers
echo -e "\n${BLUE}Step 2: Restarting containers...${NC}"
echo "Stopping containers..."
docker-compose down
check_status "Container shutdown"

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

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

# Step 3: Copy WordPress files to the container
echo -e "\n${BLUE}Step 3: Copying WordPress files...${NC}"
echo "Copying WordPress files to container..."
cp -r "$BACKUP_DIR/wordpress/"* wordpress/
check_status "WordPress files copy"

# Step 4: Import database
echo -e "\n${BLUE}Step 4: Importing database...${NC}"
echo "Importing database..."
cat "$BACKUP_DIR/database.sql" | docker-compose exec -T db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" "$DEV_DB_NAME"
check_status "Database import" || exit 1

# Step 5: Update site URL
echo -e "\n${BLUE}Step 5: Updating site URL...${NC}"
echo "Updating site URL to localhost:8080..."
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 "Site URL update"

# Step 6: Update wp-config.php
echo -e "\n${BLUE}Step 6: Updating wp-config.php...${NC}"
echo "Creating wp-config.php..."
cat > wordpress/wp-config.php << EOF
<?php
/**
 * The base configuration for WordPress
 */

// ** Database settings ** //
define( 'DB_NAME', '$DEV_DB_NAME' );
define( 'DB_USER', '$DEV_DB_USER' );
define( 'DB_PASSWORD', '$DEV_DB_PASSWORD' );
define( 'DB_HOST', 'db' );
define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication Unique Keys and Salts.
 */
define('AUTH_KEY',         '{mDN$=c{&a=>j1]e+Z$.80AT++:6?Xhrodxd$xz17K[_S;54<L8a_ban$|SO6h$h');
define('SECURE_AUTH_KEY',  '?2QF|-!eUjx2cs{,yWmqGM%4.SfRi@v-dm-e0/Pej}q0GBukP<u+x[w0Wo-lPm[d');
define('LOGGED_IN_KEY',    'HOt?vigXMHbW=-F187\`5Q2Zsi$bo&P!rssD$OT#zILN)C5|;YKl?(36>*mdD<{xG');
define('NONCE_KEY',        ' %WDT]#vSTmbCs.OKE+83/iC>-jn\`Hl73uzayMt+eDOv/{Pr-Rp,j-WZ$A.L5w!5');
define('AUTH_SALT',        '5v0-0Memr/s.r,T$K(6(,Y^VE4Qb2bP-vlXrb+sq5+acjj]RqxQaGhT-d3E7%bI}');
define('SECURE_AUTH_SALT', 'YX]7zD&X*[,U&G 2ce.5}ST4tdvl)1:Mmk\`9_)P!Ei>.`xO3&(9YfQ:@.-Fxz7ey');
define('LOGGED_IN_SALT',   '1X*6CKC;PeJA>Ho9$|*VCv-1q9eA2o&@#Q+Sk7?^m=z|s4l+<@zLQx_;k+U5[Ns*');
define('NONCE_SALT',       '%,Vo(QDn\`:}Ehc!]MMA%D?{=sN>_ 6[ytAL#<wI->Y:7hZm4[hSXgW^6*n}~lZw&');

/**#@-*/

/**
 * WordPress Database Table prefix.
 */
\$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 */
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true );
@ini_set( 'display_errors', 1 );

/* Disable SSL/HTTPS in admin */
define('FORCE_SSL_ADMIN', false);
define('FORCE_SSL_LOGIN', false);

/* Override site URL */
define('WP_HOME', 'http://localhost:8080');
define('WP_SITEURL', 'http://localhost:8080');

/* Add any custom values between this line and the "stop editing" line. */

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
    define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
EOF
check_status "wp-config.php creation"

# Step 7: Set correct permissions
echo -e "\n${BLUE}Step 7: Setting file permissions...${NC}"
echo "Setting file permissions..."
docker-compose exec wordpress chown -R www-data:www-data /var/www/html
check_status "File permissions"

# Step 8: Clear cache
echo -e "\n${BLUE}Step 8: Clearing cache...${NC}"
echo "Clearing cache..."
docker-compose exec wordpress wp cache flush --allow-root
check_status "Cache clearing"

# Step 9: Verify environment
echo -e "\n${BLUE}Step 9: Verifying environment...${NC}"
echo "Running verification..."
./bin/verify-simple.sh
check_status "Environment verification"

# Step 10: Check required plugins
echo -e "\n${BLUE}Step 10: Checking required plugins...${NC}"
echo "Checking required plugins..."
REQUIRED_PLUGINS=(
    "the-events-calendar"
    "events-calendar-pro"
    "event-tickets"
    "event-tickets-plus"
    "tribe-community-events"
)

for plugin in "${REQUIRED_PLUGINS[@]}"; do
    if docker-compose exec wordpress wp plugin is-active "$plugin" --allow-root > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Plugin active: $plugin${NC}"
    else
        echo -e "${YELLOW}⚠ Plugin not active: $plugin${NC}"
        echo "Attempting to activate plugin: $plugin"
        docker-compose exec wordpress wp plugin activate "$plugin" --allow-root || true
    fi
done

# Final message
echo -e "\n${GREEN}=========================================================${NC}"
echo -e "${GREEN}   Production to Development Sync Completed Successfully   ${NC}"
echo -e "${GREEN}=========================================================${NC}"
echo ""
echo -e "${YELLOW}Access your site at:${NC} http://localhost:8080"
echo -e "${YELLOW}Access admin at:${NC} http://localhost:8080/wp-admin"
echo -e "${YELLOW}Access phpMyAdmin at:${NC} http://localhost:8081"
echo ""
echo -e "${BLUE}Note:${NC} If you encounter any issues, run the following command to verify the environment:"
echo "./bin/verify-dev-fixed.sh"