<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class MetaTags
{
    private array $settings;

    /**
     * 构造函数
     *
     * @param array $settings 插件设置
     */
    public function __construct(array $settings)
    {
        $this->settings = $settings;
    }

    /**
     * 添加 SEO Meta 标签到 <head>
     */
    public function add_seo_meta_tags()
    {
        global $post; // 需要访问全局 $post 对象

        $meta_enabled = $this->settings['global_tabs']['seo-meta-enabled'] ?? false; // 默认关闭

        if (!$meta_enabled || !is_single() || !isset($post->ID)) {
            return;
        }

        $meta_keywords = get_post_meta($post->ID, '_ai_post_keywords', true);
        $meta_description = get_post_meta($post->ID, '_ai_post_description', true);

        // 新增多语言描述验证逻辑
        $min_length = 25; // 最小描述长度
        $is_valid_description = !empty($meta_description) && mb_strlen($meta_description) >= $min_length;

        echo "\n";
        if ($meta_keywords) {
            echo '<meta name="keywords" content="' . esc_attr($meta_keywords) . '">' . "\n";
        }
        if ($is_valid_description) {
            echo '<meta name="description" content="' . esc_attr($meta_description) . '">' . "\n";
        } else {
            // 自动生成备用描述
            $fallback_desc = mb_substr(wp_strip_all_tags($post->post_content), 0, 200);
            echo '<meta name="description" content="' . esc_attr($fallback_desc) . '">' . "\n";
        }
        // echo "<!-- AI Post SEO Meta End -->\n"; // 可以移除或保留结束标记
    }

    /**
     * 根据标签数组和限制数量生成逗号分隔的关键词字符串。
     *
     * @param mixed $tags 标签数组 (可以是对象、字符串或混合)。
     * @param int   $limit 要包含的关键词数量上限。
     * @return string 逗号分隔的关键词字符串，或空字符串。
     */
    public static function format_tags_as_keywords_string($tags, $limit = 5)
    {
        if (empty($tags)) {
            return '';
        }

        $keywords_array = [];
        $count = 0;

        if (is_string($tags)) {
            // 如果是字符串，直接按逗号分割
            $tags_array = array_map('trim', explode(',', $tags));
            foreach ($tags_array as $tag_name) {
                if ($count >= $limit) {
                    break;
                }
                if (!empty($tag_name)) {
                    $keywords_array[] = $tag_name;
                    $count++;
                }
            }
        } elseif (is_array($tags)) {
            // 如果是数组，遍历并获取标签名
            foreach ($tags as $tag) {
                if ($count >= $limit) {
                    break;
                }
                $tag_name = '';
                if (is_object($tag) && isset($tag->name)) {
                    $tag_name = $tag->name;
                } elseif (is_string($tag)) {
                    $tag_name = $tag;
                }

                if (!empty($tag_name)) {
                    $keywords_array[] = $tag_name;
                    $count++;
                }
            }
        }

        return implode(',', $keywords_array);
    }

    /**
     * 输出存储在 post meta 中的 Schema.org JSON-LD 数据。
     *
     * @return void
     */
    public static function output_stored_schema_json_ld()
    {
        // Only output on single post pages
        if (!is_single()) {
            return;
        }

        $post_id = get_the_ID();
        if (!$post_id) {
            return;
        }

        $schema_json = get_post_meta($post_id, '_ai_post_schema_json_ld', true);

        if (!empty($schema_json)) {
            $fix_mojibake = function($s){
                $s = is_string($s) ? $s : '';
                if ($s === '' || preg_match('/[\x{4E00}-\x{9FFF}]/u', $s)) { return $s; }
                $candidates = [];
                if (function_exists('iconv')) {
                    $candidates[] = @iconv('UTF-8', 'Windows-1252//IGNORE', $s);
                    $candidates[] = @iconv('UTF-8', 'ISO-8859-1//IGNORE', $s);
                } elseif (function_exists('mb_convert_encoding')) {
                    $candidates[] = @mb_convert_encoding($s, 'Windows-1252', 'UTF-8');
                    $candidates[] = @mb_convert_encoding($s, 'ISO-8859-1', 'UTF-8');
                }
                foreach ($candidates as $b) {
                    if (is_string($b) && $b !== '' && preg_match('/[\x{4E00}-\x{9FFF}]/u', $b)) {
                        return $b;
                    }
                }
                return $s;
            };

            $decoded = json_decode((string) $schema_json, true);
            if (is_array($decoded)) {
                $changed = false;
                $walk = function($v) use (&$walk, $fix_mojibake, &$changed) {
                    if (is_string($v)) {
                        $fixed = $fix_mojibake($v);
                        if ($fixed !== $v) { $changed = true; }
                        return $fixed;
                    }
                    if (is_array($v)) {
                        $out = [];
                        foreach ($v as $k => $vv) {
                            $out[$k] = $walk($vv);
                        }
                        return $out;
                    }
                    return $v;
                };
                $fixed_decoded = $walk($decoded);
                if ($changed) {
                    $schema_json = wp_json_encode($fixed_decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
                    if ($schema_json) {
                        update_post_meta($post_id, '_ai_post_schema_json_ld', $schema_json);
                    } else {
                        $schema_json = get_post_meta($post_id, '_ai_post_schema_json_ld', true);
                    }
                }
            }

            echo '<script type="application/ld+json">' . $schema_json . '</script>' . "\n";
        }
    }
} 