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

# Create emergency fix script
echo "Creating emergency fix script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > emergency-fix.php << 'EOF'
<?php
// Skip WordPress loading to avoid the broken class
echo \"Emergency dashboard fix starting...\n\";

// Simple file replacement using pure PHP
\$class_content = '<?php
if ( ! defined( \"ABSPATH\" ) ) {
	exit;
}

class HVAC_Dashboard_Data {
	private \$user_id;

	public function __construct( \$user_id ) {
		\$this->user_id = \$user_id;
	}

	public function get_total_events_count() {
		global \$wpdb;
		\$count = \$wpdb->get_var( \$wpdb->prepare(
			\"SELECT COUNT(*) FROM {\$wpdb->posts} 
			 WHERE post_type = %s 
			 AND post_author = %d 
			 AND post_status IN (\\\"publish\\\", \\\"future\\\", \\\"draft\\\", \\\"pending\\\", \\\"private\\\")\",
			\"tribe_events\",
			\$this->user_id
		) );
		return (int) \$count;
	}

	public function get_upcoming_events_count() {
		global \$wpdb;
		\$today = date( \"Y-m-d H:i:s\" );
		\$count = \$wpdb->get_var( \$wpdb->prepare(
			\"SELECT COUNT(*) FROM {\$wpdb->posts} p
			 LEFT JOIN {\$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = \\\"_EventStartDate\\\"
			 WHERE p.post_type = %s 
			 AND p.post_author = %d 
			 AND p.post_status IN (\\\"publish\\\", \\\"future\\\")
			 AND (pm.meta_value >= %s OR pm.meta_value IS NULL)\",
			\"tribe_events\",
			\$this->user_id,
			\$today
		) );
		return (int) \$count;
	}

	public function get_past_events_count() {
		global \$wpdb;
		\$today = date( \"Y-m-d H:i:s\" );
		\$count = \$wpdb->get_var( \$wpdb->prepare(
			\"SELECT COUNT(*) FROM {\$wpdb->posts} p
			 LEFT JOIN {\$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = \\\"_EventEndDate\\\"
			 WHERE p.post_type = %s 
			 AND p.post_author = %d 
			 AND p.post_status IN (\\\"publish\\\", \\\"private\\\")
			 AND pm.meta_value < %s\",
			\"tribe_events\",
			\$this->user_id,
			\$today
		) );
		return (int) \$count;
	}

	public function get_total_tickets_sold() {
		\$total_tickets = 0;
		\$args = array(
			\"post_type\" => \"tribe_events\",
			\"author\" => \$this->user_id,
			\"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 ) {
				\$sold = get_post_meta( \$event_id, \"_tribe_tickets_sold\", true );
				if ( is_numeric( \$sold ) ) {
					\$total_tickets += (int) \$sold;
				}
			}
		}
		return \$total_tickets;
	}

	public function get_total_revenue() {
		\$total_revenue = 0.0;
		\$args = array(
			\"post_type\" => \"tribe_events\",
			\"author\" => \$this->user_id,
			\"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;
				}
			}
		}
		return \$total_revenue;
	}

	public function get_events_table_data( \$filter_status = \"all\" ) {
		\$events_data = [];
		\$valid_statuses = array( \"publish\", \"future\", \"draft\", \"pending\", \"private\" );
		\$post_status = ( \"all\" === \$filter_status || ! in_array( \$filter_status, \$valid_statuses, true ) )
						? \$valid_statuses
						: array( \$filter_status );

		\$args = array(
			\"post_type\" => \"tribe_events\",
			\"author\" => \$this->user_id,
			\"post_status\" => \$post_status,
			\"posts_per_page\" => -1,
			\"orderby\" => \"meta_value\",
			\"meta_key\" => \"_EventStartDate\",
			\"order\" => \"DESC\",
		);

		\$query = new WP_Query( \$args );
		if ( \$query->have_posts() ) {
			while ( \$query->have_posts() ) {
				\$query->the_post();
				\$event_id = get_the_ID();
				\$sold = get_post_meta( \$event_id, \"_tribe_tickets_sold\", true );
				\$revenue = get_post_meta( \$event_id, \"_tribe_revenue_total\", true );

				\$events_data[] = array(
					\"id\" => \$event_id,
					\"status\" => get_post_status( \$event_id ),
					\"name\" => get_the_title(),
					\"link\" => get_permalink( \$event_id ),
					\"start_date_ts\" => strtotime( get_post_meta( \$event_id, \"_EventStartDate\", true ) ),
					\"organizer_id\" => (int) get_post_meta( \$event_id, \"_EventOrganizerID\", true ),
					\"capacity\" => \"Unlimited\",
					\"sold\" => is_numeric( \$sold ) ? (int) \$sold : 0,
					\"revenue\" => is_numeric( \$revenue ) ? (float) \$revenue : 0.0,
				);
			}
			wp_reset_postdata();
		}
		return \$events_data;
	}
}';

// Write the new class
\$dashboard_file = \"wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php\";
if (file_put_contents(\$dashboard_file, \$class_content)) {
    echo \"Successfully created working dashboard class\n\";
} else {
    echo \"Failed to create dashboard class\n\";
}

echo \"Emergency fix complete\n\";
EOF"

echo "Executing emergency fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php emergency-fix.php"

# Now test with WordPress loaded
echo "Testing the fixed dashboard..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > test-emergency-fix.php << 'EOF'
<?php
require_once('wp-load.php');

echo \"Testing emergency dashboard fix...\n\";

\$user = get_user_by('login', 'test_trainer');
if (!\$user) {
    echo \"test_trainer user not found\n\";
    exit(1);
}

// Create test event if none exists
\$events = get_posts(array(
    'post_type' => 'tribe_events',
    'author' => \$user->ID,
    'posts_per_page' => 1
));

if (empty(\$events)) {
    echo \"Creating test event...\n\";
    
    \$event_id = wp_insert_post(array(
        'post_title' => 'Emergency Test Event',
        'post_content' => 'Test event created during emergency fix.',
        'post_status' => 'publish',
        'post_type' => 'tribe_events',
        'post_author' => \$user->ID
    ));
    
    if (\$event_id) {
        update_post_meta(\$event_id, '_EventStartDate', date('Y-m-d H:i:s', strtotime('+2 weeks')));
        update_post_meta(\$event_id, '_EventEndDate', date('Y-m-d H:i:s', strtotime('+2 weeks +4 hours')));
        update_post_meta(\$event_id, '_tribe_tickets_sold', 8);
        update_post_meta(\$event_id, '_tribe_revenue_total', 800.00);
        echo \"Created test event with ID: \$event_id\n\";
    }
}

// Test dashboard
\$dashboard_data = new HVAC_Dashboard_Data(\$user->ID);

echo \"Dashboard Test Results:\n\";
echo \"Total Events: \" . \$dashboard_data->get_total_events_count() . \"\n\";
echo \"Upcoming Events: \" . \$dashboard_data->get_upcoming_events_count() . \"\n\";
echo \"Past Events: \" . \$dashboard_data->get_past_events_count() . \"\n\";
echo \"Total Tickets: \" . \$dashboard_data->get_total_tickets_sold() . \"\n\";
echo \"Total Revenue: $\" . \$dashboard_data->get_total_revenue() . \"\n\";

echo \"Emergency fix test complete!\n\";
EOF"

sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php test-emergency-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 emergency-fix.php test-emergency-fix.php"

echo -e "\n===== Emergency Dashboard Fix Complete ====="
echo "The dashboard class has been restored to a working state."
echo "Please refresh the dashboard page - it should now show data correctly."