#!/bin/bash

# HVAC jQuery Dependency Fixes Deployment Script
# ==============================================
# 
# This script applies comprehensive fixes for "jQuery is not defined" errors
# on master trainer pages and provides verification steps.
# 
# Author: Claude Code WordPress Specialist
# Date: 2025-01-02

set -e

echo "🔧 HVAC jQuery Dependency Fixes Deployment"
echo "=========================================="

# 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

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in the plugin directory
if [[ ! -f "hvac-community-events.php" ]]; then
    print_error "Please run this script from the HVAC plugin root directory"
    exit 1
fi

print_status "Starting jQuery dependency fixes deployment..."

# Step 1: Backup current configuration
print_status "Creating backup of current configuration..."
BACKUP_DIR="backups/jquery-fix-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"

cp includes/class-hvac-scripts-styles.php "$BACKUP_DIR/" 2>/dev/null || true
cp includes/class-hvac-bundled-assets.php "$BACKUP_DIR/" 2>/dev/null || true
cp includes/class-hvac-announcements-manager.php "$BACKUP_DIR/" 2>/dev/null || true
cp includes/class-hvac-import-export-manager.php "$BACKUP_DIR/" 2>/dev/null || true
cp includes/class-hvac-trainer-communication-templates.php "$BACKUP_DIR/" 2>/dev/null || true

print_success "Backup created in $BACKUP_DIR"

# Step 2: Verify fixes are in place
print_status "Verifying jQuery dependency fixes are applied..."

FIXES_APPLIED=true

# Check for critical fix markers in files
if ! grep -q "CRITICAL FIX.*jQuery" includes/class-hvac-scripts-styles.php; then
    print_error "Scripts_Styles jQuery fixes not found"
    FIXES_APPLIED=false
fi

if ! grep -q "should_use_legacy_scripts_system" includes/class-hvac-bundled-assets.php; then
    print_error "Bundled_Assets conflict prevention not found"
    FIXES_APPLIED=false
fi

if ! grep -q "CRITICAL FIX.*jQuery" includes/class-hvac-announcements-manager.php; then
    print_error "Announcements jQuery fixes not found"
    FIXES_APPLIED=false
fi

if ! grep -q "CRITICAL FIX.*jQuery" includes/class-hvac-import-export-manager.php; then
    print_error "Import-Export jQuery fixes not found"
    FIXES_APPLIED=false
fi

if ! grep -q "CRITICAL FIX.*jQuery" includes/class-hvac-trainer-communication-templates.php; then
    print_error "Communication Templates jQuery fixes not found"
    FIXES_APPLIED=false
fi

if [[ "$FIXES_APPLIED" == false ]]; then
    print_error "Some fixes are missing. Please ensure all files have been updated."
    exit 1
fi

print_success "All jQuery dependency fixes are in place"

# Step 3: Create wp-config additions for immediate deployment
print_status "Creating wp-config additions for stable deployment..."

cat > wp-config-additions.txt << 'EOF'
// HVAC jQuery Dependency Fixes - Add to wp-config.php
// ==================================================

// CRITICAL: Force legacy script loading to prevent jQuery conflicts
define('HVAC_FORCE_LEGACY_SCRIPTS', true);

// Disable bundled assets system to prevent dual script loading
define('HVAC_USE_BUNDLES', false);

// Enable script debugging for troubleshooting
define('HVAC_SCRIPT_DEBUG', true);
EOF

print_success "wp-config additions created in wp-config-additions.txt"

# Step 4: Run validation tests if available
print_status "Running validation tests..."

if command -v node &> /dev/null && [[ -f "test-jquery-dependency-fixes.js" ]]; then
    print_status "Node.js found. Running jQuery dependency tests..."
    
    # Install playwright if not available
    if ! npm list playwright &> /dev/null; then
        print_status "Installing Playwright for testing..."
        npm install playwright
    fi
    
    print_status "Running jQuery dependency test suite..."
    if node test-jquery-dependency-fixes.js; then
        print_success "jQuery dependency tests PASSED"
    else
        print_warning "jQuery dependency tests had issues - check logs above"
    fi
else
    print_warning "Node.js not available - skipping automated tests"
    print_status "Manual testing required on:"
    echo "  - /master-trainer/master-dashboard/"
    echo "  - /master-trainer/announcements/"
    echo "  - /master-trainer/communication-templates/"
    echo "  - /master-trainer/import-export/"
fi

# Step 5: WordPress CLI checks if available
if command -v wp &> /dev/null; then
    print_status "WordPress CLI found. Running WordPress checks..."
    
    # Check if WordPress can load
    if wp core version &> /dev/null; then
        print_success "WordPress core is accessible"
        
        # Check plugin status
        if wp plugin is-active hvac-community-events &> /dev/null; then
            print_success "HVAC plugin is active"
        else
            print_warning "HVAC plugin is not active - activate it to test fixes"
        fi
    else
        print_warning "WordPress CLI cannot connect - manual verification needed"
    fi
else
    print_warning "WordPress CLI not available - manual verification needed"
fi

# Step 6: Create verification checklist
print_status "Creating manual verification checklist..."

cat > jquery-fix-verification-checklist.md << 'EOF'
# HVAC jQuery Dependency Fixes - Verification Checklist

## Pre-Deployment Setup

