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

# Create dashboard data fix script with minimal changes
FIX_SCRIPT="<?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 original content for backup
    \$original_content = file_get_contents(\$dashboard_data_path);
    file_put_contents(\$dashboard_data_path . '.bak', \$original_content);
    echo \"Created backup of original file\\n\";
    
    // Update the entire file with fixed content
    \$fixed_content = '<?php
/**
 * Dashboard Data Class
 *
 * Provides data for the trainer dashboard
 */

class HVAC_Dashboard_Data {
    /**
     * User ID
     */
    private \$user_id;
    
    /**
     * Constructor
     */
    public function __construct(\$user_id = 0) {
        \$this->user_id = \$user_id ?: get_current_user_id();
    }
    
    /**
     * Get total events count
     */
    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;
    }
    
    /**
     * Get upcoming events count
     */
    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;
    }
    
    /**
     * Get past events count
     */
    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;
    }
    
    /**
     * Get total tickets sold
     */
    public function get_total_tickets_sold() : int {
        // 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;
    }
    
    /**
     * Get total revenue
     */
    public function get_total_revenue() : float {
        // 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;
    }
    
    /**
     * Get events
     */
    public function get_events(\$args = array()) {
        \$defaults = array(
            \'post_type\' => Tribe__Events__Main::POSTTYPE,
            \'author\' => \$this->user_id,
            \'posts_per_page\' => 10,
            \'post_status\' => array(\'publish\', \'future\', \'draft\', \'pending\', \'private\')
        );
        
        \$args = wp_parse_args(\$args, \$defaults);
        
        return get_posts(\$args);
    }
    
    /**
     * Get upcoming events
     */
    public function get_upcoming_events(\$limit = 10) {
        \$now = current_time(\'mysql\');
        
        return \$this->get_events(array(
            \'posts_per_page\' => \$limit,
            \'meta_query\' => array(
                array(
                    \'key\' => \'_EventStartDate\',
                    \'value\' => \$now,
                    \'compare\' => \'>=\'
                )
            ),
            \'orderby\' => \'meta_value\',
            \'meta_key\' => \'_EventStartDate\',
            \'order\' => \'ASC\'
        ));
    }
    
    /**
     * Get past events
     */
    public function get_past_events(\$limit = 10) {
        \$now = current_time(\'mysql\');
        
        return \$this->get_events(array(
            \'posts_per_page\' => \$limit,
            \'meta_query\' => array(
                array(
                    \'key\' => \'_EventStartDate\',
                    \'value\' => \$now,
                    \'compare\' => \'<\'
                )
            ),
            \'orderby\' => \'meta_value\',
            \'meta_key\' => \'_EventStartDate\',
            \'order\' => \'DESC\'
        ));
    }
}';
    
    if (file_put_contents(\$dashboard_data_path, \$fixed_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\";
    
    // Create a backup
    \$original_content = file_get_contents(\$cert_reports_path);
    file_put_contents(\$cert_reports_path . '.bak', \$original_content);
    echo \"Created backup of certificate reports template\\n\";
    
    // Look for debug statements
    if (strpos(\$original_content, 'var_dump') !== false || strpos(\$original_content, 'print_r') !== false) {
        // Remove debug statements
        \$fixed_content = preg_replace('/(var_dump|print_r)\\s*\\([^;]*\\);/', '', \$original_content);
        
        if (file_put_contents(\$cert_reports_path, \$fixed_content)) {
            echo \"Removed debug statements from certificate reports template\\n\";
        } else {
            echo \"Failed to update certificate reports template\\n\";
        }
    } else {
        echo \"No debug statements found in 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-data.php << 'EOF'
$FIX_SCRIPT
EOF"

# Execute the fix script
echo "Executing dashboard data 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-data.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-data.php"

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