#!/bin/bash
# Fix TEC Template Deployment Script
# Deploys enhanced TEC template and partials to staging server

set -e

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

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo -e "${BLUE}🚀 TEC Enhanced Template Deployment Fix${NC}"
echo -e "${BLUE}=====================================${NC}"
echo ""

# Check if running from correct directory
if [ ! -f "$PROJECT_ROOT/hvac-community-events.php" ]; then
    echo -e "${RED}❌ Error: Please run from HVAC plugin root directory${NC}"
    exit 1
fi

echo -e "${YELLOW}📋 Step 1: Preparing template files...${NC}"

# Create staging commands
STAGING_COMMANDS=$(cat << 'EOF'
#!/bin/bash
# Staging server deployment commands

echo "🔍 Setting up TEC template deployment..."

# Get active theme
ACTIVE_THEME=$(wp theme status --format=csv | grep "active" | cut -d',' -f1)
echo "Active theme: $ACTIVE_THEME"

# Create theme directory structure
THEME_PATH="/var/www/html/wp-content/themes/$ACTIVE_THEME"
TEC_THEME_DIR="$THEME_PATH/tribe-events/community"
PARTIALS_DIR="$TEC_THEME_DIR/partials"

echo "📁 Creating theme directories..."
mkdir -p "$TEC_THEME_DIR"
mkdir -p "$PARTIALS_DIR"

# Copy enhanced template
echo "📋 Copying enhanced template..."
if [ -f "/var/www/html/wp-content/plugins/hvac-community-events/templates/community-edit-event-enhanced.php" ]; then
    cp "/var/www/html/wp-content/plugins/hvac-community-events/templates/community-edit-event-enhanced.php" \
       "$TEC_THEME_DIR/edit-event.php"
    echo "✅ Enhanced template copied to theme"
else
    echo "❌ Enhanced template not found in plugin"
    exit 1
fi

# Copy partials
echo "📋 Copying template partials..."
PLUGIN_PARTIALS_DIR="/var/www/html/wp-content/plugins/hvac-community-events/templates/partials"

if [ -d "$PLUGIN_PARTIALS_DIR" ]; then
    cp -r "$PLUGIN_PARTIALS_DIR"/* "$PARTIALS_DIR/"
    echo "✅ Template partials copied"
    
    # List copied files
    echo "📂 Copied partials:"
    ls -la "$PARTIALS_DIR/"
else
    echo "❌ Partials directory not found"
    exit 1
fi

# Set proper permissions
echo "🔐 Setting permissions..."
chown -R www-data:www-data "$TEC_THEME_DIR"
chmod -R 644 "$TEC_THEME_DIR"/*.php
chmod -R 644 "$PARTIALS_DIR"/*.php

# Verify deployment
echo "🔍 Verifying deployment..."
if [ -f "$TEC_THEME_DIR/edit-event.php" ]; then
    echo "✅ Enhanced template deployed successfully"
else
    echo "❌ Template deployment failed"
    exit 1
fi

# Count partials
PARTIAL_COUNT=$(ls -1 "$PARTIALS_DIR"/*.php 2>/dev/null | wc -l)
if [ "$PARTIAL_COUNT" -eq 4 ]; then
    echo "✅ All 4 template partials deployed successfully"
else
    echo "⚠️ Only $PARTIAL_COUNT partials found (expected 4)"
fi

# Clear caches
echo "🧹 Clearing caches..."
wp cache flush
if command -v wp-cli >/dev/null 2>&1; then
    wp rewrite flush
fi

echo "🎉 TEC template deployment completed!"
echo ""
echo "📍 Deployed files:"
echo "   - Theme template: $TEC_THEME_DIR/edit-event.php"
echo "   - Partials: $PARTIALS_DIR/"
echo ""
echo "🔗 Test URL: https://upskill-staging.measurequick.com/events/network/add"

EOF
)

echo -e "${YELLOW}📋 Step 2: Uploading deployment script to staging...${NC}"

# Upload and execute on staging
echo "$STAGING_COMMANDS" > /tmp/deploy-tec-template.sh
chmod +x /tmp/deploy-tec-template.sh

# Use rsync or scp to upload (adjust for your staging server access)
echo -e "${YELLOW}📤 Manual deployment required:${NC}"
echo ""
echo "Copy this script to your staging server and run it:"
echo "=================================="
cat /tmp/deploy-tec-template.sh
echo "=================================="
echo ""

echo -e "${GREEN}✅ TEC Template Deployment Fix Ready${NC}"
echo -e "${YELLOW}📋 Next Steps:${NC}"
echo "   1. Copy the script above to staging server"
echo "   2. Run it as root or with proper permissions"
echo "   3. Test the enhanced template at:"
echo "      https://upskill-staging.measurequick.com/events/network/add"
echo ""
echo -e "${BLUE}🎯 Expected Results:${NC}"
echo "   - Enhanced template indicator visible"
echo "   - All 4 field sections (excerpt, categories, featured image, tags) render"
echo "   - Field population system available"
echo "   - 100% validation success rate"

# Save deployment script for reference
cp /tmp/deploy-tec-template.sh "$PROJECT_ROOT/scripts/staging-tec-deployment.sh"
echo ""
echo -e "${GREEN}💾 Deployment script saved to: scripts/staging-tec-deployment.sh${NC}"