<?php
namespace CWPM\Compat;

defined( 'ABSPATH' ) || exit;

class Multilingual {

	/**
	 * Check if a multilingual plugin is active.
	 *
	 * @return bool
	 */
	public static function is_active() {
		return self::is_wpml() || self::is_polylang();
	}

	/**
	 * @return bool
	 */
	public static function is_wpml() {
		return defined( 'ICL_SITEPRESS_VERSION' );
	}

	/**
	 * @return bool
	 */
	public static function is_polylang() {
		return function_exists( 'pll_get_post' );
	}

	/**
	 * Get all translation IDs for an attachment.
	 *
	 * Given an attachment ID, returns all translated versions of that attachment
	 * (including the original). This ensures that if any translation is used,
	 * none of them are flagged as unused.
	 *
	 * @param int $attachment_id Original attachment ID.
	 * @return int[] All translated attachment IDs (including the original).
	 */
	public static function get_all_translations( $attachment_id ) {
		$ids = array( $attachment_id );

		if ( self::is_wpml() ) {

			// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WPML-owned external filter.
			$languages = apply_filters( 'wpml_active_languages', array() );

			if ( ! is_array( $languages ) ) {
				$languages = array();
			}
			foreach ( $languages as $lang ) {
				if ( ! is_array( $lang ) || empty( $lang['code'] ) ) {
					continue;
				}
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WPML-owned external filter.
				$translated_id = apply_filters( 'wpml_object_id', $attachment_id, 'attachment', false, $lang['code'] );
				if ( $translated_id && $translated_id !== $attachment_id ) {
					$ids[] = (int) $translated_id;
				}
			}
		} elseif ( self::is_polylang() ) {

			if ( function_exists( 'pll_get_post_translations' ) ) {
				$translations = pll_get_post_translations( $attachment_id );
				foreach ( $translations as $lang => $trans_id ) {
					if ( $trans_id && (int) $trans_id !== $attachment_id ) {
						$ids[] = (int) $trans_id;
					}
				}
			}
		}

		return array_unique( $ids );
	}

	/**
	 * Check if any translation of an attachment is used.
	 *
	 * @param int   $attachment_id The attachment ID to check.
	 * @param array $usage_map     The pre-built usage map (ID => usages).
	 * @return bool True if any translation is found in the usage map.
	 */
	public static function is_any_translation_used( $attachment_id, $usage_map ) {
		$all_ids = self::get_all_translations( $attachment_id );
		foreach ( $all_ids as $id ) {
			if ( ! empty( $usage_map[ $id ] ) ) {
				return true;
			}
		}
		return false;
	}
}
