<?php
// 导入theme-options.php文件，主题配置文件
require_once 'theme-options.php';

// 导入customizer.php文件，自定义器配置文件
require_once get_template_directory() . '/inc/customizer.php';

// 导入assets-loader.php文件，资源加载管理器
require_once get_template_directory() . '/inc/assets-loader.php';

// 添加自定义重写规则来处理archive页面分页
function add_archive_pagination_rules() {
    // 添加/news/page/数字/的重写规则
    add_rewrite_rule(
        '^news/page/([0-9]+)/?$',
        'index.php?pagename=archive&paged=$1',
        'top'
    );
    
    // 添加/news/的重写规则
    add_rewrite_rule(
        '^news/?$',
        'index.php?pagename=archive',
        'top'
    );
}
add_action('init', 'add_archive_pagination_rules');

// 刷新重写规则（仅在主题激活时执行一次）
function flush_archive_rewrite_rules() {
    add_archive_pagination_rules();
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'flush_archive_rewrite_rules');

// 处理archive页面的查询
function handle_archive_query($query) {
    if (!is_admin() && $query->is_main_query()) {
        if (get_query_var('pagename') === 'archive') {
            // 设置为archive页面查询
            $query->set('post_type', 'post');
            $query->set('post_status', 'publish');
            $query->set('posts_per_page', 5);
            
            // 获取分页参数
            $paged = get_query_var('paged') ? get_query_var('paged') : 1;
            $query->set('paged', $paged);
            
            // 设置模板
            add_filter('template_include', function($template) {
                return get_template_directory() . '/archive.php';
            });
        }
    }
}
add_action('pre_get_posts', 'handle_archive_query');

// 全局设置文章每页显示数量，修复分页404问题
function set_posts_per_page_global($query) {
    if (!is_admin() && $query->is_main_query()) {
        if ($query->is_category() || $query->is_search() || $query->is_archive()) {
            $query->set('posts_per_page', 5);
        }
    }
}
add_action('pre_get_posts', 'set_posts_per_page_global', 99);

// 维护模式检查
function check_maintenance_mode() {
    // 如果是管理员或在后台，不显示维护页面
    if (is_admin() || current_user_can('manage_options')) {
        return;
    }
    
    // 获取维护模式设置
    $options = get_option('themes_demo');
    $maintenance_mode = isset($options['maintenance_mode']) ? $options['maintenance_mode'] : '0';
    
    // 检查定时维护模式
    $is_scheduled_maintenance = check_scheduled_maintenance();
    
    // 如果启用了维护模式或处于定时维护期间，显示维护页面
    if ($maintenance_mode === '1' || $is_scheduled_maintenance) {
        $maintenance_title = isset($options['maintenance_title']) ? $options['maintenance_title'] : '网站维护中';
        $maintenance_message = isset($options['maintenance_message']) ? $options['maintenance_message'] : '我们正在对网站进行维护升级，请稍后再访问。给您带来的不便，敬请谅解！';
        
        // 设置503状态码
        status_header(503);
        
        // 显示维护页面
        show_maintenance_page($maintenance_title, $maintenance_message);
        exit;
    }
}
add_action('template_redirect', 'check_maintenance_mode');

/**
 * 检查是否处于定时维护期间
 */
function check_scheduled_maintenance() {
    $options = get_option('themes_demo');
    $start_time = isset($options['maintenance_start_time']) ? $options['maintenance_start_time'] : '';
    $end_time = isset($options['maintenance_end_time']) ? $options['maintenance_end_time'] : '';
    $timezone = isset($options['maintenance_timezone']) ? $options['maintenance_timezone'] : 'Asia/Shanghai';
    
    // 如果没有设置时间，返回false
    if (empty($start_time) && empty($end_time)) {
        return false;
    }
    
    try {
        // 设置时区
        $tz = new DateTimeZone($timezone);
        $current_time = new DateTime('now', $tz);
        
        // 如果只设置了结束时间，检查是否已过期
        if (empty($start_time) && !empty($end_time)) {
            $end_datetime = new DateTime($end_time, $tz);
            return $current_time < $end_datetime;
        }
        
        // 如果只设置了开始时间，检查是否已开始
        if (!empty($start_time) && empty($end_time)) {
            $start_datetime = new DateTime($start_time, $tz);
            return $current_time >= $start_datetime;
        }
        
        // 如果都设置了，检查是否在时间范围内
        if (!empty($start_time) && !empty($end_time)) {
            $start_datetime = new DateTime($start_time, $tz);
            $end_datetime = new DateTime($end_time, $tz);
            return $current_time >= $start_datetime && $current_time < $end_datetime;
        }
        
    } catch (Exception $e) {
        // 时间解析错误，记录日志
        error_log('Maintenance mode time parsing error: ' . $e->getMessage());
        return false;
    }
    
    return false;
}

