#!/bin/bash

# Pre-Deployment Check Script
# Runs all validation before any deployment

set -e

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

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

echo -e "${BLUE}=== Pre-Deployment Validation Check ===${NC}"
echo "Running comprehensive checks before deployment..."
echo ""

# Track overall success
overall_success=true

# Check 1: Template Structure Validation (DISABLED)
echo -e "${BLUE}📋 Step 1: Template Structure Validation${NC}"
# Template validation permanently disabled as these templates are no longer used
echo -e "${YELLOW}⚠️  Template validation skipped (templates no longer in use)${NC}"
echo ""

# Check 2: CSS File Existence
echo -e "${BLUE}📋 Step 2: CSS File Validation${NC}"
css_files=(
    "assets/css/hvac-dashboard.css"
    "assets/css/hvac-dashboard-enhanced.css" 
    "assets/css/communication-templates.css"
)

missing_css=false
for css_file in "${css_files[@]}"; do
    if [ -f "$PROJECT_DIR/$css_file" ]; then
        echo -e "${GREEN}✅ Found: $css_file${NC}"
    else
        echo -e "${RED}❌ Missing: $css_file${NC}"
        missing_css=true
        overall_success=false
    fi
done

if [ "$missing_css" = false ]; then
    echo -e "${GREEN}✅ All required CSS files found${NC}"
fi
echo ""

# Check 3: PHP Syntax Validation
echo -e "${BLUE}📋 Step 3: PHP Syntax Validation${NC}"

# Check if PHP is available
if ! command -v php >/dev/null 2>&1; then
    echo -e "${YELLOW}⚠️  PHP not available locally - syntax will be validated on server${NC}"
else
    php_errors=false
    while IFS= read -r -d '' file; do
        if ! php -l "$file" >/dev/null 2>&1; then
            echo -e "${RED}❌ PHP syntax error in: $(basename "$file")${NC}"
            php -l "$file"
            php_errors=true
            overall_success=false
        fi
    done < <(find "$PROJECT_DIR" -name "*.php" -not -path "*/vendor/*" -not -path "*/node_modules/*" -not -path "*/archive/*" -not -path "*/wordpress-dev/*" -not -path "*/tests/*" -not -path "*/playwright/*" -print0)

    if [ "$php_errors" = false ]; then
        echo -e "${GREEN}✅ All PHP files have valid syntax${NC}"
    fi
fi
echo ""

# Check 4: JavaScript Syntax (basic)
echo -e "${BLUE}📋 Step 4: JavaScript Validation${NC}"
js_files_found=false
js_errors=false

# Check only plugin JavaScript files
plugin_js_files=(
    "hvac-dashboard.js"
    "hvac-dashboard-enhanced.js"
    "hvac-registration.js"
    "hvac-certificate-actions.js"
    "hvac-certificate-admin.js"
    "hvac-mobile-nav.js"
    "hvac-accessibility.js"
    "hvac-animations.js"
    "hvac-attendee-profile.js"
    "hvac-event-summary.js"
    "hvac-help-system.js"
    "hvac-ux-enhancements.js"
    "community-login.js"
    "communication-templates.js"
    "advanced-settings.js"
)

for js_file in "${plugin_js_files[@]}"; do
    if [ -f "$PROJECT_DIR/assets/js/$js_file" ]; then
        js_files_found=true
        echo -e "${GREEN}✅ Found: $js_file${NC}"
    fi
done

if [ "$js_files_found" = false ]; then
    echo -e "${YELLOW}⚠️  No JavaScript files found${NC}"
elif [ "$js_errors" = false ]; then
    echo -e "${GREEN}✅ JavaScript files validated${NC}"
fi
echo ""

# Check 5: Required Directories
echo -e "${BLUE}📋 Step 5: Directory Structure Validation${NC}"
required_dirs=(
    "includes"
    "templates"
    "assets/css"
    "assets/js"
)

missing_dirs=false
for dir in "${required_dirs[@]}"; do
    if [ -d "$PROJECT_DIR/$dir" ]; then
        echo -e "${GREEN}✅ Found: $dir${NC}"
    else
        echo -e "${RED}❌ Missing: $dir${NC}"
        missing_dirs=true
        overall_success=false
    fi
done

if [ "$missing_dirs" = false ]; then
    echo -e "${GREEN}✅ All required directories found${NC}"
fi
echo ""

# Check 6: Environment Configuration
echo -e "${BLUE}📋 Step 6: Environment Configuration${NC}"
if [ -f "$PROJECT_DIR/.env" ]; then
    echo -e "${GREEN}✅ .env file found${NC}"
    
    # Check for required variables
    required_vars=("UPSKILL_STAGING_IP" "UPSKILL_STAGING_SSH_USER" "UPSKILL_STAGING_PATH")
    for var in "${required_vars[@]}"; do
        if grep -q "^$var=" "$PROJECT_DIR/.env"; then
            echo -e "${GREEN}✅ Found: $var${NC}"
        else
            echo -e "${RED}❌ Missing: $var${NC}"
            overall_success=false
        fi
    done
else
    echo -e "${RED}❌ .env file not found${NC}"
    overall_success=false
fi
echo ""

# Summary
echo -e "${BLUE}=== Pre-Deployment Check Summary ===${NC}"
if [ "$overall_success" = true ]; then
    echo -e "${GREEN}🎉 ALL CHECKS PASSED!${NC}"
    echo ""
    echo -e "${YELLOW}⚠️  Templates validation skipped (no longer in use)${NC}"
    echo -e "${GREEN}✅ CSS files present${NC}" 
    echo -e "${GREEN}✅ PHP syntax correct${NC}"
    echo -e "${GREEN}✅ JavaScript files ok${NC}"
    echo -e "${GREEN}✅ Directory structure complete${NC}"
    echo -e "${GREEN}✅ Environment configured${NC}"
    echo ""
    echo -e "${BLUE}🚀 Ready for deployment!${NC}"
    exit 0
else
    echo -e "${RED}🚨 DEPLOYMENT BLOCKED!${NC}"
    echo ""
    echo "Fix the issues above before deploying."
    echo "This prevents broken templates from reaching users."
    echo ""
    echo -e "${YELLOW}💡 Quick fixes:${NC}"
    echo "• Add get_header()/get_footer() to templates"
    echo "• Check CSS file paths and names"  
    echo "• Fix PHP syntax errors"
    echo "• Create missing directories"
    echo "• Configure environment variables"
    exit 1
fi