#!/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}   Development Environment Setup from Existing Backup     ${NC}"
echo -e "${BLUE}=========================================================${NC}"
echo ""
echo -e "${YELLOW}This script will:${NC}"
echo "1. Use the latest backup from backups/ directory"
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 ""

# Check if backups directory exists
if [ ! -d "backups" ]; then
    echo -e "${RED}Error: backups directory not found!${NC}"
    exit 1
fi

# Find the latest backup
LATEST_BACKUP=$(ls -td backups/2* | head -1)
if [ -z "$LATEST_BACKUP" ]; then
    echo -e "${RED}Error: No backup found in backups/ directory!${NC}"
    exit 1
fi

echo -e "${YELLOW}Using backup: $LATEST_BACKUP${NC}"

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

# Step 1: Stop and restart containers
echo -e "\n${BLUE}Step 1: 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 2: Copy WordPress files to the container
echo -e "\n${BLUE}Step 2: Copying WordPress files...${NC}"
echo "Copying WordPress files to container..."
cp -r "$LATEST_BACKUP/wordpress/"* wordpress/
check_status "WordPress files copy"

# Step 3: Import database
echo -e "\n${BLUE}Step 3: Importing database...${NC}"
echo "Importing database..."
cat "$LATEST_BACKUP/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 4: Update site URL directly in the database
echo -e "\n${BLUE}Step 4: Updating site URL in database...${NC}"
echo "Updating site URL to localhost:8080..."
docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" "$DEV_DB_NAME" -e "UPDATE wp_options SET option_value='http://localhost:8080' WHERE option_name='siteurl' OR option_name='home';"
check_status "Site URL update"

# Step 5: Create a simple wp-config.php file
echo -e "\n${BLUE}Step 5: Creating wp-config.php...${NC}"
cat > wordpress/wp-config.php << EOFWPCONFIG
<?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=-F1875Q2Zsi$bo&P!rssD$OT#zILN)C5|;YKl?(36>*mdD<{xG');
define('NONCE_KEY',        ' %WDT]#vSTmbCs.OKE+83/iC>-jnHl73uzayMt+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:Mmk9_)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';
EOFWPCONFIG
check_status "wp-config.php creation"

# Step 6: Set correct permissions
echo -e "\n${BLUE}Step 6: 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 7: Verify database connection
echo -e "\n${BLUE}Step 7: Verifying database connection...${NC}"
echo "Checking database connection..."
docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "SELECT 1;" > /dev/null 2>&1
check_status "Database connection"

# Step 8: Wait a bit longer for WordPress to initialize
echo -e "\n${BLUE}Step 8: Waiting for WordPress to initialize...${NC}"
echo "Giving WordPress a moment to initialize..."
sleep 5

# Step 9: Test homepage accessibility
echo -e "\n${BLUE}Step 9: Testing homepage accessibility...${NC}"
echo "Testing homepage accessibility..."
curl -s -I "http://localhost:8080" | grep -q "200 OK"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Homepage is accessible${NC}"
else
    echo -e "${YELLOW}⚠ Homepage is not accessible yet${NC}"
    echo "Note: It may take a few moments for the site to be fully ready. Try again in a minute."
fi

# Final message
echo -e "\n${GREEN}=========================================================${NC}"
echo -e "${GREEN}   Development Environment Setup 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, try the following:"
echo "1. Wait a few minutes for the site to fully initialize"
echo "2. Check the container logs: docker-compose logs"
echo "3. Verify database connection: docker-compose exec db mysql -u$DEV_DB_USER -p$DEV_DB_PASSWORD -e 'SHOW DATABASES;'"
echo "4. Run the verification script: ./bin/verify-dev.sh"