/**
 * 获取维护模式结束时间（用于倒计时）
 */
function get_maintenance_end_time() {
    $options = get_option('themes_demo');
    $end_time = isset($options['maintenance_end_time']) ? $options['maintenance_end_time'] : '';
    $timezone = isset($options['maintenance_timezone']) ? $options['maintenance_timezone'] : 'Asia/Shanghai';
    
    if (empty($end_time)) {
        return null;
    }
    
    try {
        $tz = new DateTimeZone($timezone);
        $end_datetime = new DateTime($end_time, $tz);
        return $end_datetime->getTimestamp();
    } catch (Exception $e) {
        error_log('获取维护结束时间错误: ' . $e->getMessage());
        return null;
    }
}

/**
 * 注册维护模式定时任务
 */
function schedule_maintenance_mode_tasks() {
    // 清除现有的定时任务
    wp_clear_scheduled_hook('maintenance_mode_start');
    wp_clear_scheduled_hook('maintenance_mode_end');
    
    $options = get_option('themes_demo');
    $start_time = isset($options['maintenance_start_time']) ? $options['maintenance_start_time'] : '';
    $end_time = isset($options['maintenance_end_time']) ? $options['maintenance_end_time'] : '';
    $timezone = isset($options['maintenance_timezone']) ? $options['maintenance_timezone'] : 'Asia/Shanghai';
    
    if (empty($start_time) && empty($end_time)) {
        return;
    }
    
    try {
        $tz = new DateTimeZone($timezone);
        $current_time = new DateTime('now', $tz);
        
        // 安排开始维护任务
        if (!empty($start_time)) {
            $start_datetime = new DateTime($start_time, $tz);
            $start_timestamp = $start_datetime->getTimestamp();
            
            // 只有当开始时间在未来时才安排任务
            if ($start_timestamp > time()) {
                wp_schedule_single_event($start_timestamp, 'maintenance_mode_start');
                error_log('已安排维护模式开始任务: ' . $start_datetime->format('Y-m-d H:i:s'));
            }
        }
        
        // 安排结束维护任务
        if (!empty($end_time)) {
            $end_datetime = new DateTime($end_time, $tz);
            $end_timestamp = $end_datetime->getTimestamp();
            
            // 只有当结束时间在未来时才安排任务
            if ($end_timestamp > time()) {
                wp_schedule_single_event($end_timestamp, 'maintenance_mode_end');
                error_log('已安排维护模式结束任务: ' . $end_datetime->format('Y-m-d H:i:s'));
            }
        }
        
    } catch (Exception $e) {
        error_log('Schedule maintenance tasks error: ' . $e->getMessage());
    }
}
add_action('update_option_themes_demo', 'schedule_maintenance_mode_tasks');

/**
 * 获取主题缓存版本号
 * 用于当文章更新时刷新所有相关的transient缓存
 */
function get_theme_cache_version() {
    $version = get_option('theme_cache_version');
    if (false === $version) {
        $version = time();
        update_option('theme_cache_version', $version);
    }
    return $version;
}

/**
 * 更新主题缓存版本号（清理缓存）
 */
function update_theme_cache_version() {
    update_option('theme_cache_version', time());
}

// 在文章保存、删除、切换主题时自动清理缓存
add_action('save_post', 'update_theme_cache_version');
add_action('deleted_post', 'update_theme_cache_version');
add_action('switch_theme', 'update_theme_cache_version');

