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

# Create dashboard data fix script
DASHBOARD_FIX="<?php
// Load WordPress
require_once('wp-load.php');

echo \"Fixing dashboard data issues...\\n\";

// 1. Fix dashboard data class
\$dashboard_data_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php';
if (file_exists(\$dashboard_data_path)) {
    echo \"Found dashboard data class\\n\";
    
    // Get the file content
    \$content = file_get_contents(\$dashboard_data_path);
    
    // Update get_total_events_count method to use post_author consistently
    \$new_total_events = 'public function get_total_events_count() : int {
        global \$wpdb;
        
        // Use direct database query to avoid TEC query hijacking
        \$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__Main::POSTTYPE,
           \$this->user_id
        ) );
        
        return (int) \$count;
    }';
    
    // Update get_upcoming_events_count method
    \$new_upcoming_events = 'public function get_upcoming_events_count() : int {
        global \$wpdb;
        
        // Get current date in MySQL format
        \$now = current_time(\'mysql\');
        
        // Use direct database query
        \$count = \$wpdb->get_var( \$wpdb->prepare(
           \"SELECT COUNT(*) FROM {\$wpdb->posts} p
            JOIN {\$wpdb->postmeta} pm ON p.ID = pm.post_id
            WHERE p.post_type = %s 
            AND p.post_author = %d 
            AND p.post_status IN (\'publish\', \'future\', \'draft\', \'pending\', \'private\')
            AND pm.meta_key = \'_EventStartDate\'
            AND pm.meta_value >= %s\",
           Tribe__Events__Main::POSTTYPE,
           \$this->user_id,
           \$now
        ) );
        
        return (int) \$count;
    }';
    
    // Update get_past_events_count method
    \$new_past_events = 'public function get_past_events_count() : int {
        global \$wpdb;
        
        // Get current date in MySQL format
        \$now = current_time(\'mysql\');
        
        // Use direct database query
        \$count = \$wpdb->get_var( \$wpdb->prepare(
           \"SELECT COUNT(*) FROM {\$wpdb->posts} p
            JOIN {\$wpdb->postmeta} pm ON p.ID = pm.post_id
            WHERE p.post_type = %s 
            AND p.post_author = %d 
            AND p.post_status IN (\'publish\', \'future\', \'draft\', \'pending\', \'private\')
            AND pm.meta_key = \'_EventStartDate\'
            AND pm.meta_value < %s\",
           Tribe__Events__Main::POSTTYPE,
           \$this->user_id,
           \$now
        ) );
        
        return (int) \$count;
    }';
    
    // Update get_total_tickets_sold method
    \$new_total_tickets = 'public function get_total_tickets_sold() : int {
        global \$wpdb;
        
        // Get all events by this author
        \$events = get_posts(array(
            \'post_type\' => Tribe__Events__Main::POSTTYPE,
            \'author\' => \$this->user_id,
            \'posts_per_page\' => -1,
            \'post_status\' => array(\'publish\', \'future\', \'draft\', \'pending\', \'private\')
        ));
        
        \$total_tickets = 0;
        foreach (\$events as \$event) {
            // Get attendees for this event
            \$attendees = get_posts(array(
                \'post_type\' => \'tribe_tpp_attendees\',
                \'posts_per_page\' => -1,
                \'meta_query\' => array(
                    array(
                        \'key\' => \'_tribe_tpp_event\',
                        \'value\' => \$event->ID
                    )
                )
            ));
            
            \$total_tickets += count(\$attendees);
        }
        
        return \$total_tickets;
    }';
    
    // Update get_total_revenue method
    \$new_total_revenue = 'public function get_total_revenue() : float {
        global \$wpdb;
        
        // Get all events by this author
        \$events = get_posts(array(
            \'post_type\' => Tribe__Events__Main::POSTTYPE,
            \'author\' => \$this->user_id,
            \'posts_per_page\' => -1,
            \'post_status\' => array(\'publish\', \'future\', \'draft\', \'pending\', \'private\')
        ));
        
        \$total_revenue = 0;
        foreach (\$events as \$event) {
            // Get tickets for this event
            \$tickets = get_posts(array(
                \'post_type\' => \'tribe_tpp_attendees\',
                \'posts_per_page\' => -1,
                \'meta_query\' => array(
                    array(
                        \'key\' => \'_tribe_tpp_event\',
                        \'value\' => \$event->ID
                    )
                )
            ));
            
            foreach (\$tickets as \$ticket) {
                // Get ticket price
                \$price = get_post_meta(\$ticket->ID, \'_tribe_tpp_price\', true);
                if (\$price) {
                    \$total_revenue += (float) \$price;
                }
            }
        }
        
        return \$total_revenue;
    }';
    
    // Replace the methods in the content
    \$content = preg_replace('/public function get_total_events_count\\(\\).*?\\}/s', \$new_total_events, \$content);
    \$content = preg_replace('/public function get_upcoming_events_count\\(\\).*?\\}/s', \$new_upcoming_events, \$content);
    \$content = preg_replace('/public function get_past_events_count\\(\\).*?\\}/s', \$new_past_events, \$content);
    \$content = preg_replace('/public function get_total_tickets_sold\\(\\).*?\\}/s', \$new_total_tickets, \$content);
    \$content = preg_replace('/public function get_total_revenue\\(\\).*?\\}/s', \$new_total_revenue, \$content);
    
    // Save the updated content
    if (file_put_contents(\$dashboard_data_path, \$content)) {
        echo \"Successfully updated dashboard data class\\n\";
    } else {
        echo \"Failed to update dashboard data class\\n\";
    }
} else {
    echo \"Dashboard data class file not found\\n\";
}

