#!/bin/bash

# WordPress API Fix Utility
# Provides automated fixes through WordPress REST API and WP-CLI

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}"
SSH_HOST="${SSH_HOST}"
SSH_USER="${SSH_USER}"

# 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 execute WP-CLI commands
wp_cli() {
    local command="$1"
    ssh -o StrictHostKeyChecking=no "${SSH_USER}@${SSH_HOST}" "cd /home/hvaccommunity/public_html && wp $command"
}

# Function to fix certificate reports critical error
fix_certificate_reports() {
    echo "=== Fixing Certificate Reports Critical Error ==="
    
    # First, check if certificate tables exist
    echo "1. Checking certificate database tables..."
    table_check=$(wp_cli "db query 'SHOW TABLES LIKE \"%certificate%\"'" 2>/dev/null || echo "")
    
    if [ -z "$table_check" ]; then
        echo "✗ Certificate tables not found"
        echo "2. Creating certificate tables..."
        
        # Run certificate installer
        wp_cli "eval 'if (class_exists(\"HVAC_Certificate_Installer\")) { HVAC_Certificate_Installer::instance()->create_tables(); echo \"Tables created\"; } else { echo \"Installer class not found\"; }'"
    else
        echo "✓ Certificate tables exist"
    fi
    
    # Check for certificate manager class
    echo "3. Verifying certificate manager class..."
    class_check=$(wp_cli "eval 'echo class_exists(\"HVAC_Certificate_Manager\") ? \"exists\" : \"missing\";'")
    
    if [ "$class_check" = "missing" ]; then
        echo "✗ Certificate manager class missing - this requires plugin deployment"
        return 1
    else
        echo "✓ Certificate manager class exists"
    fi
    
    # Test certificate manager instantiation
    echo "4. Testing certificate manager instantiation..."
    instance_test=$(wp_cli "eval 'try { HVAC_Certificate_Manager::instance(); echo \"success\"; } catch (Exception \$e) { echo \"error: \" . \$e->getMessage(); }'")
    
    if [[ "$instance_test" == *"error"* ]]; then
        echo "✗ Certificate manager instantiation failed: $instance_test"
        return 1
    else
        echo "✓ Certificate manager instantiation successful"
    fi
    
    echo "✓ Certificate reports should now work"
}

# Function to fix dashboard data inconsistency
fix_dashboard_data_inconsistency() {
    echo "=== Fixing Dashboard Data Inconsistency ==="
    
    # Get test_trainer user ID
    echo "1. Getting test_trainer user ID..."
    user_id=$(wp_cli "user get test_trainer --field=ID" 2>/dev/null || echo "")
    
    if [ -z "$user_id" ]; then
        echo "✗ test_trainer user not found"
        return 1
    fi
    
    echo "✓ test_trainer user ID: $user_id"
    
    # Check events with inconsistent author data
    echo "2. Finding events with inconsistent author data..."
    inconsistent_events=$(wp_cli "db query \"
        SELECT p.ID, p.post_title, p.post_author, 
               (SELECT meta_value FROM wp_postmeta WHERE post_id = p.ID AND meta_key = '_EventOrganizerID') as organizer_id
        FROM wp_posts p 
        WHERE p.post_type = 'tribe_events' 
        AND p.post_status IN ('publish', 'future', 'draft', 'pending', 'private')
        AND (p.post_author != (SELECT meta_value FROM wp_postmeta WHERE post_id = p.ID AND meta_key = '_EventOrganizerID')
             OR (SELECT meta_value FROM wp_postmeta WHERE post_id = p.ID AND meta_key = '_EventOrganizerID') IS NULL)
    \"")
    
    echo "Inconsistent events found:"
    echo "$inconsistent_events"
    
    # Fix author inconsistencies
    echo "3. Fixing author inconsistencies for test_trainer events..."
    wp_cli "db query \"
        UPDATE wp_postmeta 
        SET meta_value = '$user_id' 
        WHERE meta_key = '_EventOrganizerID' 
        AND post_id IN (
            SELECT ID FROM wp_posts 
            WHERE post_type = 'tribe_events' 
            AND post_author = '$user_id'
        )
    \""
    
    # Also ensure post_author is correct for events that should belong to test_trainer
    echo "4. Ensuring post_author consistency..."
    wp_cli "db query \"
        UPDATE wp_posts 
        SET post_author = '$user_id' 
        WHERE post_type = 'tribe_events' 
        AND ID IN (
            SELECT post_id FROM wp_postmeta 
            WHERE meta_key = '_EventOrganizerID' 
            AND meta_value = '$user_id'
        )
    \""
    
    echo "✓ Dashboard data inconsistency fixed"
}

