<?php
/**
 * JSON-LD output.
 *
 * @package MicropediaAISearchOptimizer
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** Schema manager. */
class Micropedia_AI_Schema {
	/** Init hooks. */
	public static function init() {
		add_action( 'wp_head', array( __CLASS__, 'output_schema' ), 30 );
	}

	/** Output basic JSON-LD only when no SEO plugin schema provider is detected. */
	public static function output_schema() {
		if ( ! micropedia_ai_get_option( 'enable_schema', 1 ) || Micropedia_AI_Compatibility::has_seo_schema_provider() ) {
			return;
		}

		$cache_key = 'micropedia_ai_schema_' . md5( ( is_singular() ? (string) get_queried_object_id() : 'global' ) . '_' . wp_json_encode( get_option( 'micropedia_ai_options', array() ) ) );
		$cached = get_transient( $cache_key );
		if ( is_string( $cached ) ) {
			echo $cached; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Cached JSON-LD script generated by this plugin.
			return;
		}

		$options = wp_parse_args( get_option( 'micropedia_ai_options', array() ), micropedia_ai_default_options() );
		$type    = isset( $options['schema_base_type'] ) ? $options['schema_base_type'] : 'Organization';
		if ( ! in_array( $type, array( 'Article', 'Organization', 'Person' ), true ) ) {
			$type = 'Organization';
		}

		$same_as = array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', (string) $options['schema_base_same_as'] ) ) );
		$entity  = array(
			'@type' => $type,
			'@id'   => ! empty( $options['schema_base_id'] ) ? $options['schema_base_id'] : home_url( '/#organization' ),
			'name'  => ! empty( $options['schema_base_name'] ) ? $options['schema_base_name'] : get_bloginfo( 'name' ),
			'url'   => ! empty( $options['schema_base_url'] ) ? $options['schema_base_url'] : home_url( '/' ),
		);

		if ( ! empty( $options['schema_base_description'] ) ) {
			$entity['description'] = $options['schema_base_description'];
		}

		if ( ! empty( $options['schema_base_image'] ) ) {
			$entity['image'] = $options['schema_base_image'];
			if ( 'Organization' === $type ) {
				$entity['logo'] = $options['schema_base_image'];
			}
		}

		if ( ! empty( $same_as ) ) {
			$entity['sameAs'] = array_values( $same_as );
		}

		$graph = array( $entity );

		if ( is_singular() ) {
			$post = get_post();
			if ( $post ) {
				$graph[] = array(
					'@type'         => is_singular( 'post' ) ? 'Article' : 'WebPage',
					'@id'           => get_permalink( $post ) . '#content',
					'headline'      => get_the_title( $post ),
					'url'           => get_permalink( $post ),
					'datePublished' => get_the_date( 'c', $post ),
					'dateModified'  => get_the_modified_date( 'c', $post ),
					'author'        => array(
						'@type' => 'Person',
						'name'  => get_the_author_meta( 'display_name', (int) $post->post_author ),
					),
					'publisher'     => array( '@id' => $entity['@id'] ),
				);
			}
		}

		$script = "\n<script type=\"application/ld+json\" class=\"micropedia-ai-jsonld\">" . wp_json_encode( array( '@context' => 'https://schema.org', '@graph' => $graph ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . "</script>\n";
		set_transient( $cache_key, $script, absint( micropedia_ai_get_option( 'cache_ttl', HOUR_IN_SECONDS ) ) );
		echo $script; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON-LD script generated by this plugin.
	}
}
