#!/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 "===== Final Dashboard Fix ====="

# Create the final fix script that will restore and fix the dashboard
FINAL_FIX="<?php
require_once('wp-load.php');

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

// Get the dashboard data file path
\$dashboard_file = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php';

// Check if backup exists, if so restore it
\$backup_file = \$dashboard_file . '.bak';
if (file_exists(\$backup_file)) {
    echo \"Restoring from backup...\\n\";
    copy(\$backup_file, \$dashboard_file);
} else {
    echo \"No backup found, working with current file...\\n\";
}

// Read the current content
\$content = file_get_contents(\$dashboard_file);

// Fix the _EventOrganizerID queries to use author instead
echo \"Fixing queries to use post_author...\\n\";

// Replace the get_total_tickets_sold method to use author
\$old_method = \"/public function get_total_tickets_sold\\(\\) : int \\{.*?\\n\\t\\treturn \\$total_tickets;\\n\\t\\}/s\";
\$new_method = 'public function get_total_tickets_sold() : int {
		\$total_tickets = 0;
		\$args = array(
			\"post_type\"      => Tribe__Events__Main::POSTTYPE,
			\"author\"         => \$this->user_id, // Use author instead of meta query
			\"post_status\"    => array( \"publish\", \"future\", \"draft\", \"pending\", \"private\" ),
			\"posts_per_page\" => -1,
			\"fields\"         => \"ids\",
		);
		\$event_ids = get_posts( \$args );

		if ( ! empty( \$event_ids ) ) {
			foreach ( \$event_ids as \$event_id ) {
				// Check both meta keys that might store sold count
				\$sold = get_post_meta( \$event_id, \"_tribe_tickets_sold\", true );
				if (!is_numeric(\$sold)) {
					\$sold = get_post_meta( \$event_id, \"_tribe_ticket_sold_count\", true );
				}
				
				if ( is_numeric( \$sold ) ) {
					\$total_tickets += (int) \$sold;
				} else {
					// If no sold count metadata found, count attendees directly
					\$attendees_count = \$this->count_event_attendees(\$event_id);
					if (\$attendees_count > 0) {
						\$total_tickets += \$attendees_count;
						update_post_meta(\$event_id, \"_tribe_tickets_sold\", \$attendees_count);
					}
				}
			}
		}

		return \$total_tickets;
	}';

\$content = preg_replace(\$old_method, \$new_method, \$content);

// Replace the get_total_revenue method to use author
\$old_revenue_method = \"/public function get_total_revenue\\(\\) : float \\{.*?\\n\\t\\treturn \\$total_revenue;\\n\\t\\}/s\";
\$new_revenue_method = 'public function get_total_revenue() : float {
		\$total_revenue = 0.0;
		\$args = array(
			\"post_type\"      => Tribe__Events__Main::POSTTYPE,
			\"author\"         => \$this->user_id, // Use author instead of meta query
			\"post_status\"    => array( \"publish\", \"future\", \"draft\", \"pending\", \"private\" ),
			\"posts_per_page\" => -1,
			\"fields\"         => \"ids\",
		);
		\$event_ids = get_posts( \$args );

		if ( ! empty( \$event_ids ) ) {
			foreach ( \$event_ids as \$event_id ) {
				\$revenue = get_post_meta( \$event_id, \"_tribe_revenue_total\", true );
				if ( is_numeric( \$revenue ) ) {
					\$total_revenue += (float) \$revenue;
				} else {
					\$event_revenue = \$this->calculate_event_revenue(\$event_id);
					if (\$event_revenue > 0) {
						\$total_revenue += \$event_revenue;
						update_post_meta(\$event_id, \"_tribe_revenue_total\", \$event_revenue);
					}
				}
			}
		}

		return \$total_revenue;
	}';

\$content = preg_replace(\$old_revenue_method, \$new_revenue_method, \$content);

// Save the updated content
if (file_put_contents(\$dashboard_file, \$content)) {
    echo \"Dashboard class updated successfully\\n\";
} else {
    echo \"Failed to update dashboard class\\n\";
    exit(1);
}

// Now create some test data if none exists
\$user = get_user_by('login', 'test_trainer');
if (!\$user) {
    echo \"test_trainer user not found\\n\";
    exit(1);
}

echo \"Checking for existing events...\\n\";
\$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) . \" existing events\\n\";

if (count(\$events) == 0) {
    echo \"Creating test events...\\n\";
    
    // Create 3 test events
    for (\$i = 1; \$i <= 3; \$i++) {
        \$event_id = wp_insert_post(array(
            'post_title' => \"Test HVAC Training Event \$i\",
            'post_content' => \"This is test training event #\$i for demonstration purposes.\",
            'post_status' => 'publish',
            'post_type' => 'tribe_events',
            'post_author' => \$user->ID
        ));
        
        if (\$event_id) {
            // Add event dates
            \$start_date = date('Y-m-d H:i:s', strtotime(\"+\$i weeks\"));
            \$end_date = date('Y-m-d H:i:s', strtotime(\"+\$i weeks +4 hours\"));
            
            update_post_meta(\$event_id, '_EventStartDate', \$start_date);
            update_post_meta(\$event_id, '_EventEndDate', \$end_date);
            update_post_meta(\$event_id, '_EventOrganizerID', \$user->ID);
            
            // Add mock sales data
            \$sold = rand(10, 25);
            \$price = rand(75, 250);
            \$revenue = \$sold * \$price;
            
            update_post_meta(\$event_id, '_tribe_tickets_sold', \$sold);
            update_post_meta(\$event_id, '_tribe_revenue_total', \$revenue);
            
            echo \"Created event \$i: ID \$event_id, Sold: \$sold, Revenue: $\$revenue\\n\";
        }
    }
}

// Test the dashboard data class
echo \"\\nTesting dashboard data class...\\n\";
\$dashboard_data = new HVAC_Dashboard_Data(\$user->ID);

\$total_events = \$dashboard_data->get_total_events_count();
\$upcoming_events = \$dashboard_data->get_upcoming_events_count();
\$past_events = \$dashboard_data->get_past_events_count();
\$total_tickets = \$dashboard_data->get_total_tickets_sold();
\$total_revenue = \$dashboard_data->get_total_revenue();

echo \"Dashboard Results:\\n\";
echo \"- Total Events: \$total_events\\n\";
echo \"- Upcoming Events: \$upcoming_events\\n\";
echo \"- Past Events: \$past_events\\n\";
echo \"- Total Tickets Sold: \$total_tickets\\n\";
echo \"- Total Revenue: $\$total_revenue\\n\";

echo \"\\nDashboard fix complete!\\n\";
"

# Execute the final fix
echo "Executing final dashboard fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > final-fix.php << 'EOF'
$FINAL_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 final-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 final-fix.php"

echo -e "\n===== Final Dashboard Fix Complete ====="
echo "The dashboard should now display events, tickets sold, and revenue correctly."
echo "Please refresh the dashboard page to see the updated data."