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

class ProbonoSEO_Article_Schema {
	private static $instance = null;

	public static function get_instance() {
		if (self::$instance === null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		$this->init_hooks();
	}

	private function init_hooks() {
		if (get_option('probonoseo_aio_article_schema', '1') === '1') {
			add_action('wp_head', array($this, 'output_article_schema'), 8);
		}
	}

	public function output_article_schema() {
		if (!is_single()) {
			return;
		}

		global $post;

		$author_id   = $post->post_author;
		$author_name = get_the_author_meta('display_name', $author_id);
		$image_url   = has_post_thumbnail($post->ID) ? get_the_post_thumbnail_url($post->ID, 'large') : '';

		$schema = array(
			'@context'      => 'https://schema.org',
			'@type'         => 'Article',
			'headline'      => get_the_title($post),
			'datePublished' => get_the_date('c', $post),
			'dateModified'  => get_the_modified_date('c', $post),
			'author'        => array(
				'@type' => 'Person',
				'name'  => $author_name,
			),
			'publisher'     => array(
				'@type' => 'Organization',
				'name'  => get_bloginfo('name'),
				'url'   => home_url('/'),
			),
			'inLanguage'    => 'ja',
			'isPartOf'      => array(
				'@id' => home_url('/#website'),
			),
		);

		$excerpt = get_the_excerpt($post);
		if (!empty($excerpt)) {
			$schema['description'] = $excerpt;
		}

		if (!empty($image_url)) {
			$schema['image'] = array(
				'@type' => 'ImageObject',
				'url'   => $image_url,
			);
		}

		echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
	}
}

function probonoseo_init_article_schema() {
	ProbonoSEO_Article_Schema::get_instance();
}
add_action('init', 'probonoseo_init_article_schema');