<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

require_once 'PostmanModuleTransport.php';

/**
 *
 * @author jasonhendriks
 */
class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport implements PostmanZendModuleTransport {
	const SLUG = 'smtp';
	public function __construct( $rootPluginFilenameAndPath ) {
		parent::__construct( $rootPluginFilenameAndPath );

		// add a hook on the plugins_loaded event
		add_action( 'admin_init', array(
				$this,
				'on_admin_init',
		) );
	}

	/**
	 * (non-PHPdoc)
	 *
	 * @see PostmanModuleTransport::createMailEngine()
	 */
	public function createMailEngine() {
		require_once 'PostmanZendMailEngine.php';
		return new PostmanZendMailEngine( $this );
	}

	/**
	 * (non-PHPdoc)
	 *
	 * @see PostmanZendModuleTransport::createZendMailTransport()
	 */
	public function createZendMailTransport( $fakeHostname, $fakeConfig ) {
		if ( PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType() ) {
			$config = PostmanOAuth2ConfigurationFactory::createConfig( $this );
		} else {
			$config = PostmanBasicAuthConfigurationFactory::createConfig( $this );
		}
		return new Postman_Zend_Mail_Transport_Smtp( $this->getHostname(), $config );
	}

	/**
	 * Determines whether Mail Engine locking is needed
	 *
	 * @see PostmanModuleTransport::requiresLocking()
	 */
	public function isLockingRequired() {
		return PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType();
	}
	public function getSlug() {
		return self::SLUG;
	}
	public function getName() {
		return 'Other SMTP';
	}
	public function getHostname() {
		$this->options = $this->options;
		return $this->options->getHostname();
	}
	public function getPort() {
		$this->options = $this->options;
		return $this->options->getPort();
	}
	public function getAuthenticationType() {
		return $this->options->getAuthenticationType();
	}
	public function getCredentialsId() {
		$this->options = $this->options;
		if ( $this->options->isAuthTypeOAuth2() ) {
			return $this->options->getClientId();
		} else {
			return $this->options->getUsername();
		}
	}
	public function getCredentialsSecret() {
		$this->options = $this->options;
		if ( $this->options->isAuthTypeOAuth2() ) {
			return $this->options->getClientSecret();
		} else {
			return $this->options->getPassword();
		}
	}

	/**
	 * (non-PHPdoc)
	 *
	 * @see PostmanTransport::getMisconfigurationMessage()
	 */
	protected function validateTransportConfiguration() {
		$messages = parent::validateTransportConfiguration();
		if ( ! $this->isHostConfigured( $this->options ) ) {
			array_push( $messages, __( 'Outgoing Mail Server Hostname and Port can not be empty.', 'post-smtp' ) );
			$this->setNotConfiguredAndReady();
		}
		if ( ! $this->isEnvelopeFromConfigured() ) {
			array_push( $messages, __( 'Envelope-From Email Address can not be empty', 'post-smtp' ) . '.' );
			$this->setNotConfiguredAndReady();
		}
		if ( $this->options->isAuthTypePassword() && ! $this->isPasswordAuthenticationConfigured( $this->options ) ) {
			array_push( $messages, __( 'Username and password can not be empty.', 'post-smtp' ) );
			$this->setNotConfiguredAndReady();
		}
		if ( $this->getAuthenticationType() == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ) {
			if ( ! $this->isOAuth2SupportedHostConfigured() ) {
				/* translators: %1$s is the Client ID label, and %2$s is the Client Secret label (e.g. Warning: OAuth 2.0 authentication requires an OAuth 2.0-capable Outgoing Mail Server, Sender Email Address, Client ID, and Client Secret.) */
				array_push( $messages, sprintf( __( 'OAuth 2.0 authentication requires a supported OAuth 2.0-capable Outgoing Mail Server.', 'post-smtp' ) ) );
				$this->setNotConfiguredAndReady();
			}
		}
		if ( empty( $messages ) ) {
			$this->setReadyForOAuthGrant();
			if ( $this->isPermissionNeeded( $this->options, $this->getOAuthToken() ) ) {
				/* translators: %1$s is the Client ID label, and %2$s is the Client Secret label */
				$message = sprintf( __( 'You have configured OAuth 2.0 authentication, but have not received permission to use it.', 'post-smtp' ), $this->getScribe()->getClientIdLabel(), $this->getScribe()->getClientSecretLabel() );
				$message .= sprintf( ' <a href="%s">%s</a>.', PostmanUtils::getGrantOAuthPermissionUrl(), $this->getScribe()->getRequestPermissionLinkText() );
				array_push( $messages, $message );
				$this->setNotConfiguredAndReady();
			}
		}
		return $messages;
	}

