<?php
/**
 * 后台管理配置文件
 * 包含评论禁用、后台菜单管理、管理员样式等功能
 */

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

/**
 * 加载后台样式
 */
function nenghui_admin_style() {
    wp_enqueue_style('nenghui-admin-style', get_template_directory_uri() . '/assets/css/admin.css');
}
add_action('admin_enqueue_scripts', 'nenghui_admin_style');

/**
 * 禁用评论功能 - 移除评论菜单
 * 从后台管理菜单中移除评论管理页面
 */
function disable_comments_admin_menu() {
    // 确保全局菜单变量是数组，防止foreach错误
    global $menu, $submenu;
    if (!is_array($menu)) {
        $menu = array();
    }
    if (!is_array($submenu)) {
        $submenu = array();
    }
    
    remove_menu_page('edit-comments.php');
}
add_action('admin_init', 'disable_comments_admin_menu');

/**
 * 禁用评论功能 - 重定向评论页面访问
 * 如果用户直接访问评论管理页面，重定向到仪表盘
 */
function disable_comments_admin_menu_redirect() {
    global $pagenow;
    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url()); 
        exit;
    }
}
add_action('admin_init', 'disable_comments_admin_menu_redirect');

/**
 * 禁用评论功能 - 移除文章类型的评论支持
 * 从所有支持评论的文章类型中移除评论和引用通告支持
 */
function disable_comments_post_types_support() {
    // 确保在正确的时机调用，避免过早执行
    if (!function_exists('get_post_types') || !function_exists('post_type_supports')) {
        return;
    }
    
    try {
        $post_types = get_post_types();
        
        // 增强的数组验证
        if (!is_array($post_types)) {
            // 记录错误并使用安全的默认值
            if (function_exists('nenghui_log_foreach_error')) {
                nenghui_log_foreach_error(array(
                    'error_type' => E_WARNING,
                    'error_message' => 'get_post_types() returned non-array value: ' . gettype($post_types),
                    'error_file' => __FILE__,
                    'error_line' => __LINE__,
                    'timestamp' => date('Y-m-d H:i:s'),
                    'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'admin',
                    'user_agent' => 'disable_comments_post_types_support'
                ));
            }
            $post_types = array('post', 'page'); // 安全的默认值
        }
        
        if (empty($post_types)) {
            return; // 如果没有文章类型，直接返回
        }
        
        // 使用安全的 foreach 循环
        foreach ($post_types as $post_type) {
            // 验证 post_type 是有效的字符串
            if (!is_string($post_type) || empty($post_type)) {
                continue;
            }
            
            // 检查函数是否存在并且文章类型支持评论
            if (function_exists('post_type_supports') && post_type_supports($post_type, 'comments')) {
                remove_post_type_support($post_type, 'comments');
                remove_post_type_support($post_type, 'trackbacks');
            }
        }
    } catch (Exception $e) {
        // 捕获任何异常并记录
        if (function_exists('nenghui_log_foreach_error')) {
            nenghui_log_foreach_error(array(
                'error_type' => E_ERROR,
                'error_message' => 'Exception in disable_comments_post_types_support: ' . $e->getMessage(),
                'error_file' => __FILE__,
                'error_line' => __LINE__,
                'timestamp' => date('Y-m-d H:i:s'),
                'request_uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'admin',
                'user_agent' => 'disable_comments_post_types_support'
            ));
        }
    }
}
add_action('admin_init', 'disable_comments_post_types_support');

/**
 * 禁用评论功能 - 移除工具栏菜单
 */
function disable_comments_admin_bar() {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
}
add_action('init', 'disable_comments_admin_bar');

/**
 * 禁用评论功能 - 过滤器
 */
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
add_filter('comments_array', '__return_empty_array', 10, 2);

/**
 * 分类图片支持
 */
// 添加分类图片字段
function category_image_add_form_fields($taxonomy) {
    ?>
    <div class="form-field term-group">
        <label for="category-image-id">分类图片</label>
        <input type="hidden" id="category-image-id" name="category-image-id" class="custom_media_url" value="">
        <div id="category-image-wrapper"></div>
        <p>
            <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="添加图片" />
            <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="移除图片" />
        </p>
    </div>
    <?php
}
add_action('category_add_form_fields', 'category_image_add_form_fields', 10, 2);

