<?php
/**
 * 错误处理和调试配置文件
 * 专门用于诊断和修复 plugin.php 中的 foreach 错误
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

/**
 * 增强的错误处理函数
 * 捕获和记录 foreach 相关的错误
 */
function nenghui_error_handler($errno, $errstr, $errfile, $errline) {
    // 只处理 foreach 相关的错误
    if (strpos($errstr, 'foreach') !== false || strpos($errstr, 'Invalid argument') !== false) {
        $error_info = array(
            'error_type' => $errno,
            'error_message' => $errstr,
            'error_file' => $errfile,
            'error_line' => $errline,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown'
        );
        
        // 记录错误日志
        nenghui_log_foreach_error($error_info);
        
        // 如果是调试模式，显示详细信息
        if (WP_DEBUG && WP_DEBUG_DISPLAY) {
            echo '<div style="background: #ffebee; border: 1px solid #f44336; padding: 10px; margin: 10px; border-radius: 4px;">';
            echo '<strong>Foreach Error Detected:</strong><br>';
            echo 'File: ' . esc_html($errfile) . '<br>';
            echo 'Line: ' . esc_html($errline) . '<br>';
            echo 'Message: ' . esc_html($errstr) . '<br>';
            echo '</div>';
        }
    }
    
    // 返回 false 让 PHP 继续处理错误
    return false;
}

/**
 * 记录 foreach 错误到日志文件
 */
function nenghui_log_foreach_error($error_info) {
    $upload_dir = wp_upload_dir();
    
    // 确保 $upload_dir 是数组且包含 basedir
    if (!is_array($upload_dir) || !isset($upload_dir['basedir'])) {
        return;
    }
    
    $log_file = $upload_dir['basedir'] . '/foreach_errors.log';
    
    $log_entry = sprintf(
        "[%s] FOREACH ERROR: %s in %s on line %d (URI: %s)\n",
        $error_info['timestamp'],
        $error_info['error_message'],
        $error_info['error_file'],
        $error_info['error_line'],
        $error_info['request_uri']
    );
    
    // 确保日志文件安全
    if (!file_exists($log_file)) {
        file_put_contents($log_file, "# Foreach Errors Log\n");
        chmod($log_file, 0600);
    }
    
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

/**
 * 安全的 foreach 包装函数
 * 确保传入的变量是可迭代的数组
 */
function nenghui_safe_foreach($array, $callback) {
    if (!is_array($array) && !($array instanceof Traversable)) {
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'nenghui_safe_foreach: Invalid argument supplied, expected array or Traversable',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_safe_foreach'
        ));
        return false;
    }
    
    if (is_callable($callback)) {
        foreach ($array as $key => $value) {
            call_user_func($callback, $value, $key);
        }
        return true;
    }
    
    return false;
}

/**
 * 修复常见的 WordPress 全局变量问题
 * 确保关键的全局变量是正确的数组格式
 */
