<?php


namespace Fliegerlogin\WpAdmin\Pages;


use Fliegerlogin\Options;
use Fliegerlogin\RequestCounter;

class ConfigurePlugin extends AbstractPage {

	public static function getSlug(): string {
		// Same slug as the parent menu so this submenu replaces the auto-created
		// "Vereinsflieger" duplicate that WordPress would otherwise add.
		return WpVereinsflieger::getSlug();
	}
	public static function getTitle(): string {
		return 'Fliegerlogin - ' . __('Configuration', 'sso-for-vereinsflieger');
	}
	public static function getMenuTitle(): string {
		return __('Configuration', 'sso-for-vereinsflieger');
	}

	public static function setup(): void {
		self::setupMenuItem(self::getTitle(), self::getMenuTitle(), self::getCapability(), self::getSlug());
		add_action('admin_enqueue_scripts', [self::class, 'enqueueAssets']);
	}

	/**
	 * Hides the spinner arrows on the numeric fields. Registered against a
	 * src-less handle: there is no stylesheet to fetch, WordPress only needs
	 * something to attach the inline rule to.
	 */
	public static function enqueueAssets(): void {
		wp_register_style('fliegerlogin-admin', false, [], FLIEGERLOGIN_VERSION);
		wp_enqueue_style('fliegerlogin-admin');
		wp_add_inline_style('fliegerlogin-admin', 'input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}input[type=number]{-moz-appearance:textfield}');
	}

	public function processRequest(): void {
		if (
			!array_key_exists('fliegerlogin_submit', $_POST) ||
			!array_key_exists('fliegerlogin_cid', $_POST) ||
			!array_key_exists('fliegerlogin_appKey', $_POST) ||
			!array_key_exists('fliegerlogin_defaultRole', $_POST)
		) {
			return;
		}

		check_admin_referer('fliegerlogin_save_config', 'fliegerlogin_nonce');

		// Unslash and sanitise once, then validate the clean values.
		$cid         = sanitize_text_field(wp_unslash($_POST['fliegerlogin_cid']));
		$appKey      = sanitize_text_field(wp_unslash($_POST['fliegerlogin_appKey']));
		$defaultRole = sanitize_text_field(wp_unslash($_POST['fliegerlogin_defaultRole']));

		if (
			!is_numeric($cid) ||
			!preg_match('/^[a-z0-9]+$/i', $appKey) ||
			!get_role($defaultRole)
		) {
			$this->addMessage('error', __('Some inputs are incorrect. Please check.', 'sso-for-vereinsflieger'));
			return;
		}

		Options::setCID((int) $cid);
		Options::setAppKey(sanitize_key($appKey));
		Options::setDefaultRole($defaultRole);

		if (array_key_exists('fliegerlogin_allowDefaultLogin', $_POST) && $_POST['fliegerlogin_allowDefaultLogin'] === '1') {
			Options::setAllowDefaultLogin(true);
		} else {
			Options::setAllowDefaultLogin(false);
		}

		$this->addMessage('success',__('Your changes were saved successfully.', 'sso-for-vereinsflieger'));
	}

	private function printRequestCounter(): void {
		$used = RequestCounter::getCount();
		$limit = RequestCounter::DAILY_LIMIT;
		$remaining = RequestCounter::getRemaining();

		$message = sprintf(
			/* translators: 1: used calls, 2: daily limit, 3: remaining calls */
			__('API requests today: %1$d of %2$d (remaining: %3$d). The Vereinsflieger API limits each app key to %2$d requests per day.', 'sso-for-vereinsflieger'),
			$used,
			$limit,
			$remaining
		);

		$class = $remaining <= 0 ? 'notice-error' : ($remaining < 50 ? 'notice-warning' : 'notice-info');
		?>
		<div class="<?php echo esc_attr($class); ?> notice">
			<p><?php echo esc_html($message); ?></p>
		</div>
		<?php
	}

	private function checkConfiguration() {
		if (!Options::setupComplete()) {
			$this->addMessage('error', __('Fliegerlogin is not configured completely.', 'sso-for-vereinsflieger'), false);
		} else {
			$this->addMessage('success', __('Fliegerlogin is configured correctly and ready for work.', 'sso-for-vereinsflieger'), false);
		}
	}

	public function printPage(): void {
		$this->checkConfiguration();
		?>

		<?php $this->printHeader(__('Configuration', 'sso-for-vereinsflieger')); ?>

		<?php $this->printRequestCounter(); ?>

		<?php $this->printMessages(); ?>

		<form action="" method="post">
			<?php wp_nonce_field('fliegerlogin_save_config', 'fliegerlogin_nonce'); ?>
			<table class="form-table">
				<tr>
					<th><?php esc_html_e('CID', 'sso-for-vereinsflieger'); ?></th>
					<td>
						<input class="regular-text" name="fliegerlogin_cid" type="number" value="<?php echo esc_attr(Options::getCID()); ?>">
						<p class="description">
							<?php esc_html_e('Please enter the ID number of your club in this field.', 'sso-for-vereinsflieger'); ?><br>
							<?php echo wp_kses_post(__('This ID can be found in Vereinsflieger at <a href="https://www.vereinsflieger.de/member/admin/community.php">Administration &gt; Verein</a>.', 'sso-for-vereinsflieger')); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e('App Key', 'sso-for-vereinsflieger'); ?></th>
					<td>
						<input class="regular-text" name="fliegerlogin_appKey" type="text" value="<?php echo esc_attr(Options::getAppKey()); ?>">
						<p class="description">
							<?php esc_html_e('The App Key is required to authenticate against the interface of Vereinsflieger.', 'sso-for-vereinsflieger'); ?><br>
							<?php echo wp_kses_post(__('If you don\'t have one you can <a href="https://www.vereinsflieger.de/public/Kontakt.htm" target="_blank">contact the support</a> for one.', 'sso-for-vereinsflieger')); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e('Role for new users', 'sso-for-vereinsflieger'); ?></th>
					<td>
						<select name="fliegerlogin_defaultRole"><?php wp_dropdown_roles( Options::getDefaultRole() ); ?></select>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e('Restriction', 'sso-for-vereinsflieger'); ?></th>
					<td>
						<fieldset>
							<label for="fliegerlogin_allowDefaultLogin">
								<input name="fliegerlogin_allowDefaultLogin" type="checkbox" id="fliegerlogin_allowDefaultLogin" value="1" <?php if (Options::getAllowDefaultLogin()) echo 'checked'; ?>>
								<?php esc_html_e('Allow users linked to Vereinsflieger.de to login with their existing wordpress credentials.', 'sso-for-vereinsflieger'); ?>
							</label>
						</fieldset>
						<p class="description">
							<?php esc_html_e('Caution: When enabling this option, users that left the club might still be able to login to your member area.', 'sso-for-vereinsflieger'); ?>
						</p>
					</td>
				</tr>
			</table>
			<p class="submit">
				<input type="submit" name="fliegerlogin_submit" class="button button-primary" value="<?php esc_html_e('Apply configuration', 'sso-for-vereinsflieger'); ?>">
			</p>
		</form>
		<?php
	}

}
