<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Controller;

use StevenBuehner\sbChurchtoolsGrouphomepage\Vendor\GuzzleHttp\Cookie\CookieJar;
use StevenBuehner\ChurchTools\Configuration;
use StevenBuehner\ChurchToolsApi\ChurchToolsUserAuthenticatedClient;
use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use StevenBuehner\sbChurchtoolsGrouphomepage\Backend\AbstractChurchToolsSettingsController;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\CtNewsletterService;

class NewsletterSettingsController extends AbstractChurchToolsSettingsController {

	const OPTION_CHURCHTOOLS_REGISTRATION_SETTINGS = 'sb_ct_nl_registration_settings';
	const OPTION_USERNAME = 'sb_ct_nl_username';
	const OPTION_PASSWORD = 'sb_ct_nl_password';
	const OPTION_URL      = 'sb_ct_nl_url';


	protected $churchToolsCredentialsAreValid = NULL;

	public function __construct($domain) {
		parent::__construct($domain, $sectionId = 'sb_ct_newsletter_section', $sectionLabel = 'Newsletter');
	}

	public function registerSetting($pageId, $sectionId) {

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

		register_setting($this->getSettingsPageSlug(), self::OPTION_USERNAME);
		add_settings_field(
			self::OPTION_USERNAME,                                                  // id of the settings field
			__('API 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_PASSWORD);
		add_settings_field(
			self::OPTION_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
		);

		add_settings_field(
			'ct_nl_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
		);

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

	}

	public function render_url() {
		$this->renderTextField(self::OPTION_URL);
	}

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

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

	public function render_verify_credentials_btn() {

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

		?>
        <p class="submit">
            <input type="button"
                   name="verify_credentials" id="verify_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_credentials_btn');

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

			});
        </script>

		<?php
	}


	public function render_newsletter_registration_settings() {

		if ($this->verifyCredentials() === FALSE)
			return;


		/** @var CtNewsletterService $newsletterService */
		$newsletterService = MyContainer::getSingleton()['CtNewsletterService'];

		$storedOptions = $newsletterService->getPersonRegistrationSettings();

		$statuses       = $newsletterService->getPersonMasterdataStatuses();
		$statuses       = $this->arrayMapAssoc($statuses, 'getId', 'getName');
		$selectedStatus = $storedOptions['status'];

		$departments        = $newsletterService->getPersonMasterdataDepartmens();
		$departments        = $this->arrayMapAssoc($departments, 'getId', 'getName');
		$selectedDepartment = $storedOptions['department'];

		$campuses       = $newsletterService->getPersonMasterdataCampuses();
		$campuses       = $this->arrayMapAssoc($campuses, 'getId', 'getName');
		$selectedCampus = $storedOptions['campus'];


		?>
        <table>
            <thead>
            </thead>
            <tbody>
            <tr>
                <td colspan="2">
                    <?php
                    _e('Which default settings should be used when creating a new user in ChurchTools? (this is required to enable new persons to register)');
                    ?>
                </td>
            </tr>
            <tr>
                <td style="width: 100px">Status:</td>
                <td>
					<?php $this->printSelectInput($statuses, self::OPTION_CHURCHTOOLS_REGISTRATION_SETTINGS . '[status]', 'select-statuses', $selectedStatus); ?>
                </td>
            </tr>
            <tr>
                <td>Bereich:</td>
                <td>
					<?php $this->printSelectInput($departments, self::OPTION_CHURCHTOOLS_REGISTRATION_SETTINGS . '[department]', 'select-departments', $selectedDepartment); ?>
                </td>
            </tr>
            <tr>
                <td>Station:</td>
                <td>
					<?php $this->printSelectInput($campuses, self::OPTION_CHURCHTOOLS_REGISTRATION_SETTINGS . '[campus]', 'select-campuses', $selectedCampus); ?>
                </td>
            </tr>
            </tbody>
        </table>
		<?php
	}

	protected function arrayMapAssoc(&$array, $keyProp, $valueProp, $asObject = TRUE) {

		$response = [];

		foreach ($array as $key => $value) {

			if ($asObject === TRUE) {
				$response[$value->$keyProp()] = $value->$valueProp();
			} else {
				$response[$value[$keyProp]] = $value[$valueProp];
			}

		}

		return $response;

	}

	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 {

		// cache result
		if (is_null($this->churchToolsCredentialsAreValid)) {

			$url = $this->getApiUrl();
			if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
				return FALSE;
			}

			$username = $this->getUsername();
			$password = $this->getPassword();

			$config = Configuration::getDefaultConfiguration();
			$config->setHost($url);
			$config->setUsername($username);
			$config->setPassword($password);

			$cookieJar = new CookieJar();

			$client = new ChurchToolsUserAuthenticatedClient($config, $cookieJar);

			try {
				$this->churchToolsCredentialsAreValid = $client->login();
				$client->logout();
			} catch (\Exception $e) {
				$this->churchToolsCredentialsAreValid = FALSE;
			}
		}

		return $this->churchToolsCredentialsAreValid;

	}

	public function getUrl() {
		return get_option(self::OPTION_URL, '');
	}

	public function getApiUrl(): string {
		return rtrim($this->getUrl(), '/') . '/api';
	}

	public function getUsername() {
		return get_option(self::OPTION_USERNAME, '');
	}

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

}
