<?php

use EmailSmtp\Includes\SmtpSettingsHelper;
use EmailSmtp\Module;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

/**
 * Email Delivery (SMTP) - Settings Modal
 *
 * Rendered inside the Advanced Settings modal. No dedicated page.
 *
 * @package EmailSmtp
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! NetworkScope::canManagePlugin() ) {
	return;
}

$module_id = $module_id ?? 'email-smtp';
$settings  = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings  = SmtpSettingsHelper::mergeWithDefaults( is_array( $settings ) ? $settings : [] );

$password_display = ! empty( $settings['smtp_password'] ) ? Module::getPasswordMask() : '';

$current_user_email   = wp_get_current_user()->user_email;
$email_logs_enabled   = OptionStoreModuleSettingsRepository::isModuleEnabled( 'email-logs' );
$email_logs_url       = add_query_arg( 'page', 'powersuite-email-logs', admin_url( 'admin.php' ) );
$conflicting_plugins  = SmtpSettingsHelper::detectConflictingPlugins();
$deliverability_warn  = SmtpSettingsHelper::getDeliverabilityWarning( $settings );
?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Configure SMTP settings for reliable email delivery. Your password is encrypted before storage.', 'wp-powersuite' ); ?>
	</p>

	<?php if ( $conflicting_plugins !== [] ) : ?>
		<div class="notice notice-warning inline" style="margin: 12px 0; padding: 10px 12px;">
			<p style="margin: 0;">
				<?php
				echo esc_html(
					sprintf(
						/* translators: %s: comma-separated plugin names */
						__( 'Another SMTP plugin is active (%s). Disable it to avoid conflicting mail transport settings.', 'wp-powersuite' ),
						implode( ', ', $conflicting_plugins )
					)
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( $deliverability_warn !== '' ) : ?>
		<div class="notice notice-info inline" style="margin: 12px 0; padding: 10px 12px;">
			<p style="margin: 0;"><?php echo esc_html( $deliverability_warn ); ?></p>
		</div>
	<?php endif; ?>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<table class="form-table">
			<tbody>
				<tr>
					<th scope="row"><label for="email-smtp_smtp_host"><?php esc_html_e( 'SMTP Host', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text"
							name="smtp_host"
							id="email-smtp_smtp_host"
							value="<?php echo esc_attr( $settings['smtp_host'] ); ?>"
							placeholder="smtp.gmail.com"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="smtp_host"
						/>
						<p class="description"><?php esc_html_e( 'Your SMTP server hostname (no protocol prefix).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_smtp_port"><?php esc_html_e( 'SMTP Port', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="number"
							name="smtp_port"
							id="email-smtp_smtp_port"
							value="<?php echo esc_attr( $settings['smtp_port'] ); ?>"
							placeholder="587"
							min="1"
							max="65535"
							class="wp-powersuite-advanced-setting"
							data-setting-key="smtp_port"
							style="width: 100px;"
						/>
						<p class="description"><?php esc_html_e( 'Usually 587 for TLS or 465 for SSL.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_smtp_encryption"><?php esc_html_e( 'Encryption', 'wp-powersuite' ); ?></label></th>
					<td>
						<select name="smtp_encryption"
							id="email-smtp_smtp_encryption"
							class="wp-powersuite-advanced-setting"
							data-setting-key="smtp_encryption"
						>
							<option value="tls" <?php selected( $settings['smtp_encryption'], 'tls' ); ?>><?php esc_html_e( 'TLS', 'wp-powersuite' ); ?></option>
							<option value="ssl" <?php selected( $settings['smtp_encryption'], 'ssl' ); ?>><?php esc_html_e( 'SSL', 'wp-powersuite' ); ?></option>
							<option value="" <?php selected( $settings['smtp_encryption'], '' ); ?>><?php esc_html_e( 'None', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Choose TLS for port 587, SSL for port 465.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'SMTP Authentication', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="smtp_auth"
								value="1"
								class="wp-powersuite-advanced-setting"
								data-setting-key="smtp_auth"
								<?php checked( $settings['smtp_auth'], '1' ); ?>
							/>
							<?php esc_html_e( 'Require SMTP authentication', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr class="email-smtp-auth-row" style="<?php echo ( $settings['smtp_auth'] === '1' || $settings['smtp_auth'] === true ) ? '' : 'display:none;'; ?>">
					<th scope="row"><label for="email-smtp_smtp_username"><?php esc_html_e( 'SMTP Username', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text"
							name="smtp_username"
							id="email-smtp_smtp_username"
							value="<?php echo esc_attr( $settings['smtp_username'] ); ?>"
							placeholder="your@email.com"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="smtp_username"
							autocomplete="off"
						/>
					</td>
				</tr>
				<tr class="email-smtp-auth-row" style="<?php echo ( $settings['smtp_auth'] === '1' || $settings['smtp_auth'] === true ) ? '' : 'display:none;'; ?>">
					<th scope="row"><label for="email-smtp_smtp_password"><?php esc_html_e( 'SMTP Password', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="password"
							name="smtp_password"
							id="email-smtp_smtp_password"
							value="<?php echo esc_attr( $password_display ); ?>"
							placeholder="••••••••"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="smtp_password"
							autocomplete="new-password"
						/>
						<p class="description"><?php esc_html_e( 'App-specific or SMTP password. Encrypted before storage.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_from_email"><?php esc_html_e( 'From Email', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="email"
							name="from_email"
							id="email-smtp_from_email"
							value="<?php echo esc_attr( $settings['from_email'] ); ?>"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="from_email"
						/>
						<p class="description"><?php esc_html_e( 'Should match your SMTP account domain for best deliverability (SPF/DKIM/DMARC).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_from_name"><?php esc_html_e( 'From Name', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text"
							name="from_name"
							id="email-smtp_from_name"
							value="<?php echo esc_attr( $settings['from_name'] ); ?>"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="from_name"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Override From address', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="override_from"
								value="1"
								class="wp-powersuite-advanced-setting"
								data-setting-key="override_from"
								<?php checked( $settings['override_from'], '1' ); ?>
							/>
							<?php esc_html_e( 'Apply From Email/Name to all outgoing mail (skip when another plugin already set a custom sender).', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_reply_to_email"><?php esc_html_e( 'Reply-To Email', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="email"
							name="reply_to_email"
							id="email-smtp_reply_to_email"
							value="<?php echo esc_attr( $settings['reply_to_email'] ); ?>"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="reply_to_email"
							placeholder="<?php esc_attr_e( 'Optional', 'wp-powersuite' ); ?>"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_reply_to_name"><?php esc_html_e( 'Reply-To Name', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text"
							name="reply_to_name"
							id="email-smtp_reply_to_name"
							value="<?php echo esc_attr( $settings['reply_to_name'] ); ?>"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="reply_to_name"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_return_path"><?php esc_html_e( 'Return-Path / Bounce Email', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="email"
							name="return_path"
							id="email-smtp_return_path"
							value="<?php echo esc_attr( $settings['return_path'] ); ?>"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="return_path"
							placeholder="<?php esc_attr_e( 'Optional — defaults to From Email', 'wp-powersuite' ); ?>"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp_smtp_debug"><?php esc_html_e( 'SMTP Debug', 'wp-powersuite' ); ?></label></th>
					<td>
						<select name="smtp_debug"
							id="email-smtp_smtp_debug"
							class="wp-powersuite-advanced-setting"
							data-setting-key="smtp_debug"
						>
							<option value="0" <?php selected( $settings['smtp_debug'], '0' ); ?>><?php esc_html_e( 'Off', 'wp-powersuite' ); ?></option>
							<option value="1" <?php selected( $settings['smtp_debug'], '1' ); ?>><?php esc_html_e( 'Client messages (server log only)', 'wp-powersuite' ); ?></option>
							<option value="2" <?php selected( $settings['smtp_debug'], '2' ); ?>><?php esc_html_e( 'Client + server messages (server log only)', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Writes to the PHP error log only. Credentials are redacted. Disable after troubleshooting.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="email-smtp-test-email"><?php esc_html_e( 'Test Email', 'wp-powersuite' ); ?></label></th>
					<td>
						<div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
							<input type="email"
								id="email-smtp-test-email"
								value="<?php echo esc_attr( $current_user_email ); ?>"
								placeholder="recipient@example.com"
								class="regular-text"
								style="width: 280px;"
							/>
							<button type="button" id="email-smtp-test-btn" class="button button-primary">
								<?php esc_html_e( 'Send Test', 'wp-powersuite' ); ?>
							</button>
						</div>
						<div id="email-smtp-test-feedback" style="display: none; margin-top: 12px;" role="status" aria-live="polite"></div>
						<p class="description"><?php esc_html_e( 'Uses current form values (save optional). Rate limit: 3 tests per 5 minutes.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Email Logs', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( $email_logs_enabled ) : ?>
							<a href="<?php echo esc_url( $email_logs_url ); ?>" class="button button-secondary">
								<?php esc_html_e( 'View Email Logs', 'wp-powersuite' ); ?>
							</a>
							<p class="description"><?php esc_html_e( 'Email Logs may store message content including password resets and order details. Disable content logging in Email Logs settings if not required.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<div class="notice notice-info inline" style="margin: 0; padding: 10px 12px;">
								<p style="margin: 0;">
									<?php
									echo wp_kses_post(
										__( 'Enable the <strong>Email Logs</strong> module to view sent mail. Consider disabling body logging for privacy-sensitive sites.', 'wp-powersuite' )
									);
									?>
								</p>
							</div>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

<script>
(function() {
	var $ = jQuery;
	if (!$ || !document.getElementById('email-smtp-test-btn')) return;

	var i18n = {
		sending: <?php echo wp_json_encode( __( 'Sending...', 'wp-powersuite' ) ); ?>,
		sendTest: <?php echo wp_json_encode( __( 'Send Test', 'wp-powersuite' ) ); ?>,
		testEmailSent: <?php echo wp_json_encode( __( 'Test email sent successfully! Check your inbox at', 'wp-powersuite' ) ); ?>,
		failedToSend: <?php echo wp_json_encode( __( 'Failed to send:', 'wp-powersuite' ) ); ?>,
		connectionError: <?php echo wp_json_encode( __( 'Connection error. Please try again.', 'wp-powersuite' ) ); ?>,
		validEmail: <?php echo wp_json_encode( __( 'Please enter a valid email address', 'wp-powersuite' ) ); ?>,
		unknownError: <?php echo wp_json_encode( __( 'The server did not return a usable error message.', 'wp-powersuite' ) ); ?>
	};

	function escapeHtml(text) {
		return $('<div/>').text(text).html();
	}

	function toggleAuthRows() {
		var auth = $('[data-setting-key="smtp_auth"]').is(':checked');
		$('.email-smtp-auth-row').toggle(auth);
	}

	function collectFormSettings() {
		var data = {};
		$('.wp-powersuite-advanced-setting[data-setting-key]').each(function() {
			var key = $(this).data('setting-key');
			if (!key) return;
			if ($(this).is(':checkbox')) {
				data[key] = $(this).is(':checked') ? '1' : '0';
			} else {
				data[key] = $(this).val();
			}
		});
		return data;
	}

	$(document).on('change', '[data-setting-key="smtp_auth"]', toggleAuthRows);

	$(document).on('click', '#email-smtp-test-btn', function() {
		var btn = $(this);
		var feedback = $('#email-smtp-test-feedback');
		var testEmail = $('#email-smtp-test-email').val().trim();

		var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!testEmail || !emailRegex.test(testEmail)) {
			feedback.removeClass('notice-success').addClass('notice notice-warning')
				.html('<p>' + escapeHtml(i18n.validEmail) + '</p>').show();
			return;
		}

		btn.prop('disabled', true).text(i18n.sending);
		feedback.hide();

		$.ajax({
			url: window.wpPowerSuite && window.wpPowerSuite.ajaxUrl ? window.wpPowerSuite.ajaxUrl : ajaxurl,
			type: 'POST',
			data: {
				action: 'wp_powersuite_test_smtp',
				test_email: testEmail,
				settings: collectFormSettings(),
				nonce: window.wpPowerSuite && window.wpPowerSuite.nonce ? window.wpPowerSuite.nonce : ''
			},
			success: function(response) {
				btn.prop('disabled', false).text(i18n.sendTest);
				if (response.success) {
					feedback.removeClass('notice-warning').addClass('notice notice-success')
						.html('<p>' + escapeHtml(i18n.testEmailSent) + ' ' + escapeHtml(testEmail) + '</p>').show();
				} else {
					var msg = response.data && response.data.message ? response.data.message : i18n.unknownError;
					feedback.removeClass('notice-success').addClass('notice notice-warning')
						.html('<p>' + escapeHtml(i18n.failedToSend) + ' ' + escapeHtml(msg) + '</p>').show();
				}
			},
			error: function() {
				btn.prop('disabled', false).text(i18n.sendTest);
				feedback.removeClass('notice-success').addClass('notice notice-warning')
					.html('<p>' + escapeHtml(i18n.connectionError) + '</p>').show();
			}
		});
	});
})();
</script>
