<?php

namespace WcJUpsellator\Helpers;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class LanguageHelper
{
	public static function hasMultiLanguagePlugin()
	{
		return function_exists( 'pll_register_string' ) || !function_exists('icl_register_string');
	}
	/*
	/* Get the translated URL of a given page_id
	*/
	public static function getTranslatedPageURL( $id ) 
	{
		$page = null;

		if ( function_exists( 'pll_get_post' ) )
		{
			$page = pll_get_post( $id, sanitize_text_field( $_GET['lang'] ?? null ) );  
		}  
		
		if ( function_exists( 'icl_object_id' ) )
		{
			$page = icl_object_id( $id, 'page', true, sanitize_text_field( $_GET['lang'] ?? null ) );  		
		} 
		
		return $page ? get_permalink( $page ) : get_permalink( $id );  
	}
	/*
	/* Translate a string
	*/
	public static function getTranslatedString( $string, $key = null )
	{
		if ( function_exists('pll_translate_string')  )
		{
			return isset( $_GET['lang'] ) ? pll_translate_string( $string, sanitize_text_field( $_GET['lang'] )) : pll__( $string ); 
		}   
		
		if ( function_exists('icl_t')  )
		{         
			return icl_t( 'J Cart Upsell', $key, $string );
		}  
	
		return $string;
	}
	/*
	/* Return list of enabled languages
	*/
	public static function getAvailableLanguages()
	{
		$langs = [];

		if ( function_exists('pll_languages_list')  )
		{
			$languages = pll_languages_list( array('fields' => [] ) );

			if( !empty( $languages ) )
			{
				foreach( $languages as $language )
				{
					
					$langs[ $language->locale ] = ['name' => $language->name, 'slug' => $language->slug ];
				}
			}
		}  
		
		if ( defined( 'ICL_SITEPRESS_VERSION' )  )
		{
			$languages = apply_filters( 'wpml_active_languages', null );
			
			if( !empty( $languages ) )
			{
				foreach( $languages as $language )
				{
					
					$langs[ $language['default_locale'] ] = ['name' => $language['native_name'], 'slug' => $language['language_code'] ];
				}
			}
		} 
		
		return $langs;
		
	}
	/*
	/* Get ID's of translated items
	*/
	public static function getTranslationsIDS( $post_id )
	{
		$ids = [];

		if( function_exists('pll_get_post_translations') )
		{
			$ids = pll_get_post_translations( $post_id );
		}

		if( defined( 'ICL_SITEPRESS_VERSION' ) )
		{
			$trid 			= apply_filters( 'wpml_element_trid', false, $post_id, 'post_product' );
			$translations 	= apply_filters( 'wpml_get_element_translations', array(), $trid, 'product' );

			if( $translations )
			{
				$ids = array_map( fn( $translation ) => $translation->element_id, $translations );
			}
		}	

		return array_values( $ids );
	}

}