	/**
	 *
	 * @return boolean
	 */
	private function isOAuth2SupportedHostConfigured() {
		$options = PostmanOptions::getInstance();
		$hostname = $options->getHostname();
		$supportedOAuthProvider = $this->isServiceProviderGoogle( $hostname ) || $this->isServiceProviderMicrosoft( $hostname ) || $this->isServiceProviderYahoo( $hostname );
		return $supportedOAuthProvider;
	}

	/**
	 * Given a hostname, what ports should we test?
	 *
	 * May return an array of several combinations.
	 */
	public function getSocketsForSetupWizardToProbe( $hostname, $smtpServerGuess ) {
		$hosts = array(
				$this->createSocketDefinition( $hostname, 25 ),
				$this->createSocketDefinition( $hostname, 465 ),
				$this->createSocketDefinition( $hostname, 587 ),
		);

		return $hosts;
	}

	/**
	 * Creates a single socket for the Wizard to test
	 */
	protected function createSocketDefinition( $hostname, $port ) {
		$socket = parent::createSocketDefinition( $hostname, $port );
		$socket ['smtp'] = true;
		return $socket;
	}

	/**
	 * SendGrid will never recommend it's configuration
	 *
	 * @param mixed $hostData
	 */
	public function getConfigurationBid( PostmanWizardSocket $hostData, $userAuthOverride, $originalSmtpServer ) {
		$port = $hostData->port;
		$hostname = $hostData->hostname;
		// because some servers, like smtp.broadband.rogers.com, report XOAUTH2 but have no OAuth2 front-end
		$supportedOAuth2Provider = $this->isServiceProviderGoogle( $hostname ) || $this->isServiceProviderMicrosoft( $hostname ) || $this->isServiceProviderYahoo( $hostname );
		$score = 1;
		$recommendation = array();
		// increment score for auth type
		if ( $hostData->mitm ) {
			$this->logger->debug( 'Losing points for MITM' );
			$score -= 10000;
			$recommendation ['mitm'] = true;
		}
		if ( ! empty( $originalSmtpServer ) && $hostname != $originalSmtpServer ) {
			$this->logger->debug( 'Losing points for Not The Original SMTP server' );
			$score -= 10000;
		}
		$secure = true;
		if ( $hostData->startTls ) {
			// STARTTLS was formalized in 2002
			// http://www.rfc-editor.org/rfc/rfc3207.txt
			$recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_STARTTLS;
			$score += 30000;
		} elseif ( $hostData->protocol == 'SMTPS' ) {
			// "The hopelessly confusing and imprecise term, SSL,
			// has often been used to indicate the SMTPS wrapper and
			// TLS to indicate the STARTTLS protocol extension."
			// http://stackoverflow.com/a/19942206/4368109
			$recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_SMTPS;
			$score += 28000;
		} elseif ( $hostData->protocol == 'SMTP' ) {
			$recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_NONE;
			$score += 26000;
			$secure = false;
		}

		// if there is a way to send mail....
		if ( $score > 10 ) {

			// determine the authentication type
			if ( $hostData->auth_xoauth && $supportedOAuth2Provider && (empty( $userAuthOverride ) || $userAuthOverride == 'oauth2') ) {
				$recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_OAUTH2;
				$recommendation ['display_auth'] = 'oauth2';
				$score += 500;
				if ( ! $secure ) {
					$this->logger->debug( 'Losing points for sending credentials in the clear' );
					$score -= 10000;
				}
			} elseif ( $hostData->auth_crammd5 && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) {
				$recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5;
				$recommendation ['display_auth'] = 'password';
				$score += 400;
				if ( ! $secure ) {
					$this->logger->debug( 'Losing points for sending credentials in the clear' );
					$score -= 10000;
				}
			} elseif ( $hostData->authPlain && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) {
				$recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_PLAIN;
				$recommendation ['display_auth'] = 'password';
				$score += 300;
				if ( ! $secure ) {
					$this->logger->debug( 'Losing points for sending credentials in the clear' );
					$score -= 10000;
				}
			} elseif ( $hostData->auth_login && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) {
				$recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_LOGIN;
				$recommendation ['display_auth'] = 'password';
				$score += 200;
				if ( ! $secure ) {
					$this->logger->debug( 'Losing points for sending credentials in the clear' );
					$score -= 10000;
				}
			} else if ( empty( $userAuthOverride ) || $userAuthOverride == 'none' ) {
				$recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_NONE;
				$recommendation ['display_auth'] = 'none';
				$score += 100;
			}

			// tiny weighting to prejudice the port selection, all things being equal
			if ( $port == 587 ) {
				$score += 4;
			} elseif ( $port == 25 ) {
				// "due to the prevalence of machines that have worms,
				// viruses, or other malicious software that generate large amounts of
				// spam, many sites now prohibit outbound traffic on the standard SMTP
				// port (port 25), funneling all mail submissions through submission
				// servers."
				// http://www.rfc-editor.org/rfc/rfc6409.txt
				$score += 3;
			} elseif ( $port == 465 ) {
				// use of port 465 for SMTP was deprecated in 1998
				// http://www.imc.org/ietf-apps-tls/mail-archive/msg00204.html
				$score += 2;
			} else {
				$score += 1;
			}

			// create the recommendation message for the user
			// this can only be set if there is a valid ['auth'] and ['enc']
			$transportDescription = $this->getTransportDescription( $recommendation ['enc'] );
			$authDesc = $this->getAuthenticationDescription( $recommendation ['auth'] );
			$recommendation ['label'] = sprintf( 'SMTP - %2$s:%3$d', $transportDescription, $hostData->hostnameDomainOnly, $port );
			/* translators: where %1$s is a description of the transport (eg. SMTPS-SSL), %2$s is a description of the authentication (eg. Password-CRAMMD5), %3$d is the TCP port (eg. 465), %4$d is the hostname */
			$recommendation ['message'] = sprintf( __( 'Postman recommends %1$s with %2$s authentication to host %4$s on port %3$d.', 'post-smtp' ), $transportDescription, $authDesc, $port, $hostname );
		}

		// fill-in the rest of the recommendation
		$recommendation ['transport'] = PostmanSmtpModuleTransport::SLUG;
		$recommendation ['priority'] = $score;
		$recommendation ['port'] = $port;
		$recommendation ['hostname'] = $hostname;
		$recommendation ['transport'] = self::SLUG;
		$recommendation['logo_url'] = $this->getLogoURL();

		return $recommendation;
	}

