#!/bin/bash

# Manual production deployment for email fix
echo "🚀 Manual production deployment starting..."

# Create deployment package
echo "📦 Creating deployment package..."
DEPLOY_DIR="/tmp/hvac-production-deploy-$(date +%s)"
mkdir -p "$DEPLOY_DIR"

# Copy plugin files
cp -r includes templates hvac-community-events.php "$DEPLOY_DIR/"

# Create archive
cd "$DEPLOY_DIR"
tar -czf "../hvac-plugin.tar.gz" .
PACKAGE_PATH="/tmp/hvac-plugin.tar.gz"

echo "📦 Package created: $PACKAGE_PATH"

# Deploy using SCP with explicit SSH key
echo "🚀 Uploading to production server..."
scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no "$PACKAGE_PATH" upskill@207.154.230.172:/tmp/

# Execute deployment commands
echo "⚙️  Executing deployment on production..."
ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no upskill@207.154.230.172 << 'EOF'
set -e

echo "🔄 Deploying HVAC plugin..."

# Navigate to WordPress root
cd /var/www/html

# Backup current plugin
BACKUP_DIR="wp-content/plugins/hvac-community-events-backup-$(date +%s)"
if [ -d "wp-content/plugins/hvac-community-events" ]; then
    cp -r "wp-content/plugins/hvac-community-events" "$BACKUP_DIR"
    echo "✅ Backup created: $BACKUP_DIR"
fi

# Deactivate plugin
wp plugin deactivate hvac-community-events --allow-root --quiet || true

# Extract new plugin files
cd wp-content/plugins/hvac-community-events
tar -xzf /tmp/hvac-plugin.tar.gz --overwrite
echo "📦 Plugin files updated"

# Reactivate plugin (this triggers page recreation)
wp plugin activate hvac-community-events --allow-root
echo "🔄 Plugin reactivated"

# Force page recreation with updated content
wp eval 'HVAC_Page_Manager::create_pages();' --allow-root
echo "📄 Pages recreated with new content"

# Clear all caches
wp cache flush --allow-root

# Clear Breeze cache if active
if wp plugin is-active breeze --allow-root; then
    wp eval 'if (class_exists("Breeze_Admin")) { Breeze_Admin::breeze_clear_all_cache(); }' --allow-root
    echo "🧹 Breeze cache cleared"
fi

# Clear OPcache if available
php -r "if (function_exists('opcache_reset')) { opcache_reset(); echo '🧹 OPcache cleared\n'; }" 2>/dev/null || true

# Cleanup
rm -f /tmp/hvac-plugin.tar.gz

echo "✅ Production deployment completed successfully!"
EOF

# Cleanup local files
rm -rf "$DEPLOY_DIR" "$PACKAGE_PATH"

echo "🎉 Manual production deployment completed!"