/**
 * 在顶部管理栏添加"清理缓存"按钮
 */
function add_clear_cache_button_to_admin_bar($wp_admin_bar) {
    if (!current_user_can('manage_options')) {
        return;
    }

    $args = array(
        'id'    => 'clear_theme_cache',
        'title' => '清理主题缓存',
        'href'  => wp_nonce_url(admin_url('admin-post.php?action=clear_theme_cache'), 'clear_theme_cache_nonce'),
        'meta'  => array('class' => 'clear-theme-cache-button')
    );
    $wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'add_clear_cache_button_to_admin_bar', 999);

/**
 * 处理手动清理缓存请求
 */
function handle_manual_cache_clearing() {
    if (!current_user_can('manage_options')) {
        wp_die('权限不足');
    }

    check_admin_referer('clear_theme_cache_nonce');

    update_theme_cache_version();

    // 获取来源页面，如果存在则跳回，否则跳回首页
    $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : home_url('/');
    
    wp_redirect($redirect_url);
    exit;
}
add_action('admin_post_clear_theme_cache', 'handle_manual_cache_clearing');


/**
 * 自动开启维护模式
 */
function auto_start_maintenance_mode() {
    $options = get_option('themes_demo');
    $options['maintenance_mode'] = '1';
    update_option('themes_demo', $options);
    error_log('自动开启维护模式');
}
add_action('maintenance_mode_start', 'auto_start_maintenance_mode');

/**
 * 自动关闭维护模式
 */
function auto_end_maintenance_mode() {
    $options = get_option('themes_demo');
    $options['maintenance_mode'] = '0';
    update_option('themes_demo', $options);
    error_log('自动关闭维护模式');
}
add_action('maintenance_mode_end', 'auto_end_maintenance_mode');

/**
 * 当主题选项更新时重新安排维护任务
 */
function reschedule_maintenance_tasks_on_update($option_name, $old_value, $value) {
    if ($option_name === 'themes_demo') {
        // 检查维护相关设置是否有变化
        $old_start = isset($old_value['maintenance_start_time']) ? $old_value['maintenance_start_time'] : '';
        $old_end = isset($old_value['maintenance_end_time']) ? $old_value['maintenance_end_time'] : '';
        $old_timezone = isset($old_value['maintenance_timezone']) ? $old_value['maintenance_timezone'] : 'Asia/Shanghai';
        
        $new_start = isset($value['maintenance_start_time']) ? $value['maintenance_start_time'] : '';
        $new_end = isset($value['maintenance_end_time']) ? $value['maintenance_end_time'] : '';
        $new_timezone = isset($value['maintenance_timezone']) ? $value['maintenance_timezone'] : 'Asia/Shanghai';
        
        if ($old_start !== $new_start || $old_end !== $new_end || $old_timezone !== $new_timezone) {
            schedule_maintenance_mode_tasks();
            error_log('维护模式设置已更新，重新安排定时任务');
        }
    }
}
add_action('updated_option', 'reschedule_maintenance_tasks_on_update', 10, 3);

/**
 * 强制触发WordPress Cron（用于测试）
 */
function force_wp_cron() {
    if (defined('DOING_CRON') && DOING_CRON) {
        return;
    }
    
    // 触发WordPress Cron
    spawn_cron();
}

// 在主题激活时安排维护任务
add_action('after_switch_theme', 'schedule_maintenance_mode_tasks');

// 包含维护模式测试文件（仅在开发环境或管理员访问时）
if (is_admin() && current_user_can('manage_options')) {
    require_once get_template_directory() . '/maintenance-test.php';
}

