<?php
//头部加载代码

add_action('wp_head', 'pix_custom_head');
function pix_custom_head()
{
    pix_custom_style();
    output_pixbtn_style();
    
}

add_action('init', 'pix_use_custom_favicon', 20);
function pix_use_custom_favicon()
{
    if (!pix_get_custom_favicon()) {
        return;
    }

    remove_action('wp_head', 'wp_site_icon', 99);
    remove_action('admin_head', 'wp_site_icon', 99);
    remove_action('login_head', 'wp_site_icon', 99);

    add_action('wp_head', 'pix_custom_favicon', 99);
    add_action('admin_head', 'pix_custom_favicon', 99);
    add_action('login_head', 'pix_custom_favicon', 99);
}

function pix_get_custom_favicon()
{
    $favicon = get_cu('favicon');
    if (is_array($favicon)) {
        $favicon = $favicon['url'] ?? '';
    }

    return $favicon ? $favicon : '';
}

function pix_custom_favicon()
{
    $favicon = pix_get_custom_favicon();
    if (empty($favicon)) {
        return;
    }

    echo '<link rel="icon" href="' . esc_url($favicon) . '" sizes="32x32">' . "\n";
    echo '<link rel="icon" href="' . esc_url($favicon) . '" sizes="192x192">' . "\n";
    echo '<link rel="apple-touch-icon" href="' . esc_url($favicon) . '">' . "\n";
    echo '<meta name="msapplication-TileImage" content="' . esc_url($favicon) . '">' . "\n";
}

//自定义样式
function pix_custom_style(){
    $style = '';
    $hb_top = get_cu('hb_top_tab');
    $hb_center = get_cu('hb_center_tab');
    $hb_bottom = get_cu('hb_bottom_tab');

    //导航构建器
    if(is_array($hb_top)){
        if($hb_top['shadow'] == true){
            $style .= '.top-nav-row.main-nav-item{box-shadow: 0px 11px 18px rgb(204 208 255 / 14%);}';
        }
        if(!empty($hb_top['img'])){
            $style .= '.top-nav-row.main-nav-item{background-image:url('.$hb_top['img'].');}';
        }
    }

    if(is_array($hb_center)){
        if($hb_center['shadow'] == true){
            $style .= '.center-nav-row.main-nav-item{box-shadow: 0px 11px 18px rgb(204 208 255 / 14%);}';
        }
        if(!empty($hb_center['img'])){
            $style .= '.center-nav-row.main-nav-item{background-image:url('.$hb_center['img'].');}';
        }
    }

    if(is_array($hb_bottom)){
        if($hb_bottom['shadow'] == true){
            $style .= '.bottom-nav-row.main-nav-item{box-shadow: 0px 11px 18px rgb(204 208 255 / 14%);}';
        }
        if(!empty($hb_bottom['img'])){
            $style .= '.bottom-nav-row.main-nav-item{background-image:url('.$hb_bottom['img'].');}';
        }
    }


    //动态计算总体宽度（经典模式）
    if (pix_layout_mode() === 'classic') {
        // 用户中心、管理中心使用独立宽度
        if (is_author() || pix_is_dashboard()) {
            $width = pix_get_content_width();
            if ($width > 0) {
                $style .= '.pix-content{max-width:'.$width.'px;}';
                $style .= '.classic-header{max-width:'.$width.'px;}';
            }
        } elseif (pix_is_fullwidth()) {
            // 全宽页面 = 全局侧栏 + 内容区 总宽度
            $total = pix_global_total_width();
            if ($total > 0) {
                $style .= '.pix-content{max-width:'.$total.'px;}';
                $style .= '.classic-header{max-width:'.$total.'px;}';
            }
        } else {
            // 其他页面计算总体宽度
            $total = pix_total_width();
            if ($total > 0) {
                $style .= '.pix-content{max-width:'.$total.'px;}';
                $style .= '.classic-header{max-width:'.$total.'px;}';
            }
        }
    }

    if ($style) {
        $style = compress_css($style);
        echo '<style type="text/css">' . $style . '</style>';
    }

}

 
/** 
* 压缩html : 清除换行符,清除制表符,去掉注释标记 
* @param $string 
* @return压缩后的$string 
* */ 
function compress_html($string){ 
    $string=str_replace("\r\n",'',$string);//清除换行符 
    $string=str_replace("\n",'',$string);//清除换行符 
    $string=str_replace("\t",'',$string);//清除制表符 
    $pattern=array( 
    "/> *([^ ]*) *</",//去掉注释标记 
    "/[\s]+/", 
    "/<!--[^!]*-->/", 
    "/\" /", 
    "/ \"/", 
    "'/\*[^*]*\*/'" 
    ); 
    $replace=array ( 
    ">\\1<", 
    " ", 
    "", 
    "\"", 
    "\"", 
    "" 
    ); 
    return preg_replace($pattern, $replace, $string); 
    } 

function compress_css($css){
    $css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css); // negative look ahead
    $css = preg_replace('/\s{2,}/', ' ', $css);
    $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
    $css = preg_replace('/;}/', '}', $css);
    return $css;
}

