<?php

namespace Travelpayouts\admin\components\landingPage;
use Travelpayouts\Vendor\DI\Annotation\Inject;
use Exception;
use Travelpayouts;
use Travelpayouts\admin\redux\ReduxOptions;
use Travelpayouts\components\HtmlHelper;
use Travelpayouts\components\InjectedModel;
use Travelpayouts\components\LanguageHelper;
use Travelpayouts\components\notices\Notice;

/**
 * Class LandingModel
 * @package Travelpayouts\admin\components\landingPage
 */
class LandingModel extends InjectedModel
{
	const LANDING_SLUG = 'travelpayouts_landing_page';

	public $token;
	public $marker;
	public $language;
	public $currency;

	/**
	 * @Inject
	 * @var Travelpayouts\components\notices\Notices
	 */
	protected $notices;

	public function rules()
	{
		return array_merge(parent::rules(), [
			[['token', 'marker'], 'required'],
			[['language'], 'string', 'length' => 2],
			[['currency'], 'string', 'length' => 3],
		]);
	}

	public function init()
	{
		parent::init(); // TODO: Change the autogenerated stub
	}

	/**
	 * @throws Exception
	 */
	public function save()
	{
		// Catch exception
		if ($this->validate()) {
			$this->saveReduxOptions();
		} else {
			// Отображает ошибки валидации
			$this->addValidationNotices();
		}
	}

	/**
	 * @param $data
	 */
	public function setSanitizedAttributes($data)
	{
		$this->token = preg_replace('/[^a-zA-Z0-9]/', '', strip_tags($data['token']));
		$this->marker = preg_replace('/[^0-9]/', '', strip_tags($data['marker']));
		$this->language = substr(
			preg_replace(
				'/[^a-z]/',
				'',
				strip_tags($data['language'])
			),
			0,
			2
		);
		$this->currency = substr(
			preg_replace(
				'/[^A-Z]/',
				'',
				strip_tags($data['currency'])
			),
			0,
			3
		);
	}

	/**
	 * save redux options
	 */
	protected function saveReduxOptions()
	{
		return $this->setLandingReduxOptions($this->token, $this->marker, $this->language, $this->currency);
	}

	/**
	 * @return string
	 */
	public function getCurrencyOptions()
	{
		return $this->getSelectOptions(
			ReduxOptions::table_widget_currencies(),
			$this->getCurrency()
		);
	}

	/**
	 * @return string
	 */
	public function getLanguageOptions()
	{
		$locales = Travelpayouts::getInstance()->translator->getLocaleNames();

		// Сортировка по алфавиту
		asort($locales, SORT_STRING);

		return $this->getSelectOptions(
			$locales,
			$this->getLanguage()
		);
	}

	/**
	 * @return mixed
	 */
	public function getToken()
	{
		return $this->getReduxValue('account', 'api_token', '');
	}

	/**
	 * @return mixed
	 */
	public function getMarker()
	{
		return $this->getReduxValue('account', 'api_marker', '');
	}

	/**
	 * @return mixed
	 */
	private function getLanguage()
	{
		return $this->getReduxValue(
			'settings',
			'language',
			LanguageHelper::dashboardLocale()
		);
	}

	/**
	 * @return mixed
	 */
	private function getCurrency()
	{
		return $this->getReduxValue(
			'settings',
			'currency',
			ReduxOptions::getDefaultCurrencyCode()
		);
	}

	/**
	 * @return string
	 */
	public static function getInstallButtonText()
	{
		$plugins = get_plugins();
		$path = 'redux-framework/redux-framework.php';

		if (isset($plugins[$path]) && !empty($plugins[$path])) {
			return Travelpayouts::__('Activate the plugin');
		}

		return Travelpayouts::__('Install the plugin');
	}

	/**
	 * @param $module
	 * @param $name
	 * @param $default
	 * @return mixed
	 */
	private function getReduxValue($module, $name, $default)
	{
		return Travelpayouts::getInstance()->{$module}->section->data->get($name, $default);
	}

	/**
	 * @param $options
	 * @param $selected
	 * @return string
	 */
	private function getSelectOptions($options, $selected)
	{
		$html = '';
		foreach ($options as $key => $name) {
			$htmlOptions = ['value' => $key];
			if ($key == $selected) {
				$htmlOptions['selected'] = 'selected';
			}
			$html .= HtmlHelper::tag('option', $htmlOptions, $name);
		}

		return $html;
	}

	/**
	 * @param $token
	 * @param $marker
	 * @param $language
	 * @param $currency
	 */
	private function setLandingReduxOptions($token, $marker, $language, $currency)
	{
		try {
			$redux = Travelpayouts::getInstance()->redux;

			$redux->setOption('account_api_token', $token);
			$redux->setOption('account_api_marker', $marker);
			$redux->setOption('settings_language', $language);
			$redux->setOption('settings_currency', $currency);
		} catch (Exception $exception) {
			$this->notices->add(
				Notice::create('redux_activated_action_error')
					->setType(Notice::NOTICE_TYPE_ERROR)
					->setTitle($exception->getMessage())
			);
		}
	}

	private function addValidationNotices()
	{
		foreach ($this->getErrors() as $key => $error) {
			$this->notices->add(
				Notice::create(TRAVELPAYOUTS_TEXT_DOMAIN . '_' . $key)
					->setType(Notice::NOTICE_TYPE_ERROR)
					->setTitle(implode(' ', $error))
			);
		}
	}
}
