<?php
/**
 * TOC Schema.org markup functions.
 *
 * @package AnchorKit_TOC
 */

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

if (!function_exists('anchorkit_generate_schema_markup')) {
	/**
	 * Generate Schema.org JSON-LD data array for TOC.
	 *
	 * @param array $headings Array of headings.
	 * @return array|null Schema data array or null if disabled.
	 */
	function anchorkit_generate_schema_markup($headings)
	{
		if (empty($headings) || !is_array($headings)) {
			return null;
		}

		// Schema markup is a pro feature - this block is stripped by Freemius.
		// Free version returns null by default
		$can_use_schema = false;

		// Premium feature overrides - this entire block is stripped from free version
		if (anchorkit_fs() && anchorkit_fs()->is__premium_only()) {
			if (anchorkit_fs()->can_use_premium_code() && anchorkit_get_option('anchorkit_toc_schema_enabled', false)) {
				$can_use_schema = true;
			}
		}

		if (!$can_use_schema) {
			return null;
		}

		global $post;
		if (!$post) {
			return null;
		}

		$schema_type = anchorkit_get_option('anchorkit_toc_schema_type', 'Article');
		$per_post_type_schema = anchorkit_get_option('anchorkit_toc_schema_type_per_post_type', array());

		if (!is_array($per_post_type_schema)) {
			$per_post_type_schema = array();
		}

		if (isset($per_post_type_schema[$post->post_type]) && !empty($per_post_type_schema[$post->post_type])) {
			$schema_type = $per_post_type_schema[$post->post_type];
		}

		// Build sanitized TOC items for JSON-LD.
		$toc_items = array();
		$post_url = get_permalink($post->ID);

		if (empty($post_url)) {
			return null;
		}

		$pos = 0;
		foreach ($headings as $heading) {
			if (empty($heading['text']) || empty($heading['anchor'])) {
				continue;
			}

			++$pos;

			// Build URL with sanitized anchor.
			$item_url = $post_url . '#' . sanitize_title($heading['anchor']);

			$toc_items[] = array(
				'@type' => 'ListItem',
				'position' => $pos,
				'name' => wp_strip_all_tags($heading['text']),
				'url' => esc_url_raw($item_url),
			);
		}

		// Validate we have items.
		if (empty($toc_items)) {
			return null;
		}

		// Build the schema with sanitized values.
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => sanitize_text_field($schema_type),
			'headline' => wp_strip_all_tags(get_the_title($post->ID)),
			'url' => esc_url_raw($post_url),
			'datePublished' => get_the_date('c', $post->ID),
			'dateModified' => get_the_modified_date('c', $post->ID),
			'author' => array(
				'@type' => 'Person',
				'name' => sanitize_text_field(get_the_author_meta('display_name', $post->post_author)),
			),
			'publisher' => array(
				'@type' => 'Organization',
				'name' => sanitize_text_field(get_bloginfo('name')),
				'url' => esc_url_raw(home_url()),
			),
			'mainEntity' => array(
				'@type' => 'ItemList',
				'name' => 'Table of Contents',
				'itemListElement' => $toc_items,
			),
		);

		// Add featured image if available.
		if (has_post_thumbnail($post->ID)) {
			$schema['image'] = esc_url_raw(get_the_post_thumbnail_url($post->ID, 'full'));
		}

		return $schema;
	}
}

if (!function_exists('anchorkit_output_schema_markup')) {
	/**
	 * Output Schema.org JSON-LD markup in wp_head.
	 *
	 * @return void
	 */
	function anchorkit_output_schema_markup()
	{
		// Only run on frontend.
		if (is_admin()) {
			return;
		}

		if (!anchorkit_get_option('anchorkit_toc_enabled', false)) {
			return;
		}

		if (!is_singular()) {
			return;
		}

		$post_types = anchorkit_get_option('anchorkit_toc_post_types', array('post', 'page'));
		if (!in_array(get_post_type(), $post_types, true)) {
			return;
		}

		global $post;
		if (!$post) {
			return;
		}

		// Parse headings.
		$content_copy = $post->post_content;
		$parsed = anchorkit_toc_parse_headings(
			$content_copy,
			anchorkit_get_global_heading_levels(),
			anchorkit_get_option('anchorkit_toc_exclude_selectors', '')
		);

		if (count($parsed['headings']) < (int) anchorkit_get_option('anchorkit_toc_min_headings', 2)) {
			return;
		}

		// Generate schema data array.
		$schema = anchorkit_generate_schema_markup($parsed['headings']);

		if (empty($schema) || !is_array($schema)) {
			return;
		}

		// Encode to JSON.
		$json = wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

		if (!$json) {
			return;
		}

		// Output JSON-LD in wp_head hook.
		wp_print_inline_script_tag($json, array('type' => 'application/ld+json'));
	}
}

if (function_exists('add_action') && !has_action('wp_head', 'anchorkit_output_schema_markup')) {
	add_action('wp_head', 'anchorkit_output_schema_markup', 20);
}
