<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Infrastructure\Compatibility;

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Features\LanguageDetection;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;
use Signocore\Multilanguage\Support\TranslationHelper;

final class Elementor
{
	use Singleton;

	protected function init(): void
	{
		if (!did_action('elementor/loaded')) {
			return;
		}

		// Filter Elementor document for translated version
		add_action('elementor/frontend/before_get_builder_content', [$this, 'switchToTranslatedDocument']);

		// Make Elementor CPTs translatable
		add_filter('signocore_ml_is_translatable_post_type', [$this, 'makeElementorTypesTranslatable'], 10, 2);

		// Copy Elementor data when duplicating
		add_filter('signocore_ml_post_meta_to_duplicate', [$this, 'includeElementorMeta'], 10, 3);

		do_action('signocore_ml_elementor_loaded');
	}

	/**
	 * Switch Elementor document to the translated version if available.
	 *
	 * @param \Elementor\Core\DocumentTypes\PageBase $document
	 */
	public function switchToTranslatedDocument($document): void
	{
		$postId = $document->get_main_id();
		$currentLang = LanguageDetection::load()->getCurrentLanguage();

		$translatedId = TranslationHelper::getTranslation($postId, $currentLang);
		if ($translatedId !== null && $translatedId !== $postId) {
			$document->switch_to_post($translatedId);
		}
	}

	/**
	 * Make Elementor library post types translatable.
	 */
	public function makeElementorTypesTranslatable(bool $translatable, string $postType): bool
	{
		$elementorTypes = ['elementor_library', 'e-landing-page'];

		if (in_array($postType, $elementorTypes, true)) {
			return true;
		}

		return $translatable;
	}

	/**
	 * Include Elementor meta keys when duplicating posts.
	 *
	 * @param string[] $keys
	 * @param int $sourcePostId
	 * @param string $langCode
	 * @return string[]
	 */
	public function includeElementorMeta(array $keys, int $sourcePostId, string $langCode): array
	{
		$elementorKeys = [
			'_elementor_data',
			'_elementor_page_settings',
			'_elementor_edit_mode',
			'_elementor_template_type',
			'_elementor_version',
			'_elementor_css',
		];

		return array_unique(array_merge($keys, $elementorKeys));
	}
}
