<?php

namespace Easymailing\App\Controller\Admin;

use Easymailing\App\Api\Exception\AuthenticationException;
use Easymailing\App\Api\Exception\RequestLimitException;
use Easymailing\App\Controller\BaseController;
use Easymailing\App\Model\Audience;
use Easymailing\App\Model\SynchronizationConfig;

class BaseSynchronizationController extends BaseController
{

	protected function checkConfig(): void
	{
		$repository = $this->getContainer()->get('config_repository');
		$config = $repository->getConfig();
		$client = $this->getContainer()->get('api_client');

		if (is_null($config)) {
			$this->forward('Easymailing\App\Controller\Admin\ConfigurationController', 'indexAction');
		}

		if (!$config->getApiKey()) {
			$this->forward('Easymailing\App\Controller\Admin\ConfigurationController', 'indexAction');
		}

		try {
			$client->checkAuth($config->getApiKey());
		} catch (AuthenticationException $e) {
			$this->forward('Easymailing\App\Controller\Admin\ConfigurationController', 'indexAction');
		}catch (RequestLimitException $e) {
			$this->render('Admin/Synchronization/error.php', [
				'message' => __('Se ha sobrepasado el limite de peticiones al API: ','easymailing'). $e->getMessage(),
				'current_page' => 0,
			]);
			wp_die();
		}catch (\Exception $e) {
			$this->render('Admin/Configuration/error.php', [
				'message' => __('Error al comprobar la clave API, vuelve a intentarlo pasados unos minutos', 'easymailing')
			]);
		}

		if (!class_exists('WooCommerce')) {
			$this->render('Admin/Synchronization/error.php', [
				'message' => __('Debes instalar woocommerce para utilizar esta parte del plugin.','easymailing') ,
				'current_page' => 0,
			]);
			wp_die();
		}
	}


	protected function checkGeneralData(): void
	{
		$synchronizationConfig = $this->getSynchronizationConfig();
		$config = $this->getConfig();

		if (is_null($synchronizationConfig)) {
			$this->redirectToMenuPage('easymailing_synchronization_configuration');
		}

		if (!$synchronizationConfig->getShopId() || !$synchronizationConfig->getAudience()) {
			$this->redirectToMenuPage('easymailing_synchronization_configuration');
		}


		$current_menu_slug = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';

		if ($current_menu_slug === 'easymailing_synchronization_reset' || $current_menu_slug === 'easymailing_synchronization_configuration_settings') {
			return;
		}

		if ($synchronizationConfig->getAppDomain() !== $config->getMySuscription()->domain) {
			$this->getFlashBag()->add('warning', __('Parece que has cambiado la clave API. Tu configuración de sincronización ya no es válida y no funcionará. Restablece la configuración de sincronización o pon una clave API de la misma cuenta con la que configuraste la sincronización.', 'easymailing'));

			$this->redirectToMenuPage('easymailing_synchronization_reset');

		}


	}

	public function render($template, $parameters = []): void
	{
		$config = $this->getConfig();
		$synchronizationConfig = $this->getSynchronizationConfig();

		$parameters['config'] = $config;
		$parameters['synchronizationConfig'] = $synchronizationConfig;

		echo '<div class="easymailing-css">';
		echo $this->getContainer()->get('templating')->render($template, $parameters);
		echo '</div>';
		wp_die();
	}

	protected function getSynchronizationConfig(): SynchronizationConfig
	{
		return $this->getContainer()->get('config_repository')->getSynchronizationConfig();
	}

	protected function getAudienceFromSynchronizationConfig(): Audience
	{
		return $this->getContainer()->get('config_repository')->getAudienceFromSynchronizationConfig();
	}

}