// ==================== SEO：普通页面标题（文章/分类/首页等） ====================
function pix_seo_title_parts($title_parts) {
    $site_name = $title_parts['site'] ?? get_bloginfo('name');

    if (is_front_page() || is_home()) {
        $home_title = get_op('seo_home_title');
        if ($home_title) {
            $title_parts['title'] = $home_title;
            unset($title_parts['tagline']);
            unset($title_parts['site']);
        }
        return $title_parts;
    }

    if (is_singular('moment')) {
        $post = get_queried_object();
        $title_parts['title'] = $post->post_title;
        $title_parts['site'] = $site_name;
        return $title_parts;
    }

    if (is_tax('moments')) {
        $term = get_queried_object();
        $title_parts['title'] = $term->name;
        $title_parts['site'] = $site_name;
        return $title_parts;
    }

    if (is_author()) {
        $author = get_queried_object();
        $title_parts['title'] = $author->display_name;
        $title_parts['site'] = $site_name;
        return $title_parts;
    }

    if (is_search()) {
        $title_parts['title'] = '搜索：' . get_search_query();
        $title_parts['site'] = $site_name;
        return $title_parts;
    }

    if (is_404()) {
        $title_parts['title'] = '页面未找到';
        $title_parts['site'] = $site_name;
        return $title_parts;
    }

    return $title_parts;
}
add_filter('document_title_parts', 'pix_seo_title_parts');

// ==================== SEO：Dashboard 页面标题（覆盖WP默认输出） ====================
add_action('wp_head', function () {
    $type = get_query_var('ppo_admin_page');
    if (empty($type)) {
        return;
    }

    $site_name = get_bloginfo('name');
    $dashboard_titles = array(
        'center' => '概览',
        'trend'  => '动态',
        'vip'    => '会员',
        'wallet' => '钱包',
        'task'   => '任务',
        'order'  => '订单',
        'edit'   => '设置',
    );
    $page_title = isset($dashboard_titles[$type]) ? $dashboard_titles[$type] : '管理中心';

    $dashboard_descriptions = array(
        'center' => '个人中心概览',
        'trend'  => '我的动态',
        'vip'    => '会员中心',
        'wallet' => '我的钱包',
        'task'   => '每日任务',
        'order'  => '我的订单',
        'edit'   => '个人设置',
    );
    $desc_text = isset($dashboard_descriptions[$type]) ? $dashboard_descriptions[$type] : '管理中心';

    remove_action('wp_head', '_wp_render_title_tag', 1);
    echo '<title>' . esc_html($page_title . ' - ' . $site_name) . '</title>' . "\n";
    echo '<meta name="description" content="' . esc_attr($site_name . ' - ' . $desc_text) . '">' . "\n";
}, 0);

// ==================== SEO：消息页面标题 ====================
add_action('wp_head', function () {
    $page_type = get_query_var('ppo_page_type');

    if ($page_type === 'msg') {
        $site_name = get_bloginfo('name');
        $msg_type = get_query_var('msg_action') ?: 'whisper';

        $msg_titles = array(
            'whisper' => '私信',
            'like'    => '点赞通知',
            'reply'   => '评论回复',
            'system'  => '系统通知',
        );
        $page_title = isset($msg_titles[$msg_type]) ? $msg_titles[$msg_type] : '消息中心';

        $msg_descriptions = array(
            'whisper' => '查看私信消息',
            'like'    => '查看点赞通知',
            'reply'   => '查看评论回复',
            'system'  => '查看系统通知',
        );
        $desc_text = isset($msg_descriptions[$msg_type]) ? $msg_descriptions[$msg_type] : '消息中心';

        remove_action('wp_head', '_wp_render_title_tag', 1);
        echo '<title>' . esc_html($page_title . ' - ' . $site_name) . '</title>' . "\n";
        echo '<meta name="description" content="' . esc_attr($site_name . ' - ' . $desc_text) . '">' . "\n";
    }

    if ($page_type === 'vip') {
        $site_name = get_bloginfo('name');
        $vip_title = '会员订阅';

        remove_action('wp_head', '_wp_render_title_tag', 1);
        echo '<title>' . esc_html($vip_title . ' - ' . $site_name) . '</title>' . "\n";
        echo '<meta name="description" content="' . esc_attr($site_name . ' - 会员订阅页面') . '">' . "\n";
    }
}, 0);

// ==================== SEO：meta description / keywords（普通页面） ====================
function pix_seo_meta() {
    if (!get_op('seo_meta_description', true)) {
        return;
    }

    $description = '';
    $keywords = '';

    if (is_front_page() || is_home()) {
        $description = get_op('seo_home_description') ?: get_bloginfo('description');
        $keywords = get_op('seo_home_keywords');
    } elseif (is_singular()) {
        $post = get_queried_object();
        if (has_excerpt($post)) {
            $description = get_the_excerpt($post);
        } else {
            $description = wp_trim_words(strip_shortcodes($post->post_content), 80, '');
        }
        $tags = wp_get_post_tags($post->ID);
        if ($tags) {
            $keywords = implode(', ', wp_list_pluck($tags, 'name'));
        }
    } elseif (is_category() || is_tag()) {
        $term = get_queried_object();
        $description = term_description($term);
        $keywords = $term->name;
    } elseif (is_tax('moments')) {
        $term = get_queried_object();
        $description = term_description($term);
    } elseif (is_author()) {
        $author = get_queried_object();
        $description = get_user_meta($author->ID, 'description', true);
    }

    if ($description) {
        $description = trim(preg_replace('/\s+/', ' ', strip_tags($description)));
        echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
    }

    if ($keywords) {
        echo '<meta name="keywords" content="' . esc_attr($keywords) . '">' . "\n";
    }
}
add_action('wp_head', 'pix_seo_meta', 2);
    
