#!/bin/bash

# Enhanced Subdomain Setup Script with Error Handling and SSL Certificate Generation
# Version: 2.0

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

# Logging function
log_step() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] STEP: $1${NC}"
}

log_success() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] SUCCESS: $1${NC}"
}

log_error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

# Error handling function
handle_error() {
    local step_name="$1"
    local error_code="$2"
    local continue_anyway="${3:-false}"
    
    log_error "$step_name failed with exit code $error_code"
    
    if [[ "$continue_anyway" == "true" ]]; then
        log_warning "Continuing with next step despite error..."
        return 0
    else
        log_error "Stopping execution due to critical error in $step_name"
        exit $error_code
    fi
}

# Function to retry commands with exponential backoff
retry_command() {
    local max_attempts="$1"
    local delay="$2"
    local command="${@:3}"
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        log_step "Attempt $attempt/$max_attempts: $command"
        
        if eval "$command"; then
            log_success "Command succeeded on attempt $attempt"
            return 0
        else
            if [ $attempt -eq $max_attempts ]; then
                log_error "Command failed after $max_attempts attempts"
                return 1
            fi
            
            log_warning "Command failed, retrying in ${delay}s..."
            sleep $delay
            delay=$((delay * 2))  # Exponential backoff
            attempt=$((attempt + 1))
        fi
    done
}

# Check if required parameters are provided
if [ $# -ne 11 ]; then
    echo "Usage: $0 SUBDOMAIN DOMAIN IP EMAIL TITLE_NAME PHONE_NUMBER ADDRESS CATEGORY SUBCATEGORY TEMPLATE HOMEPAGE"
    exit 1
fi

# Assign input parameters to variables
SUBDOMAIN=$1
DOMAIN=$2
IP=$3
EMAIL=$4
TITLE_NAME=$5
PHONE_NUMBER=$6
ADDRESS=$7
CATEGORY=$8
SUBCATEGORY=$9
TEMPLATE=${10}
HOMEPAGE=${11}

FIRST_PART="${DOMAIN%%.*}"
EMAIL_ADMIN="${SUBDOMAIN}@${SUBDOMAIN}.${DOMAIN}"

log_step "Starting subdomain setup for ${SUBDOMAIN}.${DOMAIN}"
echo "Domain parts: FIRST_PART=$FIRST_PART"

# Generate random passwords
password_admin=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12)
password=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12)

# Define database configuration
DB_NAME="${SUBDOMAIN}DB"
TABLE_PREFIX="${SUBDOMAIN}_wp_"

# SMTP configuration - these should be moved to environment variables
SMTP_SERVER="in-v3.mailjet.com"
SMTP_PORT="587"
SMTP_USER="129c46308e46f861e50776d98fd67379"
SMTP_PASS="19b45e04bcee86493fad483bfe1464e4"
FROM_EMAIL="info@best-local-services.com"
FROM_NAME="Best Local Services"

log_step "Generated credentials: admin_password_length=${#password_admin}, user_password_length=${#password}"

# =============================================================================
# STEP 1: ADD DNS RECORD TO HOSTINGER
# =============================================================================
log_step "Adding DNS record to Hostinger"

if /home/find-local-services/public_html/hostinger_dns_script.sh --domain="${DOMAIN}" --name="${SUBDOMAIN}" --content="${IP}" --token=lwebd9UCeZtV23eEY2I5D29YjB95XpDgaL2FTQRd5fa30df6; then
    log_success "DNS record added successfully"
else
    handle_error "DNS record creation" $? true
fi

# Wait for DNS propagation
log_step "Waiting for DNS propagation (30 seconds)"
sleep 30

# =============================================================================
# STEP 2: CREATE VIRTUAL SERVER
# =============================================================================
log_step "Creating virtual server for ${SUBDOMAIN}.${DOMAIN}"

# Use retry mechanism for virtual server creation
if retry_command 3 10 "sudo virtualmin create-domain --domain '${SUBDOMAIN}.${DOMAIN}' --parent '${DOMAIN}' --pass '${password}' --dir --webmin --dns --web --ssl --mysql"; then
    log_success "Virtual server created successfully"
else
    handle_error "Virtual server creation" $? false
fi

# =============================================================================
# STEP 3: GENERATE SSL CERTIFICATE
# =============================================================================
log_step "Generating Let's Encrypt SSL certificate for ${SUBDOMAIN}.${DOMAIN}"

# Wait a bit for the domain to be fully configured
sleep 15

if retry_command 3 20 "sudo virtualmin generate-letsencrypt-cert --domain '${SUBDOMAIN}.${DOMAIN}'"; then
    log_success "SSL certificate generated successfully"
else
    log_warning "SSL certificate generation failed - continuing without SSL"
fi

# =============================================================================
# STEP 4: INSTALL WORDPRESS
# =============================================================================
log_step "Installing WordPress on ${SUBDOMAIN}.${DOMAIN}"