// 2. Fix certificate reports template
\$cert_reports_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/certificates/template-certificate-reports.php';
if (file_exists(\$cert_reports_path)) {
    echo \"\\nFound certificate reports template\\n\";
    
    // Get the file content
    \$content = file_get_contents(\$cert_reports_path);
    
    // Check if there are debug statements that might be causing issues
    if (strpos(\$content, 'var_dump') !== false || strpos(\$content, 'print_r') !== false) {
        echo \"Found debug statements in certificate reports template\\n\";
        
        // Remove debug statements
        \$content = preg_replace('/(var_dump|print_r)\\s*\\([^;]*\\);/', '', \$content);
        
        // Save the updated content
        if (file_put_contents(\$cert_reports_path, \$content)) {
            echo \"Successfully removed debug statements from certificate reports template\\n\";
        } else {
            echo \"Failed to update certificate reports template\\n\";
        }
    } else {
        echo \"No debug statements found in certificate reports template\\n\";
    }
}

// 3. Clear cache
echo \"\\nClearing cache...\\n\";
\$cache_dirs = array(
    WP_CONTENT_DIR . '/cache/breeze',
    WP_CONTENT_DIR . '/uploads/breeze/css',
    WP_CONTENT_DIR . '/uploads/breeze/js'
);

foreach (\$cache_dirs as \$dir) {
    if (is_dir(\$dir)) {
        \$files = glob(\$dir . '/*');
        if (\$files) {
            foreach (\$files as \$file) {
                if (is_file(\$file)) {
                    @unlink(\$file);
                }
            }
        }
        echo \"Cleared cache directory: \$dir\\n\";
    }
}

echo \"\\nFixes applied. Please refresh the dashboard page.\\n\";
"

# Create the 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 > fix-dashboard.php << 'EOF'
$DASHBOARD_FIX
EOF"

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

# Create data verification script
DATA_VERIFY="<?php
// Load WordPress
require_once('wp-load.php');

echo \"Verifying dashboard data...\\n\";

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

// Load dashboard data class
if (class_exists('HVAC_Dashboard_Data')) {
    \$dashboard_data = new HVAC_Dashboard_Data(\$user->ID);
    
    // Get counts
    \$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 Data Results:\\n\";
    echo \"- Total Events: {\$total_events}\\n\";
    echo \"- Upcoming Events: {\$upcoming_events}\\n\";
    echo \"- Past Events: {\$past_events}\\n\";
    echo \"- Total Tickets: {\$total_tickets}\\n\";
    echo \"- Total Revenue: {\$total_revenue}\\n\";
}

// Verify certificate reports page
\$cert_reports_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/certificates/template-certificate-reports.php';
if (file_exists(\$cert_reports_path)) {
    echo \"\\nCertificate reports template exists\\n\";
} else {
    echo \"\\nCertificate reports template missing\\n\";
}

echo \"\\nVerification complete.\\n\";
"

# Create the verification 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 > verify-dashboard.php << 'EOF'
$DATA_VERIFY
EOF"

# Execute the verification script
echo -e "\nVerifying dashboard data after fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php verify-dashboard.php"

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

echo -e "\n===== Dashboard Fix Complete ====="
echo "Please refresh the dashboard and certificate reports pages to see if the issues have been fixed."