// 显示维护页面
function show_maintenance_page($title, $message) {
    $site_name = get_bloginfo('name');
    $logo = get_theme_option('site_logo');
    $end_timestamp = get_maintenance_end_time();
    
    ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo esc_html($title); ?> - <?php echo esc_html($site_name); ?></title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .maintenance-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 60px 40px;
            text-align: center;
            max-width: 500px;
            margin: 20px;
        }
        .maintenance-logo {
            max-width: 200px;
            height: auto;
            margin-bottom: 30px;
        }
        .maintenance-title {
            color: #333;
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 20px;
        }
        .maintenance-message {
            color: #666;
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 30px;
        }
        .maintenance-icon {
            font-size: 64px;
            color: #667eea;
            margin-bottom: 20px;
        }
        .countdown-container {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        .countdown-title {
            color: #333;
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
        }
        .countdown-timer {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 15px;
        }
        .countdown-item {
            background: #667eea;
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            min-width: 60px;
        }
        .countdown-number {
            font-size: 24px;
            font-weight: bold;
            display: block;
        }
        .countdown-label {
            font-size: 12px;
            opacity: 0.9;
        }
        .back-link {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 5px;
            transition: background 0.3s;
        }
        .back-link:hover {
            background: #5a6fd8;
        }
    </style>
</head>
<body>
    <div class="maintenance-container">
        <?php if ($logo): ?>
            <img src="<?php echo esc_url($logo); ?>" alt="<?php echo esc_attr($site_name); ?>" class="maintenance-logo">
        <?php else: ?>
            <div class="maintenance-icon">🔧</div>
        <?php endif; ?>
        
        <h1 class="maintenance-title"><?php echo esc_html($title); ?></h1>
        <p class="maintenance-message"><?php echo esc_html($message); ?></p>
        
        <?php if ($end_timestamp): ?>
        <div class="countdown-container">
            <div class="countdown-title">预计恢复时间</div>
            <div class="countdown-timer" id="countdown">
                <div class="countdown-item">
                    <span class="countdown-number" id="days">00</span>
                    <span class="countdown-label">天</span>
                </div>
                <div class="countdown-item">
                    <span class="countdown-number" id="hours">00</span>
                    <span class="countdown-label">时</span>
                </div>
                <div class="countdown-item">
                    <span class="countdown-number" id="minutes">00</span>
                    <span class="countdown-label">分</span>
                </div>
                <div class="countdown-item">
                    <span class="countdown-number" id="seconds">00</span>
                    <span class="countdown-label">秒</span>
                </div>
            </div>
        </div>
        
        <script>
        function updateCountdown() {
            const endTime = <?php echo $end_timestamp * 1000; ?>;
            const now = new Date().getTime();
            const distance = endTime - now;
            
            if (distance < 0) {
                document.getElementById('countdown').innerHTML = '<div style="color: #28a745; font-size: 18px; font-weight: bold;">维护已结束，正在刷新页面...</div>';
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
                return;
            }
            
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            
            document.getElementById('days').textContent = String(days).padStart(2, '0');
            document.getElementById('hours').textContent = String(hours).padStart(2, '0');
            document.getElementById('minutes').textContent = String(minutes).padStart(2, '0');
            document.getElementById('seconds').textContent = String(seconds).padStart(2, '0');
        }
        
        updateCountdown();
        setInterval(updateCountdown, 1000);
        </script>
        <?php endif; ?>
        
        <a href="<?php echo esc_url(home_url('/')); ?>" class="back-link">刷新页面</a>
    </div>
</body>
</html><?php
}

// 导入资源加载管理器
require_once get_template_directory() . '/inc/assets-loader.php';

// 导入自定义器配置
require_once get_template_directory() . '/inc/customizer.php';

// 导入简码功能
require_once get_template_directory() . '/inc/shortcode.php';

// 主题支持功能
function nenghui_theme_setup() {
    // 启用特色图像支持
    add_theme_support('post-thumbnails');
    
    // 设置特色图像尺寸
    set_post_thumbnail_size(800, 600, true);
    
    // 添加自定义图像尺寸
    add_image_size('news-large', 800, 600, true);
    add_image_size('news-medium', 400, 300, true);
    add_image_size('news-small', 200, 150, true);
    
    // 启用HTML5支持
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption'
    ));
    
    // 启用标题标签支持
    add_theme_support('title-tag');
    
    // 启用自定义logo支持
    add_theme_support('custom-logo', array(
        'height'      => 100,
        'width'       => 400,
        'flex-height' => true,
        'flex-width'  => true,
    ));
}
add_action('after_setup_theme', 'nenghui_theme_setup');

