<?php
/**
 * Name: Email Delivery (SMTP)
 * Description: Configure SMTP settings for reliable email delivery using mail servers like Gmail, Mailgun, SendGrid, or custom SMTP to prevent emails going to spam
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-06-25
 * Tags: smtp, email, mail, delivery, phpmailer
 * WhereToFind: {
 *   "location": "Email Delivery",
 *   "url": "",
 *   "instructions": "Configure SMTP settings, then test by sending a WordPress email (password reset, comment notification, etc.). Check Email Logs if available.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardEmailSmtp {

    private $encryption_key = 'switchboard_smtp_key_v1'; // Simple key for basic encryption
    private $last_mail_error = ''; // Store last wp_mail error

    public function __construct() {
        // Use high priority (99999) to run AFTER other plugins that might set From/Sender
        add_action('phpmailer_init', [$this, 'configure_smtp'], 99999);
        add_action('wp_ajax_switchboard_test_smtp', [$this, 'ajax_test_smtp']);
        add_filter('switchboard_before_save_settings', [$this, 'encrypt_password_before_save'], 10, 2);
        add_action('wp_mail_failed', [$this, 'capture_mail_error']);
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_email-smtp_settings'
            ]
        ];
    }
    
    /**
     * Render settings panel for Email Delivery (SMTP)
     *
     * Displays comprehensive SMTP configuration interface with:
     * - SMTP host and port input fields with common provider examples
     * - Encryption type selector (TLS, SSL, None) for secure connections
     * - Require authentication checkbox with conditional username/password fields
     * - Password masking for encrypted passwords (shows ••• for encrypted values)
     * - From email and from name fields for outgoing mail identity
     * - Styled test email section with recipient input and send button
     * - Real-time AJAX test email functionality with success/error feedback
     * - Visual feedback system with color-coded success/error messages
     * - Common SMTP provider examples (Gmail, SendGrid, Mailgun, Mailtrap)
     * - JavaScript toggle for showing/hiding authentication fields
     *
     * The interface provides a complete SMTP mail configuration solution. Password
     * fields display masked values (••••) if previously encrypted during save. The
     * test email section allows immediate verification of SMTP settings without
     * saving first, using AJAX to send a test message and display real-time feedback.
     * The authentication checkbox dynamically shows/hides username and password fields
     * using jQuery slideDown/slideUp animations. Port validation ensures values are
     * within the valid TCP port range (1-65535). The module includes detailed CSS
     * for a polished, professional appearance with hover states and transitions. Error
     * messages from failed test sends are captured and displayed to help troubleshoot
     * SMTP configuration issues. This replaces WordPress's default PHP mail() function
     * with proper SMTP authentication, greatly improving email deliverability and
     * preventing emails from landing in spam folders.
     *
     * @param array $settings Current module settings with 'smtp_host', 'smtp_port', 'smtp_auth', 'smtp_username', 'smtp_password', 'smtp_encryption', 'from_email', 'from_name' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $smtp_host = isset($settings['smtp_host']) ? $settings['smtp_host'] : '';
        $smtp_port = isset($settings['smtp_port']) ? $settings['smtp_port'] : '587';
        $smtp_auth = isset($settings['smtp_auth']) ? $settings['smtp_auth'] : '1';
        $smtp_username = isset($settings['smtp_username']) ? $settings['smtp_username'] : '';
        $smtp_password = isset($settings['smtp_password']) ? $settings['smtp_password'] : '';
        $smtp_encryption = isset($settings['smtp_encryption']) ? $settings['smtp_encryption'] : 'tls';
        $from_email = isset($settings['from_email']) ? $settings['from_email'] : get_option('admin_email');
        $from_name = isset($settings['from_name']) ? $settings['from_name'] : get_option('blogname');

        $current_user_email = wp_get_current_user()->user_email;

        // Display masked password if encrypted
        $password_display = '';
        if (!empty($smtp_password)) {
            // If encrypted, show masked value
            if (strpos($smtp_password, 'ENC:') === 0) {
                $password_display = '••••••••••••';
            } else {
                $password_display = $smtp_password;
            }
        }

        // Prepare i18n strings for JavaScript
        $i18n = [
            'sending' => __('Sending...', 'wpswitchboard'),
            'sendTest' => __('Send Test', 'wpswitchboard'),
            'testEmailSent' => __('Test email sent successfully! Check your inbox at', 'wpswitchboard'),
            'failedToSend' => __('Failed to send:', 'wpswitchboard'),
            'connectionError' => __('Connection error. Please try again.', 'wpswitchboard'),
            'validEmail' => __('Please enter a valid email address', 'wpswitchboard')
        ];

        ?>
        <input type="hidden" name="module" value="email-smtp">
        <input type="hidden" id="email-smtp-i18n" value="<?php echo esc_attr(wp_json_encode($i18n)); ?>">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin: 0;">Configure SMTP settings for reliable email delivery using mail servers like Gmail, Mailgun, SendGrid, or custom SMTP to prevent emails going to spam. Your password is encrypted before storage.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">SMTP Configuration</h3>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_smtp_host" class="sb-sp-label"><?php esc_html_e('SMTP Host', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Your SMTP server address (e.g., smtp.gmail.com, smtp.sendgrid.net)', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_smtp_host" id="setting_smtp_host" value="<?php echo esc_attr($smtp_host); ?>" placeholder="smtp.gmail.com" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_smtp_port" class="sb-sp-label"><?php esc_html_e('SMTP Port', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Usually 587 for TLS or 465 for SSL (valid range: 1-65535)', 'wpswitchboard'); ?></p>
            </div>
            <input type="number" name="setting_smtp_port" id="setting_smtp_port" value="<?php echo esc_attr($smtp_port); ?>" placeholder="587" min="1" max="65535" class="sb-sp-input" style="width: 150px;">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_smtp_encryption" class="sb-sp-label"><?php esc_html_e('Encryption', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose TLS for port 587, SSL for port 465', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_smtp_encryption" id="setting_smtp_encryption" class="sb-sp-select">
                <option value="tls" <?php selected($smtp_encryption, 'tls'); ?>><?php esc_html_e('TLS', 'wpswitchboard'); ?></option>
                <option value="ssl" <?php selected($smtp_encryption, 'ssl'); ?>><?php esc_html_e('SSL', 'wpswitchboard'); ?></option>
                <option value="" <?php selected($smtp_encryption, ''); ?>><?php esc_html_e('None', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <div class="sb-module-option-item sb-module-toggle-item">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title"><?php esc_html_e('Require SMTP Authentication', 'wpswitchboard'); ?></strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_smtp_auth" id="setting_smtp_auth" value="1" <?php checked($smtp_auth, '1'); ?>>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text"><?php esc_html_e('Uncheck only if your SMTP server does not require authentication (rare)', 'wpswitchboard'); ?></p>
                </div>
            </div>

            <div id="smtp-auth-fields" style="<?php echo $smtp_auth !== '1' ? 'display: none;' : ''; ?> margin-top: 16px;">
                <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
                    <div class="sb-sp-field-horizontal-left">
                        <label for="setting_smtp_username" class="sb-sp-label"><?php esc_html_e('SMTP Username', 'wpswitchboard'); ?></label>
                        <p class="sb-sp-description"><?php esc_html_e('Usually your email address', 'wpswitchboard'); ?></p>
                    </div>
                    <input type="text" name="setting_smtp_username" id="setting_smtp_username" value="<?php echo esc_attr($smtp_username); ?>" placeholder="your@email.com" class="sb-sp-input">
                </div>

                <div class="sb-sp-group sb-sp-field-horizontal">
                    <div class="sb-sp-field-horizontal-left">
                        <label for="setting_smtp_password" class="sb-sp-label"><?php esc_html_e('SMTP Password', 'wpswitchboard'); ?></label>
                        <p class="sb-sp-description"><?php esc_html_e('Your SMTP password or app-specific password. Passwords are encrypted before storage.', 'wpswitchboard'); ?></p>
                    </div>
                    <input type="password" name="setting_smtp_password" id="setting_smtp_password" value="<?php echo esc_attr($password_display); ?>" placeholder="••••••••" class="sb-sp-input">
                </div>
            </div>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Email Settings</h3>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_from_email" class="sb-sp-label"><?php esc_html_e('From Email', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('The email address that appears as the sender', 'wpswitchboard'); ?></p>
            </div>
            <input type="email" name="setting_from_email" id="setting_from_email" value="<?php echo esc_attr($from_email); ?>" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_from_name" class="sb-sp-label"><?php esc_html_e('From Name', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('The name that appears as the sender', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_from_name" id="setting_from_name" value="<?php echo esc_attr($from_name); ?>" class="sb-sp-input">
        </div>

        <hr class="sb-sp-divider">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Test Email</h3>
            <div style="display: flex; gap: 8px; align-items: flex-start; flex-wrap: wrap;">
                <input type="email" id="smtp-test-email" value="<?php echo esc_attr($current_user_email); ?>" placeholder="recipient@example.com" class="sb-sp-input" style="flex: 1; min-width: 250px; max-width: 400px;">
                <button type="button" id="smtp-test-btn" class="button button-primary">
                    <span class="dashicons dashicons-email-alt" style="vertical-align: middle; margin-right: 4px;"></span>
                    <?php esc_html_e('Send Test', 'wpswitchboard'); ?>
                </button>
            </div>
            <div id="smtp-test-feedback" style="display: none; margin-top: 12px;"></div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Common SMTP Settings</h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong>Gmail:</strong> smtp.gmail.com, Port 587, TLS</li>
                <li class="sb-sp-list-item"><strong>SendGrid:</strong> smtp.sendgrid.net, Port 587, TLS</li>
                <li class="sb-sp-list-item"><strong>Mailgun:</strong> smtp.mailgun.org, Port 587, TLS</li>
                <li class="sb-sp-list-item"><strong>Mailtrap (testing):</strong> smtp.mailtrap.io, Port 587, TLS</li>
            </ul>
        </div>

        <script>
        jQuery(document).ready(function($) {
            const i18n = JSON.parse($("#email-smtp-i18n").val());

            // Toggle SMTP auth fields
            $("#setting_smtp_auth").on("change", function() {
                if ($(this).is(":checked")) {
                    $("#smtp-auth-fields").slideDown(200);
                } else {
                    $("#smtp-auth-fields").slideUp(200);
                }
            });

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

                // Validate email format
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!testEmail || !emailRegex.test(testEmail)) {
                    $feedback.removeClass("sb-sp-info-box-success").addClass("sb-sp-info-box sb-sp-info-box-tip")
                        .html("<div class=\"sb-sp-heading-sm\">" + i18n.validEmail + "</div>")
                        .fadeIn(200);
                    return;
                }

                $btn.prop("disabled", true).html('<span class="dashicons dashicons-update" style="vertical-align: middle; margin-right: 4px; animation: spin 1s linear infinite;"></span>' + i18n.sending);
                $feedback.hide();

                $.ajax({
                    url: ajaxurl,
                    type: "POST",
                    data: {
                        action: "switchboard_test_smtp",
                        test_email: testEmail,
                        nonce: "<?php echo esc_attr(wp_create_nonce('switchboard_test_smtp')); ?>"
                    },
                    success: function(response) {
                        $btn.prop("disabled", false).html('<span class="dashicons dashicons-email-alt" style="vertical-align: middle; margin-right: 4px;"></span>' + i18n.sendTest);

                        if (response.success) {
                            $feedback.removeClass("sb-sp-info-box-tip").addClass("sb-sp-info-box sb-sp-info-box-success")
                                .html("<div class=\"sb-sp-heading-sm\">" + i18n.testEmailSent + " " + testEmail + "</div>")
                                .fadeIn(200);
                        } else {
                            $feedback.removeClass("sb-sp-info-box-success").addClass("sb-sp-info-box sb-sp-info-box-tip")
                                .html("<div class=\"sb-sp-heading-sm\">" + i18n.failedToSend + " " + $("<span>").text(response.data.message || "Unknown error").html() + "</div>")
                                .fadeIn(200);
                        }
                    },
                    error: function() {
                        $btn.prop("disabled", false).html('<span class="dashicons dashicons-email-alt" style="vertical-align: middle; margin-right: 4px;"></span>' + i18n.sendTest);
                        $feedback.removeClass("sb-sp-info-box-success").addClass("sb-sp-info-box sb-sp-info-box-tip")
                            .html("<div class=\"sb-sp-heading-sm\">" + i18n.connectionError + "</div>")
                            .fadeIn(200);
                    }
                });
            });
        });
        </script>
        <?php
    }

    /**
     * Encrypt password before saving
     */
    public function encrypt_password_before_save($settings, $module) {
        if ($module !== 'email-smtp') {
            return $settings;
        }

        // Encrypt password if present
        if (isset($settings['smtp_password']) && !empty($settings['smtp_password'])) {
            // Skip if password is the masked placeholder
            if ($settings['smtp_password'] === '••••••••••••') {
                // Keep existing encrypted password - don't re-encrypt the mask
                $existing_settings = get_option('switchboard_email-smtp_settings', []);
                if (isset($existing_settings['smtp_password'])) {
                    $settings['smtp_password'] = $existing_settings['smtp_password'];
                }
                return $settings;
            }

            // Only encrypt if it's not already encrypted (doesn't start with our marker)
            if (strpos($settings['smtp_password'], 'ENC:') !== 0) {
                $settings['smtp_password'] = $this->encrypt($settings['smtp_password']);
            }
        }

        return $settings;
    }

    /**
     * Simple encryption for SMTP password
     */
    private function encrypt($value) {
        if (empty($value)) {
            return '';
        }

        $auth_key = defined('AUTH_KEY') && AUTH_KEY ? AUTH_KEY : ABSPATH;

        $key = hash('sha256', $this->encryption_key . $auth_key, true); // 32 bytes binary
        $iv = openssl_random_pseudo_bytes(16);

        $encrypted = openssl_encrypt(
            $value,
            'AES-256-CBC',
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        if ($encrypted === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Switchboard SMTP: Encryption failed - ' . openssl_error_string()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
            return '';
        }

        // Prepend IV to ciphertext so it can be extracted on decrypt
        return 'ENC2:' . base64_encode($iv . $encrypted);
    }

    /**
     * Simple decryption for SMTP password
     */
    private function decrypt($value) {
        if (empty($value)) {
            return $value;
        }

        // Handle new ENC2 format (random IV)
        if (strpos($value, 'ENC2:') === 0) {
            return $this->decrypt_v2(substr($value, 5));
        }

        // Handle legacy ENC format (static IV) for backward compatibility
        if (strpos($value, 'ENC:') === 0) {
            return $this->decrypt_v1(substr($value, 4));
        }

        return $value; // Return as-is if not encrypted
    }

    /**
     * Decrypt v2 format (random IV, AES-256-CBC)
     */
    private function decrypt_v2($encoded) {
        $auth_key = defined('AUTH_KEY') && AUTH_KEY ? AUTH_KEY : ABSPATH;
        $key = hash('sha256', $this->encryption_key . $auth_key, true);

        $data = base64_decode($encoded);
        if ($data === false || strlen($data) < 17) {
            return '';
        }

        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);

        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

        if ($decrypted === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Switchboard SMTP: Password decryption failed'); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
            return '';
        }

        return $decrypted;
    }

    /**
     * Decrypt legacy v1 format (static IV, AES-128-CBC) for backward compatibility
     */
    private function decrypt_v1($encoded) {
        $auth_key = defined('AUTH_KEY') && AUTH_KEY ? AUTH_KEY : ABSPATH;
        $secure_auth_key = defined('SECURE_AUTH_KEY') && SECURE_AUTH_KEY ? SECURE_AUTH_KEY : ABSPATH;

        $key = substr(hash('sha256', $this->encryption_key . $auth_key), 0, 32);
        $iv = substr(hash('sha256', $this->encryption_key . $secure_auth_key), 0, 16);

        $decrypted = openssl_decrypt(
            base64_decode($encoded),
            'AES-128-CBC',
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        if ($decrypted === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Switchboard SMTP: Legacy password decryption failed'); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
            return '';
        }

        return $decrypted;
    }
    

    /**
     * Capture wp_mail errors for better error reporting
     */
    public function capture_mail_error($wp_error) {
        if (is_wp_error($wp_error)) {
            $this->last_mail_error = $wp_error->get_error_message();
        }
    }

    public function ajax_test_smtp() {
        check_ajax_referer('switchboard_test_smtp', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
        }

        // Rate limiting: Max 3 test emails per 5 minutes per user
        $user_id = get_current_user_id();
        $rate_key = 'smtp_test_rate_' . $user_id;
        $attempts = get_transient($rate_key);

        if ($attempts && $attempts >= 3) {
            wp_send_json_error(['message' => esc_html__('Rate limit exceeded. Please wait 5 minutes before sending another test email.', 'wpswitchboard')]);
        }

        $test_email = isset($_POST['test_email']) ? sanitize_email(wp_unslash($_POST['test_email'])) : '';

        if (!is_email($test_email)) {
            wp_send_json_error(['message' => esc_html__('Invalid email address', 'wpswitchboard')]);
        }

        $settings = get_option('switchboard_email-smtp_settings', []);

        if (empty($settings['smtp_host'])) {
            wp_send_json_error(['message' => esc_html__('SMTP Host not configured. Please save your settings first.', 'wpswitchboard')]);
        }

        // Clear previous error
        $this->last_mail_error = '';

        $subject = 'SMTP Test Email from ' . get_bloginfo('name');
        $message = "This is a test email sent from Switchboard Email SMTP module.\n\n";
        $message .= "Your SMTP configuration is working correctly!\n\n";
        $message .= "Settings used:\n";
        $message .= "- Host: " . $settings['smtp_host'] . "\n";
        $message .= "- Port: " . (isset($settings['smtp_port']) ? $settings['smtp_port'] : '587') . "\n";
        $message .= "- Encryption: " . (isset($settings['smtp_encryption']) ? $settings['smtp_encryption'] : 'tls') . "\n";
        $message .= "- From: " . (isset($settings['from_email']) ? $settings['from_email'] : get_option('admin_email')) . "\n";
        $message .= "\nSent at: " . current_time('Y-m-d H:i:s') . "\n";

        $result = wp_mail($test_email, $subject, $message);

        if ($result) {
            // Increment rate limit counter on successful send
            set_transient($rate_key, ($attempts ? $attempts + 1 : 1), 5 * MINUTE_IN_SECONDS);
            wp_send_json_success(['message' => esc_html__('Test email sent successfully!', 'wpswitchboard')]);
        } else {
            $error_message = esc_html__('Failed to send email.', 'wpswitchboard');

            // Use captured wp_mail error if available
            if (!empty($this->last_mail_error)) {
                $error_message .= ' ' . esc_html__('Error:', 'wpswitchboard') . ' ' . esc_html($this->last_mail_error);
            }

            wp_send_json_error(['message' => $error_message]);
        }
    }

    public function configure_smtp($phpmailer) {
        try {
            $settings = get_option('switchboard_email-smtp_settings', []);

            if (empty($settings['smtp_host'])) {
                return;
            }

            $phpmailer->isSMTP();
            $phpmailer->Host = sanitize_text_field($settings['smtp_host']);

            // Validate and set port
            $port = isset($settings['smtp_port']) ? intval($settings['smtp_port']) : 587;
            if ($port < 1 || $port > 65535) {
                $port = 587; // Fallback to safe default
            }
            $phpmailer->Port = $port;

            // Configurable SMTP authentication
            // Default to true if not set, or if set to '1' (checked)
            $smtp_auth = !isset($settings['smtp_auth']) || $settings['smtp_auth'] === '1';
            $phpmailer->SMTPAuth = $smtp_auth;

            if ($smtp_auth) {
                $phpmailer->Username = isset($settings['smtp_username']) ? sanitize_text_field($settings['smtp_username']) : '';
                // Decrypt password before using
                $phpmailer->Password = isset($settings['smtp_password']) ? $this->decrypt($settings['smtp_password']) : '';
            }

            $phpmailer->SMTPSecure = isset($settings['smtp_encryption']) ? sanitize_text_field($settings['smtp_encryption']) : 'tls';

            // Validate and set From email and envelope sender
            $from_email = isset($settings['from_email']) ? sanitize_email($settings['from_email']) : get_option('admin_email');
            $from_name = isset($settings['from_name']) ? sanitize_text_field($settings['from_name']) : get_option('blogname');

            if (is_email($from_email)) {
                // Force the From address - override any previously set From
                $phpmailer->From = $from_email;
                $phpmailer->FromName = $from_name;

                // Set the envelope sender (return-path) to match From email
                // This is critical for SMTP servers that verify sender matches authenticated user
                // The Sender property controls the SMTP "MAIL FROM" command
                $phpmailer->Sender = $from_email;
            }

            // Set timeout (30 seconds)
            $phpmailer->Timeout = 30;

        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Switchboard SMTP Configuration Error: ' . $e->getMessage()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
        }
    }
    
}

$switchboard_instance = new SwitchboardEmailSmtp();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
