<?php

namespace WPEventGenius\Common\Services;

use WPEventGenius\Common\SEO\Compatibility\AIOSEOCompatibility;
use WPEventGenius\Common\SEO\Compatibility\RankMathSEOCompatibility;
use WPEventGenius\Common\SEO\Compatibility\SEOPressSEOCompatibility;
use WPEventGenius\Common\SEO\Compatibility\SEOCompatibilityInterface;
use WPEventGenius\Common\SEO\Compatibility\YoastSEOCompatibility;
use WPEventGenius\Common\Utils\SEODetector;

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

class BreadcrumbService {

	/**
	 * @var array<string,SEOCompatibilityInterface>
	 */
	protected $compatibilities = array();

	public function __construct() {
		$this->compatibilities = array(
			'yoast'     => new YoastSEOCompatibility(),
			'rank_math' => new RankMathSEOCompatibility(),
			'aioseo'    => new AIOSEOCompatibility(),
			'seopress'  => new SEOPressSEOCompatibility(),
		);
	}

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public function init_hooks() {
		add_action( 'evge_before_single_event_title', array( $this, 'render_breadcrumbs' ), 10, 1 );
	}

	/**
	 * Render breadcrumbs for the currently active SEO plugin.
	 *
	 * @param mixed $event_context Event object or post ID.
	 * @return void
	 */
	public function render_breadcrumbs( $event_context = null ) {
		$post_id = 0;

		if ( is_object( $event_context ) && method_exists( $event_context, 'should_show_section' ) ) {
			if ( ! $event_context->should_show_section( 'breadcrumbs' ) ) {
				return;
			}
		}

		if ( is_object( $event_context ) && method_exists( $event_context, 'get_the_id' ) ) {
			$post_id = absint( $event_context->get_the_id() );
		} else {
			$post_id = absint( $event_context );
		}

		if ( $post_id <= 0 ) {
			$post_id = get_the_ID();
		}

		if ( $post_id <= 0 ) {
			return;
		}

		$seo_plugin = SEODetector::get_active_seo_plugin();

		if ( empty( $seo_plugin ) || empty( $this->compatibilities[ $seo_plugin ] ) ) {
			return;
		}

		$compatibility = $this->compatibilities[ $seo_plugin ];
		if ( ! $compatibility->is_available() ) {
			return;
		}

		$breadcrumbs_html = $compatibility->render( $post_id );
		if ( empty( $breadcrumbs_html ) ) {
			return;
		}

		$breadcrumbs_html = apply_filters( 'evge_breadcrumbs_html', $breadcrumbs_html, $seo_plugin, $post_id );
		if ( empty( $breadcrumbs_html ) ) {
			return;
		}

		echo '<div class="evge-breadcrumbs-wrap" data-evge-seo-plugin="' . esc_attr( $seo_plugin ) . '">';
		echo '<nav class="evge-breadcrumbs" aria-label="' . esc_attr__( 'Breadcrumb', 'event-genius' ) . '">';
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $breadcrumbs_html;
		echo '</nav>';
		echo '</div>';
	}
}
