#!/bin/bash

# Exit on error
set -e

# Source environment variables
if [ -f ".env" ]; then
    source .env
else
    echo "Error: .env file not found. Please create it with the required variables."
    exit 1
fi

echo "===== Simple Dashboard Fix ====="

# First, copy the correct dashboard data class from our local version
echo "Uploading corrected dashboard data class..."
scp -o StrictHostKeyChecking=no wordpress/wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:$UPSKILL_STAGING_PATH/wp-content/plugins/hvac-community-events/includes/"

# Apply a simple fix to use post_author instead of _EventOrganizerID
SIMPLE_FIX="<?php
require_once('wp-load.php');

echo \"Applying simple dashboard fix...\\n\";

\$dashboard_file = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php';
\$content = file_get_contents(\$dashboard_file);

// Replace _EventOrganizerID meta queries with author queries
\$content = str_replace(
    \"'meta_key'       => '_EventOrganizerID',\\n\\t\\t\\t'meta_value'     => \\\$this->user_id,\",
    \"// Fixed to use author instead of organizer\\n\\t\\t\\t// 'meta_key' => '_EventOrganizerID',\\n\\t\\t\\t// 'meta_value' => \\\$this->user_id,\",
    \$content
);

// Also fix any other occurrences
\$content = str_replace(
    \"'meta_compare'   => '=', // Explicitly set compare\\n\\t\\t\\t'meta_type'      => 'NUMERIC', // Specify numeric comparison\",
    \"// Fixed to use author instead\\n\\t\\t\\t// 'meta_compare' => '=',\\n\\t\\t\\t// 'meta_type' => 'NUMERIC',\",
    \$content
);

if (file_put_contents(\$dashboard_file, \$content)) {
    echo \"Dashboard file updated successfully\\n\";
} else {
    echo \"Failed to update dashboard file\\n\";
}

// Create some basic test data if none exists
\$user = get_user_by('login', 'test_trainer');
if (\$user) {
    \$events = get_posts(array(
        'post_type' => 'tribe_events',
        'author' => \$user->ID,
        'posts_per_page' => 1
    ));
    
    if (empty(\$events)) {
        echo \"Creating basic test event...\\n\";
        
        \$event_id = wp_insert_post(array(
            'post_title' => 'Test HVAC Training Event',
            'post_content' => 'This is a test training event to demonstrate the dashboard functionality.',
            'post_status' => 'publish',
            'post_type' => 'tribe_events',
            'post_author' => \$user->ID
        ));
        
        if (\$event_id) {
            // Add event dates
            update_post_meta(\$event_id, '_EventStartDate', date('Y-m-d H:i:s', strtotime('+1 week')));
            update_post_meta(\$event_id, '_EventEndDate', date('Y-m-d H:i:s', strtotime('+1 week +4 hours')));
            
            // Add some mock sales data
            update_post_meta(\$event_id, '_tribe_tickets_sold', 15);
            update_post_meta(\$event_id, '_tribe_revenue_total', 1500.00);
            
            echo \"Created test event with ID: \$event_id\\n\";
        }
    }
    
    // Test the dashboard data class
    \$dashboard_data = new HVAC_Dashboard_Data(\$user->ID);
    echo \"\\nDashboard test results:\\n\";
    echo \"Total Events: \" . \$dashboard_data->get_total_events_count() . \"\\n\";
    echo \"Total Tickets: \" . \$dashboard_data->get_total_tickets_sold() . \"\\n\";
    echo \"Total Revenue: \" . \$dashboard_data->get_total_revenue() . \"\\n\";
}

echo \"\\nFix complete.\\n\";
"

# Execute the simple fix
echo "Executing simple dashboard fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > simple-fix.php << 'EOF'
$SIMPLE_FIX
EOF"

# Run the fix
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php simple-fix.php"

# Clean up
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && rm simple-fix.php"

echo -e "\n===== Simple Dashboard Fix Complete ====="
echo "The dashboard should now show data correctly. Please refresh the page."