<?php
/**
 * Current config provider.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\Config;

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\InvalidValue;

/**
 * Current config provider.
 */
class CurrentConfigProvider extends ConfigProviderBase {
	/**
	 * The option name for the option holding this config.
	 *
	 * @var string
	 */
	private string $option_name;

	/**
	 * {@inheritDoc}
	 */
	public function collect(): ?array {
		$this->config = null;

		// Always retrieve the current config from the database.
		$config = get_option( $this->option_name, new InvalidValue() );

		if ( ! ( $config instanceof InvalidValue ) ) {
			// The option is set.
			// Dev note: do not perform any side effects here, like modifying the config and saving right after!
			// The config is not supposed to be modified here. Leave that to the manager.
			$this->config = json_decode( $config, true );

			return $this->config;
		}

		return null;
	}

	/**
	 * The option name for the option holding this config.
	 *
	 * @return string The option name.
	 */
	public static function buildOptionName( string $manager_id ): string {
		return 'deploy_sync_content__current_config__' . $manager_id;
	}

	/**
	 * {@inheritDoc}
	 */
	public function init( ConfigProviderManagerBase $config_provider_manager, ?array $options = null ): void {
		parent::init( $config_provider_manager, $options );

		$this->option_name = static::buildOptionName( $config_provider_manager::getManagerId() );
	}

	/**
	 * {@inheritDoc}
	 */
	protected function saveConfig( ?array $config ): void {
		// The current config works with the database.
		update_option( $this->option_name, json_encode( $config ) );
	}
}
