<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Backend;

use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Mail\SmtpMailer;

class MailerSettingsController extends AbstractChurchToolsSettingsController {

	// Cached checking Credentials
	protected $credentialsAreValid = NULL;

	const SMTP_SETTINGS        = 'sb_ct_mailer';
	const OPTION_SMTP_HOST     = 'sb_ct_mailer_host';
	const OPTION_SMTP_USER     = 'sb_ct_mailer_user';
	const OPTION_SMTP_PASSWORD = 'sb_ct_mailer_pw';
	const OPTION_SMTP_SECURE   = 'sb_ct_mailer_secure';
	const OPTION_SMTP_TIMEOUT  = 'sb_ct_mailer_timeout';

	public function __construct($domain) {
		parent::__construct($domain, $sectionId = 'sb_ct_mailer_section', $sectionLabel = 'SMTP Mailer');
	}

	public function registerSetting($pageId, $sectionId) {

		register_setting($this->getSettingsPageSlug(), self::OPTION_SMTP_HOST);
		add_settings_field(
			self::OPTION_SMTP_HOST,                                                                                                                                         // id of the settings field
			__('Host', $this->domain),                                                                                                                                      // title
			[$this, 'render_host'],                                                                                                                                         // callback function
			$pageId,                                                                                                                                                        // page on which settings display
			$sectionId // section on which to show settings
		);

		register_setting($this->getSettingsPageSlug(), self::OPTION_SMTP_USER);
		add_settings_field(
			self::OPTION_SMTP_USER,                                                  // id of the settings field
			__('Username', $this->domain),                                           // title
			[$this, 'render_username'],                                              // callback function
			$pageId,                                                                 // page on which settings display
			$sectionId // section on which to show settings
		);

		register_setting($this->getSettingsPageSlug(), self::OPTION_SMTP_PASSWORD);
		add_settings_field(
			self::OPTION_SMTP_PASSWORD,                                                  // id of the settings field
			__('Password', $this->domain),                                               // title
			[$this, 'render_password'],                                                  // callback function
			$pageId,                                                                     // page on which settings display
			$sectionId // section on which to show settings
		);

		register_setting($this->getSettingsPageSlug(), self::OPTION_SMTP_SECURE);
		add_settings_field(
			self::OPTION_SMTP_SECURE,                                                  // id of the settings field
			__('Security', $this->domain),                                             // title
			[$this, 'render_secure'],                                                  // callback function
			$pageId,                                                                   // page on which settings display
			$sectionId // section on which to show settings
		);

		register_setting($this->getSettingsPageSlug(), self::OPTION_SMTP_TIMEOUT);
		add_settings_field(
			self::OPTION_SMTP_TIMEOUT,                                                  // id of the settings field
			__('Timeout', $this->domain),                                               // title
			[$this, 'render_timeout'],                                                  // callback function
			$pageId,                                                                    // page on which settings display
			$sectionId // section on which to show settings
		);

		add_settings_field(
			'ct_mailer_verify_credentials_btn',                                                                // id of the settings field
			'',                                                                                                // title
			[$this, 'render_verify_credentials_btn'],                                                          // callback function
			$pageId,                                                                                           // page on which settings display
			$sectionId // section on which to show settings
		);

	}

	public function render_host() {
		$this->renderTextField(self::OPTION_SMTP_HOST);
	}

	public function render_username() {
		$this->renderTextField(self::OPTION_SMTP_USER);
	}

	public function render_password() {
		$this->renderTextField(self::OPTION_SMTP_PASSWORD, 'password');
	}

	public function render_secure() {
		$this->printSelectInput([
			'ssl' => 'SSL',
			'tls' => 'TLS',
			''    => __('No Security', $this->domain)
		], self::OPTION_SMTP_SECURE, self::getSecure());
	}

	public function render_timeout() {
		$this->renderTextField(self::OPTION_SMTP_TIMEOUT, 'number', 7);
	}


	public function render_verify_credentials_btn() {

		if ($this->verifyCredentials() === TRUE) {
			$text  = __('SMTP Credentials Are Valid', $this->domain);
			$color = '#22b15c';
		} else {
			$text  = __('SMTP Credentials Are Invalid', $this->domain);
			$color = '#b12222';
		}

		?>
		<p class="submit">
			<input type="button"
				   name="verify_credentials" id="verify_mailer_credentials_btn" class="button button-secondary"
				   value="<?php echo esc_attr($text); ?>"
				   style="cursor:not-allowed; color: <?php echo $color; ?>; border-color: <?php echo $color; ?>"/>
		</p>

		<script type="application/javascript">
			jQuery(document).ready(function () {

				var checkBtn = jQuery('#verify_mailer_credentials_btn');

				jQuery('#<?php echo self::OPTION_SMTP_HOST; ?>_id,#<?php echo self::OPTION_SMTP_USER; ?>_id,#<?php echo self::OPTION_SMTP_PASSWORD; ?>_id,#<?php echo self::OPTION_SMTP_SECURE; ?>_id')
					.one('input', function () {
						checkBtn.prop('disabled', 'disabled').val('<?php echo esc_attr(__('Save Changes first and verify afterwards', $this->domain)); ?>');
					});

			});
		</script>

		<?php
	}


	protected function printSelectInput($options, $inputName, $class = '', $selectedValue = NULL) {
		?>
		<select name="<?php echo esc_attr($inputName); ?>" class="<?php echo esc_attr($class); ?>">
			<?php
			foreach ($options as $key => $label) {
				?>
				<option
					value="<?php echo esc_attr($key); ?>" <?php if ($key === $selectedValue) echo ' selected '; ?>><?php esc_html_e($label); ?></option>
				<?php
			}
			?>
		</select>
		<?php
	}

	public function verifyCredentials(): bool {

		if ($this->credentialsAreValid === NULL) {

			$mailer = new SmtpMailer([
				'host'     => self::getHost(),
				'username' => self::getUsername(),
				'password' => self::getPassword(),
				'secure'   => self::getSecure(),
				'timeout'  => self::getTimeout()
			]);


			try {
				$this->credentialsAreValid = $mailer->credentialsValid();
			} catch (\Exception $e) {
				$this->credentialsAreValid = FALSE;
			}

		}

		return $this->credentialsAreValid;

	}

	public static function getHost() {
		return get_option(self::OPTION_SMTP_HOST, '');
	}

	public static function getUsername(): string {
		return get_option(self::OPTION_SMTP_USER, '');
	}

	public static function getPassword() {
		return get_option(self::OPTION_SMTP_PASSWORD, '');
	}

	public static function getSecure() {
		return get_option(self::OPTION_SMTP_SECURE, 'ssl');
	}

	public static function getTimeout() {
		return get_option(self::OPTION_SMTP_TIMEOUT, 7);
	}

}