if retry_command 2 15 "sudo virtualmin install-script --domain '${SUBDOMAIN}.${DOMAIN}' --type wordpress --version latest --path / --db mysql '${DB_NAME}' --newdb --user '${SUBDOMAIN}_admin' --pass '${password_admin}'"; then
    log_success "WordPress installed successfully"
else
    handle_error "WordPress installation" $? false
fi

# =============================================================================
# STEP 5: CREATE USER ACCOUNT
# =============================================================================
log_step "Creating user account for ${SUBDOMAIN}"

if retry_command 2 5 "sudo virtualmin create-user --domain '${SUBDOMAIN}.${DOMAIN}' --user '${SUBDOMAIN}' --pass '${password_admin}' --quota 1024"; then
    log_success "User account created successfully"
else
    handle_error "User account creation" $? true
fi

# =============================================================================
# STEP 6: CONFIGURE WORDPRESS
# =============================================================================
log_step "Configuring WordPress installation"

# Change to WordPress content directory
WP_CONTENT_DIR="/home/${FIRST_PART}/domains/${SUBDOMAIN}.${DOMAIN}/public_html/wp-content"
WP_ROOT_DIR="/home/${FIRST_PART}/domains/${SUBDOMAIN}.${DOMAIN}/public_html"

if [[ ! -d "$WP_CONTENT_DIR" ]]; then
    log_error "WordPress content directory not found: $WP_CONTENT_DIR"
    handle_error "WordPress content directory check" 1 false
fi

cd "$WP_CONTENT_DIR" || handle_error "Change to WP content directory" $? false

# =============================================================================
# STEP 7: INSTALL AND ACTIVATE PLUGINS
# =============================================================================
log_step "Installing WordPress plugins"

PLUGIN_PATH="/home/${FIRST_PART}/public_html/plugins/all-in-one-wp-migration-unlimited-extension_v2.68.zip"

if [[ -f "$PLUGIN_PATH" ]]; then
    if wp plugin install "$PLUGIN_PATH" 2>/dev/null; then
        log_success "Plugin installed successfully"
    else
        log_warning "Plugin installation failed - continuing anyway"
    fi
else
    log_warning "Plugin file not found: $PLUGIN_PATH - skipping plugin installation"
fi

# Activate all plugins
log_step "Activating WordPress plugins"
if wp plugin activate --all 2>/dev/null; then
    log_success "Plugins activated successfully"
else
    log_warning "Plugin activation failed - continuing anyway"
fi

# =============================================================================
# STEP 8: DOWNLOAD AND RESTORE BACKUP
# =============================================================================
log_step "Downloading and restoring website template"

file_url="https://find-local-services.com/bkps/${CATEGORY}/${SUBCATEGORY}/${TEMPLATE}.wpress"
backup_dir="/home/${FIRST_PART}/domains/${SUBDOMAIN}.${DOMAIN}/public_html/wp-content/ai1wm-backups"
destination_path="${backup_dir}/${TEMPLATE}.wpress"

# Create backup directory if it doesn't exist
mkdir -p "$backup_dir"

log_step "Downloading template from: $file_url"

if retry_command 3 10 "curl -L -o '$destination_path' '$file_url'"; then
    log_success "Template downloaded successfully"
else
    handle_error "Template download" $? false
fi

# Restore the backup
log_step "Restoring WordPress template"
if wp ai1wm restore "${TEMPLATE}.wpress" --yes 2>/dev/null; then
    log_success "Template restored successfully"
else
    handle_error "Template restoration" $? false
fi

# =============================================================================
# STEP 9: CUSTOMIZE CONTENT
# =============================================================================
log_step "Customizing website content"

# Perform search and replace operations
declare -a replacements=(
    "subdomain.domain.tld:${SUBDOMAIN}.${DOMAIN}"
    "My Blog:${TITLE_NAME}"
    "Company Name:${TITLE_NAME}"
    "555-555-5555:${PHONE_NUMBER}"
    "1-800-123-1234:${PHONE_NUMBER}"
    "info@example.com:${EMAIL}"
    "123 Main St, Anytown, NY, 90210 USA:${ADDRESS}"
    "handyman.best-local-services:${SUBDOMAIN}.find-local-services"
    "best-local-services:${FIRST_PART}"
    "find-local-services@find-local-services.com:${SUBDOMAIN}@${SUBDOMAIN}.${DOMAIN}"
    "Hanadyman Services:${TITLE_NAME}"
    "Brooklyn, NY 10036, United States:${ADDRESS}"
    "example@example.com:${EMAIL}"
    "Test1:${TITLE_NAME}"
    "Cleaning Services:${TITLE_NAME}"
    "+90 456 789 251:${PHONE_NUMBER}"
    "914 Columbia Avenue - South Milwaukee, WI 53172:${ADDRESS}"
)

for replacement in "${replacements[@]}"; do
    IFS=':' read -r search replace <<< "$replacement"
    if [[ -n "$search" && -n "$replace" ]]; then
        log_step "Replacing '$search' with '$replace'"
        if wp search-replace "$search" "$replace" 2>/dev/null; then
            log_success "Replacement completed: $search -> $replace"
        else
            log_warning "Replacement failed: $search -> $replace"
        fi
    fi
