<?php
/**
 * Manual Geocoding Trigger Script
 * 
 * This script manually triggers geocoding for all trainer profiles
 * Run with: wp eval-file manual-geocoding-trigger.php
 */

// Ensure we're in WordPress environment
if (!defined('ABSPATH')) {
    // Try to load WordPress
    $wp_load_paths = [
        '../../../wp-load.php',
        '../../../../wp-load.php',
        '../../../../../wp-load.php'
    ];
    
    foreach ($wp_load_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            break;
        }
    }
    
    if (!defined('ABSPATH')) {
        die("Could not load WordPress. Please run with wp eval-file command.\n");
    }
}

echo "🗺️ MANUAL GEOCODING TRIGGER\n";
echo "================================================================================\n";

// Check if required classes exist
$required_classes = [
    'HVAC_Trainer_Profile_Manager',
    'HVAC_Geocoding_Service',
    'HVAC_Trainer_Profile_Settings'
];

foreach ($required_classes as $class) {
    if (!class_exists($class)) {
        echo "❌ Required class {$class} not found\n";
        exit(1);
    }
}

try {
    // Get initial statistics
    echo "📊 Getting initial statistics...\n";
    $settings = HVAC_Trainer_Profile_Settings::get_instance();
    $reflection = new ReflectionClass($settings);
    $method = $reflection->getMethod('get_profile_statistics');
    $method->setAccessible(true);
    $initial_stats = $method->invoke($settings);
    
    echo "   Total Profiles: " . $initial_stats['total_profiles'] . "\n";
    echo "   Initially Geocoded: " . $initial_stats['geocoded_profiles'] . "\n";
    
    // Get geocoding service
    $geocoding_service = HVAC_Geocoding_Service::get_instance();
    
    // Get all trainer profiles
    $profiles = get_posts([
        'post_type' => 'trainer_profile',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'fields' => 'ids'
    ]);
    
    if (empty($profiles)) {
        echo "❌ No trainer profiles found\n";
        exit(1);
    }
    
    echo "\n🔍 Found " . count($profiles) . " trainer profiles to process\n";
    echo "================================================================================\n";
    
    $geocoded_count = 0;
    $skipped_count = 0;
    $error_count = 0;
    
    foreach ($profiles as $profile_id) {
        $profile = get_post($profile_id);
        $profile_title = $profile->post_title ?: "Profile #{$profile_id}";
        
        echo "\n📍 Processing: {$profile_title} (ID: {$profile_id})\n";
        
        // Check if already geocoded
        $existing_lat = get_post_meta($profile_id, 'latitude', true);
        $existing_lng = get_post_meta($profile_id, 'longitude', true);
        
        if (!empty($existing_lat) && !empty($existing_lng)) {
            echo "   ✅ Already geocoded: {$existing_lat}, {$existing_lng}\n";
            $geocoded_count++;
            continue;
        }
        
        // Get address components
        $address_parts = [];
        $city = get_post_meta($profile_id, 'trainer_city', true);
        $state = get_post_meta($profile_id, 'trainer_state', true);
        $country = get_post_meta($profile_id, 'trainer_country', true);
        $address = get_post_meta($profile_id, 'trainer_address', true);
        
        if ($address) $address_parts[] = $address;
        if ($city) $address_parts[] = $city;
        if ($state) $address_parts[] = $state;
        if ($country) $address_parts[] = $country;
        
        if (empty($address_parts)) {
            echo "   ⚠️ No address data found - skipping\n";
            $skipped_count++;
            continue;
        }
        
        $full_address = implode(', ', $address_parts);
        echo "   🔍 Address: {$full_address}\n";
        
        // Attempt geocoding
        try {
            $coordinates = $geocoding_service->geocode_address($full_address);
            
            if ($coordinates && isset($coordinates['lat']) && isset($coordinates['lng'])) {
                // Store coordinates
                update_post_meta($profile_id, 'latitude', $coordinates['lat']);
                update_post_meta($profile_id, 'longitude', $coordinates['lng']);
                update_post_meta($profile_id, 'geocoded_at', current_time('mysql'));
                update_post_meta($profile_id, 'geocoding_source', $coordinates['source'] ?? 'manual');
                
                echo "   ✅ Geocoded successfully: {$coordinates['lat']}, {$coordinates['lng']}\n";
                $geocoded_count++;
                
                // Small delay to respect API rate limits
                sleep(1);
                
            } else {
                echo "   ❌ Geocoding failed - no coordinates returned\n";
                $error_count++;
            }
            
        } catch (Exception $e) {
            echo "   ❌ Geocoding error: " . $e->getMessage() . "\n";
            $error_count++;
        }
    }
    
    echo "\n================================================================================\n";
    echo "📊 GEOCODING SUMMARY\n";
    echo "================================================================================\n";
    echo "   Total Profiles Processed: " . count($profiles) . "\n";
    echo "   Successfully Geocoded: {$geocoded_count}\n";
    echo "   Skipped (no address): {$skipped_count}\n";
    echo "   Errors: {$error_count}\n";
    
    // Get final statistics
    echo "\n📈 Final Statistics:\n";
    $final_stats = $method->invoke($settings);
    echo "   Total Profiles: " . $final_stats['total_profiles'] . "\n";
    echo "   Now Geocoded: " . $final_stats['geocoded_profiles'] . "\n";
    echo "   Improvement: +" . ($final_stats['geocoded_profiles'] - $initial_stats['geocoded_profiles']) . "\n";
    
    if ($final_stats['total_profiles'] > 0) {
        $geocoded_percent = round(($final_stats['geocoded_profiles'] / $final_stats['total_profiles']) * 100, 1);
        echo "   Geocoding Coverage: {$geocoded_percent}%\n";
    }
    
    echo "\n🎉 Manual geocoding trigger completed!\n";
    
} catch (Exception $e) {
    echo "❌ Fatal error during geocoding: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
?>