	/**
	 * Functions to execute on the admin_init event
	 *
	 * "Runs at the beginning of every admin page before the page is rendered."
	 * ref: http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request
	 */
	public function on_admin_init() {
		// only administrators should be able to trigger this
		if ( PostmanUtils::isAdmin() ) {
			$this->addSettings();
			$this->registerStylesAndScripts();
		}
	}

	/**
	 */
	public function registerStylesAndScripts() {
		// register the stylesheet and javascript external resources
		$pluginData = apply_filters( 'postman_get_plugin_metadata', null );
		wp_register_script( 'postman_smtp_script', plugins_url( 'Postman/Postman-Mail/postman_smtp.js', $this->rootPluginFilenameAndPath ), array(
				PostmanViewController::JQUERY_SCRIPT,
				'jquery_validation',
				PostmanViewController::POSTMAN_SCRIPT,
		), $pluginData ['version'] );
	}

	/*
	 * What follows in the code responsible for creating the Admin Settings page
	 */

	/**
	 */
	public function enqueueScript() {
		wp_enqueue_script( 'postman_smtp_script' );
	}

	/**
	 */
	public function addSettings() {
		$transport = $this;
		$this->options = $this->options;
		$oauthScribe = $transport->getScribe();
		$gmail_oneclick_enabled = in_array( 'gmail-oneclick', get_option( 'post_smtp_pro', [] )['extensions'] ?? [] );
		// Sanitize
		add_settings_section( PostmanAdminController::SMTP_SECTION, __( 'Transport Settings', 'post-smtp' ), array(
				$this,
				'printSmtpSectionInfo',
		), PostmanAdminController::SMTP_OPTIONS );

		add_settings_field( PostmanOptions::HOSTNAME, __( 'Outgoing Mail Server Hostname', 'post-smtp' ), array(
				$this,
				'hostname_callback',
		), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION );

		add_settings_field( PostmanOptions::PORT, __( 'Outgoing Mail Server Port', 'post-smtp' ), array(
				$this,
				'port_callback',
		), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION );

		add_settings_field( PostmanOptions::ENVELOPE_SENDER, __( 'Envelope-From Email Address', 'post-smtp' ), array(
				$this,
				'sender_email_callback',
		), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION );

		add_settings_field( PostmanOptions::SECURITY_TYPE, _x( 'Security', 'Configuration Input Field', 'post-smtp' ), array(
				$this,
				'encryption_type_callback',
		), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION );

		add_settings_field( PostmanOptions::AUTHENTICATION_TYPE, __( 'Authentication', 'post-smtp' ), array(
				$this,
				'authentication_type_callback',
		), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION );

		add_settings_section( PostmanAdminController::BASIC_AUTH_SECTION, __( 'Authentication', 'post-smtp' ), array(
				$this,
				'printBasicAuthSectionInfo',
		), PostmanAdminController::BASIC_AUTH_OPTIONS );

		add_settings_field( PostmanOptions::BASIC_AUTH_USERNAME, __( 'Username', 'post-smtp' ), array(
				$this,
				'basic_auth_username_callback',
		), PostmanAdminController::BASIC_AUTH_OPTIONS, PostmanAdminController::BASIC_AUTH_SECTION );

		add_settings_field( PostmanOptions::BASIC_AUTH_PASSWORD, __( 'Password', 'post-smtp' ), array(
				$this,
				'basic_auth_password_callback',
		), PostmanAdminController::BASIC_AUTH_OPTIONS, PostmanAdminController::BASIC_AUTH_SECTION );

		// the OAuth section
		add_settings_section( PostmanAdminController::OAUTH_SECTION, __( 'Authentication', 'post-smtp' ), array(
				$this,
				'printOAuthSectionInfo',
		), PostmanAdminController::OAUTH_AUTH_OPTIONS );

		add_settings_field(
			'enable_gmail_oneclick',
			__( 'Enable One-Click Setup '.(post_smtp_has_pro() ? '': '<span class="ps-wizard-pro-tag">PRO</span>').'', 'post-smtp' ),
			array( $this, 'renderGmailOneClickSwitch' ),
			PostmanAdminController::OAUTH_AUTH_OPTIONS,
			PostmanAdminController::OAUTH_SECTION
		);

		add_settings_field( 'callback_domain', sprintf( '<span id="callback_domain">%s</span>', $oauthScribe->getCallbackDomainLabel() ), array(
				$this,
				'callback_domain_callback',
		), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION );

		add_settings_field( 'redirect_url', sprintf( '<span id="redirect_url">%s</span>', $oauthScribe->getCallbackUrlLabel() ), array(
				$this,
				'redirect_url_callback',
		), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION );

		add_settings_field( PostmanOptions::CLIENT_ID, $oauthScribe->getClientIdLabel(), array(
				$this,
				'oauth_client_id_callback',
		), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION );

		add_settings_field( PostmanOptions::CLIENT_SECRET, $oauthScribe->getClientSecretLabel(), array(
				$this,
				'oauth_client_secret_callback',
		), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION );
		
		$hide_style = $gmail_oneclick_enabled ? '' : 'style="display:none;"'; 
		add_settings_field(
			'gmail_auth_buttons',
			'<span class="ps-disable-gmail-setup" '.  $hide_style .'  >' . __( 'Gmail Authorization', 'post-smtp' ) . '</span>',
			array( $this, 'renderGmailAuthButtons' ),
			PostmanAdminController::OAUTH_AUTH_OPTIONS,
			PostmanAdminController::OAUTH_SECTION
		);
	}

