<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Features;

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;
use Signocore\Multilanguage\Support\TranslationHelper;

final class MediaTranslation
{
	use Singleton;

	protected function init(): void
	{
		// Filter attachment URLs on frontend to serve language-specific media
		if (!Constants::$isAdmin) {
			add_filter('wp_get_attachment_url', [$this, 'filterAttachmentUrl'], 10, 2);
			add_filter('wp_get_attachment_image_src', [$this, 'filterAttachmentImageSrc'], 10, 4);
		}
	}

	/**
	 * Filter attachment URL to serve language-specific version.
	 *
	 * @param string $url
	 * @param int $attachmentId
	 */
	public function filterAttachmentUrl(string $url, int $attachmentId): string
	{
		$currentLang = LanguageDetection::load()->getCurrentLanguage();
		$defaultLang = LanguageManager::load()->getDefaultLanguageCode();

		if ($currentLang === $defaultLang) {
			return $url;
		}

		$translatedId = TranslationHelper::getTranslation($attachmentId, $currentLang, 'post');
		if ($translatedId !== null) {
			$translatedUrl = wp_get_attachment_url($translatedId);
			if (is_string($translatedUrl) && $translatedUrl !== '') {
				// Prevent infinite recursion
				remove_filter('wp_get_attachment_url', [$this, 'filterAttachmentUrl'], 10);
				$result = wp_get_attachment_url($translatedId);
				add_filter('wp_get_attachment_url', [$this, 'filterAttachmentUrl'], 10, 2);

				return is_string($result) ? $result : $url;
			}
		}

		return $url;
	}

	/**
	 * Filter attachment image source for language-specific version.
	 *
	 * @param array<int, mixed>|false $image
	 * @param int $attachmentId
	 * @param string|int[] $size
	 * @param bool $icon
	 * @return array<int, mixed>|false
	 */
	public function filterAttachmentImageSrc(array|false $image, int $attachmentId, string|array $size, bool $icon): array|false
	{
		$currentLang = LanguageDetection::load()->getCurrentLanguage();
		$defaultLang = LanguageManager::load()->getDefaultLanguageCode();

		if ($currentLang === $defaultLang) {
			return $image;
		}

		$translatedId = TranslationHelper::getTranslation($attachmentId, $currentLang, 'post');
		if ($translatedId !== null) {
			remove_filter('wp_get_attachment_image_src', [$this, 'filterAttachmentImageSrc'], 10);
			$translatedImage = wp_get_attachment_image_src($translatedId, $size, $icon);
			add_filter('wp_get_attachment_image_src', [$this, 'filterAttachmentImageSrc'], 10, 4);

			if ($translatedImage !== false) {
				return $translatedImage;
			}
		}

		return $image;
	}
}
