<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Aegisify_Admin_Emails {

	public static function render_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$notice = '';

		if ( isset( $_POST['aegisify_email_settings_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aegisify_email_settings_nonce'] ) ), 'aegisify_email_settings_save' ) ) {
			$settings = Aegisify_Emails::get_settings();

			$settings['smtp_enabled']    = ! empty( $_POST['smtp_enabled'] ) ? 'yes' : 'no';

			$allowed_providers = array( 'aegisify_smtp', 'custom', 'amazon_ses', 'sendgrid', 'mailgun', 'postmark', 'smtp2go', 'other' );
			$settings['smtp_provider']  = isset( $_POST['smtp_provider'] ) ? sanitize_key( wp_unslash( $_POST['smtp_provider'] ) ) : 'custom';
			if ( ! in_array( $settings['smtp_provider'], $allowed_providers, true ) ) {
				$settings['smtp_provider'] = 'custom';
			}

			$settings['smtp_host']       = isset( $_POST['smtp_host'] ) ? sanitize_text_field( wp_unslash( $_POST['smtp_host'] ) ) : '';
			$settings['smtp_port']       = isset( $_POST['smtp_port'] ) ? absint( $_POST['smtp_port'] ) : 587;

			$allowed_enc                = array( 'none', 'ssl', 'tls' );
			$settings['smtp_encryption'] = isset( $_POST['smtp_encryption'] ) ? sanitize_key( wp_unslash( $_POST['smtp_encryption'] ) ) : 'tls';
			if ( ! in_array( $settings['smtp_encryption'], $allowed_enc, true ) ) {
				$settings['smtp_encryption'] = 'tls';
			}

			$settings['smtp_auth']      = ! empty( $_POST['smtp_auth'] ) ? 'yes' : 'no';
			$settings['smtp_username']  = isset( $_POST['smtp_username'] ) ? sanitize_text_field( wp_unslash( $_POST['smtp_username'] ) ) : '';
			$settings['smtp_password']  = isset( $_POST['smtp_password'] ) ? sanitize_text_field( wp_unslash( $_POST['smtp_password'] ) ) : '';

			$settings['smtp_from_email'] = isset( $_POST['smtp_from_email'] ) ? sanitize_email( wp_unslash( $_POST['smtp_from_email'] ) ) : '';
			$settings['smtp_from_name']  = isset( $_POST['smtp_from_name'] ) ? sanitize_text_field( wp_unslash( $_POST['smtp_from_name'] ) ) : '';
			$settings['smtp_reply_to']   = isset( $_POST['smtp_reply_to'] ) ? sanitize_email( wp_unslash( $_POST['smtp_reply_to'] ) ) : '';

			Aegisify_Emails::update_settings( $settings );

			$notice = __( 'Settings saved.', 'aegisify' );
		}

		$test_result = null;
		if ( isset( $_POST['aegisify_smtp_test_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aegisify_smtp_test_nonce'] ) ), 'aegisify_smtp_test' ) ) {
			$test_result = Aegisify_Emails::test_smtp_connection();
		}

		$send_result = null;
		if ( isset( $_POST['aegisify_smtp_send_test_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aegisify_smtp_send_test_nonce'] ) ), 'aegisify_smtp_send_test' ) ) {
			$to = get_option( 'admin_email' );
			/* translators: %s: Site name. */
			$subject = sprintf( __( '[%s] SMTP Test Email', 'aegisify' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) );
			$body = __( "This is a test email from Aegisify Email Settings.\n\nIf you are using Amazon SES Sandbox, recipients must be verified identities.", 'aegisify' );

			$ok = wp_mail( $to, $subject, $body );
			$send_result = array(
				'ok'      => (bool) $ok,
				'to'      => (string) $to,
			);
		}

		$settings = Aegisify_Emails::get_settings();

		echo '<div class="wrap">';
		echo '<h1>' . esc_html__( 'Aegisify Email Settings', 'aegisify' ) . '</h1>';

		if ( $notice ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $notice ) . '</p></div>';
		}

		if ( is_array( $test_result ) ) {
			if ( ! empty( $test_result['ok'] ) ) {
				echo '<div class="notice notice-success"><p>' . esc_html__( 'SMTP connection test passed.', 'aegisify' ) . '</p></div>';
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'SMTP connection test failed.', 'aegisify' ) . '</p></div>';
			}
			echo '<pre style="background:#fff;border:1px solid #ccd0d4;padding:10px;max-width:100%;overflow:auto;">' . esc_html( wp_json_encode( $test_result, JSON_PRETTY_PRINT ) ) . '</pre>';
		}

		if ( is_array( $send_result ) ) {
			if ( ! empty( $send_result['ok'] ) ) {
				echo '<div class="notice notice-success"><p>' . esc_html__( 'Test email sent (check inbox).', 'aegisify' ) . '</p></div>';
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'Test email failed to send. (If using SES Sandbox, the recipient must be verified.)', 'aegisify' ) . '</p></div>';
			}
		}

		echo '<form method="post" action="">';
		wp_nonce_field( 'aegisify_email_settings_save', 'aegisify_email_settings_nonce' );

		echo '<table class="form-table" role="presentation"><tbody>';

		echo '<tr><th scope="row">' . esc_html__( 'Enable SMTP', 'aegisify' ) . '</th><td>';
		echo '<label><input type="checkbox" name="smtp_enabled" value="1" ' . checked( $settings['smtp_enabled'], 'yes', false ) . ' /> ' . esc_html__( 'Send all WordPress emails via SMTP', 'aegisify' ) . '</label>';
		echo '</td></tr>';

		echo '<tr><th scope="row">' . esc_html__( 'Provider', 'aegisify' ) . '</th><td>';
		echo '<select name="smtp_provider" id="aegisify-smtp-provider">';
		$providers = array(
			'aegisify_smtp' => __( 'Aegisify SMTP', 'aegisify' ),
			'custom'        => __( 'Custom SMTP', 'aegisify' ),
			'amazon_ses'    => __( 'Amazon SES (SMTP)', 'aegisify' ),
			'sendgrid'      => __( 'SendGrid', 'aegisify' ),
			'mailgun'       => __( 'Mailgun', 'aegisify' ),
			'postmark'      => __( 'Postmark', 'aegisify' ),
			'smtp2go'       => __( 'SMTP2GO', 'aegisify' ),
			'other'         => __( 'Other', 'aegisify' ),
		);
		foreach ( $providers as $k => $label ) {
			echo '<option value="' . esc_attr( $k ) . '" ' . selected( $settings['smtp_provider'], $k, false ) . '>' . esc_html( $label ) . '</option>';
		}
		echo '</select>';
		echo '<p class="description">' . esc_html__( 'Select Aegisify SMTP to relay mail through the Aegisify SMTP service when Aegisify Core license is active. Other providers use the manual SMTP fields below.', 'aegisify' ) . '</p>';
		echo '</td></tr>';

		echo '<tr id="aegisify-smtp-service-note"><th scope="row">' . esc_html__( 'Aegisify SMTP', 'aegisify' ) . '</th><td>';
		echo '<p class="description">' . esc_html__( 'When Aegisify SMTP is selected, Aegisify Core uses the Aegisify SMTP service only when your Aegisify Core license is active and the Aegisify SMTP relay integration is available.', 'aegisify' ) . '</p>';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'SMTP Host', 'aegisify' ) . '</th><td>';
		echo '<input type="text" class="regular-text" name="smtp_host" value="' . esc_attr( $settings['smtp_host'] ) . '" placeholder="email-smtp.us-east-1.amazonaws.com" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'SMTP Port', 'aegisify' ) . '</th><td>';
		echo '<input type="number" class="small-text" name="smtp_port" value="' . esc_attr( (string) $settings['smtp_port'] ) . '" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'Encryption', 'aegisify' ) . '</th><td>';
		echo '<select name="smtp_encryption">';
		foreach ( array( 'none' => __( 'None', 'aegisify' ), 'tls' => __( 'TLS (STARTTLS)', 'aegisify' ), 'ssl' => __( 'SSL', 'aegisify' ) ) as $k => $label ) {
			echo '<option value="' . esc_attr( $k ) . '" ' . selected( $settings['smtp_encryption'], $k, false ) . '>' . esc_html( $label ) . '</option>';
		}
		echo '</select>';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'Authentication', 'aegisify' ) . '</th><td>';
		echo '<label><input type="checkbox" name="smtp_auth" value="1" ' . checked( $settings['smtp_auth'], 'yes', false ) . ' /> ' . esc_html__( 'Use SMTP authentication', 'aegisify' ) . '</label>';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'Username', 'aegisify' ) . '</th><td>';
		echo '<input type="text" class="regular-text" name="smtp_username" value="' . esc_attr( $settings['smtp_username'] ) . '" autocomplete="off" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'Password', 'aegisify' ) . '</th><td>';
		echo '<input type="password" class="regular-text" name="smtp_password" value="' . esc_attr( (string) $settings['smtp_password'] ) . '" autocomplete="new-password" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'From Email', 'aegisify' ) . '</th><td>';
		echo '<input type="email" class="regular-text" name="smtp_from_email" value="' . esc_attr( $settings['smtp_from_email'] ) . '" placeholder="no-reply@yourdomain.com" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'From Name', 'aegisify' ) . '</th><td>';
		echo '<input type="text" class="regular-text" name="smtp_from_name" value="' . esc_attr( $settings['smtp_from_name'] ) . '" placeholder="Aegisify" />';
		echo '</td></tr>';

		echo '<tr class="aegisify-smtp-manual-row"><th scope="row">' . esc_html__( 'Reply-To', 'aegisify' ) . '</th><td>';
		echo '<input type="email" class="regular-text" name="smtp_reply_to" value="' . esc_attr( $settings['smtp_reply_to'] ) . '" />';
		echo '</td></tr>';

		echo '</tbody></table>';

		submit_button( __( 'Save Settings', 'aegisify' ) );

		echo '</form>';

		echo '<div id="aegisify-smtp-manual-sections">';
		echo '<h2 style="margin-top:28px;">' . esc_html__( 'Diagnostics', 'aegisify' ) . '</h2>';

		echo '<form method="post" action="" style="margin-top:12px;">';
		wp_nonce_field( 'aegisify_smtp_test', 'aegisify_smtp_test_nonce' );
		submit_button( __( 'Test Connection', 'aegisify' ), 'secondary', 'submit', false );
		echo '</form>';

		echo '<form method="post" action="" style="margin-top:12px;">';
		wp_nonce_field( 'aegisify_smtp_send_test', 'aegisify_smtp_send_test_nonce' );
		submit_button( __( 'Send Test Email', 'aegisify' ), 'secondary', 'submit', false );
		echo '<p class="description">' . esc_html__( 'Sends to the WordPress admin email. If Amazon SES is in Sandbox, the recipient must be verified in SES.', 'aegisify' ) . '</p>';
		echo '</form>';

		echo '<h2 style="margin-top:28px;">' . esc_html__( 'Secure wp-config.php overrides (recommended)', 'aegisify' ) . '</h2>';
		echo '<pre style="background:#fff;border:1px solid #ccd0d4;padding:10px;max-width:100%;overflow:auto;">' . esc_html(
"define('AEGISIFY_SMTP_ENABLED', 'yes');
define('AEGISIFY_SMTP_HOST', 'email-smtp.us-east-1.amazonaws.com');
define('AEGISIFY_SMTP_PORT', 587);
define('AEGISIFY_SMTP_ENCRYPTION', 'tls');
define('AEGISIFY_SMTP_AUTH', 'yes');
define('AEGISIFY_SMTP_USERNAME', 'YOUR_SMTP_USERNAME');
define('AEGISIFY_SMTP_PASSWORD', 'YOUR_SMTP_PASSWORD');
define('AEGISIFY_SMTP_FROM_EMAIL', 'no-reply@yourdomain.com');
define('AEGISIFY_SMTP_FROM_NAME', 'Aegisify');" ) . '</pre>';

		echo '</div>';
		echo '<script>document.addEventListener("DOMContentLoaded",function(){var provider=document.getElementById("aegisify-smtp-provider");if(!provider){return;}var manualRows=document.querySelectorAll(".aegisify-smtp-manual-row");var manualSections=document.getElementById("aegisify-smtp-manual-sections");var serviceNote=document.getElementById("aegisify-smtp-service-note");var toggle=function(){var isAegisify=(provider.value==="aegisify_smtp");manualRows.forEach(function(row){row.style.display=isAegisify?"none":"";});if(manualSections){manualSections.style.display=isAegisify?"none":"";}if(serviceNote){serviceNote.style.display=isAegisify?"":"none";}};provider.addEventListener("change",toggle);toggle();});</script>';
		echo '</div>';
	}
}