	/**
	 * Print the Section text
	 */
	public function printSmtpSectionInfo() {
		print __( 'Configure the communication with the mail server.', 'post-smtp' );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function hostname_callback() {
		printf( '<input type="text" id="input_hostname" name="postman_options[hostname]" value="%s" size="40" class="required" placeholder="%s"/>', null !== $this->options->getHostname() ? esc_attr( $this->options->getHostname() ) : '', __( 'Required', 'post-smtp' ) );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function port_callback( $args ) {
		printf( '<input type="text" id="input_port" name="postman_options[port]" value="%s" %s placeholder="%s"/>', null !== $this->options->getPort() ? esc_attr( $this->options->getPort() ) : '', isset( $args ['style'] ) ? $args ['style'] : '', __( 'Required', 'post-smtp' ) );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function encryption_type_callback() {
		$encType = $this->options->getEncryptionType();
		print '<select id="input_enc_type" class="input_encryption_type" name="postman_options[enc_type]">';
		printf( '<option class="input_enc_type_none" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_NONE, $encType == PostmanOptions::SECURITY_TYPE_NONE ? 'selected="selected"' : '', __( 'None', 'post-smtp' ) );
		printf( '<option class="input_enc_type_ssl" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_SMTPS, $encType == PostmanOptions::SECURITY_TYPE_SMTPS ? 'selected="selected"' : '', 'SMTPS' );
		printf( '<option class="input_enc_type_tls" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_STARTTLS, $encType == PostmanOptions::SECURITY_TYPE_STARTTLS ? 'selected="selected"' : '', 'STARTTLS' );
		print '</select>';
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function authentication_type_callback() {
		$authType = $this->options->getAuthenticationType();
		printf( '<select id="input_%2$s" class="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE );
		printf( '<option class="input_auth_type_none" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_NONE, $authType == PostmanOptions::AUTHENTICATION_TYPE_NONE ? 'selected="selected"' : '', 'None' );
		printf( '<option class="input_auth_type_plain" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_PLAIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_PLAIN ? 'selected="selected"' : '', 'Plain' );
		printf( '<option class="input_auth_type_login" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_LOGIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_LOGIN ? 'selected="selected"' : '', 'Login' );
		printf( '<option class="input_auth_type_crammd5" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5, $authType == PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5 ? 'selected="selected"' : '', 'CRAM-MD5' );
		printf( '<option class="input_auth_type_oauth2" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_OAUTH2, $authType == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ? 'selected="selected"' : '', 'OAuth 2.0' );
		print '</select>';
	}

	/**
	 * Print the Section text
	 */
	public function printBasicAuthSectionInfo() {
		print __( 'Enter the account credentials.', 'post-smtp' );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function basic_auth_username_callback() {
		$inputValue = (null !== $this->options->getUsername() ? esc_attr( $this->options->getUsername() ) : '');
		$inputDescription = __( 'The Username is usually the same as the Envelope-From Email Address.', 'post-smtp' );
		print ('<input tabindex="99" id="fake_user_name" name="fake_user[name]" style="position:absolute; top:-500px;" type="text" value="Safari Autofill Me">') ;
		printf( '<input type="text" id="input_basic_auth_username" name="postman_options[basic_auth_username]" value="%s" size="40" class="required ps-w-75" placeholder="%s"/><br/><span class="postman_input_description ps-input ps-w-75">%s</span>', $inputValue, __( 'Required', 'post-smtp' ), $inputDescription );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function basic_auth_password_callback() {
		printf(
			'<input type="password" id="input_basic_auth_password" 
				name="postman_options[basic_auth_password]" 
				value="%s" size="40" 
				class="required ps-w-75" 
				placeholder="%s" 
				autocomplete="new-password"/>',
			null !== $this->options->getPassword() ? esc_attr( PostmanUtils::obfuscatePassword( $this->options->getPassword() ) ) : '',
			__( 'Required', 'post-smtp' )
		);
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function oauth_client_id_callback() {
		printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" id="oauth_client_id" name="postman_options[oauth_client_id]" value="%s" size="60" class="required ps-w-75" placeholder="%s"/>', null !== $this->options->getClientId() ? esc_attr( $this->options->getClientId() ) : '', __( 'Required', 'post-smtp' ) );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function oauth_client_secret_callback() {
		printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" autocomplete="off" id="oauth_client_secret" name="postman_options[oauth_client_secret]" value="%s" size="60" class="required ps-w-75" placeholder="%s"/>', null !== $this->options->getClientSecret() ? esc_attr( $this->options->getClientSecret() ) : '', __( 'Required', 'post-smtp' ) );
	}

	/**
	 * Render the Gmail One-Click Setup switch.
	 *
	 * Displays a toggle switch for enabling or disabling the Gmail One-Click Setup feature.
	 *
	 * @since 3.1.0
	 */
	public function renderGmailOneClickSwitch() {
		$url = POST_SMTP_URL . '/Postman/Wizard/assets/images/wizard-google.png';
		$data = array(
			'transport_name' => '<strong>1-Click</strong> Google Mailer Setup?',
			'product_url'    => 'https://postmansmtp.com/pricing/?utm_source=plugin&utm_medium=wizard_gmail_one_click&utm_campaign=plugin',
		);
		$json_data   = htmlspecialchars( json_encode( $data ), ENT_QUOTES, 'UTF-8' );
		$post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
		$bonus_extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : array();
    	$gmail_oneclick_enabled = in_array( 'gmail-oneclick', $bonus_extensions );
		$is_checked  = $gmail_oneclick_enabled ? 'checked' : '';
		$is_disabled = ! post_smtp_has_pro() ? 'disabled' : '';
		$class       = 'ps-enable-gmail-one-click ' . ( ! post_smtp_has_pro() ? ' disabled' : '' );
		
		// Add popup trigger file
		require_once POST_SMTP_PATH. '/Postman/Popup/popup.php';
		
		echo '<div class="ps-form-switch-control">
			<label class="ps-switch-1 '.(!post_smtp_has_pro() ? 'ps-gmail-one-click' : '').'">
				<input type="hidden" id="ps-one-click-data" value="' . esc_attr( $json_data ) . '">
				<input type="checkbox" class="' . esc_attr( $class ) . '" name="enable_gmail_oneclick" ' . $is_checked .'>
				<span class="slider round"></span>
			</label> 
			'.esc_html__('Enable the option for a quick, easy way to connect to Google Workspace (Gmail) API without manually creating an app.', 'post-smtp').'
		</div>';
	}

	/**
	 * Render Gmail OAuth buttons.
	 *
	 * Displays buttons to connect to or disconnect from Gmail using OAuth authentication.
	 *
	 * @since 3.1.0
	 */
	public function renderGmailAuthButtons() {
		// Action URLs for buttons.
		$nonce               = wp_create_nonce( 'remove_oauth_action' );
		$postman_auth_token  = get_option( 'postman_auth_token' );

		// Try to obtain a fresh Gmail OAuth URL (with a fresh nonce) at runtime.
		$auth_url = '';
		if ( function_exists( 'post_smtp_get_gmail_auth_url' ) ) {
			$auth_url = post_smtp_get_gmail_auth_url();
		}

		// Fallback to the stored option if the runtime fetch failed.
		if ( empty( $auth_url ) ) {
			$auth_url = get_option( 'post_smtp_gmail_auth_url' );
		}

		$post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
		$bonus_extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : array();
		$gmail_oneclick_enabled = in_array( 'gmail-oneclick', $bonus_extensions );
		$remove_auth_url     = esc_url( add_query_arg(
			array(
				'_wpnonce' => $nonce,
				'action'   => 'remove_oauth_action',
			),
			admin_url( 'admin-post.php' )
		) );

		// Determine whether to hide the entire Gmail auth section
		$hide_style = $gmail_oneclick_enabled ? '' : 'style="display:none;"';
		
		$helping_text =  "<p>Before proceeding, you’ll need to authorize this plugin to send emails using the Gmail API. This <a href=\"https://postmansmtp.com/docs/mailers/google-workspace-gmail-one-click-setup/\" target='_blank'>step-by-step guide</a> will walk you through the entire process.</p>";

		echo '<div id="ps-gmail-auth-buttons" ' . $hide_style . '>';

		if ( ! empty( $postman_auth_token ) && isset( $postman_auth_token['user_email'] ) ) {
			// Show the "Remove Authorization" button if token exists
			echo '<a href="' . esc_url( $remove_auth_url ) . '" class="button button-secondary ps-remove-gmail-btn ps-disable-gmail-setup">';
			echo esc_html__( 'Remove Authorization', 'post-smtp' );
			echo '</a>';

			// Show connected email
			if ( isset( $postman_auth_token['user_email'] ) ) {
				echo '<b class="ps-connect-with ps-disable-gmail-setup" style="position: relative; top: 10px;">' .
					 sprintf( esc_html__( 'Connected with: %s', 'post-smtp' ), esc_html( $postman_auth_token['user_email'] ) ) .
					 '</b>';
			}
		} else {
			// Show the "Sign in with Google" button
			echo '<a href="' . esc_url( $auth_url ) . '" class="button button-primary ps-gmail-btn" id="ps-wizard-connect-gmail">';
			echo esc_html__( 'Sign in with Google', 'post-smtp' );
			echo '</a>';
			echo $helping_text;
		}

		echo '</div>';


	}
	

	/**
	 * Print the Section text
	 */
	public function printOAuthSectionInfo() {
		$this->options = $this->options;
		$transport = $this;
		$oauthScribe = $transport->getScribe();
		printf( '<p id="wizard_oauth2_help">%s</p>', $oauthScribe->getOAuthHelp() );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function callback_domain_callback() {
		printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" class="ps-input ps-w-75" id="input_oauth_callback_domain" value="%s" size="60"/>', $this->getCallbackDomain() );
	}

	/**
	 */
	private function getCallbackDomain() {
		try {
			$this->options = $this->options;
			$transport = $this;
			$oauthScribe = $transport->getScribe();
			return $oauthScribe->getCallbackDomain();
		} catch ( Exception $e ) {
			return __( 'Error computing your domain root - please enter it manually', 'post-smtp' );
		}
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function redirect_url_callback() {
		$this->options = $this->options;
		$transport = $this;
		$oauthScribe = $transport->getScribe();
		printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" id="input_oauth_redirect_url" class="ps-input ps-w-75" value="%s" size="60"/>', $oauthScribe->getCallbackUrl() );
	}

	/**
	 * Get the settings option array and print one of its values
	 */
	public function sender_email_callback() {
		$inputValue = (null !== $this->options->getEnvelopeSender() ? esc_attr( $this->options->getEnvelopeSender() ) : '');
		$requiredLabel = __( 'Required', 'post-smtp' );
		$envelopeFromMessage = __( 'This address, like the <b>return address</b> printed on an envelope, identifies the account owner to the SMTP server.', 'post-smtp' );
		$spfMessage = sprintf( __( 'For reliable delivery, this domain must specify an <a target="_blank" href="%s">SPF record</a> permitting the use of the SMTP server named above.', 'post-smtp' ), 'https://www.mail-tester.com/spf/' );
		printf( '<input type="email" id="input_envelope_sender_email" name="postman_options[envelope_sender]" value="%s" size="40" class="required" placeholder="%s"/> <br/><span class="postman_input_description">%s %s</span>', $inputValue, $requiredLabel, $envelopeFromMessage, $spfMessage );
	}

	/**
	 */
	public function printWizardMailServerHostnameStep() {
		printf( '<legend>%s</legend>', _x( 'Which host will relay the mail?', 'Wizard Step Title', 'post-smtp' ) );
		printf( '<p><label>%s</label></p>', __( 'If you want to use SendinBlue, Mandrill, Mailgun, SendGrid or other (API), You can skip this step by pressing next.', 'post-smtp' ) );
		printf( '<p>%s</p>', __( 'This is the Outgoing (SMTP) Mail Server, or Mail Submission Agent (MSA), which Postman delegates mail delivery to. This server is specific to your email account, and if you don\'t know what to use, ask your email service provider.', 'post-smtp' ) );
		printf( '<p><label>%s<label></p>', __( 'Note that many WordPress hosts, such as GoDaddy, Bluehost and Dreamhost, require that you use their mail accounts with their mail servers, and prevent you from using others.', 'post-smtp' ) );

		//printf( '<div><strong><u>%s</u></strong></div><br>', __( 'If you plan to use An API and not SMTP just type any value.', 'post-smtp' ) );
		printf( '<label for="hostname">%s</label>', __( 'Outgoing Mail Server Hostname', 'post-smtp' ) );
		print $this->hostname_callback();
		printf( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url( 'post-smtp/style/ajax-loader.gif' ) );
		$warning = __( 'Warning', 'post-smtp' );
		/* Translators: Where (%s) is the name of the web host */
		$nonGodaddyDomainMessage = sprintf( __( 'Your email address <b>requires</b> access to a remote SMTP server blocked by %s.', 'post-smtp' ), 'GoDaddy' );
		$nonGodaddyDomainMessage .= sprintf( ' %s', __( 'If you have access to cPanel, enable the Remote Mail Exchanger.', 'post-smtp' ) );
		printf( '<p id="godaddy_block"><span style="background-color:yellow"><b>%s</b>: %s</span></p>', $warning, $nonGodaddyDomainMessage );
		/* Translators: Where (%1$s) is the SPF-info URL and (%2$s) is the name of the web host */
		$godaddyCustomDomainMessage = sprintf( __( 'If you own this domain, make sure it has an <a href="%1$s">SPF record authorizing %2$s</a> as a relay, or you will have delivery problems.', 'post-smtp' ), 'http://www.mail-tester.com/spf/godaddy', 'GoDaddy' );
		$godaddy_note = __( 'Note: You may have delivery problems if you continue using the default outgoing mail server hostname.', 'post-smtp' );
		printf( '<div id="godaddy_spf_required"><p><span style="background-color:yellow"><b>%s</b>: %s</span></p><p class="ps-default-host-name"><label>%s<label></p></div>', $warning, $godaddyCustomDomainMessage, $godaddy_note );
	}

	/**
	 */
	public function printWizardAuthenticationStep() {
		print '<section class="wizard-auth-oauth2">';
		print '<p id="wizard_oauth2_help"></p>';
		printf( '<label id="callback_domain" for="callback_domain">%s</label>', $this->getScribe()->getCallbackDomainLabel() );
		print '<br />';
		print $this->callback_domain_callback();
		print '<br />';
		printf( '<label id="redirect_url" for="redirect_uri">%s</label>', $this->getScribe()->getCallbackUrlLabel() );
		print '<br />';
		print $this->redirect_url_callback();
		print '<br />';
		printf( '<label id="client_id" for="client_id">%s</label>', $this->getScribe()->getClientIdLabel() );
		print '<br />';
		print $this->oauth_client_id_callback();
		print '<br />';
		printf( '<label id="client_secret" for="client_secret">%s</label>', $this->getScribe()->getClientSecretLabel() );
		print '<br />';
		print $this->oauth_client_secret_callback();
		print '<br />';
		print '</section>';

		print '<section class="wizard-auth-basic">';
		printf( '<p class="port-explanation-ssl">%s</p>', __( 'Enter the account credentials.', 'post-smtp' ) );
		printf( '<label for="username">%s</label>', __( 'Username', 'post-smtp' ) );
		print '<br />';
		print $this->basic_auth_username_callback();
		print '<br />';
		printf( '<label for="password">%s</label>', __( 'Password', 'post-smtp' ) );
		print '<br />';
		print $this->basic_auth_password_callback();
		print '</section>';
	}

	/**
	 * Returns true, to prevent from errors because it's default Module Transport.
	 * 
	 * @since 2.1.4
	 * @version 1.0
	 */
	public function has_granted() {

		return true;

	}

	/**
	 * Get Socket's logo
	 * 
	 * @since 2.1
	 * @version 1.0
	 */
	public function getLogoURL() {

		return POST_SMTP_ASSETS . "images/logos/smtp.png";

	}
}