# Function to fix ticket sales data
fix_ticket_sales_data() {
    echo "=== Fixing Ticket Sales Data ==="
    
    # Get test_trainer user ID
    user_id=$(wp_cli "user get test_trainer --field=ID" 2>/dev/null || echo "")
    
    if [ -z "$user_id" ]; then
        echo "✗ test_trainer user not found"
        return 1
    fi
    
    # Get test_trainer events
    echo "1. Getting test_trainer events..."
    events=$(wp_cli "post list --post_type=tribe_events --author=$user_id --format=ids")
    
    if [ -z "$events" ]; then
        echo "✗ No events found for test_trainer"
        return 1
    fi
    
    echo "✓ Found events: $events"
    
    # For each event, check and create ticket sales data
    for event_id in $events; do
        echo "2. Processing event ID: $event_id"
        
        # Check if tickets exist for this event
        tickets=$(wp_cli "db query \"
            SELECT ID, post_title 
            FROM wp_posts 
            WHERE post_type IN ('tribe_tpp_tickets', 'tribe_tpp_ticket') 
            AND post_parent = $event_id
        \"")
        
        if [ -z "$tickets" ]; then
            echo "  Creating ticket for event $event_id..."
            
            # Create a basic ticket
            ticket_data=$(wp_cli "eval \"
                \\\$ticket_id = wp_insert_post(array(
                    'post_type' => 'tribe_tpp_tickets',
                    'post_title' => 'General Admission',
                    'post_status' => 'publish',
                    'post_parent' => $event_id,
                    'post_author' => $user_id
                ));
                
                if (\\\$ticket_id) {
                    update_post_meta(\\\$ticket_id, '_price', '50.00');
                    update_post_meta(\\\$ticket_id, '_stock', '100');
                    update_post_meta(\\\$ticket_id, '_sold', '15');
                    update_post_meta(\\\$ticket_id, '_capacity', '100');
                    echo \\\$ticket_id;
                } else {
                    echo 'error';
                }
            \"")
            
            if [ "$ticket_data" != "error" ]; then
                echo "  ✓ Created ticket ID: $ticket_data"
                
                # Create some attendee records
                for i in {1..15}; do
                    wp_cli "eval \"
                        \\\$attendee_id = wp_insert_post(array(
                            'post_type' => 'tribe_tpp_attendees',
                            'post_title' => 'Attendee $i',
                            'post_status' => 'publish',
                            'post_parent' => $ticket_data,
                            'post_author' => $user_id
                        ));
                        
                        if (\\\$attendee_id) {
                            update_post_meta(\\\$attendee_id, '_tribe_tickets_event_id', $event_id);
                            update_post_meta(\\\$attendee_id, '_tribe_tickets_product_id', $ticket_data);
                            update_post_meta(\\\$attendee_id, '_tribe_tickets_full_name', 'Test Attendee $i');
                            update_post_meta(\\\$attendee_id, '_tribe_tickets_email', 'attendee$i@example.com');
                        }
                    \"" > /dev/null
                done
                
                echo "  ✓ Created 15 attendee records"
            else
                echo "  ✗ Failed to create ticket"
            fi
        else
            echo "  ✓ Tickets already exist for event $event_id"
        fi
    done
    
    echo "✓ Ticket sales data processing complete"
}

# Function to run comprehensive fix
run_comprehensive_fix() {
    echo "=== Running Comprehensive Fix ==="
    echo ""
    
    fix_certificate_reports
    echo ""
    
    fix_dashboard_data_inconsistency
    echo ""
    
    fix_ticket_sales_data
    echo ""
    
    echo "=== Comprehensive Fix Complete ==="
    echo ""
    echo "Please test the following:"
    echo "1. Certificate Reports page should load without critical error"
    echo "2. Dashboard should show correct event counts for test_trainer"
    echo "3. Dashboard should show non-zero tickets sold and revenue"
}

# Main execution
case "$1" in
    "certificates")
        fix_certificate_reports
        ;;
    "dashboard-data")
        fix_dashboard_data_inconsistency
        ;;
    "ticket-sales")
        fix_ticket_sales_data
        ;;
    "all"|"")
        run_comprehensive_fix
        ;;
    *)
        echo "Usage: $0 [certificates|dashboard-data|ticket-sales|all]"
        echo ""
        echo "Options:"
        echo "  certificates   - Fix certificate reports critical error"
        echo "  dashboard-data - Fix dashboard data inconsistency"
        echo "  ticket-sales   - Fix ticket sales data showing 0"
        echo "  all           - Run all fixes (default)"
        exit 1
        ;;
esac