#!/bin/bash

# API-Only Debug Utility (No SSH required)
# Uses only WordPress REST API for debugging

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}" 2>/dev/null
    else
        curl -s -X "$method" \
            -H "$auth_header" \
            "${API_BASE}${endpoint}" 2>/dev/null
    fi
}

echo "=== API-Only Dashboard Debug ==="
echo "Base URL: $API_BASE"
echo ""

# Test API connectivity
echo "1. Testing API connectivity..."
api_result=$(api_call "/wp-json/wp/v2/posts?per_page=1")
if echo "$api_result" | jq -e '.[0].id' > /dev/null 2>&1; then
    echo "✓ API connection successful"
else
    echo "✗ API connection failed"
    echo "Response: $api_result"
    exit 1
fi

# Get test_trainer user
echo ""
echo "2. Getting test_trainer user..."
user_data=$(api_call "/wp-json/wp/v2/users?search=test_trainer")
user_id=$(echo "$user_data" | jq -r '.[0].id // empty' 2>/dev/null)

if [ -n "$user_id" ] && [ "$user_id" != "null" ] && [ "$user_id" != "" ]; then
    echo "✓ Found test_trainer user: ID $user_id"
    user_name=$(echo "$user_data" | jq -r '.[0].name' 2>/dev/null)
    user_email=$(echo "$user_data" | jq -r '.[0].email' 2>/dev/null)
    echo "  Name: $user_name"
    echo "  Email: $user_email"
else
    echo "✗ test_trainer user not found"
    echo "User data response: $user_data"
    exit 1
fi

# Get ALL events first
echo ""
echo "3. 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' 2>/dev/null)
echo "✓ Total events in system: $all_events_count"

# Get events by test_trainer
echo ""
echo "4. Getting events for test_trainer (author=$user_id)..."
events_data=$(api_call "/wp-json/tribe/events/v1/events?author=${user_id}&per_page=100")
events_count=$(echo "$events_data" | jq -r 'length // 0' 2>/dev/null)

echo "✓ Found $events_count events authored by test_trainer"

if [ "$events_count" -gt 0 ]; then
    echo ""
    echo "Event details:"
    echo "$events_data" | jq -r '.[] | "  ID: \(.id) - \(.title.rendered) - Status: \(.status)"' 2>/dev/null
    
    # Get first event for detailed analysis
    first_event_id=$(echo "$events_data" | jq -r '.[0].id' 2>/dev/null)
    echo ""
    echo "5. Analyzing first event (ID: $first_event_id)..."
    
    # Try to get tickets (this may fail if endpoint doesn't exist)
    tickets_data=$(api_call "/wp-json/tribe/tickets/v1/tickets?event=${first_event_id}" 2>/dev/null)
    tickets_count=$(echo "$tickets_data" | jq -r 'length // 0' 2>/dev/null)
    
    if [ "$tickets_count" -gt 0 ]; then
        echo "  ✓ Tickets available: $tickets_count"
        echo "$tickets_data" | jq -r '.[] | "    Ticket ID: \(.id) - \(.name) - Price: \(.price)"' 2>/dev/null
    else
        echo "  ✗ No tickets found or tickets API unavailable"
    fi
    
    # Try to get attendees
    attendees_data=$(api_call "/wp-json/tribe/tickets/v1/attendees?event=${first_event_id}" 2>/dev/null)
    attendees_count=$(echo "$attendees_data" | jq -r 'length // 0' 2>/dev/null)
    
    if [ "$attendees_count" -gt 0 ]; then
        echo "  ✓ Attendees: $attendees_count"
        echo "$attendees_data" | jq -r '.[] | "    Attendee ID: \(.id) - \(.holder_name) - Status: \(.checked_in)"' 2>/dev/null
    else
        echo "  ✗ No attendees found or attendees API unavailable"
    fi
else
    echo ""
    echo "⚠️  ISSUE IDENTIFIED: Dashboard shows 18 events total but 0 events for test_trainer"
    echo "   This explains why tickets sold and revenue show 0"
fi

# Analyze all events by author
echo ""
echo "6. Analyzing all events by author..."
if [ "$all_events_count" -gt 0 ]; then
    authors=$(echo "$all_events" | jq -r '.[] | .author' 2>/dev/null | sort | uniq -c | sort -nr)
    echo "Events by author ID:"
    echo "$authors"
    
    # Check if any events have test_trainer as organizer in meta
    echo ""
    echo "7. Checking for meta data inconsistencies..."
    events_with_meta=$(echo "$all_events" | jq -r ".[] | select(.meta._EventOrganizerID == \"$user_id\") | .id" 2>/dev/null)
    if [ -n "$events_with_meta" ]; then
        echo "✓ Found events with test_trainer as organizer in meta:"
        echo "$events_with_meta"
    else
        echo "✗ No events found with test_trainer as organizer in meta"
    fi
fi

echo ""
echo "=== Debug Summary ==="
echo "- Total events in system: $all_events_count"
echo "- Events authored by test_trainer: $events_count"
echo "- test_trainer user ID: $user_id"

if [ "$events_count" -eq 0 ] && [ "$all_events_count" -gt 0 ]; then
    echo ""
    echo "🔍 ROOT CAUSE IDENTIFIED:"
    echo "   Dashboard counts events using different queries than author-based queries"
    echo "   This suggests the dashboard may be using _EventOrganizerID meta instead of post_author"
    echo "   Or there's a data inconsistency where events exist but aren't properly attributed"
fi

echo ""
echo "=== Next Steps ==="
echo "1. Check dashboard query logic in class-hvac-dashboard-data.php"
echo "2. Verify if events have _EventOrganizerID meta matching post_author"
echo "3. Fix data inconsistency or query logic"