<?php
/**
 * Clears elementor cache on import.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor;

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemValueHandler\ItemValueHandlerBase;
use Elementor\Plugin;

/**
 * Clears elementor cache on import.
 */
class ClearElementorCacheOnImportProcessor extends ValueProcessorBase {
	/**
	 * Clears the elementor cache.
	 */
	public static function clearElementorCache(): void {
		if ( class_exists( 'Elementor\Plugin' ) ) {
			Plugin::$instance->files_manager->clear_cache();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public static function getId(): string {
		return 'clear_elementor_cache_on_import';
	}

	/**
	 * {@inheritDoc}
	 */
	public static function getLabel(): string {
		return _dpgettext( 'deployer-core', 'processor label', 'Clear Elementor cache on import' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function process( $value, int $operation, ?callable $progress_callback = null ) {
		if ( ItemValueHandlerBase::OPERATION__IMPORT__FINALIZE !== $operation ) {
			return $value;
		}

		$progress_callback = $progress_callback ?? static function ( array $progress ) {
		};

		// Notifiy the callers the post action to call at the end of the import process (if we are in one).
		$progress_callback(
			array(
				'add_import_post_actions' => array(
					static::getId() => static function ( ?callable $progress_callback = null ): void {
						if ( class_exists( 'Elementor\Plugin' ) ) {
							return;
						}

						$files_manager = Plugin::instance()->files_manager ?? null;

						if ( empty( $files_manager ) ) {
							return;
						}

						$files_manager->clear_cache();

						is_callable( $progress_callback ) && $progress_callback(
							array(
								'message_line' => _dgettext( 'deployer-core', 'The Elementor cache has been cleared.' ),
							)
						);
					},
				),
			)
		);

		return $value;
	}
}