done

# =============================================================================
# STEP 10: CONFIGURE WORDPRESS SETTINGS
# =============================================================================
log_step "Configuring WordPress settings"

# Change to WordPress root directory
cd "$WP_ROOT_DIR" || handle_error "Change to WP root directory" $? false

# Create .htaccess file
log_step "Creating .htaccess file"
cat << 'EOF' > .htaccess
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
EOF

if chmod 644 .htaccess; then
    log_success ".htaccess file created and permissions set"
else
    log_warning ".htaccess permissions setting failed"
fi

# Create WordPress user
log_step "Creating WordPress user: ${SUBDOMAIN}"
if wp user create "${SUBDOMAIN}" "${EMAIL}" --role=contributor --user_pass="${password}" 2>/dev/null; then
    log_success "WordPress user created successfully"
else
    log_warning "WordPress user creation failed - user may already exist"
fi

# =============================================================================
# STEP 11: SET HOMEPAGE BASED ON TEMPLATE
# =============================================================================
log_step "Setting homepage based on template: ${TEMPLATE}"

case "${TEMPLATE}" in
    "boldman")
        case "${HOMEPAGE}" in
            "main") wp option update page_on_front 33 2>/dev/null ;;
            "4") wp option update page_on_front 4015 2>/dev/null ;;
            "7") wp option update page_on_front 7607 2>/dev/null ;;
        esac
        ;;
    "repairer")
        case "${HOMEPAGE}" in
            "main") wp option update page_on_front 853 2>/dev/null ;;
            "plumber") wp option update page_on_front 325 2>/dev/null ;;
            "electrician") wp option update page_on_front 253 2>/dev/null ;;
            "painter") wp option update page_on_front 13007 2>/dev/null ;;
        esac
        ;;
esac

log_success "Homepage configuration completed"

# =============================================================================
# STEP 12: SEND NOTIFICATION EMAILS
# =============================================================================
log_step "Sending notification emails"

# Prepare customer email content
SUBJECT="New Website Setup Complete for ${SUBDOMAIN}.${DOMAIN}"
BODY="Dear ${TITLE_NAME},\n\n"
BODY+="Your new website has been successfully created with the following details:\n\n"
BODY+="Website URL: https://${SUBDOMAIN}.${DOMAIN}\n"
BODY+="Admin Panel: https://${SUBDOMAIN}.${DOMAIN}/wp-admin\n"
BODY+="Login Username: ${SUBDOMAIN}\n"
BODY+="Login Password: ${password}\n\n"
BODY+="Administrator Access:\n"
BODY+="Admin Username: ${SUBDOMAIN}_admin\n"
BODY+="Admin Password: ${password_admin}\n\n"
BODY+="Please store this information securely and change your passwords after first login.\n\n"
BODY+="Website created on: $(date)\n"
BODY+="IP Address: ${IP}\n\n"
BODY+="Thank you for using our service!\n"
BODY+="Best Local Services Team"

# Send customer email
if curl --url "smtp://${SMTP_SERVER}:${SMTP_PORT}" \
        --ssl-reqd \
        --mail-from "${FROM_EMAIL}" \
        --mail-rcpt "${EMAIL}" \
        --user "${SMTP_USER}:${SMTP_PASS}" \
        -T <(echo -e "From: ${FROM_NAME} <${FROM_EMAIL}>\nTo: ${EMAIL}\nSubject: ${SUBJECT}\n\n${BODY}") \
        --silent --show-error 2>/dev/null; then
    log_success "Customer notification email sent to ${EMAIL}"
else
    log_warning "Failed to send customer notification email"
fi

# Send admin notification email
ADMIN_EMAIL="admin@${DOMAIN}"
if curl --url "smtp://${SMTP_SERVER}:${SMTP_PORT}" \
        --ssl-reqd \
        --mail-from "${FROM_EMAIL}" \
        --mail-rcpt "${ADMIN_EMAIL}" \
        --user "${SMTP_USER}:${SMTP_PASS}" \
        -T <(echo -e "From: ${FROM_NAME} <${FROM_EMAIL}>\nTo: ${ADMIN_EMAIL}\nSubject: ${SUBJECT}\n\n${BODY}") \
        --silent --show-error 2>/dev/null; then
    log_success "Admin notification email sent to ${ADMIN_EMAIL}"
else
    log_warning "Failed to send admin notification email"
fi

# =============================================================================
# FINAL SUCCESS MESSAGE
# =============================================================================
log_success "Website setup completed successfully!"
echo ""
echo "================================================================"
echo "                    SETUP COMPLETE                             "
echo "================================================================"
echo "Website URL: https://${SUBDOMAIN}.${DOMAIN}"
echo "Admin Panel: https://${SUBDOMAIN}.${DOMAIN}/wp-admin"
echo "Customer Login: ${SUBDOMAIN} / ${password}"
echo "Admin Login: ${SUBDOMAIN}_admin / ${password_admin}"
echo "Database: ${DB_NAME}"
echo "================================================================"
echo ""

echo "SITE_CREATION_SUCCESS"
exit 0