<?php
/**
 * Adds WPML support for Essential Grid.
 *
 * @package   Essential_Grid
 * @author    ThemePunch <info@themepunch.com>
 * @link      https://www.essential-grid.com/
 * @copyright 2025 ThemePunch
 */

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

/**
 * WPML Class For Essential Grid.
 */
class Essential_Grid_Wpml {

	/**
	 * Instance of this class.
	 *
	 * @var null|object
	 */
	protected static $instance = null;

	/**
	 * Return an instance of this class.
	 *
	 * @return object A single instance of this class.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Set up hooks.
	 */
	private function __construct() {
		add_action( 'init', array( $this, 'init_wpml' ) );
	}

	/**
	 * Set up hooks for translation
	 *
	 * @return void
	 */
	public function init_wpml() {
		if ( ! $this->is_wpml_exists() ) {
			return;
		}

		add_filter( 'essgrid_get_lang_code', array( $this, 'get_current_lang_code' ) );
		add_filter( 'essgrid_get_taxonomy_id', array( $this, 'get_taxonomy_id' ), 10, 2 );
		add_filter( 'essgrid_strip_category_additions', array( $this, 'strip_category_additions' ) );
	}

	/**
	 * Is wpml plugin exists?
	 *
	 * @return bool
	 */
	public function is_wpml_exists() {
		return class_exists( 'SitePress' ) && function_exists( 'wpml_object_id_filter' );
	}

	/**
	 * Get current wpml language code.
	 *
	 * @return string
	 */
	public function get_current_lang_code() {
		return ICL_LANGUAGE_CODE;
	}

	/**
	 * Get WPML taxonomy ID.
	 *
	 * @param int    $id taxonomy ID.
	 * @param string $type taxonomy type.
	 *
	 * @return int|NULL
	 */
	public function get_taxonomy_id( $id, $type = 'category' ) {
		return wpml_object_id_filter( $id, $type, true );
	}

	/**
	 * Remove for example @en from categories.
	 *
	 * @param string $text text to process.
	 * @return string
	 */
	public function strip_category_additions( $text ) {
		return apply_filters( 'essgrid_wpml_strip_category_additions', $text );
	}
}
