<?php
/**
 * Compatibility fixes for structured data emitted by third-party SEO plugins.
 *
 * @package Yatoon_Booking_System
 */

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

final class YATOON_SEO_Compatibility {
	/** Register compatibility filters. */
	public static function init() {
		add_filter( 'rank_math/json_ld', array( __CLASS__, 'repair_breadcrumb_names' ), 99, 2 );
	}

	/**
	 * Ensure every BreadcrumbList ListItem has the name required by Google.
	 *
	 * Rank Math can emit the home item as only {"item":{"@id":"..."}} on
	 * Brizy pages. Google then rejects the whole BreadcrumbList. This preserves
	 * Rank Math's graph and supplies a deterministic label only when absent.
	 *
	 * @param mixed $data Rank Math JSON-LD graph.
	 * @return mixed
	 */
	public static function repair_breadcrumb_names( $data ) {
		return is_array( $data ) ? self::walk_schema( $data ) : $data;
	}

	/** Recursively inspect a JSON-LD graph for BreadcrumbList nodes. */
	private static function walk_schema( array $node ) {
		$type = isset( $node['@type'] ) ? $node['@type'] : '';
		$is_breadcrumb = 'BreadcrumbList' === $type || ( is_array( $type ) && in_array( 'BreadcrumbList', $type, true ) );
		if ( $is_breadcrumb && ! empty( $node['itemListElement'] ) && is_array( $node['itemListElement'] ) ) {
			foreach ( $node['itemListElement'] as $index => $list_item ) {
				if ( ! is_array( $list_item ) || ! empty( $list_item['name'] ) || ( is_array( $list_item['item'] ?? null ) && ! empty( $list_item['item']['name'] ) ) ) {
					continue;
				}
				$node['itemListElement'][ $index ]['name'] = self::breadcrumb_label( $list_item );
			}
		}

		foreach ( $node as $key => $value ) {
			if ( is_array( $value ) && 'itemListElement' !== $key ) {
				$node[ $key ] = self::walk_schema( $value );
			}
		}
		return $node;
	}

	/** Build a stable human-readable label from the breadcrumb URL. */
	private static function breadcrumb_label( array $list_item ) {
		$item = $list_item['item'] ?? '';
		$url  = is_array( $item ) ? (string) ( $item['@id'] ?? $item['url'] ?? '' ) : (string) $item;
		$home = untrailingslashit( home_url( '/' ) );
		if ( $url && untrailingslashit( $url ) === $home ) {
			return sanitize_text_field( get_bloginfo( 'name' ) ?: __( 'Home', 'yatoon-booking-system' ) );
		}
		$path  = trim( (string) wp_parse_url( $url, PHP_URL_PATH ), '/' );
		$slug  = $path ? basename( $path ) : '';
		$label = $slug ? ucwords( str_replace( array( '-', '_' ), ' ', rawurldecode( $slug ) ) ) : __( 'Home', 'yatoon-booking-system' );
		return sanitize_text_field( $label );
	}
}

YATOON_SEO_Compatibility::init();