// 注册导航菜单
function register_theme_menus() {
    register_nav_menus(array(
        'primary-menu' => '主导航菜单'
    ));
}
add_action('init', 'register_theme_menus');

// 允许上传SVG和WebP格式文件
function allow_svg_webp_upload($mimes) {
    // 添加SVG支持
    $mimes['svg'] = 'image/svg+xml';
    $mimes['svgz'] = 'image/svg+xml';
    
    // 添加WebP支持
    $mimes['webp'] = 'image/webp';
    
    return $mimes;
}
add_filter('upload_mimes', 'allow_svg_webp_upload');

// 修复SVG文件的MIME类型检查
function fix_svg_mime_type($data, $file, $filename, $mimes) {
    $filetype = wp_check_filetype($filename, $mimes);
    if ($filetype['ext'] === 'svg') {
        $data['ext'] = 'svg';
        $data['type'] = 'image/svg+xml';
    }
    return $data;
}
add_filter('wp_check_filetype_and_ext', 'fix_svg_mime_type', 10, 4);

// 为SVG文件添加安全检查
function sanitize_svg_upload($file) {
    if ($file['type'] === 'image/svg+xml') {
        $svg_content = file_get_contents($file['tmp_name']);
        
        // 检查是否包含潜在危险的标签
        $dangerous_tags = array('script', 'object', 'embed', 'iframe', 'link');
        foreach ($dangerous_tags as $tag) {
            if (strpos($svg_content, '<' . $tag) !== false) {
                $file['error'] = 'SVG文件包含不安全的内容，上传被拒绝。';
                return $file;
            }
        }
    }
    return $file;
}
add_filter('wp_handle_upload_prefilter', 'sanitize_svg_upload');

// 在媒体库中正确显示SVG文件
function display_svg_in_media_library($response, $attachment, $meta) {
    if ($response['type'] === 'image' && $response['subtype'] === 'svg+xml') {
        $response['image'] = array(
            'src' => $response['url'],
            'width' => 150,
            'height' => 150,
        );
        $response['thumb'] = array(
            'src' => $response['url'],
            'width' => 150,
            'height' => 150,
        );
        $response['sizes'] = array(
            'full' => array(
                'url' => $response['url'],
                'width' => 150,
                'height' => 150,
                'orientation' => 'landscape'
            )
        );
    }
    return $response;
}
add_filter('wp_prepare_attachment_for_js', 'display_svg_in_media_library', 10, 3);

// 加载自定义器JavaScript文件
function nenghui_customizer_scripts() {
    // 加载自定义器控制脚本
    wp_enqueue_script(
        'nenghui-customizer-controls',
        get_template_directory_uri() . '/assets/js/customizer-controls.js',
        array('jquery', 'customize-controls'),
        '1.5.0',
        true
    );
}
add_action('customize_controls_enqueue_scripts', 'nenghui_customizer_scripts');

// 加载自定义器预览脚本
function nenghui_customizer_preview_scripts() {
    wp_enqueue_script(
        'nenghui-customizer-preview',
        get_template_directory_uri() . '/assets/js/customizer-preview.js',
        array('jquery', 'customize-preview'),
        '1.5.0',
        true
    );
}
add_action('customize_preview_init', 'nenghui_customizer_preview_scripts');

// 禁用自动生成的图片尺寸
function shapeSpace_disable_image_sizes($sizes) {
    unset($sizes['thumbnail']); // 禁用缩略图尺寸
    unset($sizes['medium']); // 禁用中等尺寸
    unset($sizes['large']); // 禁用大尺寸
    unset($sizes['medium_large']); // 禁用中大型尺寸
    unset($sizes['1536x1536']); // 禁用2倍中大型尺寸
    unset($sizes['2048x2048']); // 禁用2倍大尺寸
    return $sizes;
}
add_action('intermediate_image_sizes_advanced', 'shapeSpace_disable_image_sizes');

// 禁用大图片自动缩放功能
add_filter('big_image_size_threshold', '__return_false');

