<?php

namespace WPMailSMTP\Admin\Pages;

use WPMailSMTP\Debug;
use WPMailSMTP\MailCatcher;
use WPMailSMTP\Options;
use WPMailSMTP\WP;
use WPMailSMTP\Admin\PageAbstract;

/**
 * Class Test is part of Area, displays email testing page of the plugin.
 *
 * @since 1.0.0
 */
class Test extends PageAbstract {

	/**
	 * @var string Slug of a tab.
	 */
	protected $slug = 'test';

	/**
	 * @inheritdoc
	 */
	public function get_label() {
		return esc_html__( 'Email Test', 'wp-mail-smtp' );
	}

	/**
	 * @inheritdoc
	 */
	public function get_title() {
		return $this->get_label();
	}

	/**
	 * @inheritdoc
	 */
	public function display() {
		?>

		<form method="POST" action="">
			<?php $this->wp_nonce_field(); ?>

			<!-- Test Email Section Title -->
			<div class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-content wp-mail-smtp-clear section-heading no-desc" id="wp-mail-smtp-setting-row-email-heading">
				<div class="wp-mail-smtp-setting-field">
					<h2><?php esc_html_e( 'Send a Test Email', 'wp-mail-smtp' ); ?></h2>
				</div>
			</div>

			<!-- Test Email -->
			<div id="wp-mail-smtp-setting-row-test_email" class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-email wp-mail-smtp-clear">
				<div class="wp-mail-smtp-setting-label">
					<label for="wp-mail-smtp-setting-test_email"><?php esc_html_e( 'Send To', 'wp-mail-smtp' ); ?></label>
				</div>
				<div class="wp-mail-smtp-setting-field">
					<input name="wp-mail-smtp[test_email]" type="email" id="wp-mail-smtp-setting-test_email" spellcheck="false" required />
					<p class="desc">
						<?php esc_html_e( 'Type an email address here and then click a button below to generate a test email.', 'wp-mail-smtp' ); ?>
					</p>
				</div>
			</div>

			<p class="wp-mail-smtp-submit">
				<button type="submit" class="wp-mail-smtp-btn wp-mail-smtp-btn-md wp-mail-smtp-btn-orange"><?php esc_html_e( 'Send Email', 'wp-mail-smtp' ); ?></button>
			</p>
		</form>

		<?php
	}

	/**
	 * @inheritdoc
	 */
	public function process_post( $data ) {

		$this->check_admin_referer();

		if ( isset( $data['test_email'] ) ) {
			$data['test_email'] = filter_var( $data['test_email'], FILTER_VALIDATE_EMAIL );
		}

		if ( empty( $data['test_email'] ) ) {
			WP::add_admin_notice(
				esc_html__( 'Test failed. Please use a valid email address and try to resend the test email.', 'wp-mail-smtp' ),
				WP::ADMIN_NOTICE_WARNING
			);
			return;
		}

		global $phpmailer;

		// Make sure the PHPMailer class has been instantiated.
		if ( ! is_object( $phpmailer ) || ! is_a( $phpmailer, 'PHPMailer' ) ) {
			require_once ABSPATH . WPINC . '/class-phpmailer.php';
			$phpmailer = new MailCatcher( true );
		}

		// Set SMTPDebug level, default is 3 (commands + data + connection status).
		$phpmailer->SMTPDebug = apply_filters( 'wp_mail_smtp_admin_test_email_smtp_debug', 3 );

		// Start output buffering to grab smtp debugging output.
		ob_start();

		// Send the test mail.
		$result = wp_mail(
			$data['test_email'],
			/* translators: %s - email address a test email will be sent to. */
			'WP Mail SMTP: ' . sprintf( esc_html__( 'Test email to %s', 'wp-mail-smtp' ), $data['test_email'] ),
			sprintf(
				/* translators: %s - mailer name. */
				esc_html__( 'This email was sent by %s mailer, and generated by the WP Mail SMTP WordPress plugin.', 'wp-mail-smtp' ),
				wp_mail_smtp()->get_providers()->get_options( Options::init()->get( 'mail', 'mailer' ) )->get_title()
			)
		);

		// Grab the smtp debugging output.
		$smtp_debug = ob_get_clean();

		/*
		 * Notify a user about the results.
		 */
		if ( $result ) {
			WP::add_admin_notice(
				esc_html__( 'Your email was sent successfully!', 'wp-mail-smtp' ),
				WP::ADMIN_NOTICE_SUCCESS
			);
		} else {
			$error = $this->get_debug_messages( $phpmailer, $smtp_debug );

			WP::add_admin_notice(
				'<p><strong>' . esc_html__( 'There was a problem while sending a test email. Related debugging output is shown below:', 'wp-mail-smtp' ) . '</strong></p>' .
				'<blockquote style="border-left:1px solid orange;padding-left:10px">' . $error . '</blockquote>' .
				'<p class="description">' . esc_html__( 'Please copy only the content of the error debug message above, identified with an orange left border, into the support forum topic if you experience any issues.', 'wp-mail-smtp' ) . '</p>',
				WP::ADMIN_NOTICE_ERROR
			);
		}
	}

	/**
	 * Prepare debug information, that will help users to identify the error.
	 *
	 * @since 1.0.0
	 *
	 * @param MailCatcher $phpmailer
	 * @param string $smtp_debug
	 *
	 * @return string
	 */
	protected function get_debug_messages( $phpmailer, $smtp_debug ) {

		$options = new Options();

		/*
		 * Versions Debug.
		 */

		$versions_text = '<strong>Versions:</strong><br>';

		$versions_text .= '<strong>WordPress:</strong> ' . get_bloginfo( 'version' ) . '<br>';
		$versions_text .= '<strong>WordPress MS:</strong> ' . ( is_multisite() ? 'Yes' : 'No' ) . '<br>';
		$versions_text .= '<strong>PHP:</strong> ' . PHP_VERSION . '<br>';
		$versions_text .= '<strong>WP Mail SMTP:</strong> ' . WPMS_PLUGIN_VER . '<br>';

		/*
		 * Mailer Debug.
		 */

		$mailer_text = '<strong>Params:</strong><br>';

		$mailer_text .= '<strong>Mailer:</strong> ' . $options->get( 'mail', 'mailer' ) . '<br>';
		$mailer_text .= '<strong>Constants:</strong> ' . ( $options->is_const_enabled() ? 'Yes' : 'No' ) . '<br>';

		// Display different debug info based on the mailer.
		$mailer = wp_mail_smtp()->get_providers()->get_mailer( $options->get( 'mail', 'mailer' ), $phpmailer );

		if ( $mailer ) {
			$mailer_text .= $mailer->get_debug_info();
		}

		/*
		 * General Debug.
		 */

		$debug_text = implode( '<br>', Debug::get() );
		Debug::clear();
		if ( ! empty( $debug_text ) ) {
			$debug_text = '<br><strong>Debug:</strong><br>' . $debug_text . '<br>';
		}

		/*
		* SMTP Debug.
		*/

		$smtp_text = '';
		if ( $options->is_mailer_smtp() ) {
			$smtp_text = '<strong>SMTP Debug:</strong><br>';
			if ( ! empty( $smtp_debug ) ) {
				$smtp_text .= esc_textarea( $smtp_debug );
			} else {
				$smtp_text .= '[empty]';
			}
		}

		$errors = apply_filters( 'wp_mail_smtp_admin_test_get_debug_messages', array(
			$versions_text,
			$mailer_text,
			$debug_text,
			$smtp_text,
		) );

		return '<pre>' . implode( '<br>', array_filter( $errors ) ) . '</pre>';
	}
}