// 编辑分类图片字段
function category_image_edit_form_fields($term, $taxonomy) {
    $image_id = get_term_meta($term->term_id, 'category-image-id', true);
    ?>
    <tr class="form-field term-group-wrap">
        <th scope="row">
            <label for="category-image-id">分类图片</label>
        </th>
        <td>
            <input type="hidden" id="category-image-id" name="category-image-id" value="<?php echo esc_attr($image_id); ?>">
            <div id="category-image-wrapper">
                <?php if ($image_id) { echo wp_get_attachment_image($image_id, 'thumbnail'); } ?>
            </div>
            <p>
                <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="添加图片" />
                <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="移除图片" />
            </p>
        </td>
    </tr>
    <?php
}
add_action('category_edit_form_fields', 'category_image_edit_form_fields', 10, 2);

// 保存分类图片
function save_category_image($term_id, $tt_id) {
    if (isset($_POST['category-image-id']) && '' !== $_POST['category-image-id']){
        $image = $_POST['category-image-id'];
        update_term_meta($term_id, 'category-image-id', $image);
    } else if (isset($_POST['category-image-id']) && '' === $_POST['category-image-id']){
        update_term_meta($term_id, 'category-image-id', '');
    }
}
add_action('created_category', 'save_category_image', 10, 2);
add_action('edited_category', 'save_category_image', 10, 2);

// 加载分类图片脚本
function category_image_script() {
    // 只在分类编辑页加载
    $screen = get_current_screen();
    if ($screen && ($screen->base === 'term' || $screen->base === 'edit-tags')) {
        wp_enqueue_media();
    } else {
        return;
    }
    ?>
    <script>
        jQuery(document).ready(function($) {
            function initMediaUploader() {
                var _custom_media = true,
                _orig_send_attachment = wp.media.editor.send.attachment;

                $('body').on('click','.ct_tax_media_button',function(e) {
                    var send_attachment_bkp = wp.media.editor.send.attachment;
                    var button = $(this);
                    var id = button.attr('id').replace('_button', '');
                    _custom_media = true;
                    wp.media.editor.send.attachment = function(props, attachment) {
                        if (_custom_media) {
                            $('#category-image-id').val(attachment.id);
                            $('#category-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
                            $('#category-image-wrapper .custom_media_image').attr('src',attachment.url).css('display','block');
                        } else {
                            return _orig_send_attachment.apply(this, [props, attachment]);
                        }
                    }
                    wp.media.editor.open(button);
                    return false;
                });

                $('.add_media').on('click', function() {
                    _custom_media = false;
                });
                
                // 修复上传按钮点击
                if(typeof ct_media_upload === 'function') {
                    ct_media_upload('.ct_tax_media_button.button');
                }
                
                $('body').on('click','.ct_tax_media_remove',function(){
                    $('#category-image-id').val('');
                    $('#category-image-wrapper').html('');
                    $('#ct_tax_media_button').val('添加图片');
                });
                
                // 页面加载时显示现有图片
                $(document).ajaxComplete(function(event, xhr, settings) {
                    if (settings.data && settings.data.indexOf('action=add-tag') !== -1) {
                        var xml = xhr.responseXML;
                        if (xml) {
                            var response = $(xml).find('term_id').text();
                            if (response !== "") {
                                // 清空表单
                                $('#category-image-wrapper').html('');
                                $('#category-image-id').val('');
                                $('#ct_tax_media_button').val('添加图片');
                            }
                        }
                    }
                });
            }
            
            // 延迟初始化，确保所有脚本都已加载
            setTimeout(initMediaUploader, 500);
        });
    </script>
    <?php
}
add_action('admin_footer', 'category_image_script');

// 获取分类图片的辅助函数
function get_category_image($category_id, $size = 'full') {
    $image_id = get_term_meta($category_id, 'category-image-id', true);
    if ($image_id) {
        return wp_get_attachment_image_src($image_id, $size);
    }
    return false;
}

// 获取分类图片URL的辅助函数
function get_category_image_url($category_id, $size = 'full') {
    $image = get_category_image($category_id, $size);
    return $image ? $image[0] : '';
}

/**
 * 集成区域跳转管理器 (Region Redirect Manager)
 */
require_once get_template_directory() . '/inc/redirect-manager/class-redirect-manager.php';

// 注册跳转管理器的自定义设置
add_action('customize_register', array('Nenghui_Redirect_Manager', 'register_customizer_settings'));
