#!/bin/bash

# WordPress API Debug Utility
# Provides comprehensive debugging through WordPress REST API

set -e

# Load environment variables
if [ -f "../.env" ]; then
    source ../.env
elif [ -f ".env" ]; then
    source .env
else
    echo "Error: .env file not found"
    exit 1
fi

# API Configuration
API_BASE="${WP_API_BASE_URL}"
USERNAME="${WP_API_USERNAME}"
PASSWORD="${WP_API_PASSWORD}"

# Function to make authenticated API calls
api_call() {
    local endpoint="$1"
    local method="${2:-GET}"
    local data="$3"
    
    local auth_header="Authorization: Basic $(echo -n "${USERNAME}:${PASSWORD}" | base64)"
    
    if [ "$method" = "POST" ] && [ -n "$data" ]; then
        curl -s -X "$method" \
            -H "Content-Type: application/json" \
            -H "$auth_header" \
            -d "$data" \
            "${API_BASE}${endpoint}"
    else
        curl -s -X "$method" \
            -H "$auth_header" \
            "${API_BASE}${endpoint}"
    fi
}

# Function to get user by login
get_user_by_login() {
    local login="$1"
    api_call "/wp-json/wp/v2/users?search=${login}"
}

# Function to get events by author
get_events_by_author() {
    local author_id="$1"
    api_call "/wp-json/tribe/events/v1/events?author=${author_id}&per_page=100"
}

# Function to get tickets by event
get_tickets_by_event() {
    local event_id="$1"
    api_call "/wp-json/tribe/tickets/v1/tickets?event=${event_id}"
}

# Function to get attendees by event
get_attendees_by_event() {
    local event_id="$1"
    api_call "/wp-json/tribe/tickets/v1/attendees?event=${event_id}"
}

# Function to debug dashboard data issues
debug_dashboard_data() {
    echo "=== WordPress API Dashboard Debug ==="
    echo "Base URL: $API_BASE"
    echo "Username: $USERNAME"
    echo ""
    
    # Test API connectivity
    echo "1. Testing API connectivity..."
    api_result=$(api_call "/wp-json/wp/v2/posts?per_page=1" 2>&1)
    if echo "$api_result" | grep -q '"id"'; then
        echo "✓ API connection successful"
    else
        echo "✗ API connection failed: $api_result"
        return 1
    fi
    
    # Get test_trainer user
    echo ""
    echo "2. Getting test_trainer user..."
    user_data=$(get_user_by_login "test_trainer")
    user_id=$(echo "$user_data" | jq -r '.[0].id // empty')
    
    if [ -n "$user_id" ] && [ "$user_id" != "null" ]; then
        echo "✓ Found test_trainer user: ID $user_id"
        user_name=$(echo "$user_data" | jq -r '.[0].name')
        user_email=$(echo "$user_data" | jq -r '.[0].email')
        echo "  Name: $user_name"
        echo "  Email: $user_email"
    else
        echo "✗ test_trainer user not found"
        return 1
    fi
    
    # Get events by author
    echo ""
    echo "3. Getting events for test_trainer..."
    events_data=$(get_events_by_author "$user_id")
    events_count=$(echo "$events_data" | jq -r 'length // 0')
    
    echo "✓ Found $events_count events for test_trainer"
    
    if [ "$events_count" -gt 0 ]; then
        echo ""
        echo "Event details:"
        echo "$events_data" | jq -r '.[] | "  ID: \(.id) - \(.title.rendered) - Status: \(.status)"'
        
        # Get first event for detailed analysis
        first_event_id=$(echo "$events_data" | jq -r '.[0].id')
        echo ""
        echo "4. Analyzing first event (ID: $first_event_id)..."
        
        # Get tickets for this event
        tickets_data=$(get_tickets_by_event "$first_event_id")
        tickets_count=$(echo "$tickets_data" | jq -r 'length // 0')
        echo "  Tickets available: $tickets_count"
        
        if [ "$tickets_count" -gt 0 ]; then
            echo "$tickets_data" | jq -r '.[] | "    Ticket ID: \(.id) - \(.name) - Price: \(.price)"'
        fi
        
        # Get attendees for this event
        attendees_data=$(get_attendees_by_event "$first_event_id")
        attendees_count=$(echo "$attendees_data" | jq -r 'length // 0')
        echo "  Attendees: $attendees_count"
        
        if [ "$attendees_count" -gt 0 ]; then
            echo "$attendees_data" | jq -r '.[] | "    Attendee ID: \(.id) - \(.holder_name) - Status: \(.checked_in)"'
        fi
    fi
    
    # Get all events to compare
    echo ""
    echo "5. Getting all events for comparison..."
    all_events=$(api_call "/wp-json/tribe/events/v1/events?per_page=100")
    all_events_count=$(echo "$all_events" | jq -r 'length // 0')
    echo "✓ Total events in system: $all_events_count"
    
    # Analyze event authors
    echo ""
    echo "6. Analyzing event authors..."
    authors=$(echo "$all_events" | jq -r '.[] | .author' | sort | uniq -c | sort -nr)
    echo "Events by author ID:"
    echo "$authors"
    
    echo ""
    echo "=== Debug Complete ==="
}

# Function to debug certificate system
debug_certificate_system() {
    echo "=== Certificate System Debug ==="
    
    # Custom API endpoint for certificates (if exists)
    cert_result=$(api_call "/wp-json/hvac/v1/certificates" 2>&1)
    if echo "$cert_result" | grep -q '"certificate_id"'; then
        echo "✓ Certificate API endpoint working"
        echo "$cert_result" | jq '.'
    else
        echo "✗ Certificate API endpoint not available or error: $cert_result"
    fi
    
    # Check for certificate custom post type
    cert_posts=$(api_call "/wp-json/wp/v2/hvac_certificates?per_page=10" 2>&1)
    if echo "$cert_posts" | grep -q '"id"'; then
        echo "✓ Certificate posts found"
        cert_count=$(echo "$cert_posts" | jq -r 'length')
        echo "  Certificate count: $cert_count"
    else
        echo "✗ No certificate posts or endpoint unavailable"
    fi
}

# Function to fix dashboard data via API
fix_dashboard_data() {
    echo "=== Attempting Dashboard Data Fix via API ==="
    
    # This would require custom REST API endpoints in the plugin
    # For now, we'll provide the framework
    
    fix_result=$(api_call "/wp-json/hvac/v1/fix-dashboard-data" "POST" '{"action":"fix_author_inconsistency"}' 2>&1)
    if echo "$fix_result" | grep -q '"success"'; then
        echo "✓ Dashboard data fix applied successfully"
        echo "$fix_result" | jq '.'
    else
        echo "✗ Dashboard data fix failed or endpoint unavailable: $fix_result"
    fi
}

# Main execution
case "$1" in
    "dashboard")
        debug_dashboard_data
        ;;
    "certificates")
        debug_certificate_system
        ;;
    "fix-dashboard")
        fix_dashboard_data
        ;;
    "all"|"")
        debug_dashboard_data
        echo ""
        debug_certificate_system
        ;;
    *)
        echo "Usage: $0 [dashboard|certificates|fix-dashboard|all]"
        echo ""
        echo "Options:"
        echo "  dashboard     - Debug dashboard data issues"
        echo "  certificates  - Debug certificate system"
        echo "  fix-dashboard - Attempt to fix dashboard data"
        echo "  all          - Run all debug checks (default)"
        exit 1
        ;;
esac