// 禁用其他自定义图片尺寸
function shapeSpace_disable_other_image_sizes() {
    // 禁用特色图片尺寸
    remove_image_size('post-thumbnail');
    
    // 如果有其他主题或插件添加的图片尺寸，可以在这里继续移除
    // 例如：remove_image_size('custom-size');
}
add_action('init', 'shapeSpace_disable_other_image_sizes');

// 自定义导航菜单Walker类，支持下拉多级菜单
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
    
    // 开始输出子菜单
    function start_lvl(&$output, $depth = 0, $args = null) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class='sub-menu'>\n";
    }
    
    // 结束输出子菜单
    function end_lvl(&$output, $depth = 0, $args = null) {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul>\n";
    }
    
    // 开始输出菜单项
    function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        $indent = ($depth) ? str_repeat("\t", $depth) : '';
        
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;
        
        // 检查是否有子菜单
        $has_children = in_array('menu-item-has-children', $classes);
        
        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
        $class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';
        
        $id = apply_filters('nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args);
        $id = $id ? ' id="' . esc_attr($id) . '"' : '';
        
        $output .= $indent . '<li' . $id . $class_names .'>';
        
        $attributes = ! empty($item->attr_title) ? ' title="'  . esc_attr($item->attr_title) .'"' : '';
        $attributes .= ! empty($item->target)     ? ' target="' . esc_attr($item->target     ) .'"' : '';
        $attributes .= ! empty($item->xfn)        ? ' rel="'    . esc_attr($item->xfn        ) .'"' : '';
        $attributes .= ! empty($item->url)        ? ' href="'   . esc_attr($item->url        ) .'"' : '';
        
        $item_output = isset($args->before) ? $args->before : '';
        $item_output .= '<a' . $attributes . '>';
        $item_output .= (isset($args->link_before) ? $args->link_before : '') . apply_filters('the_title', $item->title, $item->ID) . (isset($args->link_after) ? $args->link_after : '');
        

        
        $item_output .= '</a>';
        $item_output .= isset($args->after) ? $args->after : '';
        
        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
    
    // 结束输出菜单项
    function end_el(&$output, $item, $depth = 0, $args = null) {
        $output .= "</li>\n";
    }
}

