#!/bin/bash

# Exit on error
set -e

# Source environment variables
source .env

echo "Deploying dashboard fix to staging..."

# Backup original dashboard data class
echo "Backing up original file..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cp wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php.bak"

# Upload the fixed version
echo "Uploading fixed dashboard data class..."
sshpass -p "$UPSKILL_STAGING_PASS" scp -o StrictHostKeyChecking=no wordpress/wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data-fixed.php "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:$UPSKILL_STAGING_PATH/wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data-fixed.php"

# Overwrite the original with the fixed version
echo "Replacing original dashboard data class..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cp wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data-fixed.php wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php"

# Clear cache
echo "Clearing cache..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && wp cache flush"

# Test the fix
echo -e "\nTesting the fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > test-dashboard-fix.php << 'EOF'
<?php
require_once('wp-load.php');

\$user_id = get_user_by('login', 'test_trainer')->ID;
echo \"User ID: \$user_id\\n\";

\$dashboard_data = new HVAC_Dashboard_Data(\$user_id);

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\";
EOF"

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

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

echo -e "\nDashboard fix deployed. You should now see the correct stats at: https://wordpress-974670-5399585.cloudwaysapps.com/hvac-dashboard/"