1. **Add to wp-config.php** (above "That's all, stop editing!" line):
   ```php
   // HVAC jQuery Dependency Fixes
   define('HVAC_FORCE_LEGACY_SCRIPTS', true);
   define('HVAC_USE_BUNDLES', false);
   define('HVAC_SCRIPT_DEBUG', true);
   ```

2. **Clear all caches**:
   - WordPress object cache
   - Page caching plugins
   - CDN cache
   - Browser cache (Ctrl+F5)

## Manual Testing Checklist

Test each page with browser developer tools open (F12 → Console tab):

### ✅ Master Dashboard (/master-trainer/master-dashboard/)
- [ ] Page loads without "jQuery is not defined" errors
- [ ] Console shows: "HVAC: jQuery successfully loaded"
- [ ] Dashboard functionality works (buttons, forms, AJAX)
- [ ] No red JavaScript errors in console

### ✅ Master Announcements (/master-trainer/announcements/)  
- [ ] Page loads without "jQuery is not defined" errors
- [ ] Announcements interface loads properly
- [ ] jQuery-dependent features work (modals, forms)
- [ ] No red JavaScript errors in console

### ✅ Communication Templates (/trainer/communication-templates/)
- [ ] Page loads without "jQuery is not defined" errors
- [ ] Template interface loads properly
- [ ] Copy-to-clipboard functionality works
- [ ] Search/filter features work
- [ ] No red JavaScript errors in console

### ✅ Import/Export (/master-trainer/import-export/)
- [ ] Page loads without "jQuery is not defined" errors
- [ ] File upload interface works
- [ ] Export buttons function properly
- [ ] AJAX operations complete successfully
- [ ] No red JavaScript errors in console

## Browser-Specific Testing

Test in multiple browsers (jQuery issues can be browser-specific):
- [ ] Chrome/Chromium
- [ ] Firefox
- [ ] Safari (especially important - this was causing conflicts)
- [ ] Edge

## Troubleshooting

If issues persist:

1. **Check Console Errors**:
   - Look for any "jQuery" or "$" related errors
   - Note the exact error message and line number

2. **Check Script Loading Order**:
   - In Network tab, verify jQuery loads before other scripts
   - Ensure no 404 errors for script files

3. **Verify Configuration**:
   - Confirm wp-config.php additions are present
   - Check that HVAC_FORCE_LEGACY_SCRIPTS is true

4. **Clear Everything**:
   - Clear all caches again
   - Hard refresh browser (Ctrl+Shift+R)
   - Try incognito/private browsing mode

## Success Criteria

✅ **Complete Success**: 
- Zero "jQuery is not defined" errors across all pages
- All interactive features work properly
- Console shows "HVAC: jQuery successfully loaded" messages

⚠️ **Partial Success**:
- Reduced errors but some issues remain
- Most features work but some edge cases fail

❌ **Needs Investigation**:
- Still getting jQuery errors
- Pages not loading properly
- Interactive features broken
EOF

print_success "Verification checklist created: jquery-fix-verification-checklist.md"

# Step 7: Create rollback script
print_status "Creating rollback script for emergency use..."

cat > rollback-jquery-fixes.sh << EOF
#!/bin/bash
# Emergency rollback script for HVAC jQuery fixes

echo "🔄 Rolling back HVAC jQuery dependency fixes..."

# Restore from backup
if [[ -d "$BACKUP_DIR" ]]; then
    cp "$BACKUP_DIR"/* includes/ 2>/dev/null || true
    echo "✅ Files restored from backup"
else
    echo "❌ No backup found - manual restoration required"
fi

echo "⚠️ Remove these lines from wp-config.php:"
echo "   define('HVAC_FORCE_LEGACY_SCRIPTS', true);"
echo "   define('HVAC_USE_BUNDLES', false);"
echo "   define('HVAC_SCRIPT_DEBUG', true);"
echo "✅ Rollback complete"
EOF

chmod +x rollback-jquery-fixes.sh
print_success "Rollback script created: rollback-jquery-fixes.sh"

# Final summary
print_success "🎉 HVAC jQuery Dependency Fixes Deployment Complete!"

echo ""
echo "📋 NEXT STEPS:"
echo "=============="
echo "1. Add contents of wp-config-additions.txt to your wp-config.php file"
echo "2. Clear all caches (WordPress, plugins, CDN, browser)"
echo "3. Test all master trainer pages using the verification checklist"
echo "4. Monitor console for 'HVAC: jQuery successfully loaded' messages"
echo ""
echo "📄 FILES CREATED:"
echo "   - wp-config-additions.txt (add to wp-config.php)"
echo "   - jquery-fix-verification-checklist.md (testing guide)"
echo "   - rollback-jquery-fixes.sh (emergency rollback)"
echo "   - test-jquery-dependency-fixes.js (automated tests)"
echo ""
echo "💾 BACKUP LOCATION: $BACKUP_DIR"
echo ""
echo "🔧 KEY IMPROVEMENTS:"
echo "   ✅ Made script loading systems mutually exclusive"
echo "   ✅ Force jQuery loading before all dependent scripts"
echo "   ✅ Added jQuery availability detection and error reporting"
echo "   ✅ Fixed component-specific script loading conflicts"
echo "   ✅ Safari browser compatibility improvements"
echo ""
echo "📞 SUPPORT:"
echo "   If issues persist, check jquery-fix-verification-checklist.md"
echo "   Emergency rollback: ./rollback-jquery-fixes.sh"

print_success "Deployment ready! Please follow the next steps above."