<?php
namespace WPLens\Schema\Generators;

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

final class BreadcrumbGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'breadcrumb'; }
	public function get_label(): string { return __( 'BreadcrumbList', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		return $post instanceof \WP_Post;
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		if ( ! $post ) { return null; }

		$items = array();
		$pos   = 1;

		// Home
		$items[] = $this->item( $pos++, __( 'Home', 'lens-ai-visibility-monitor' ), home_url( '/' ) );

		if ( 'post' === $post->post_type ) {
			// Primary category, if available.
			$categories = get_the_category( $post->ID );
			if ( $categories ) {
				$cat = $categories[0];
				$items[] = $this->item( $pos++, $cat->name, get_category_link( $cat->term_id ) );
			}
		} elseif ( 'page' === $post->post_type ) {
			// Ancestors
			$ancestors = array_reverse( get_post_ancestors( $post ) );
			foreach ( $ancestors as $aid ) {
				$items[] = $this->item( $pos++, get_the_title( $aid ), get_permalink( $aid ) );
			}
		}

		// Current
		$items[] = $this->item( $pos, wp_strip_all_tags( get_the_title( $post ) ), get_permalink( $post ) );

		return array(
			'@type'           => 'BreadcrumbList',
			'@id'             => get_permalink( $post ) . '#breadcrumbs',
			'itemListElement' => $items,
		);
	}

	private function item( int $pos, string $name, string $url ): array {
		return array(
			'@type'    => 'ListItem',
			'position' => $pos,
			'name'     => $name,
			'item'     => $url,
		);
	}
}
