<?php
namespace AcademyProWpml\Classes;

use Exception;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
class LessonTranslation extends Base {
	protected bool $is_translation_active;
	public function __construct() {
		$this->is_translation_active = $GLOBALS['academy_settings']->lesson_translation ?? false;
	}
	public function set_lang_query( array $meta_query ): array {
		if ( ! $this->is_translation_active ) {
			return $meta_query;
		}

		try {
			$this->load_conf( false, true );
		} catch ( Exception $e ) {
			return $meta_query;
		}
		// self::$current_lang = 'en';
		// self::$default_lang= 'bn';
		if ( self::$current_lang === self::$default_lang ) {
			$meta_query[] = [
				'relation' => 'OR',
				[
					'key'     => 'wpml:lang',
					'value'   => self::$current_lang,
					'compare' => '=',
				],
				[
					'key'     => 'wpml:lang',
					'compare' => 'NOT EXISTS',
				]
			];
		} else {
			$meta_query[] = [
				'key'     => 'wpml:lang',
				'value'   => self::$current_lang,
				'compare' => '=',
			];
		}//end if
		return $meta_query;
	}

	public function set_meta_data( array $meta ): array {
		if ( ! $this->is_translation_active ) {
			return $meta;
		}

		try {
			$this->load_conf( false, true );
		} catch ( Exception $e ) {
			return $meta;
		}
		// self::$current_lang = 'br';
		// self::$default_lang= 'en';
		$meta['wpml:lang'] = self::$current_lang;
		return $meta;
	}
	public static function init(): void {
		$ins = new self();
		add_filter( 'academy/lesson/meta_query', [ $ins, 'set_lang_query' ] );
		add_filter( 'academy/lesson/set_meta_data', [ $ins, 'set_meta_data' ] );
	}
}
