<?php
if (!defined('ABSPATH')) exit;

function output_schema_data() {
    $site_url = get_home_url();
    $site_name = get_bloginfo('name');
    $site_description = get_bloginfo('description');
    $current_title = get_the_title();
    $current_description = has_excerpt() ? get_the_excerpt() : '';
	
	if (is_archive() || is_category() || is_tag() || is_tax()) {
        $current_url = get_archive_url(); // アーカイブ用URL
        $current_title = wp_strip_all_tags(remove_prefix_from_archive_title(get_the_archive_title())); // アーカイブタイトルからプレフィックスとHTMLタグを削除
        $current_description = wp_strip_all_tags(get_the_archive_description()); // アーカイブ説明からHTMLタグを削除
    } else {
        $current_url = get_permalink(); // その他のページ用URL
        $current_title = get_the_title();
        $current_description = has_excerpt() ? get_the_excerpt() : '';
    }
    
    $schema_data = [
        "@context" => "https://schema.org",
        "@graph" => [
            [
                "@type" => "Organization",
                "@id" => $site_url . "#organization",
                "name" => $site_name,
                "url" => $site_url
            ]
        ]
    ];

    // トップページの場合のみ WebSite スキーマを追加
    if (is_front_page()) {
        $schema_data["@graph"][] = [
            "@type" => "WebSite",
            "@id" => $site_url . "#website",
            "url" => $site_url,
            "name" => $site_name . " - " . $site_description
        ];
    }

    // パンくずリスト
    $position = 2;  // ホームページの後から開始
    $breadcrumbs = [
        "@type" => "BreadcrumbList",
		"@id" => $site_url . "#breadcrumb",
        "itemListElement" => [
            [
                "@type" => "ListItem",
                "position" => 1,
                "item" => [
                    "name" => "Home",
                    "@id" => $site_url
                ]
            ]
        ]
    ];

    if (is_single() || is_page() || is_archive()) {
        // カテゴリー
        if (is_single()) {
            $categories = get_the_category();
            if (!empty($categories)) {
                $category = $categories[0];  // IDが一番若いカテゴリーを取得
                $ancestors = get_ancestors($category->term_id, 'category');
                foreach (array_reverse($ancestors) as $ancestor) {
                    $ancestor_category = get_term_by('id', $ancestor, 'category');
                    $breadcrumbs["itemListElement"][] = [
                        "@type" => "ListItem",
                        "position" => $position++,
                        "item" => [
                            "name" => $ancestor_category->name,
                            "@id" => get_category_link($ancestor_category->term_id)
                        ]
                    ];
                }
                // 現在のカテゴリー
                $breadcrumbs["itemListElement"][] = [
                    "@type" => "ListItem",
                    "position" => $position++,
                    "item" => [
                        "name" => $category->name,
                        "@id" => get_category_link($category->term_id)
                    ]
                ];
            }

            // ブログ記事としての情報
            $published = get_the_time('c');
            $modified = get_the_modified_time('c');
            
            $schema_data["@graph"][] = [
                "@type" => "BlogPosting",
                "headline" => $current_title,
                "datePublished" => $published,
                "dateModified" => $modified,
                "mainEntityOfPage" => [
                    "@type" => "WebPage",
                    "@id" => $current_url
                ],
                "author" => [
                    "@type" => "Person",
                    "name" => get_the_author()
                ]
            ];
        }

        // 現在のページ
        $breadcrumbs["itemListElement"][] = [
            "@type" => "ListItem",
            "position" => $position,
            "item" => [
                "name" => $current_title,
                "@id" => $current_url
            ]
        ];
    }

    $schema_data["@graph"][] = $breadcrumbs;

    echo '<script type="application/ld+json">' . json_encode($schema_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '</script>';
}

add_action('wp_footer', 'output_schema_data');

//アーカイブページのURLを取得する関数
function get_archive_url() {
    if (is_category() || is_tag() || is_tax()) {
        $term = get_queried_object();
        return get_term_link($term);
    } elseif (is_post_type_archive()) {
        return get_post_type_archive_link(get_post_type());
    } elseif (is_author()) {
        return get_author_posts_url(get_queried_object_id());
    } elseif (is_date()) {
        return get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'));
    }

    return home_url('/');
}
?>