<?php
/**
 * Debug script for MapGeo integration
 * Tests filter registration and plugin connectivity
 */

// Ensure we're in WordPress context
if (!defined('ABSPATH')) {
    // Set up WordPress environment
    require_once '/var/www/html/wp-config.php';
}

// Set up basic debugging
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

echo "<h2>HVAC MapGeo Integration Debugging</h2>\n";

// 1. Check if Interactive Geo Maps plugin is active
echo "<h3>1. Interactive Geo Maps Plugin Status</h3>\n";
$igm_plugin_file = 'interactive-geo-maps/interactive-geo-maps.php';
if (is_plugin_active($igm_plugin_file)) {
    echo "✅ Interactive Geo Maps plugin is ACTIVE<br>\n";
} else {
    echo "❌ Interactive Geo Maps plugin is NOT ACTIVE<br>\n";
    echo "Plugin path checked: {$igm_plugin_file}<br>\n";
    
    // Check if plugin exists but is inactive
    $all_plugins = get_plugins();
    echo "All available plugins:<br>\n";
    foreach ($all_plugins as $plugin_path => $plugin_data) {
        if (stripos($plugin_path, 'interactive') !== false || stripos($plugin_path, 'geo') !== false || stripos($plugin_path, 'map') !== false) {
            echo "- {$plugin_path}: {$plugin_data['Name']} (Version: {$plugin_data['Version']})<br>\n";
        }
    }
}

// 2. Check if our integration class exists and is loaded
echo "<h3>2. HVAC MapGeo Integration Class Status</h3>\n";
if (class_exists('HVAC_MapGeo_Integration')) {
    echo "✅ HVAC_MapGeo_Integration class EXISTS<br>\n";
    
    // Check if instance was created
    $reflection = new ReflectionClass('HVAC_MapGeo_Integration');
    $instance_property = $reflection->getProperty('instance');
    $instance_property->setAccessible(true);
    $instance = $instance_property->getValue();
    
    if ($instance !== null) {
        echo "✅ MapGeo Integration instance is CREATED<br>\n";
    } else {
        echo "❌ MapGeo Integration instance is NOT created<br>\n";
        echo "Attempting to create instance...<br>\n";
        $instance = HVAC_MapGeo_Integration::get_instance();
        echo "✅ Instance created successfully<br>\n";
    }
} else {
    echo "❌ HVAC_MapGeo_Integration class does NOT exist<br>\n";
    
    // Check if the file exists
    $integration_file = '/home/ben/dev/upskill-event-manager/includes/find-trainer/class-hvac-mapgeo-integration.php';
    if (file_exists($integration_file)) {
        echo "✅ Integration file exists: {$integration_file}<br>\n";
        echo "Attempting to load it manually...<br>\n";
        require_once $integration_file;
        
        if (class_exists('HVAC_MapGeo_Integration')) {
            echo "✅ Class loaded successfully<br>\n";
            $instance = HVAC_MapGeo_Integration::get_instance();
            echo "✅ Instance created<br>\n";
        } else {
            echo "❌ Class still not available after manual load<br>\n";
        }
    } else {
        echo "❌ Integration file does NOT exist<br>\n";
    }
}

// 3. Check filter registration
echo "<h3>3. WordPress Filter Registration Status</h3>\n";
global $wp_filter;

$filters_to_check = ['igm_add_meta', 'igm_marker_data'];
foreach ($filters_to_check as $filter_name) {
    if (isset($wp_filter[$filter_name])) {
        echo "✅ Filter '{$filter_name}' is REGISTERED<br>\n";
        echo "Callbacks registered:<br>\n";
        foreach ($wp_filter[$filter_name]->callbacks as $priority => $callbacks) {
            foreach ($callbacks as $callback_id => $callback_data) {
                $callback_name = 'Unknown';
                if (is_array($callback_data['function'])) {
                    if (is_object($callback_data['function'][0])) {
                        $callback_name = get_class($callback_data['function'][0]) . '::' . $callback_data['function'][1];
                    } elseif (is_string($callback_data['function'][0])) {
                        $callback_name = $callback_data['function'][0] . '::' . $callback_data['function'][1];
                    }
                } elseif (is_string($callback_data['function'])) {
                    $callback_name = $callback_data['function'];
                }
                echo "  Priority {$priority}: {$callback_name}<br>\n";
            }
        }
    } else {
        echo "❌ Filter '{$filter_name}' is NOT registered<br>\n";
    }
}

