<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Infrastructure\Compatibility;

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

use Signocore\Multilanguage\Features\LanguageDetection;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;
use Signocore\Multilanguage\Support\TranslationHelper;

/**
 * Rank Math SEO compatibility — provides translated SEO meta per language.
 *
 * Rank Math does not output its own hreflang tags, so our built-in
 * hreflang output works without conflicts. OG locale uses get_locale()
 * which is already filtered by our locale switching.
 */
final class RankMath
{
	use Singleton;

	protected function init(): void
	{
		if (!defined('RANK_MATH_FILE')) {
			return;
		}

		add_filter('rank_math/frontend/title', [$this, 'filterMetaTitle']);
		add_filter('rank_math/frontend/description', [$this, 'filterMetaDescription']);
		add_filter('rank_math/frontend/canonical', [$this, 'filterCanonicalUrl']);

		do_action('signocore_ml_rankmath_loaded');
	}

	/**
	 * Filter meta title to use the translated post's Rank Math title.
	 */
	public function filterMetaTitle(string $title): string
	{
		$postId = $this->getQueriedPostId();
		if ($postId === null) {
			return $title;
		}

		$translatedId = $this->getTranslatedPostId($postId);
		if ($translatedId === null) {
			return $title;
		}

		$translatedTitle = get_post_meta($translatedId, 'rank_math_title', true);
		if (is_string($translatedTitle) && $translatedTitle !== '') {
			return $translatedTitle;
		}

		return $title;
	}

	/**
	 * Filter meta description to use the translated post's Rank Math description.
	 */
	public function filterMetaDescription(string $description): string
	{
		$postId = $this->getQueriedPostId();
		if ($postId === null) {
			return $description;
		}

		$translatedId = $this->getTranslatedPostId($postId);
		if ($translatedId === null) {
			return $description;
		}

		$translatedDesc = get_post_meta($translatedId, 'rank_math_description', true);
		if (is_string($translatedDesc) && $translatedDesc !== '') {
			return $translatedDesc;
		}

		return $description;
	}

	/**
	 * Filter canonical URL to point to the correct language version.
	 */
	public function filterCanonicalUrl(string $canonical): string
	{
		$postId = $this->getQueriedPostId();
		if ($postId === null) {
			return $canonical;
		}

		$translatedId = $this->getTranslatedPostId($postId);
		if ($translatedId === null) {
			return $canonical;
		}

		return get_permalink($translatedId) ?: $canonical;
	}

	/**
	 * Get the current queried post ID on singular pages.
	 */
	private function getQueriedPostId(): ?int
	{
		if (!is_singular()) {
			return null;
		}

		$postId = get_queried_object_id();
		return $postId > 0 ? $postId : null;
	}

	/**
	 * Get the translated post ID for the current language.
	 *
	 * Returns null if the post is already in the current language
	 * or no translation exists.
	 */
	private function getTranslatedPostId(int $postId): ?int
	{
		$currentLang = LanguageDetection::load()->getCurrentLanguage();
		$postLang = TranslationHelper::getElementLanguage($postId);

		if ($postLang === $currentLang) {
			return null;
		}

		return TranslationHelper::getTranslation($postId, $currentLang);
	}
}
