<?php

namespace Easymailing\App\Repository;

use Easymailing\App\Api\Hydrator;
use Easymailing\App\Core\ParameterBag;
use Easymailing\App\Core\Provider\Woocommerce\Service\MetadataHelper;
use Easymailing\App\Model\Audience;
use Easymailing\App\Model\Config;
use Easymailing\App\Model\SynchronizationConfig;
use Easymailing\App\Utils\Security;

class ConfigRepository
{
	private $parameterBag;
	private $hydrator;

	public function __construct(ParameterBag $parameterBag, Hydrator $hydrator)
	{
		$this->parameterBag = $parameterBag;
		$this->hydrator = $hydrator;
	}

	public function saveConfig(Config $config): void
	{
		if ($config->getApiKey()) {
			$config->setApiKey(Security::safeEncrypt($config->getApiKey(), $this->parameterBag->get('encrypt_key')));
		}

		update_option(MetadataHelper::getConfiguration(), $config);
	}

	public function getConfig(): ?Config
	{
		$config = get_site_option(MetadataHelper::getConfiguration());

		if ($config instanceof Config) {
			if ($config->getApiKey()) {
				$config->setApiKey(Security::safeDecrypt($config->getApiKey(), $this->parameterBag->get('encrypt_key')));
			}

			return $config;
		}

		return null;
	}

	public function saveSynchronizationConfig(SynchronizationConfig $synchronizationConfig): void
	{
		update_option(MetadataHelper::getSynchronizationConfig(), $synchronizationConfig);
	}

	public function getSynchronizationConfig(): SynchronizationConfig
	{
		$config = get_site_option(MetadataHelper::getSynchronizationConfig());

		if ($config instanceof SynchronizationConfig) {
			return $config;
		}

		return new SynchronizationConfig();
	}

	public function getAudienceFromSynchronizationConfig(): ?Audience
	{
		$synchronizationConfig = $this->getSynchronizationConfig();

		if($synchronizationConfig->getAudienceJson()){
			$data =  json_decode($synchronizationConfig->getAudienceJson(), true);
			return $this->hydrator->hydrate($data);
		}

		return null;
	}
}
