#!/bin/bash
#
# Local Test Script for Floating Circle Button
# Run this BEFORE pushing to Git to catch issues early
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "╔═══════════════════════════════════════════╗"
echo "║   Floating Circle Button - Local Tests    ║"
echo "╚═══════════════════════════════════════════╝"
echo ""

# 1. PHP Syntax Check
echo "📌 Step 1: PHP Syntax Check"
echo "─────────────────────────────"
find . -name "*.php" -not -path "./node_modules/*" | while read file; do
    php -l "$file" > /dev/null 2>&1 || { echo "❌ Syntax error in $file"; exit 1; }
done
echo "✅ All PHP files are valid"
echo ""

# 2. JavaScript Mock Tests
echo "📌 Step 2: JavaScript Tests (Mock)"
echo "─────────────────────────────"
if [ ! -d "node_modules/playwright" ]; then
    echo "Installing Playwright..."
    npm install --silent
    npx playwright install chromium --with-deps
fi
node tests/automated-test.js
echo ""

# 3. Optional: Docker E2E Tests
if [ "$1" == "--full" ]; then
    echo "📌 Step 3: Full E2E Tests (Docker)"
    echo "─────────────────────────────"
    
    # Check if Docker is running and accessible
    if ! docker info > /dev/null 2>&1; then
        echo "⚠️ Docker is not running or permission denied."
        echo "   Try: sudo usermod -aG docker \$USER (and restart session)"
        echo "   Skipping E2E tests."
    else
        echo "Starting containers..."
        docker-compose up -d
        
        echo "Waiting for WordPress to be ready (30s)..."
        # Wait until port 8080 is open
        for i in {1..30}; do
            if curl -s http://localhost:8080 > /dev/null; then
                break
            fi
            sleep 1
        done
        
        echo "Activating plugin and setting up WP..."
        docker-compose run --rm cli wp core install --url="http://localhost:8080" --title="Test Site" --admin_user="admin" --admin_password="admin" --admin_email="test@example.com" --skip-email || true
        docker-compose run --rm cli wp plugin activate idevelop-floating-circle-button || true
        
        # Run E2E tests
        WP_URL="http://localhost:8080" node tests/e2e-test.js
        
        echo "Stopping containers..."
        docker-compose down
    fi
fi

echo ""
echo "╔═══════════════════════════════════════════╗"
echo "║         ✅ All Tests Passed!              ║"
echo "╚═══════════════════════════════════════════╝"
echo ""
echo "Safe to push to Git!"