// 添加菜单JavaScript支持
function enqueue_dropdown_menu_scripts() {
    wp_enqueue_script(
        'dropdown-menu',
        get_template_directory_uri() . '/assets/js/dropdown-menu.js',
        array('jquery'),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_dropdown_menu_scripts');

// 股票信息短代码函数
function nenghui_stock_info_shortcode($atts) {
    $attributes = shortcode_atts(array(
        'stock_code' => 'sz301046',
        'theme' => 'default',
        'show_chart' => false,
        'block_id' => 'stock-info-' . uniqid()
    ), $atts);

    // 开始输出缓冲
    ob_start();
    
    // 设置属性数组供模板使用
    $template_attributes = array(
        'stockCode' => $attributes['stock_code'],
        'theme' => $attributes['theme'],
        'showChart' => $attributes['show_chart'],
        'blockId' => $attributes['block_id']
    );
    
    // 包含股票信息区块模板
    $template_path = get_template_directory() . '/template-parts/block/block-stock-info.php';
    if (file_exists($template_path)) {
        // 将属性设置为全局变量供模板使用
        global $stock_info_attributes;
        $stock_info_attributes = $template_attributes;
        include $template_path;
    } else {
        echo '<div class="error">股票信息模板文件未找到</div>';
    }
    
    return ob_get_clean();
}

// 注册短代码
add_shortcode('nenghui_stock_info', 'nenghui_stock_info_shortcode');

// 投资者接待短代码函数
function nenghui_investor_reception_shortcode($atts) {
    $attributes = shortcode_atts(array(
        'title' => '投资者接待',
        'subtitle' => '投资者交流平台',
        'contact_person' => '董事会秘书 罗联明',
        'contact_phone' => '021-50896255',
        'contact_email' => 'nenghui@nhet.com.cn',
        'background_image' => 'http://nh.matepress.cn/wp-content/uploads/2025/09/touzizhe-banner.webp',
        'theme' => 'default',
        'block_id' => 'investor-reception-' . uniqid()
    ), $atts);

    // 开始输出缓冲
    ob_start();
    
    // 设置属性数组供模板使用
    $template_attributes = array(
        'title' => $attributes['title'],
        'subtitle' => $attributes['subtitle'],
        'contactPerson' => $attributes['contact_person'],
        'contactPhone' => $attributes['contact_phone'],
        'contactEmail' => $attributes['contact_email'],
        'backgroundImage' => $attributes['background_image'],
        'theme' => $attributes['theme'],
        'blockId' => $attributes['block_id']
    );
    
    // 包含投资者接待区块模板
    $template_path = get_template_directory() . '/template-parts/block/block-investor-reception.php';
    if (file_exists($template_path)) {
        // 将属性设置为全局变量供模板使用
        global $investor_reception_attributes;
        $investor_reception_attributes = $template_attributes;
        include $template_path;
    } else {
        echo '<div class="error">投资者接待模板文件未找到</div>';
    }
    
    return ob_get_clean();
}

// 注册投资者接待短代码
add_shortcode('nenghui_investor_reception', 'nenghui_investor_reception_shortcode');

// 高管简历短代码函数
function nenghui_executive_profiles_shortcode($atts) {
    $attributes = shortcode_atts(array(
        'title' => '高管团队',
        'theme' => 'default',
        'columns' => '1',
        'block_id' => 'executive-profiles-' . uniqid()
    ), $atts);

    // 开始输出缓冲
    ob_start();
    
    // 设置属性数组供模板使用
    $template_attributes = array(
        'title' => $attributes['title'],
        'theme' => $attributes['theme'],
        'columns' => intval($attributes['columns']),
        'blockId' => $attributes['block_id']
    );
    
    // 包含高管简历区块模板
    $template_path = get_template_directory() . '/template-parts/block/block-executive-profiles.php';
    if (file_exists($template_path)) {
        // 将属性设置为全局变量供模板使用
        global $executive_profiles_attributes;
        $executive_profiles_attributes = $template_attributes;
        include $template_path;
    } else {
        echo '<div class="error">高管简历模板文件未找到</div>';
    }
    
    return ob_get_clean();
}

// 注册高管简历短代码
add_shortcode('nenghui_executive_profiles', 'nenghui_executive_profiles_shortcode');

// HTML压缩功能集成
// 引入HTML压缩集成文件
require_once get_template_directory() . '/inc/html-compression-integration.php';

/**
 * 初始化HTML压缩功能
 * 在主题激活时设置默认选项
 */
function nenghui_init_html_compression() {
    // 设置默认的压缩选项
    $default_options = array(
        'nenghui_compression_enabled' => true,
        'nenghui_compression_remove_comments' => true,
        'nenghui_compression_remove_whitespace' => true,
        'nenghui_compression_compress_css' => true,
        'nenghui_compression_compress_js' => true,
        'nenghui_compression_preserve_line_breaks' => false,
        'nenghui_compression_excluded_pages' => 'wp-admin,wp-login,xmlrpc'
    );
    
    // 只在首次激活时设置默认值
    foreach ($default_options as $option_name => $default_value) {
        if (get_theme_mod($option_name) === false) {
            set_theme_mod($option_name, $default_value);
        }
    }
}

// 在主题激活时初始化压缩功能
add_action('after_switch_theme', 'nenghui_init_html_compression');

/**
 * 添加HTML压缩相关的管理员通知
 */
function nenghui_compression_admin_notices() {
    // 检查是否启用了压缩功能
    $compression_enabled = get_theme_mod('nenghui_compression_enabled', true);
    
    if (!$compression_enabled) {
        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p><strong>能汇能源主题：</strong>HTML压缩功能已禁用。您可以在 <a href="' . admin_url('customize.php?autofocus[section]=nenghui_compression_settings') . '">自定义器</a> 中启用它以提升网站性能。</p>';
        echo '</div>';
    }
}
add_action('admin_notices', 'nenghui_compression_admin_notices');

/**
 * 添加压缩功能到主题支持
 */
function nenghui_add_compression_theme_support() {
    // 添加主题支持HTML压缩
    add_theme_support('nenghui-html-compression', array(
        'remove_comments' => true,
        'remove_whitespace' => true,
        'compress_css' => true,
        'compress_js' => true,
        'preserve_content' => array('pre', 'textarea', 'script', 'style'),
        'excluded_pages' => array('wp-admin', 'wp-login', 'xmlrpc')
    ));
}
add_action('after_setup_theme', 'nenghui_add_compression_theme_support');

/**
 * 清理主题停用时的压缩相关数据
 */
function nenghui_cleanup_compression_data() {
    // 清理压缩统计数据
    delete_option('nenghui_compression_stats');
    
    // 清理自定义器设置（可选，根据需要决定是否保留用户设置）
    // remove_theme_mod('nenghui_compression_enabled');
    // remove_theme_mod('nenghui_compression_remove_comments');
    // remove_theme_mod('nenghui_compression_remove_whitespace');
    // remove_theme_mod('nenghui_compression_compress_css');
    // remove_theme_mod('nenghui_compression_compress_js');
    // remove_theme_mod('nenghui_compression_excluded_pages');
}
add_action('switch_theme', 'nenghui_cleanup_compression_data');

/**
 * 手机轮播图简码功能
 * 使用方法: [phone_carousel]
 */
function phone_carousel_shortcode($atts) {
    // 设置默认属性
    $atts = shortcode_atts(array(
        'width' => '220px',
        'height' => '800px',
        'mobile_width' => '300px',
        'mobile_height' => '600px'
    ), $atts, 'phone_carousel');
    
    // 开始输出缓冲
    ob_start();
    
    // 包含轮播图模板
    include get_template_directory() . '/template-parts/block/block-phone-carousel.php';
    
    // 获取缓冲内容并清理缓冲区
    $output = ob_get_clean();
    
    return $output;
}
add_shortcode('phone_carousel', 'phone_carousel_shortcode');

/**
 * 为手机轮播图简码添加自定义CSS样式
 */
function phone_carousel_shortcode_styles() {
    // 只在使用了简码的页面加载样式
    global $post;
    if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'phone_carousel')) {
        // 样式已经包含在模板文件中，这里可以添加额外的样式覆盖
        echo '<style>
            .phone-carousel-wrapper {
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 400px;
                padding: 20px;
            }
        </style>';
    }
}
add_action('wp_head', 'phone_carousel_shortcode_styles');