// 4. Test filter execution
echo "<h3>4. Test Filter Execution</h3>\n";
$test_meta = [
    'test_key' => 'test_value',
    'roundMarkers' => [],
    'map_id' => '5872'
];

echo "Testing igm_add_meta filter...<br>\n";
$filtered_meta = apply_filters('igm_add_meta', $test_meta, 5872);

if ($filtered_meta !== $test_meta) {
    echo "✅ Filter WAS executed - meta was modified<br>\n";
    echo "Original keys: " . implode(', ', array_keys($test_meta)) . "<br>\n";
    echo "Filtered keys: " . implode(', ', array_keys($filtered_meta)) . "<br>\n";
} else {
    echo "❌ Filter was NOT executed - no changes made<br>\n";
}

// 5. Check for Interactive Geo Maps functions/classes
echo "<h3>5. Interactive Geo Maps Functions/Classes</h3>\n";
$igm_functions_to_check = [
    'igm_add_meta_filter',
    'igm_get_map_data',
    'interactive_geo_maps_init',
];

$igm_classes_to_check = [
    'Interactive_Geo_Maps',
    'IGM_Core',
    'IGM_Map',
    'IGM_Admin'
];

foreach ($igm_functions_to_check as $function_name) {
    if (function_exists($function_name)) {
        echo "✅ Function '{$function_name}' EXISTS<br>\n";
    } else {
        echo "❌ Function '{$function_name}' does NOT exist<br>\n";
    }
}

foreach ($igm_classes_to_check as $class_name) {
    if (class_exists($class_name)) {
        echo "✅ Class '{$class_name}' EXISTS<br>\n";
    } else {
        echo "❌ Class '{$class_name}' does NOT exist<br>\n";
    }
}

// 6. Check for map shortcode in page content
echo "<h3>6. Map Shortcode in Page Content</h3>\n";
$find_trainer_page = get_page_by_path('find-a-trainer');
if ($find_trainer_page) {
    $page_content = $find_trainer_page->post_content;
    echo "Find-a-trainer page content length: " . strlen($page_content) . " characters<br>\n";
    
    if (strpos($page_content, '[display-map') !== false) {
        echo "✅ Found [display-map shortcode in page content<br>\n";
        preg_match('/\[display-map[^]]*\]/', $page_content, $matches);
        if ($matches) {
            echo "Shortcode: {$matches[0]}<br>\n";
        }
    } else {
        echo "❌ No [display-map shortcode found in page content<br>\n";
    }
} else {
    echo "❌ Find-a-trainer page not found<br>\n";
}

// 7. Check WordPress hook timing
echo "<h3>7. WordPress Hook Timing</h3>\n";
$current_hook = current_action();
echo "Current action: " . ($current_hook ?: 'None') . "<br>\n";

$hooks_fired = [
    'init' => did_action('init'),
    'wp_loaded' => did_action('wp_loaded'),
    'plugins_loaded' => did_action('plugins_loaded'),
    'wp_footer' => did_action('wp_footer'),
    'wp_head' => did_action('wp_head')
];

foreach ($hooks_fired as $hook_name => $times_fired) {
    echo "Hook '{$hook_name}' fired {$times_fired} times<br>\n";
}

// 8. Manual filter test with logging
echo "<h3>8. Manual Filter Test with Logging</h3>\n";
if (class_exists('HVAC_MapGeo_Integration')) {
    $integration = HVAC_MapGeo_Integration::get_instance();
    
    // Create test data that should trigger our integration
    $test_map_meta = [
        'roundMarkers' => [
            [
                'id' => 'test_marker_1',
                'title' => 'Test Trainer',
                'coordinates' => ['lat' => 40.7128, 'lng' => -74.0060],
                'action' => 'igm_display_right_1_3'
            ]
        ]
    ];
    
    echo "Testing modify_map_layout directly...<br>\n";
    $result = $integration->modify_map_layout($test_map_meta, 5872);
    
    echo "Result keys: " . implode(', ', array_keys($result)) . "<br>\n";
    if (isset($result['roundMarkers']) && is_array($result['roundMarkers'])) {
        echo "Result has " . count($result['roundMarkers']) . " markers<br>\n";
        foreach ($result['roundMarkers'] as $i => $marker) {
            echo "Marker {$i} action: " . ($marker['action'] ?? 'none') . "<br>\n";
        }
    }
}

echo "<h3>Debug Complete</h3>\n";
echo "Check error logs for additional debugging information.<br>\n";