#!/bin/bash

# Cache Trainer Event Counts Script
# Pre-populates event count cache to improve find-a-trainer page performance

echo "=== Caching Trainer Event Counts ==="

# For staging server
if [[ "$1" == "staging" ]]; then
    echo "Caching event counts on staging server..."
    ssh roodev@146.190.76.204 'cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html && wp eval "
    \$profiles = get_posts([
        \"post_type\" => \"trainer_profile\",
        \"posts_per_page\" => -1,
        \"post_status\" => \"publish\"
    ]);
    
    \$cached = 0;
    
    foreach (\$profiles as \$profile) {
        \$user_id = get_post_meta(\$profile->ID, \"user_id\", true);
        if (\$user_id) {
            \$count_query = new WP_Query([
                \"post_type\" => \"tribe_events\",
                \"author\" => \$user_id,
                \"post_status\" => \"publish\",
                \"fields\" => \"ids\",
                \"posts_per_page\" => 1,
                \"no_found_rows\" => false
            ]);
            \$event_count = \$count_query->found_posts;
            wp_reset_postdata();
            
            update_post_meta(\$profile->ID, \"cached_event_count\", \$event_count);
            update_post_meta(\$profile->ID, \"cached_event_count_timestamp\", time());
            
            \$trainer_name = get_post_meta(\$profile->ID, \"trainer_display_name\", true);
            echo \"Cached \" . \$trainer_name . \": \" . \$event_count . \" events\" . PHP_EOL;
            \$cached++;
        }
    }
    
    echo \"Cached event counts for \" . \$cached . \" trainers\" . PHP_EOL;
    "'

else
    echo "Usage: $0 staging"
    echo "Caches trainer event counts to improve find-a-trainer page performance"
fi

echo "=== Cache Update Complete ==="