/**
 * 修复 Elementor Google Fonts 的 Mixed Content 错误
 * 强制所有外部资源使用 HTTPS
 */
function fix_elementor_google_fonts_mixed_content() {
    // 修复 Google Fonts 的 HTTP 链接
    add_filter('elementor/frontend/print_google_fonts', function($google_fonts_url) {
        if (is_ssl() && strpos($google_fonts_url, 'http://') === 0) {
            return str_replace('http://', 'https://', $google_fonts_url);
        }
        return $google_fonts_url;
    });
    
    // 修复所有样式表的 HTTP 链接
    add_filter('style_loader_src', function($src) {
        if (is_ssl() && strpos($src, 'http://') === 0) {
            return str_replace('http://', 'https://', $src);
        }
        return $src;
    });
    
    // 修复所有脚本的 HTTP 链接
    add_filter('script_loader_src', function($src) {
        if (is_ssl() && strpos($src, 'http://') === 0) {
            return str_replace('http://', 'https://', $src);
        }
        return $src;
    });
}
add_action('init', 'fix_elementor_google_fonts_mixed_content');

/**
 * 禁用 Elementor 的 Google Fonts（可选方案）
 * 如果上面的修复不起作用，可以取消注释下面的代码来完全禁用 Google Fonts
 */
/*
function disable_elementor_google_fonts() {
    // 禁用 Elementor 的 Google Fonts
    add_filter('elementor/frontend/print_google_fonts', '__return_false');
    
    // 移除 Google Fonts 样式表
    add_action('wp_enqueue_scripts', function() {
        wp_dequeue_style('google-fonts');
        wp_deregister_style('google-fonts');
    }, 20);
}
add_action('init', 'disable_elementor_google_fonts');
*/

?>
