#!/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"
