<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

function haup_add_page_schema() {
	if (is_page() && !is_front_page()) {
		global $post;

		//投稿IDの取得
		$post_id = get_the_ID();

		// 投稿情報
			//タイトル
			$page_title = haup_common_title_callback();
			//抜粋
			$page_description = haup_common_description_callback();

		// 投稿者情報
			// 作者IDの取得
			$author_id = get_post_field('post_author', $post_id);

			// SNSプロフィールURLをまとめる関数
			$author_social_profiles = [];
			$twitter_username = get_the_author_meta('ha-user-x-url', $author_id);
			if (!empty($twitter_username)) {
				$author_social_profiles[] = 'https://twitter.com/' . $twitter_username;
			}
			$fb_url = get_the_author_meta('ha-user-facebook-url', $author_id);
			if (!empty($fb_url)) {
				$author_social_profiles[] = 'https://www.facebook.com/'.$fb_url;
			}
			$insta_url = get_the_author_meta('ha-user-insta-url', $author_id);
			if (!empty($insta_url)) {
				$author_social_profiles[] = 'https://www.instagram.com/'.$insta_url;
			}

			// 作者画像
			// 変数を初期化
			$author_image_url = '';
			$author_image_width = '';
			$author_image_height = '';

			// カスタムプロフィール画像のURLを取得
			$custom_profile_image_url = get_the_author_meta('haup_custom_profile_image', $author_id);

			if (!empty($custom_profile_image_url)) {
				// カスタム画像が設定されている場合
				$author_image_url = esc_url($custom_profile_image_url);
    
				// 画像サイズを取得（パフォーマンスのため、URLから直接取得）
				$image_size = getimagesize($custom_profile_image_url);
				if ($image_size) {
					$author_image_width = absint($image_size[0]);
					$author_image_height = absint($image_size[1]);
				}
			} else {
				// カスタム画像が設定されていない場合、Gravatar情報を取得
				$author_email = get_the_author_meta('user_email', $author_id);
				if (!empty($author_email)) {
					// GravatarのURLとサイズを設定（デフォルトで96x96ピクセル）
					$avatar_size = 96;
					$author_image_url = get_avatar_url($author_email, ['size' => $avatar_size]);
					$author_image_width = $author_image_height = absint($avatar_size);
				}
			}

			// 作者のその他の情報
			$author_name = get_the_author_meta('display_name', $author_id);
			$author_url = get_author_posts_url($author_id);
			$author_work = get_the_author_meta('ha-user-work', $author_id);

		// サイト情報
			//サイトタイトル
			$site_title = get_bloginfo('name');
			//サイトのURL
			$site_url = home_url();
			//サイトの説明文
			$site_description = get_bloginfo('description');

			// パブリッシャーロゴ情報情報
			$pub_image_data = haup_schema_pub_image_data_callback();
 
		// 出力する内容
		$schema = [
			"@context" => "https://schema.org",

			"name" => esc_html($page_title),
			"url" => get_permalink($post_id),
			"description" => esc_html($page_description),
			"publisher" => [
				"@type" => "Organization",
				"name" => esc_html(haup_top_archive_schema_output_site_owner()),
				"url" => esc_url(haup_top_archive_schema_output_site_owner_url()),
				"logo" => [
					"@type" => "ImageObject",
					"url" => esc_url($pub_image_data['url']),
					"width" => absint($pub_image_data['width']),
					"height" => absint($pub_image_data['height'])
				]
			],
			"wordCount" => absint(str_word_count(wp_strip_all_tags(get_the_content($post_id))))
		];

		//@typeを追加
			//カスタムフィールドからスキーマタイプを取得
			$schema_type = get_post_meta(get_the_ID(), 'haup-page-schema-type', true);

			if(empty( $schema_type ) || $schema_type == 'WebPage' ){
				$schema['@type'] = 'WebPage';
			}else{
				$schema['@type'] = $schema_type;
				// mainEntityOfPageの追加
				$schema['mainEntityOfPage'] = [
					"@type" => $schema_type,
					"@id" => get_permalink($post_id)
				];
			}

		//作者情報を追加
		if(!empty( $author_image_url )){
			$schema['author'] = [
				"@type" => "Person",
				"name" => esc_html($author_name),
				"url" => esc_url($author_url),
				"jobTitle" => esc_html($author_work),
				"worksFor" => [
					"@type" => "Organization",
					"name" => esc_html(haup_top_archive_schema_output_site_owner() )
				],
				"image" =>  [
					"@type" => "ImageObject",
					"url" => $author_image_url,
					"width" => $author_image_width,
					"height" => $author_image_height
				],
				"sameAs" => $author_social_profiles
			];
		}else{
			$schema['author'] = [
				"@type" => "Person",
				"name" => esc_html($author_name),
				"url" => esc_url($author_url),
				"jobTitle" => esc_html($author_work),
				"worksFor" => [
					"@type" => "Organization",
					"name" => esc_html(haup_top_archive_schema_output_site_owner() )
				],
				"sameAs" => $author_social_profiles
			];
		}

		// アイキャッチ画像があれば追加
		if (has_post_thumbnail($post_id)) {
			$image_url = get_the_post_thumbnail_url($post_id, 'full');
			// URLが空でないことを確認
			if (!empty($image_url)) {
				$image_size = getimagesize($image_url);
				if ($image_size) {
					$schema['image'] = [
						"@type" => "ImageObject",
 						"url" => esc_url($image_url),
						"width" => absint($image_size[0]),
						"height" => absint($image_size[1])
					];
				}
			}
		}

		echo '<!-- HAUP Schema Data for page -->';
		echo "\n";//HTML上で改行
		//echo '<script type="application/ld+json">' . json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';
		echo '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';
	}
}
add_action('wp_head', 'haup_add_page_schema' , 3);