#!/bin/bash
#
# WordPress Plugin Validation Script
# Validates PHP syntax and checks plugin header for WordPress.org compliance
#

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

# Plugin root directory
PLUGIN_DIR="${1:-.}"

# Counters
TOTAL_FILES=0
ERROR_COUNT=0
WARNING_COUNT=0

echo "================================================"
echo "WordPress Plugin Validation Script"
echo "================================================"
echo ""
echo "Validating plugin: $PLUGIN_DIR"
echo ""

# Function to check PHP syntax
check_php_syntax() {
    local file="$1"
    local result=$(php -l "$file" 2>&1)

    if echo "$result" | grep -q "No syntax errors detected"; then
        echo -e "${GREEN}[PASS]${NC} $file"
        return 0
    else
        echo -e "${RED}[FAIL]${NC} $file"
        echo "$result"
        return 1
    fi
}

# Function to check plugin header
check_plugin_header() {
    local file="$1"
    local dir=$(dirname "$file")
    local basename=$(basename "$dir")

    # Check for required plugin header fields
    if ! grep -q "Plugin Name:" "$file"; then
        echo -e "${RED}[MISSING]${NC} Plugin Name header in $file"
        return 1
    fi

    if ! grep -q "Version:" "$file"; then
        echo -e "${RED}[MISSING]${NC} Version header in $file"
        return 1
    fi

    if ! grep -q "Text Domain:" "$file"; then
        echo -e "${YELLOW}[WARNING]${NC} Text Domain header missing in $file"
        return 2
    fi

    echo -e "${GREEN}[OK]${NC} Plugin header in $file"
    return 0
}

# Function to validate file structure
validate_structure() {
    local plugin_file="$1"
    local plugin_dir=$(dirname "$plugin_file")
    local plugin_slug=$(basename "$plugin_file" .php)

    echo ""
    echo "Checking plugin structure..."
    echo ""

    # Check for required files
    local required_files=(
        "pc-changelog-manager-abc123.php"
        "uninstall.php"
    )

    local required_dirs=(
        "includes"
        "admin"
        "public"
    )

    local missing=0

    for file in "${required_files[@]}"; do
        if [ ! -f "$plugin_dir/$file" ]; then
            echo -e "${RED}[MISSING]${NC} Required file: $file"
            missing=1
        else
            echo -e "${GREEN}[FOUND]${NC} $file"
        fi
        TOTAL_FILES=$((TOTAL_FILES + 1))
    done

    for dir in "${required_dirs[@]}"; do
        if [ ! -d "$plugin_dir/$dir" ]; then
            echo -e "${RED}[MISSING]${NC} Required directory: $dir"
            missing=1
        else
            echo -e "${GREEN}[FOUND]${NC} $dir/"
        fi
    done

    if [ $missing -eq 1 ]; then
        return 1
    fi

    return 0
}

# Function to find all PHP files
find_php_files() {
    local dir="$1"
    find "$dir" -name "*.php" -type f
}

# Main execution
main() {
    # Check if plugin directory exists
    if [ ! -d "$PLUGIN_DIR" ]; then
        echo -e "${RED}[ERROR]${NC} Directory not found: $PLUGIN_DIR"
        exit 1
    fi

    # Find the main plugin file
    local main_file=""
    local plugin_slug=""

    # Look for PHP files with plugin header
    for file in $(find_php_files "$PLUGIN_DIR"); do
        if grep -q "Plugin Name:" "$file" && grep -q "Version:" "$file"; then
            main_file="$file"
            plugin_slug=$(basename "$file" .php)
            break
        fi
    done

    if [ -z "$main_file" ]; then
        echo -e "${RED}[ERROR]${NC} No plugin main file found in $PLUGIN_DIR"
        exit 1
    fi

    echo "Main plugin file: $main_file"
    echo "Plugin slug: $plugin_slug"
    echo ""

    # Validate structure
    validate_structure "$main_file"
    struct_result=$?
    if [ $struct_result -ne 0 ]; then
        ERROR_COUNT=$((ERROR_COUNT + 1))
    fi

    # Check main plugin header
    check_plugin_header "$main_file"
    header_result=$?
    if [ $header_result -eq 1 ]; then
        ERROR_COUNT=$((ERROR_COUNT + 1))
    elif [ $header_result -eq 2 ]; then
        WARNING_COUNT=$((WARNING_COUNT + 1))
    fi

    # Find and check all PHP files
    echo ""
    echo "Validating PHP syntax..."
    echo ""

    while IFS= read -r file; do
        TOTAL_FILES=$((TOTAL_FILES + 1))
        check_php_syntax "$file"
        result=$?
        if [ $result -ne 0 ]; then
            ERROR_COUNT=$((ERROR_COUNT + 1))
        fi
    done < <(find_php_files "$PLUGIN_DIR")

    # Check for common issues
    echo ""
    echo "Checking for common issues..."
    echo ""

    # Check for debug statements
    debug_patterns=("var_dump" "print_r" "console.log" "error_log")
    for pattern in "${debug_patterns[@]}"; do
        if grep -rq "$pattern" "$PLUGIN_DIR" --include="*.php" | grep -v "uninstall.php" | grep -v ".git"; then
            echo -e "${YELLOW}[WARNING]${NC} Potential debug statement found: $pattern"
            WARNING_COUNT=$((WARNING_COUNT + 1))
        fi
    done

    # Check for proper escaping
    if grep -rq "echo \$" "$PLUGIN_DIR" --include="*.php" | grep -v "esc_html\|esc_attr\|esc_url\|esc_textarea"; then
        echo -e "${YELLOW}[WARNING]${NC} Potential missing escaping found"
        WARNING_COUNT=$((WARNING_COUNT + 1))
    fi

    # Summary
    echo ""
    echo "================================================"
    echo "Validation Summary"
    echo "================================================"
    echo ""
    echo "Total files checked: $TOTAL_FILES"
    echo -e "Errors: ${RED}$ERROR_COUNT${NC}"
    echo -e "Warnings: ${YELLOW}$WARNING_COUNT${NC}"
    echo ""

    if [ $ERROR_COUNT -gt 0 ]; then
        echo -e "${RED}Validation FAILED${NC}"
        echo "Please fix the errors above."
        exit 1
    elif [ $WARNING_COUNT -gt 0 ]; then
        echo -e "${YELLOW}Validation PASSED with warnings${NC}"
        echo "Review the warnings above."
        exit 0
    else
        echo -e "${GREEN}Validation PASSED${NC}"
        echo "Plugin is ready for use."
        exit 0
    fi
}

# Run main function
main
