<?php

namespace rentsyst\admin\components;

use rentsyst\includes\RS_Company;

class Rentsyst_Language
{
	public static function getLanguageCode()
	{
		$language = RS_Company::getInstance()->getLanguageOfCommunication();
		if(function_exists('pll_current_language') && pll_current_language()) {
			$language = pll_current_language();
		} elseif (apply_filters( 'wpml_current_language', NULL )) {
			$language = apply_filters( 'wpml_current_language', NULL );
		} elseif (isset($_REQUEST['lang'])) {
			$language = sanitize_text_field($_REQUEST['lang']);
		} elseif (function_exists('weglot_get_current_language') && weglot_get_current_language()) {
			$language = weglot_get_current_language();
		}
		return $language;
	}

	public static function getConnectedPagesId( $catalog_page_id )
	{
		if(function_exists('pll_get_post_translations') && pll_get_post_translations($catalog_page_id)) {
			return pll_get_post_translations($catalog_page_id);
		}
		if(function_exists('icl_object_id')) {
			$translated_page_id = icl_object_id($catalog_page_id, 'page', false, ICL_LANGUAGE_CODE);
			if($translated_page_id) {
				return [self::getLanguageCode() => $translated_page_id];
			}
		}

		return [$catalog_page_id];
	}

	/**
	 * Whether WPML is active.
	 */
	private static function isWpmlActive()
	{
		return defined('ICL_SITEPRESS_VERSION') || function_exists('icl_object_id');
	}

	/**
	 * Whether any multilingual plugin API is loaded in this process.
	 */
	public static function isMultilingualPluginLoaded()
	{
		return function_exists('pll_languages_list') || self::isWpmlActive();
	}

	/**
	 * Whether the database carries multilingual footprints (Polylang language
	 * terms or the WPML translations table) regardless of whether the plugin
	 * that wrote them is currently loaded. Used to tell "single-language site"
	 * apart from "multilingual site whose language plugin is not running right
	 * now" — destructive sync passes must not act on the latter.
	 */
	public static function hasStoredLanguageData()
	{
		global $wpdb;

		$languageTerms = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->term_taxonomy} WHERE taxonomy = 'language'");
		if((int) $languageTerms > 0) {
			return true;
		}

		$iclTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix . 'icl_translations'));

		return !empty($iclTable);
	}

	/**
	 * Whether Polylang is active.
	 */
	private static function isPolylangActive()
	{
		return function_exists('pll_set_post_language') && function_exists('pll_save_post_translations');
	}

	/**
	 * List of active language slugs for plugins that store a separate post per
	 * language (Polylang, WPML). Returns an empty array for single-language
	 * sites or for on-the-fly translators (e.g. Weglot) that do not create posts.
	 *
	 * @return string[]
	 */
	public static function getLanguages()
	{
		if(function_exists('pll_languages_list')) {
			$languages = pll_languages_list();
			return is_array($languages) ? array_values($languages) : [];
		}
		if(self::isWpmlActive()) {
			$languages = apply_filters('wpml_active_languages', null, ['skip_missing' => 0]);
			if(is_array($languages)) {
				return array_values(array_keys($languages));
			}
		}
		return [];
	}

	/**
	 * Default language slug, or empty string if not applicable.
	 *
	 * @return string
	 */
	public static function getDefaultLanguage()
	{
		if(function_exists('pll_default_language')) {
			return (string) pll_default_language();
		}
		if(self::isWpmlActive()) {
			return (string) apply_filters('wpml_default_language', null);
		}
		return '';
	}

	/**
	 * Language slug assigned to a given post, or empty string if none.
	 *
	 * @param int $post_id
	 * @return string
	 */
	public static function getPostLanguage( $post_id )
	{
		if(function_exists('pll_get_post_language')) {
			return (string) pll_get_post_language($post_id);
		}
		if(self::isWpmlActive()) {
			$lang = apply_filters('wpml_element_language_code', null, [
				'element_id'   => $post_id,
				'element_type' => 'post_' . get_post_type($post_id),
			]);
			return (string) $lang;
		}
		return '';
	}

	/**
	 * Assign a language to each post and link them together as one translation
	 * group. Works for Polylang and WPML; no-op otherwise.
	 *
	 * @param array  $map         [ langSlug => postId ]
	 * @param string $defaultLang Slug to treat as the translation source.
	 */
	public static function syncTranslations( array $map, $defaultLang = '' )
	{
		$map = array_filter($map);
		if(count($map) < 2) {
			return;
		}

		if(self::isPolylangActive()) {
			foreach ($map as $lang => $post_id) {
				pll_set_post_language($post_id, $lang);
			}
			pll_save_post_translations($map);
			return;
		}

		if(self::isWpmlActive()) {
			if(isset($map[$defaultLang])) {
				$sourceLang = $defaultLang;
			} else {
				reset($map);
				$sourceLang = key($map);
			}
			$sourceId   = $map[$sourceLang];
			$type       = 'post_' . get_post_type($sourceId);

			$trid = apply_filters('wpml_element_trid', null, $sourceId, $type);
			do_action('wpml_set_element_language_details', [
				'element_id'           => $sourceId,
				'element_type'         => $type,
				'trid'                 => $trid,
				'language_code'        => $sourceLang,
				'source_language_code' => null,
			]);
			$trid = apply_filters('wpml_element_trid', null, $sourceId, $type);

			foreach ($map as $lang => $post_id) {
				if($lang === $sourceLang) {
					continue;
				}
				do_action('wpml_set_element_language_details', [
					'element_id'           => $post_id,
					'element_type'         => $type,
					'trid'                 => $trid,
					'language_code'        => $lang,
					'source_language_code' => $sourceLang,
				]);
			}
		}
	}
}