function nenghui_fix_wp_globals() {
    global $wp_filter, $wp_actions, $wp_current_filter, $wp_meta_boxes, $wp_settings_sections, $wp_settings_fields;
    
    // 确保 $wp_filter 是数组
    if (!is_array($wp_filter)) {
        $wp_filter = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_filter global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
    
    // 确保 $wp_actions 是数组
    if (!is_array($wp_actions)) {
        $wp_actions = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_actions global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
    
    // 确保 $wp_current_filter 是数组
    if (!is_array($wp_current_filter)) {
        $wp_current_filter = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_current_filter global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
    
    // 确保 $wp_meta_boxes 是数组
    if (!is_array($wp_meta_boxes)) {
        $wp_meta_boxes = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_meta_boxes global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
    
    // 确保 $wp_settings_sections 是数组
    if (!is_array($wp_settings_sections)) {
        $wp_settings_sections = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_settings_sections global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
    
    // 确保 $wp_settings_fields 是数组
    if (!is_array($wp_settings_fields)) {
        $wp_settings_fields = array();
        nenghui_log_foreach_error(array(
            'error_type' => E_WARNING,
            'error_message' => 'Fixed $wp_settings_fields global variable - was not array',
            'error_file' => __FILE__,
            'error_line' => __LINE__,
            'timestamp' => date('Y-m-d H:i:s'),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
            'user_agent' => 'nenghui_fix_wp_globals'
        ));
    }
}

/**
 * 在插件加载前修复全局变量
 */
function nenghui_pre_plugin_fix() {
    nenghui_fix_wp_globals();
}

/**
 * 检查和修复主题选项中的数组
 */
function nenghui_fix_theme_options() {
    // 检查常用的主题选项
    $options_to_check = array(
        'banner_images',
        'futures_items',
        'news_posts',
        'menu_items',
        'tab_items'
    );
    
    foreach ($options_to_check as $option) {
        $value = get_theme_mod($option);
        if ($value !== false && !is_array($value)) {
            // 尝试将非数组值转换为数组
            if (is_string($value) && !empty($value)) {
                // 如果是 JSON 字符串，尝试解码
                $decoded = json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    set_theme_mod($option, $decoded);
                } else {
                    // 否则包装为数组
                    set_theme_mod($option, array($value));
                }
            } else {
                // 设置为空数组
                set_theme_mod($option, array());
            }
        }
    }
}

/**
 * 专门修复 plugin.php 第 1853 行的 foreach 错误
 * 这个错误通常发生在钩子系统中的数组操作
 */
function nenghui_fix_plugin_foreach_error() {
    global $wp_filter;
    
    // 确保 $wp_filter 的每个钩子都是正确的数组结构
    if (is_array($wp_filter)) {
        foreach ($wp_filter as $hook_name => $hook_callbacks) {
            if (!is_object($hook_callbacks) && !is_array($hook_callbacks)) {
                // 如果钩子回调不是对象或数组，重置为空的 WP_Hook 对象
                $wp_filter[$hook_name] = new WP_Hook();
                nenghui_log_foreach_error(array(
                    'error_type' => E_WARNING,
                    'error_message' => "Fixed invalid hook callbacks for '$hook_name' - was " . gettype($hook_callbacks),
                    'error_file' => __FILE__,
                    'error_line' => __LINE__,
                    'timestamp' => date('Y-m-d H:i:s'),
                    'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown',
                    'user_agent' => 'nenghui_fix_plugin_foreach_error'
                ));
            }
        }
    }
}

/**
 * 在最早期修复全局变量
 * 确保在任何插件或主题代码执行前修复问题
 */
function nenghui_early_fix() {
    nenghui_fix_wp_globals();
    nenghui_fix_plugin_foreach_error();
}

/**
 * 立即修复全局变量 - 在文件加载时就执行
 * 这确保在任何WordPress函数调用前就修复了全局变量
 */
function nenghui_immediate_fix() {
    global $menu, $submenu, $wp_filter, $wp_actions, $wp_current_filter;
    
    // 立即确保关键全局变量是数组
    if (!is_array($menu)) {
        $menu = array();
    }
    if (!is_array($submenu)) {
        $submenu = array();
    }
    if (!is_array($wp_filter)) {
        $wp_filter = array();
    }
    if (!is_array($wp_actions)) {
        $wp_actions = array();
    }
    if (!is_array($wp_current_filter)) {
        $wp_current_filter = array();
    }
}

// 立即执行修复
nenghui_immediate_fix();

// 注册错误处理器（仅在调试模式下）
if (WP_DEBUG) {
    set_error_handler('nenghui_error_handler', E_WARNING | E_NOTICE);
}

// 在最早期修复全局变量 - 在 muplugins_loaded 之前
add_action('muplugins_loaded', 'nenghui_early_fix', 1);
// 在插件加载前再次修复
add_action('plugins_loaded', 'nenghui_pre_plugin_fix', 1);
// 在主题设置后修复主题选项
add_action('after_setup_theme', 'nenghui_fix_theme_options', 1);
// 在管理页面初始化前修复
add_action('admin_init', 'nenghui_early_fix', 1);
// 在前端初始化前修复
add_action('init', 'nenghui_early_fix', 1);
// 在admin_menu动作前确保菜单变量正确
add_action('admin_menu', 'nenghui_immediate_fix', 1);

?>