<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : igny8-wp-load-handler.php
 * @location     : /igny8-wp-load-handler.php
 * @type         : CRON Handler
 * @scope        : Global
 * @allowed      : CRON processing, automation triggers, background tasks
 * @reusability  : Globally Reusable
 * @notes        : WordPress load handler for CRON requests
 */

// Only process if this is an Igny8 CRON request
if (isset($_GET['import_id']) && $_GET['import_id'] === 'igny8_cron') {
    
    // Log: CRON request started
    echo "<div style='background:#f0f0f0;padding:10px;margin:5px;border:1px solid #ccc;'>";
    echo "<strong>Igny8 CRON: Request started</strong><br>";
    error_log("Igny8 CRON: Request started - " . date('Y-m-d H:i:s'));
    
    // Force load Igny8 plugin if not already loaded
    echo "<strong>Igny8 CRON: Checking if plugin is active</strong><br>";
    if (!function_exists('igny8_get_ai_setting')) {
        echo "<strong>Igny8 CRON: Plugin not loaded, attempting to load</strong><br>";
        
        // Try to load the plugin manually - check multiple possible locations
        $possible_paths = [
            'igny8-ai-seo/igny8.php',
            'igny8/igny8.php',
            'igny8-ai-seo.php'
        ];
        
        $plugin_loaded = false;
        foreach ($possible_paths as $plugin_file) {
            $full_path = WP_PLUGIN_DIR . '/' . $plugin_file;
            echo "<strong>Igny8 CRON: Checking path:</strong> " . $full_path . "<br>";
            if (file_exists($full_path)) {
                echo "<strong>Igny8 CRON: Plugin file found at:</strong> " . $full_path . ", loading<br>";
                include_once $full_path;
                $plugin_loaded = true;
                break;
            }
        }
        
        if (!$plugin_loaded) {
            echo "<strong>Igny8 CRON: Plugin file not found in any expected location</strong><br>";
            echo "<strong>Igny8 CRON: WP_PLUGIN_DIR:</strong> " . WP_PLUGIN_DIR . "<br>";
            echo "<strong>Igny8 CRON: Available plugins:</strong> " . implode(', ', array_diff(scandir(WP_PLUGIN_DIR), array('.', '..'))) . "<br>";
        }
        
        // Check again after manual load
        if (!function_exists('igny8_get_ai_setting')) {
            echo "<strong>Igny8 CRON: Plugin still not active after manual load, trying WordPress plugin loading</strong><br>";
            
        // Try to trigger WordPress plugin loading
        if (function_exists('do_action')) {
            echo "<strong>Igny8 CRON: Triggering plugins_loaded action</strong><br>";
            do_action('plugins_loaded');
        }
        
        // Manually load cron handlers if still not found
        if (!function_exists('igny8_auto_cluster_cron_handler')) {
            echo "<strong>Igny8 CRON: Manually loading cron handlers</strong><br>";
            $cron_handlers_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/cron/igny8-cron-handlers.php';
            if (file_exists($cron_handlers_path)) {
                echo "<strong>Igny8 CRON: Loading cron handlers from:</strong> " . $cron_handlers_path . "<br>";
                include_once $cron_handlers_path;
            } else {
                echo "<strong>Igny8 CRON: Cron handlers file not found at:</strong> " . $cron_handlers_path . "<br>";
            }
        }
            
            // Final check
            if (!function_exists('igny8_get_ai_setting')) {
                echo "<strong>Igny8 CRON: Plugin still not active after all attempts</strong><br>";
                error_log("Igny8 CRON: Plugin not active - igny8_get_ai_setting function not found");
                http_response_code(500);
                die(json_encode(['error' => 'Igny8 plugin not active']));
            }
        }
    }
    echo "<strong>Igny8 CRON: Plugin is active</strong><br>";
    
    // Ensure cron handlers are loaded
    if (!function_exists('igny8_auto_cluster_cron_handler')) {
        echo "<strong>Igny8 CRON: Loading cron handlers manually</strong><br>";
        $cron_handlers_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/cron/igny8-cron-handlers.php';
        if (file_exists($cron_handlers_path)) {
            echo "<strong>Igny8 CRON: Loading cron handlers from:</strong> " . $cron_handlers_path . "<br>";
            include_once $cron_handlers_path;
        } else {
            echo "<strong>Igny8 CRON: Cron handlers file not found at:</strong> " . $cron_handlers_path . "<br>";
        }
    }
    echo "<strong>Igny8 CRON: Cron handlers loaded</strong><br>";
    
    // Load global helpers for sector options function
    if (!function_exists('igny8_get_sector_options')) {
        echo "<strong>Igny8 CRON: Loading global helpers for sector options</strong><br>";
        $global_helpers_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/admin/global-helpers.php';
        if (file_exists($global_helpers_path)) {
            echo "<strong>Igny8 CRON: Loading global helpers from:</strong> " . $global_helpers_path . "<br>";
            include_once $global_helpers_path;
        } else {
            echo "<strong>Igny8 CRON: Global helpers file not found at:</strong> " . $global_helpers_path . "<br>";
        }
    }
    echo "<strong>Igny8 CRON: Global helpers loaded</strong><br>";
    
    // Load AJAX handlers for clustering function
    if (!function_exists('igny8_ajax_ai_cluster_keywords')) {
        echo "<strong>Igny8 CRON: Loading AJAX handlers for clustering</strong><br>";
        $ajax_handlers_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/admin/ajax.php';
        if (file_exists($ajax_handlers_path)) {
            echo "<strong>Igny8 CRON: Loading AJAX handlers from:</strong> " . $ajax_handlers_path . "<br>";
            include_once $ajax_handlers_path;
        } else {
            echo "<strong>Igny8 CRON: AJAX handlers file not found at:</strong> " . $ajax_handlers_path . "<br>";
        }
    }
    echo "<strong>Igny8 CRON: AJAX handlers loaded</strong><br>";
    
    // Load model rates configuration to prevent PHP warnings
    echo "<strong>Igny8 CRON: Loading model rates configuration</strong><br>";
    $model_rates_path = WP_PLUGIN_DIR . '/igny8-ai-seo/ai/model-rates-config.php';
    if (file_exists($model_rates_path)) {
        echo "<strong>Igny8 CRON: Loading model rates from:</strong> " . $model_rates_path . "<br>";
        include_once $model_rates_path;
        
        // Verify the global variable is set
        if (isset($GLOBALS['IGNY8_MODEL_RATES'])) {
            echo "<strong>Igny8 CRON: Model rates global variable loaded successfully</strong><br>";
        } else {
            echo "<strong>Igny8 CRON: WARNING - Model rates global variable not set</strong><br>";
        }
    } else {
        echo "<strong>Igny8 CRON: Model rates file not found at:</strong> " . $model_rates_path . "<br>";
    }
    echo "<strong>Igny8 CRON: Model rates loaded</strong><br>";
    
    // Load database functions for taxonomy registration
    if (!function_exists('igny8_register_taxonomies')) {
        echo "<strong>Igny8 CRON: Loading database functions for taxonomy registration</strong><br>";
        $db_functions_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/db/db.php';
        if (file_exists($db_functions_path)) {
            echo "<strong>Igny8 CRON: Loading database functions from:</strong> " . $db_functions_path . "<br>";
            include_once $db_functions_path;
        } else {
            echo "<strong>Igny8 CRON: Database functions file not found at:</strong> " . $db_functions_path . "<br>";
        }
    }
    echo "<strong>Igny8 CRON: Database functions loaded</strong><br>";
    
    // Load master dispatcher for smart automation
    if (!function_exists('igny8_master_dispatcher_run')) {
        echo "<strong>Igny8 CRON: Loading master dispatcher</strong><br>";
        $master_dispatcher_path = WP_PLUGIN_DIR . '/igny8-ai-seo/core/cron/igny8-cron-master-dispatcher.php';
        if (file_exists($master_dispatcher_path)) {
            echo "<strong>Igny8 CRON: Loading master dispatcher from:</strong> " . $master_dispatcher_path . "<br>";
            include_once $master_dispatcher_path;
        } else {
            echo "<strong>Igny8 CRON: Master dispatcher file not found at:</strong> " . $master_dispatcher_path . "<br>";
        }
    }
    echo "<strong>Igny8 CRON: Master dispatcher loaded</strong><br>";

    // 🔧 PATCH: Enable full WordPress taxonomy and rewrite support in CRON context
    echo "<strong>Igny8 CRON: Initializing WordPress rewrite and taxonomy system</strong><br>";
    
    // Set globals for rewrite + taxonomy system
    global $wp_rewrite, $wp_taxonomies;
    
    // ✅ Fix: Initialize rewrite system (prevents "add_rewrite_tag() on null" error)
    if (!isset($wp_rewrite)) {
        echo "<strong>Igny8 CRON: Initializing WP_Rewrite system</strong><br>";
        $wp_rewrite = new WP_Rewrite();
        $wp_rewrite->init();
        echo "<strong>Igny8 CRON: WP_Rewrite system initialized</strong><br>";
    } else {
        echo "<strong>Igny8 CRON: WP_Rewrite system already initialized</strong><br>";
    }
    
    // ✅ Trigger key WP hooks (needed for taxonomy registration) - but be selective
    echo "<strong>Igny8 CRON: Triggering WordPress hooks for taxonomy support</strong><br>";
    
    // Only trigger plugins_loaded (safest for external cron)
    if (!did_action('plugins_loaded')) {
        do_action('plugins_loaded');
        echo "<strong>Igny8 CRON: plugins_loaded hook triggered</strong><br>";
    } else {
        echo "<strong>Igny8 CRON: plugins_loaded hook already executed</strong><br>";
    }
    
    // Skip after_setup_theme and init to avoid widget system issues
    echo "<strong>Igny8 CRON: Skipping after_setup_theme and init hooks to avoid widget system conflicts</strong><br>";
    
    // ✅ Load and register Igny8 taxonomies manually
    echo "<strong>Igny8 CRON: Registering Igny8 taxonomies</strong><br>";
    if (function_exists('igny8_register_taxonomies')) {
        // Ensure WordPress global taxonomies array exists
        global $wp_taxonomies;
        if (!is_array($wp_taxonomies)) {
            $wp_taxonomies = [];
            echo "<strong>Igny8 CRON: Initialized wp_taxonomies global array</strong><br>";
        }
        
        igny8_register_taxonomies();
        echo "<strong>Igny8 CRON: Igny8 taxonomies registered</strong><br>";
    } else {
        echo "<strong>Igny8 CRON: WARNING - igny8_register_taxonomies function not found</strong><br>";
    }
    
    // ✅ Verify taxonomy registration
    if (!taxonomy_exists('clusters')) {
        echo "<strong>Igny8 CRON: ❌ Taxonomy 'clusters' not registered</strong><br>";
        error_log('[CRON] ❌ Taxonomy "clusters" not registered');
        
        // Fallback: Try to register clusters taxonomy directly
        echo "<strong>Igny8 CRON: Attempting direct taxonomy registration as fallback</strong><br>";
        if (function_exists('register_taxonomy')) {
            register_taxonomy('clusters', ['post', 'page', 'product'], [
                'hierarchical' => true,
                'labels' => [
                    'name' => 'Content Clusters',
                    'singular_name' => 'Cluster',
                ],
                'public' => true,
                'show_ui' => true,
                'show_admin_column' => true,
                'show_in_nav_menus' => true,
                'show_tagcloud' => true,
                'show_in_rest' => true,
            ]);
            echo "<strong>Igny8 CRON: Direct clusters taxonomy registration attempted</strong><br>";
        }
    } else {
        echo "<strong>Igny8 CRON: ✅ Taxonomy 'clusters' registered successfully</strong><br>";
        error_log('[CRON] ✅ Taxonomy "clusters" registered successfully');
    }
    
    if (!taxonomy_exists('sectors')) {
        echo "<strong>Igny8 CRON: ❌ Taxonomy 'sectors' not registered</strong><br>";
        error_log('[CRON] ❌ Taxonomy "sectors" not registered');
        
        // Fallback: Try to register sectors taxonomy directly
        if (function_exists('register_taxonomy')) {
            register_taxonomy('sectors', ['post', 'page', 'product'], [
                'hierarchical' => true,
                'labels' => [
                    'name' => 'Sectors',
                    'singular_name' => 'Sector',
                ],
                'public' => true,
                'show_ui' => true,
                'show_admin_column' => true,
                'show_in_nav_menus' => true,
                'show_tagcloud' => true,
                'show_in_rest' => true,
            ]);
            echo "<strong>Igny8 CRON: Direct sectors taxonomy registration attempted</strong><br>";
        }
    } else {
        echo "<strong>Igny8 CRON: ✅ Taxonomy 'sectors' registered successfully</strong><br>";
        error_log('[CRON] ✅ Taxonomy "sectors" registered successfully');
    }

    // === STEP 1: Validate Security Key ===
    echo "<strong>Igny8 CRON: Validating security key</strong><br>";
    $provided_key = isset($_GET['import_key']) ? sanitize_text_field($_GET['import_key']) : '';
    $stored_key = get_option('igny8_secure_cron_key');
    
    echo "<strong>Igny8 CRON: Provided key:</strong> " . substr($provided_key, 0, 8) . "...<br>";
    echo "<strong>Igny8 CRON: Stored key:</strong> " . substr($stored_key, 0, 8) . "...<br>";

    if (empty($stored_key) || $provided_key !== $stored_key) {
        echo "<strong>Igny8 CRON: Security key validation failed</strong><br>";
        error_log("Igny8 CRON: Security key validation failed - provided: " . substr($provided_key, 0, 8) . ", stored: " . substr($stored_key, 0, 8));
        status_header(403);
        echo json_encode(['error' => 'Invalid or missing security key']);
        exit;
    }
    echo "<strong>Igny8 CRON: Security key validated</strong><br>";

    // === STEP 2: Capture Action ===
    echo "<strong>Igny8 CRON: Capturing action parameter</strong><br>";
    $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
    echo "<strong>Igny8 CRON: Action:</strong> " . $action . "<br>";

    if (empty($action)) {
        echo "<strong>Igny8 CRON: Missing action parameter</strong><br>";
        error_log("Igny8 CRON: Missing action parameter");
        status_header(400);
        echo json_encode(['error' => 'Missing action parameter']);
        exit;
    }

    // === STEP 3: Execute CRON Function ===
    echo "<strong>Igny8 CRON: Building allowed actions list</strong><br>";
    $allowed_actions = [
        'master_scheduler' => 'igny8_master_dispatcher_run',
        'auto_cluster'     => 'igny8_auto_cluster_cron',
        'auto_ideas'       => 'igny8_auto_generate_ideas_cron',
        'auto_queue'       => 'igny8_auto_queue_cron',
        'auto_content'     => 'igny8_auto_generate_content_cron',
        'auto_images'      => 'igny8_auto_generate_images_cron',
        'auto_publish'     => 'igny8_auto_publish_drafts_cron',
        'auto_optimizer'   => 'igny8_auto_optimizer_cron',
        'auto_recalc'      => 'igny8_auto_recalc_cron',
        'health_check'     => 'igny8_health_check_cron',
        'test'             => 'igny8_test_cron_endpoint',
    ];
    echo "<strong>Igny8 CRON: Allowed actions:</strong> " . implode(', ', array_keys($allowed_actions)) . "<br>";

    if (!array_key_exists($action, $allowed_actions)) {
        echo "<strong>Igny8 CRON: Invalid action name:</strong> " . $action . "<br>";
        error_log("Igny8 CRON: Invalid action name: " . $action);
        status_header(400);
        echo json_encode(['error' => 'Invalid action name']);
        exit;
    }
    echo "<strong>Igny8 CRON: Action validated:</strong> " . $action . "<br>";

    // Execute safely and catch errors
    echo "<strong>Igny8 CRON: Starting execution</strong><br>";
    try {
        // Handle test action specially
        if ($action === 'test') {
            echo "<strong>Igny8 CRON: Executing test action</strong><br>";
            status_header(200);
            echo json_encode([
                'success' => true, 
                'message' => 'Igny8 CRON endpoint is working via wp-load.php', 
                'timestamp' => date('Y-m-d H:i:s'),
                'server' => $_SERVER['SERVER_NAME'] ?? 'unknown',
                'url_structure' => 'wp-load.php?import_key=[KEY]&import_id=igny8_cron&action=[ACTION]'
            ]);
            exit;
        }
        
        echo "<strong>Igny8 CRON: Executing action:</strong> " . $action . "<br>";
        echo "<strong>Igny8 CRON: Hook to execute:</strong> " . $allowed_actions[$action] . "<br>";
        
        // Check if the hook function exists
        $hook_function = $allowed_actions[$action];
        $handler_function = $hook_function . '_handler';
        
        echo "<strong>Igny8 CRON: Checking hook function:</strong> " . $hook_function . "<br>";
        echo "<strong>Igny8 CRON: Checking handler function:</strong> " . $handler_function . "<br>";
        
        if (!function_exists($hook_function) && !function_exists($handler_function)) {
            echo "<strong>Igny8 CRON: Neither hook nor handler function found</strong><br>";
            echo "<strong>Igny8 CRON: Available functions containing 'igny8_auto_cluster':</strong><br>";
            $functions = get_defined_functions()['user'];
            foreach ($functions as $func) {
                if (strpos($func, 'igny8_auto_cluster') !== false) {
                    echo "- " . $func . "<br>";
                }
            }
            error_log("Igny8 CRON: Hook function not found: " . $hook_function);
            status_header(500);
            echo json_encode(['error' => 'Hook function not found', 'hook' => $hook_function]);
            exit;
        }
        echo "<strong>Igny8 CRON: Hook function exists:</strong> " . $allowed_actions[$action] . "<br>";
        
        // Execute the hook
        echo "<strong>Igny8 CRON: Calling do_action(" . $allowed_actions[$action] . ")</strong><br>";
        do_action($allowed_actions[$action]);
        echo "<strong>Igny8 CRON: do_action completed successfully</strong><br>";
        
        status_header(200);
        echo json_encode(['success' => true, 'message' => "CRON action '{$action}' executed successfully."]);
    } catch (Throwable $e) {
        echo "<strong>Igny8 CRON: Exception caught:</strong> " . $e->getMessage() . "<br>";
        error_log("Igny8 CRON: Exception caught: " . $e->getMessage() . " in " . $e->getFile() . " line " . $e->getLine());
        status_header(500);
        echo json_encode(['error' => 'Execution failed', 'details' => $e->getMessage()]);
    }
    echo "<strong>Igny8 CRON: Request completed</strong><br>";
    echo "</div>"; // Close the main div
    exit;
}
