#!/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 "===== Restoring and Fixing Dashboard Data ====="

# Restore from backup and apply minimal fix
RESTORE_FIX="<?php
// Load WordPress
require_once('wp-load.php');

echo \"Restoring and fixing dashboard data...\\n\";

\$dashboard_data_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php';
\$backup_path = \$dashboard_data_path . '.bak';

// Restore from backup if it exists
if (file_exists(\$backup_path)) {
    \$backup_content = file_get_contents(\$backup_path);
    file_put_contents(\$dashboard_data_path, \$backup_content);
    echo \"Restored dashboard data class from backup\\n\";
} else {
    echo \"No backup found, checking current file...\\n\";
}

// Now apply minimal targeted fixes
if (file_exists(\$dashboard_data_path)) {
    \$content = file_get_contents(\$dashboard_data_path);
    
    // Only fix the query methods to use post_author instead of _EventOrganizerID
    \$fixes_applied = false;
    
    // Fix get_upcoming_events_count if it uses _EventOrganizerID
    if (strpos(\$content, '_EventOrganizerID') !== false) {
        echo \"Found _EventOrganizerID usage, fixing to use post_author...\\n\";
        
        // Replace organizer meta query with author query
        \$content = str_replace(
            \"'meta_query' => array(\\n\\t\\t\\t\\tarray(\\n\\t\\t\\t\\t\\t'key' => '_EventOrganizerID',\\n\\t\\t\\t\\t\\t'value' => \\\$this->user_id\\n\\t\\t\\t\\t)\\n\\t\\t\\t)\",
            \"'author' => \\\$this->user_id\",
            \$content
        );
        
        // Also handle variations
        \$content = str_replace(
            \"'_EventOrganizerID' => \\\$this->user_id\",
            \"'author' => \\\$this->user_id\",
            \$content
        );
        
        \$fixes_applied = true;
    }
    
    // Check if we need to add a basic get_events method
    if (strpos(\$content, 'public function get_events') === false) {
        // Add get_events method before the closing brace
        \$new_method = \"\\n\\t/**\\n\\t * Get events\\n\\t */\\n\\tpublic function get_events(\\\$args = array()) {\\n\\t\\t\\\$defaults = array(\\n\\t\\t\\t'post_type' => Tribe__Events__Main::POSTTYPE,\\n\\t\\t\\t'author' => \\\$this->user_id,\\n\\t\\t\\t'posts_per_page' => 10,\\n\\t\\t\\t'post_status' => array('publish', 'future', 'draft', 'pending', 'private')\\n\\t\\t);\\n\\t\\t\\n\\t\\t\\\$args = wp_parse_args(\\\$args, \\\$defaults);\\n\\t\\t\\n\\t\\treturn get_posts(\\\$args);\\n\\t}\\n\";
        
        \$content = str_replace(
            \"\\n}\",
            \$new_method . \"\\n}\",
            \$content
        );
        
        \$fixes_applied = true;
    }
    
    if (\$fixes_applied) {
        if (file_put_contents(\$dashboard_data_path, \$content)) {
            echo \"Applied minimal fixes to dashboard data class\\n\";
        } else {
            echo \"Failed to apply fixes\\n\";
        }
    } else {
        echo \"No fixes needed or already applied\\n\";
    }
}

// Create test data if needed
echo \"\\nChecking test data for test_trainer...\\n\";
\$user = get_user_by('login', 'test_trainer');
if (\$user) {
    // Check for existing events
    \$events = get_posts(array(
        'post_type' => 'tribe_events',
        'author' => \$user->ID,
        'posts_per_page' => -1,
        'post_status' => array('publish', 'future', 'draft', 'pending', 'private')
    ));
    
    echo \"Found \" . count(\$events) . \" events for test_trainer\\n\";
    
    if (count(\$events) == 0) {
        echo \"No events found, running test data creation...\\n\";
        
        // Run the test data creation script
        \$script_path = ABSPATH . 'create-test-data-working.sh';
        if (file_exists(\$script_path)) {
            exec('bash ' . \$script_path, \$output, \$return_var);
            echo \"Test data creation output: \" . implode(\"\\n\", \$output) . \"\\n\";
        } else {
            echo \"Test data script not found at: \$script_path\\n\";
            
            // Create minimal test data directly
            echo \"Creating minimal test data...\\n\";
            
            // Create a simple test event
            \$event_id = wp_insert_post(array(
                'post_title' => 'Test Training Event',
                'post_content' => 'This is a test training event for demo purposes.',
                'post_status' => 'publish',
                'post_type' => 'tribe_events',
                'post_author' => \$user->ID
            ));
            
            if (\$event_id) {
                // Add event meta
                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')));
                update_post_meta(\$event_id, '_EventOrganizerID', \$user->ID);
                
                echo \"Created test event with ID: \$event_id\\n\";
            }
        }
    }
}

echo \"\\nFixes complete. Please refresh the dashboard.\\n\";
"

# Create the restore and fix script on the server
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > restore-fix-dashboard.php << 'EOF'
$RESTORE_FIX
EOF"

# Execute the restore and fix script
echo "Executing restore and fix script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php restore-fix-dashboard.php"

# Now let's also run our existing test data script if it exists
echo -e "\nRunning test data creation script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && if [ -f create-test-data-working.sh ]; then bash create-test-data-working.sh; else echo 'Test data script not found'; fi"

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

echo -e "\n===== Dashboard Restore and Fix Complete ====="
echo "Please refresh the dashboard page to see if the data now appears correctly."