<?php
/**
 * SMTP Mailer Module
 *
 * Configure SMTP relay with fallback support and email logging.
 *
 * @package BlaminhorEssentials
 */

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

/**
 * SMTP module class
 */
class Blaminhor_Essentials_Module_SMTP extends Blaminhor_Essentials_Module {

    /**
     * Module ID
     *
     * @var string
     */
    protected $id = 'smtp';

    /**
     * Module name
     *
     * @var string
     */
    protected $name = 'SMTP Mailer';

    /**
     * Email log table name
     *
     * @var string
     */
    private $log_table;

    /**
     * Available SMTP providers
     *
     * @var array
     */
    private $providers = array();

    /**
     * Database version for migrations
     *
     * @var string
     */
    private $db_version = '1.0';

    /**
     * Initialize module
     */
    protected function init() {
        global $wpdb;

        // Note: Strings are translated in the base class get_name() and get_description() methods.
        $this->name        = 'SMTP Mailer';
        $this->description = 'Configure SMTP relay with fallback support and email logging.';
        $this->log_table   = $wpdb->prefix . 'blaminhor_essentials_email_log';

        $this->define_providers();
        $this->maybe_create_log_table();
    }

    /**
     * Define available SMTP providers
     */
    private function define_providers() {
        $this->providers = array(
            'brevo'        => array(
                'name'       => 'Brevo',
                'host'       => 'smtp-relay.brevo.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'sendgrid'     => array(
                'name'       => 'SendGrid',
                'host'       => 'smtp.sendgrid.net',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'mailgun'      => array(
                'name'       => 'Mailgun',
                'host'       => 'smtp.mailgun.org',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'amazon_ses'   => array(
                'name'       => 'Amazon SES',
                'host'       => 'email-smtp.us-east-1.amazonaws.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'postmark'     => array(
                'name'       => 'Postmark',
                'host'       => 'smtp.postmarkapp.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'sparkpost'    => array(
                'name'       => 'SparkPost',
                'host'       => 'smtp.sparkpostmail.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'mailjet'      => array(
                'name'       => 'Mailjet',
                'host'       => 'in-v3.mailjet.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'smtp2go'      => array(
                'name'       => 'SMTP2GO',
                'host'       => 'mail.smtp2go.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'elasticemail' => array(
                'name'       => 'Elastic Email',
                'host'       => 'smtp.elasticemail.com',
                'port'       => 2525,
                'encryption' => 'tls',
            ),
            'gmail'        => array(
                'name'       => 'Gmail / Google Workspace',
                'host'       => 'smtp.gmail.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'outlook'      => array(
                'name'       => 'Outlook / Office 365',
                'host'       => 'smtp.office365.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'zoho'         => array(
                'name'       => 'Zoho Mail',
                'host'       => 'smtp.zoho.com',
                'port'       => 587,
                'encryption' => 'tls',
            ),
            'other'        => array(
                'name'       => __( 'Other / Custom SMTP', 'blaminhor-essentials' ),
                'host'       => '',
                'port'       => 587,
                'encryption' => 'tls',
            ),
        );

        $this->providers = apply_filters( 'blaminhor_essentials_smtp_providers', $this->providers );
    }

    /**
     * Get provider logo SVG
     *
     * @param string $provider Provider key.
     * @return string SVG markup.
     */
    private function get_provider_color( $provider ) {
        $colors = array(
            'brevo'        => '#0B996E',
            'sendgrid'     => '#1A82E2',
            'mailgun'      => '#F06B54',
            'amazon_ses'   => '#FF9900',
            'postmark'     => '#FFDE00',
            'sparkpost'    => '#FA6423',
            'mailjet'      => '#9B59B6',
            'smtp2go'      => '#2ECC71',
            'elasticemail' => '#0073AA',
            'gmail'        => '#EA4335',
            'outlook'      => '#0078D4',
            'zoho'         => '#E42527',
            'other'        => '#6B7280',
        );

        return isset( $colors[ $provider ] ) ? $colors[ $provider ] : $colors['other'];
    }

    /**
     * Get provider setup tutorials
     *
     * @return array
     */
    private function get_provider_tutorials() {
        return array(
            'brevo' => array(
                'title' => __( 'Brevo Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create a free account at <a href="https://www.brevo.com/" target="_blank">brevo.com</a>', 'blaminhor-essentials' ),
                    __( 'Authenticate your domain in <strong>Settings</strong> → <strong>Senders & IP</strong> → <strong>Domains</strong>', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>SMTP & API</strong>', 'blaminhor-essentials' ),
                    __( 'Click <strong>Generate a new SMTP key</strong>', 'blaminhor-essentials' ),
                    __( 'Copy the SMTP key (this is your password) and the Login shown on this page', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp-relay.brevo.com',
                'port' => '587',
                'encryption' => 'tls',
                'note' => __( 'Important: Your From Email must use an authenticated domain. Domain authentication (DKIM/SPF) is required since February 2024.', 'blaminhor-essentials' ),
            ),
            'sendgrid' => array(
                'title' => __( 'SendGrid Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create a free account at <a href="https://sendgrid.com/" target="_blank">sendgrid.com</a>', 'blaminhor-essentials' ),
                    __( 'Verify your domain in <strong>Settings</strong> → <strong>Sender Authentication</strong>', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>API Keys</strong>', 'blaminhor-essentials' ),
                    __( 'Click <strong>Create API Key</strong> → <strong>Full Access</strong>', 'blaminhor-essentials' ),
                    __( 'Use <code>apikey</code> as username and the API key as password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.sendgrid.net',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'mailgun' => array(
                'title' => __( 'Mailgun Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create an account at <a href="https://www.mailgun.com/" target="_blank">mailgun.com</a> (credit card required)', 'blaminhor-essentials' ),
                    __( 'Add and verify your domain in <strong>Sending</strong> → <strong>Domains</strong>', 'blaminhor-essentials' ),
                    __( 'Go to your domain settings → <strong>SMTP credentials</strong>', 'blaminhor-essentials' ),
                    __( 'Create SMTP credentials or use the default ones', 'blaminhor-essentials' ),
                    __( 'The username is usually <code>postmaster@yourdomain.com</code>', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.mailgun.org',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'amazon_ses' => array(
                'title' => __( 'Amazon SES Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Sign in to <a href="https://console.aws.amazon.com/ses/" target="_blank">AWS SES Console</a>', 'blaminhor-essentials' ),
                    __( 'Verify your domain or email in <strong>Verified identities</strong>', 'blaminhor-essentials' ),
                    __( 'Request production access if in sandbox mode', 'blaminhor-essentials' ),
                    __( 'Go to <strong>SMTP settings</strong> → <strong>Create SMTP credentials</strong>', 'blaminhor-essentials' ),
                    __( 'Download the credentials (shown only once)', 'blaminhor-essentials' ),
                ),
                'host' => 'email-smtp.eu-west-1.amazonaws.com',
                'port' => '587',
                'encryption' => 'tls',
                'note' => __( 'Change the region in the host to match your SES region.', 'blaminhor-essentials' ),
            ),
            'postmark' => array(
                'title' => __( 'Postmark Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create an account at <a href="https://postmarkapp.com/" target="_blank">postmarkapp.com</a>', 'blaminhor-essentials' ),
                    __( 'Create a new Server in your account', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Server</strong> → <strong>API Tokens</strong>', 'blaminhor-essentials' ),
                    __( 'Copy your Server API Token', 'blaminhor-essentials' ),
                    __( 'Use the API token as both username and password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.postmarkapp.com',
                'port' => '587',
                'encryption' => 'tls',
                'note' => __( 'Postmark is for transactional emails only (no marketing).', 'blaminhor-essentials' ),
            ),
            'sparkpost' => array(
                'title' => __( 'SparkPost Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create an account at <a href="https://www.sparkpost.com/" target="_blank">sparkpost.com</a>', 'blaminhor-essentials' ),
                    __( 'Add and verify your sending domain', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Configuration</strong> → <strong>API Keys</strong>', 'blaminhor-essentials' ),
                    __( 'Create an API key with <strong>Send via SMTP</strong> permission', 'blaminhor-essentials' ),
                    __( 'Use <code>SMTP_Injection</code> as username and the API key as password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.sparkpostmail.com',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'mailjet' => array(
                'title' => __( 'Mailjet Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create a free account at <a href="https://www.mailjet.com/" target="_blank">mailjet.com</a>', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Account Settings</strong> → <strong>SMTP and SEND API Settings</strong>', 'blaminhor-essentials' ),
                    __( 'Your API Key is your SMTP username', 'blaminhor-essentials' ),
                    __( 'Your Secret Key is your SMTP password', 'blaminhor-essentials' ),
                    __( 'Verify your sender email in <strong>Sender addresses</strong>', 'blaminhor-essentials' ),
                ),
                'host' => 'in-v3.mailjet.com',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'smtp2go' => array(
                'title' => __( 'SMTP2GO Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create a free account at <a href="https://www.smtp2go.com/" target="_blank">smtp2go.com</a>', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>Users</strong>', 'blaminhor-essentials' ),
                    __( 'Click <strong>Add SMTP User</strong>', 'blaminhor-essentials' ),
                    __( 'Use the generated username and password', 'blaminhor-essentials' ),
                    __( 'Verify your sender domain or email', 'blaminhor-essentials' ),
                ),
                'host' => 'mail.smtp2go.com',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'elasticemail' => array(
                'title' => __( 'Elastic Email Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Create a free account at <a href="https://elasticemail.com/" target="_blank">elasticemail.com</a>', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>SMTP</strong>', 'blaminhor-essentials' ),
                    __( 'Note your SMTP username (your account email)', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>API</strong> to create an API key', 'blaminhor-essentials' ),
                    __( 'Use the API key as your SMTP password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.elasticemail.com',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'gmail' => array(
                'title' => __( 'Gmail / Google Workspace Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Enable 2-Factor Authentication on your Google account', 'blaminhor-essentials' ),
                    __( 'Go to <a href="https://myaccount.google.com/apppasswords" target="_blank">Google App Passwords</a>', 'blaminhor-essentials' ),
                    __( 'Select <strong>Mail</strong> and <strong>Other (Custom name)</strong>', 'blaminhor-essentials' ),
                    __( 'Generate and copy the 16-character app password', 'blaminhor-essentials' ),
                    __( 'Use your Gmail address as username, app password as password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.gmail.com',
                'port' => '587',
                'encryption' => 'tls',
                'note' => __( 'For Google Workspace, you may need to enable "Less secure apps" or use OAuth.', 'blaminhor-essentials' ),
            ),
            'outlook' => array(
                'title' => __( 'Outlook / Office 365 Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Enable 2-Factor Authentication on your Microsoft account', 'blaminhor-essentials' ),
                    __( 'Go to <a href="https://account.live.com/proofs/AppPassword" target="_blank">Microsoft App Passwords</a>', 'blaminhor-essentials' ),
                    __( 'Create a new app password', 'blaminhor-essentials' ),
                    __( 'Use your Outlook email as username', 'blaminhor-essentials' ),
                    __( 'Use the app password as your SMTP password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.office365.com',
                'port' => '587',
                'encryption' => 'tls',
            ),
            'zoho' => array(
                'title' => __( 'Zoho Mail Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Log in to your Zoho Mail account', 'blaminhor-essentials' ),
                    __( 'Go to <strong>Settings</strong> → <strong>Security</strong> → <strong>App Passwords</strong>', 'blaminhor-essentials' ),
                    __( 'Generate a new app-specific password', 'blaminhor-essentials' ),
                    __( 'Use your Zoho email as username', 'blaminhor-essentials' ),
                    __( 'Use the app password as your SMTP password', 'blaminhor-essentials' ),
                ),
                'host' => 'smtp.zoho.com',
                'port' => '587',
                'encryption' => 'tls',
                'note' => __( 'For EU accounts, use smtp.zoho.eu instead.', 'blaminhor-essentials' ),
            ),
            'other' => array(
                'title' => __( 'Custom SMTP Setup', 'blaminhor-essentials' ),
                'steps' => array(
                    __( 'Contact your email provider or hosting company for SMTP details', 'blaminhor-essentials' ),
                    __( 'Common settings: Host, Port, Username, Password, Encryption', 'blaminhor-essentials' ),
                    __( 'Try port 587 with TLS, or port 465 with SSL', 'blaminhor-essentials' ),
                    __( 'If using cPanel, check <strong>Email Accounts</strong> → <strong>Connect Devices</strong>', 'blaminhor-essentials' ),
                ),
                'host' => '',
                'port' => '587',
                'encryption' => 'tls',
            ),
        );
    }

    /**
     * Get default settings
     *
     * @return array
     */
    protected function get_default_settings() {
        return array(
            'relays'             => array(),
            'force_from_email'   => false,
            'from_email'         => '',
            'force_from_name'    => false,
            'from_name'          => '',
            'return_path'        => false,
            'enable_logging'     => false,
            'log_retention_days' => 30,
            'disable_ssl_verify' => false,
        );
    }

    /**
     * Register hooks
     */
    protected function register_hooks() {
        // Admin hooks
        add_action( 'admin_init', array( $this, 'handle_settings_submission' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

        // Override WordPress mail
        add_action( 'phpmailer_init', array( $this, 'configure_phpmailer' ), 999 );

        // Force from email/name
        add_filter( 'wp_mail_from', array( $this, 'filter_from_email' ), 1000 );
        add_filter( 'wp_mail_from_name', array( $this, 'filter_from_name' ), 1000 );

        // Only register logging hooks if logging is enabled
        if ( $this->get_setting( 'enable_logging', false ) ) {
            add_action( 'wp_mail_succeeded', array( $this, 'log_email_success' ) );
            add_action( 'wp_mail_failed', array( $this, 'log_email_failure' ) );

            // Cron for log cleanup
            add_action( 'blaminhor_essentials_cleanup_email_logs', array( $this, 'cleanup_old_logs' ) );
            if ( ! wp_next_scheduled( 'blaminhor_essentials_cleanup_email_logs' ) ) {
                wp_schedule_event( time(), 'daily', 'blaminhor_essentials_cleanup_email_logs' );
            }
        }

        // AJAX handlers
        add_action( 'wp_ajax_blaminhor_essentials_smtp_test', array( $this, 'ajax_test_email' ) );
        add_action( 'wp_ajax_blaminhor_essentials_smtp_test_relay', array( $this, 'ajax_test_relay' ) );
        add_action( 'wp_ajax_blaminhor_essentials_smtp_delete_relay', array( $this, 'ajax_delete_relay' ) );
        add_action( 'wp_ajax_blaminhor_essentials_smtp_reorder', array( $this, 'ajax_reorder_relays' ) );
        add_action( 'wp_ajax_blaminhor_essentials_smtp_clear_logs', array( $this, 'ajax_clear_logs' ) );
        add_action( 'wp_ajax_blaminhor_essentials_smtp_import', array( $this, 'ajax_import_smtp' ) );
    }

    /**
     * Enqueue module assets
     *
     * @param string $hook Admin page hook.
     */
    public function enqueue_assets( $hook ) {
        if ( strpos( $hook, 'blaminhor-essentials-smtp' ) === false ) {
            return;
        }

        $config = array(
            'nonce'     => wp_create_nonce( 'blaminhor_essentials_admin' ),
            'ajaxurl'   => admin_url( 'admin-ajax.php' ),
            'providers' => $this->providers,
            'strings'   => array(
                'note'            => __( 'Note:', 'blaminhor-essentials' ),
                'editRelay'       => __( 'Edit Relay', 'blaminhor-essentials' ),
                'updateRelay'     => __( 'Update Relay', 'blaminhor-essentials' ),
                'addNewRelay'     => __( 'Add New SMTP Relay', 'blaminhor-essentials' ),
                'addRelay'        => __( 'Add Relay', 'blaminhor-essentials' ),
                'unchanged'       => __( 'Unchanged', 'blaminhor-essentials' ),
                'success'         => __( 'Success! Email sent.', 'blaminhor-essentials' ),
                'failed'          => __( 'Failed: ', 'blaminhor-essentials' ),
                'ajaxError'       => __( 'AJAX Error', 'blaminhor-essentials' ),
                'sending'         => __( 'Sending...', 'blaminhor-essentials' ),
                'sendTestEmail'   => __( 'Send Test Email', 'blaminhor-essentials' ),
                'confirmClearLogs' => __( 'Are you sure you want to delete all email logs?', 'blaminhor-essentials' ),
            ),
        );

        wp_add_inline_script(
            'blaminhor-essentials-modules',
            'jQuery(document).ready(function($) { BlaminhorEssentialsSmtp.init(' . wp_json_encode( $config ) . '); });'
        );
    }

    /**
     * Create email log table if needed
     */
    private function maybe_create_log_table() {
        $installed_version = get_option( 'blaminhor_essentials_smtp_db_version', '0' );

        if ( version_compare( $installed_version, $this->db_version, '>=' ) ) {
            return;
        }

        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$this->log_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            date_sent datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            to_email varchar(255) NOT NULL,
            subject varchar(255) NOT NULL,
            relay_name varchar(100) DEFAULT NULL,
            status varchar(20) NOT NULL DEFAULT 'sent',
            error_message text DEFAULT NULL,
            headers text DEFAULT NULL,
            attachments text DEFAULT NULL,
            PRIMARY KEY (id),
            KEY date_sent (date_sent),
            KEY status (status)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );

        update_option( 'blaminhor_essentials_smtp_db_version', $this->db_version );
    }

    /**
     * Configure PHPMailer
     *
     * @param PHPMailer\PHPMailer\PHPMailer $phpmailer PHPMailer instance.
     */
    public function configure_phpmailer( $phpmailer ) {
        $relays = $this->get_setting( 'relays', array() );

        if ( empty( $relays ) ) {
            return;
        }

        // Get active relays sorted by priority
        $active_relays = array_filter( $relays, function ( $relay ) {
            return ! empty( $relay['enabled'] );
        } );

        if ( empty( $active_relays ) ) {
            return;
        }

        // Use first active relay
        $relay = reset( $active_relays );

        // Store for logging
        $phpmailer->ap_relay_name = $relay['name'];

        // Configure SMTP
        $phpmailer->isSMTP();
        $phpmailer->Host     = $relay['host'];
        $phpmailer->Port     = (int) $relay['port'];
        $phpmailer->SMTPAuth = ! empty( $relay['username'] );
        $phpmailer->Username = $relay['username'];
        $phpmailer->Password = blaminhor_essentials_decrypt( $relay['password'] );

        // Per-relay Sender Overrides
        if ( ! empty( $relay['from_email'] ) && is_email( $relay['from_email'] ) ) {
            $phpmailer->From   = $relay['from_email'];
            $phpmailer->Sender = $relay['from_email'];

            if ( ! empty( $relay['from_name'] ) ) {
                $phpmailer->FromName = $relay['from_name'];
            }
        }

        // Encryption
        switch ( $relay['encryption'] ) {
            case 'ssl':
                $phpmailer->SMTPSecure = 'ssl';
                break;
            case 'tls':
                $phpmailer->SMTPSecure = 'tls';
                break;
            default:
                $phpmailer->SMTPSecure  = '';
                $phpmailer->SMTPAutoTLS = false;
                break;
        }

        // SSL verification
        if ( $this->get_setting( 'disable_ssl_verify', false ) ) {
            $phpmailer->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true,
                ),
            );
        }

        // Return path from global settings
        $global_from = $this->get_setting( 'from_email' );
        if ( ! empty( $global_from ) && is_email( $global_from ) ) {
            $phpmailer->Sender = $global_from;
        }

        // Debug mode for testing
        if ( defined( 'BLAMINHOR_ESSENTIALS_SMTP_DEBUG' ) && BLAMINHOR_ESSENTIALS_SMTP_DEBUG ) {
            $phpmailer->SMTPDebug = 2;
        }
    }

    /**
     * Filter from email
     *
     * @param string $email Original email.
     * @return string
     */
    public function filter_from_email( $email ) {
        if ( $this->get_setting( 'force_from_email', false ) ) {
            $custom_email = $this->get_setting( 'from_email', '' );
            if ( ! empty( $custom_email ) && is_email( $custom_email ) ) {
                return $custom_email;
            }
        }
        return $email;
    }

    /**
     * Filter from name
     *
     * @param string $name Original name.
     * @return string
     */
    public function filter_from_name( $name ) {
        if ( $this->get_setting( 'force_from_name', false ) ) {
            $custom_name = $this->get_setting( 'from_name', '' );
            if ( ! empty( $custom_name ) ) {
                return $custom_name;
            }
        }
        return $name;
    }

    /**
     * Log successful email
     *
     * @param array $mail_data Email data.
     */
    public function log_email_success( $mail_data ) {
        global $wpdb, $phpmailer;

        $relay_name = isset( $phpmailer->ap_relay_name ) ? $phpmailer->ap_relay_name : '';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            $this->log_table,
            array(
                'date_sent'   => current_time( 'mysql' ),
                'to_email'    => is_array( $mail_data['to'] ) ? implode( ', ', $mail_data['to'] ) : $mail_data['to'],
                'subject'     => $mail_data['subject'],
                'relay_name'  => $relay_name,
                'status'      => 'sent',
                'headers'     => is_array( $mail_data['headers'] ) ? wp_json_encode( $mail_data['headers'] ) : $mail_data['headers'],
                'attachments' => is_array( $mail_data['attachments'] ) ? wp_json_encode( $mail_data['attachments'] ) : '',
            ),
            array( '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
        );
    }

    /**
     * Log failed email
     *
     * @param WP_Error $error Error object.
     */
    public function log_email_failure( $error ) {
        global $wpdb, $phpmailer;

        $relay_name = isset( $phpmailer->ap_relay_name ) ? $phpmailer->ap_relay_name : '';
        $mail_data  = $error->get_error_data();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            $this->log_table,
            array(
                'date_sent'     => current_time( 'mysql' ),
                'to_email'      => is_array( $mail_data['to'] ) ? implode( ', ', $mail_data['to'] ) : $mail_data['to'],
                'subject'       => isset( $mail_data['subject'] ) ? $mail_data['subject'] : '',
                'relay_name'    => $relay_name,
                'status'        => 'failed',
                'error_message' => $error->get_error_message(),
                'headers'       => is_array( $mail_data['headers'] ) ? wp_json_encode( $mail_data['headers'] ) : '',
                'attachments'   => is_array( $mail_data['attachments'] ) ? wp_json_encode( $mail_data['attachments'] ) : '',
            ),
            array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
        );

        // Try fallback relay
        $this->try_fallback_relay( $mail_data );
    }

    /**
     * Try fallback relay
     *
     * @param array $mail_data Email data.
     */
    private function try_fallback_relay( $mail_data ) {
        $relays        = $this->get_setting( 'relays', array() );
        $active_relays = array_filter( $relays, function ( $relay ) {
            return ! empty( $relay['enabled'] );
        } );

        // If only one relay, no fallback available
        if ( count( $active_relays ) <= 1 ) {
            return;
        }

        // Skip to next relay and retry
        array_shift( $active_relays );

        if ( ! empty( $active_relays ) ) {
            // Temporarily update settings to use next relay
            $temp_relays            = $active_relays;
            $this->settings['relays'] = $temp_relays;

            // Retry sending
            wp_mail(
                $mail_data['to'],
                $mail_data['subject'],
                $mail_data['message'],
                $mail_data['headers'],
                $mail_data['attachments']
            );
        }
    }

    /**
     * Cleanup old logs
     */
    public function cleanup_old_logs() {
        global $wpdb;

        $days = $this->get_setting( 'log_retention_days', 30 );
        $date = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );

        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$this->log_table} WHERE date_sent < %s",
                $date
            )
        );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
    }

    /**
     * AJAX test email
     */
    public function ajax_test_email() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

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

        if ( ! is_email( $email ) ) {
            wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'blaminhor-essentials' ) ) );
        }

        // Check if a valid sender is available
        $global_from      = $this->get_setting( 'from_email' );
        $has_relay_config = false;
        $relays           = $this->get_setting( 'relays', array() );

        foreach ( $relays as $relay ) {
            if ( ! empty( $relay['enabled'] ) && ! empty( $relay['from_email'] ) ) {
                $has_relay_config = true;
                break;
            }
        }

        if ( empty( $global_from ) && ! $has_relay_config ) {
            wp_send_json_error( array( 'message' => __( 'Configuration Error: No "From Email" configured. Please set a "From Email" in your Relay settings (recommended) or General Settings.', 'blaminhor-essentials' ) ) );
        }

        $subject = sprintf(
            /* translators: %s: Site name */
            __( '[%s] Test Email from Blaminhor Essentials SMTP', 'blaminhor-essentials' ),
            get_bloginfo( 'name' )
        );

        $message  = '<h2>' . esc_html__( 'Test Email Success!', 'blaminhor-essentials' ) . '</h2>';
        $message .= '<p>' . esc_html__( 'This is a test email sent from Blaminhor Essentials SMTP module.', 'blaminhor-essentials' ) . '</p>';
        $message .= '<p>' . esc_html__( 'If you are reading this, your SMTP configuration is working correctly!', 'blaminhor-essentials' ) . '</p>';
        $message .= '<hr>';
        $message .= '<p>';
        $message .= '<strong>' . esc_html__( 'Site:', 'blaminhor-essentials' ) . '</strong> ' . esc_html( get_bloginfo( 'name' ) ) . '<br>';
        $message .= '<strong>' . esc_html__( 'URL:', 'blaminhor-essentials' ) . '</strong> <a href="' . esc_url( home_url() ) . '">' . esc_html( home_url() ) . '</a><br>';
        $message .= '<strong>' . esc_html__( 'Time:', 'blaminhor-essentials' ) . '</strong> ' . esc_html( current_time( 'mysql' ) );
        $message .= '</p>';

        $headers = array( 'Content-Type: text/html; charset=UTF-8' );

        $result = wp_mail( $email, $subject, $message, $headers );

        if ( $result ) {
            wp_send_json_success( array(
                'message'         => __( 'Test email sent successfully! Check your inbox.', 'blaminhor-essentials' ),
                'logging_enabled' => (bool) $this->get_setting( 'enable_logging', false ),
            ) );
        } else {
            global $phpmailer;
            $error_message = '';

            if ( isset( $phpmailer ) && isset( $phpmailer->ErrorInfo ) ) {
                $error_message = $phpmailer->ErrorInfo;
            }

            wp_send_json_error( array(
                'message' => sprintf(
                    /* translators: %s: Error message */
                    __( 'Failed to send test email. Error: %s', 'blaminhor-essentials' ),
                    $error_message ? $error_message : __( 'Unknown error', 'blaminhor-essentials' )
                ),
            ) );
        }
    }

    /**
     * AJAX test specific relay
     */
    public function ajax_test_relay() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

        $relay_index = isset( $_POST['relay_index'] ) ? absint( $_POST['relay_index'] ) : -1;
        $relays      = $this->get_setting( 'relays', array() );

        if ( ! isset( $relays[ $relay_index ] ) ) {
            wp_send_json_error( array( 'message' => __( 'Relay not found.', 'blaminhor-essentials' ) ) );
        }

        $relay    = $relays[ $relay_index ];
        $to_email = wp_get_current_user()->user_email;

        // Store relay config for test
        $this->temp_relay_config = $relay;

        // Remove standard hook and add temp hook
        remove_action( 'phpmailer_init', array( $this, 'configure_phpmailer' ), 999 );
        add_action( 'phpmailer_init', array( $this, 'configure_phpmailer_for_test' ), 999 );

        $subject = sprintf(
            /* translators: %s: Relay name */
            __( 'Test Email via Relay: %s', 'blaminhor-essentials' ),
            $relay['name']
        );

        $message  = '<h2>' . esc_html__( 'Relay Connection Test', 'blaminhor-essentials' ) . '</h2>';
        $message .= '<p>' . sprintf(
            /* translators: %s: Relay name */
            esc_html__( 'This is a test email sent specifically via the relay: %s', 'blaminhor-essentials' ),
            '<strong>' . esc_html( $relay['name'] ) . '</strong>'
        ) . '</p>';
        $message .= '<p><strong>' . esc_html__( 'Host:', 'blaminhor-essentials' ) . '</strong> ' . esc_html( $relay['host'] ) . ':' . intval( $relay['port'] ) . '</p>';
        $message .= '<p><strong>' . esc_html__( 'Encryption:', 'blaminhor-essentials' ) . '</strong> ' . esc_html( strtoupper( $relay['encryption'] ) ) . '</p>';
        $message .= '<hr>';
        $message .= '<p>' . esc_html__( 'If you received this, the relay configuration is correct.', 'blaminhor-essentials' ) . '</p>';

        // Build headers with From email from relay config
        $headers = array( 'Content-Type: text/html; charset=UTF-8' );
        if ( ! empty( $relay['from_email'] ) && is_email( $relay['from_email'] ) ) {
            $from_name = ! empty( $relay['from_name'] ) ? $relay['from_name'] : get_bloginfo( 'name' );
            $headers[] = 'From: ' . $from_name . ' <' . $relay['from_email'] . '>';
        }

        $result = wp_mail( $to_email, $subject, $message, $headers );

        // Cleanup
        remove_action( 'phpmailer_init', array( $this, 'configure_phpmailer_for_test' ), 999 );
        add_action( 'phpmailer_init', array( $this, 'configure_phpmailer' ), 999 );
        unset( $this->temp_relay_config );

        if ( $result ) {
            wp_send_json_success( array( 'message' => __( 'Test email sent successfully.', 'blaminhor-essentials' ) ) );
        } else {
            global $phpmailer;
            $error_msg = __( 'Unknown error', 'blaminhor-essentials' );

            if ( isset( $phpmailer->ErrorInfo ) && ! empty( $phpmailer->ErrorInfo ) ) {
                $error_msg = $phpmailer->ErrorInfo;
            }

            wp_send_json_error( array( 'message' => $error_msg ) );
        }
    }

    /**
     * Temporary mailer config for testing
     *
     * @param PHPMailer\PHPMailer\PHPMailer $phpmailer PHPMailer instance.
     */
    public function configure_phpmailer_for_test( $phpmailer ) {
        if ( ! isset( $this->temp_relay_config ) ) {
            return;
        }

        $relay = $this->temp_relay_config;

        // Store relay name for logging
        $phpmailer->ap_relay_name = $relay['name'];

        $phpmailer->isSMTP();
        $phpmailer->Host       = $relay['host'];
        $phpmailer->Port       = $relay['port'];
        $phpmailer->SMTPSecure = 'none' === $relay['encryption'] ? '' : $relay['encryption'];
        $phpmailer->SMTPAuth   = true;
        $phpmailer->Username   = $relay['username'];
        $phpmailer->Password   = blaminhor_essentials_decrypt( $relay['password'] );

        // Sender
        if ( ! empty( $relay['from_email'] ) && is_email( $relay['from_email'] ) ) {
            $phpmailer->setFrom( $relay['from_email'], ! empty( $relay['from_name'] ) ? $relay['from_name'] : '' );
            $phpmailer->Sender = $relay['from_email'];
        }
    }

    /**
     * AJAX delete relay
     */
    public function ajax_delete_relay() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

        $relay_id = isset( $_POST['relay_id'] ) ? absint( $_POST['relay_id'] ) : 0;

        $relays = $this->get_setting( 'relays', array() );

        if ( isset( $relays[ $relay_id ] ) ) {
            unset( $relays[ $relay_id ] );
            $relays = array_values( $relays );
            $this->save_settings( array_merge( $this->settings, array( 'relays' => $relays ) ) );
            wp_send_json_success( array( 'message' => __( 'Relay deleted.', 'blaminhor-essentials' ) ) );
        }

        wp_send_json_error( array( 'message' => __( 'Relay not found.', 'blaminhor-essentials' ) ) );
    }

    /**
     * AJAX reorder relays
     */
    public function ajax_reorder_relays() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

        $order = isset( $_POST['order'] ) ? array_map( 'absint', wp_unslash( (array) $_POST['order'] ) ) : array();

        $relays     = $this->get_setting( 'relays', array() );
        $new_relays = array();

        foreach ( $order as $index ) {
            if ( isset( $relays[ $index ] ) ) {
                $new_relays[] = $relays[ $index ];
            }
        }

        $this->save_settings( array_merge( $this->settings, array( 'relays' => $new_relays ) ) );

        wp_send_json_success( array( 'message' => __( 'Order saved.', 'blaminhor-essentials' ) ) );
    }

    /**
     * AJAX clear logs
     */
    public function ajax_clear_logs() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

        global $wpdb;

        // Use prepared statement for table name safety
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( "TRUNCATE TABLE `{$wpdb->prefix}blaminhor_essentials_email_log`" );

        wp_send_json_success( array( 'message' => __( 'Email logs cleared.', 'blaminhor-essentials' ) ) );
    }

    /**
     * Get email logs
     *
     * @param int $per_page Items per page.
     * @param int $page     Current page.
     * @return array
     */
    private function get_email_logs( $per_page = 20, $page = 1 ) {
        global $wpdb;

        $offset = ( $page - 1 ) * $per_page;

        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
        $logs = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$this->log_table} ORDER BY date_sent DESC LIMIT %d OFFSET %d",
                $per_page,
                $offset
            )
        );

        $total = $wpdb->get_var( "SELECT COUNT(*) FROM {$this->log_table}" );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter

        return array(
            'logs'  => $logs,
            'total' => (int) $total,
            'pages' => ceil( $total / $per_page ),
        );
    }

    /**
     * Process settings
     *
     * @param array $data Form data.
     */
    protected function process_settings( $data ) {
        // WordPress slashes $_POST automatically. Unslash once recursively so
        // sanitize_* calls below receive clean input and apostrophes do not
        // accumulate backslashes across successive saves.
        $data = wp_unslash( $data );

        $settings = $this->settings;

        // Handle relay form submission
        if ( isset( $data['add_relay'] ) ) {
            $relay_from_email = sanitize_email( $data['relay_from_email'] );

            if ( empty( $relay_from_email ) ) {
                add_action( 'admin_notices', function () {
                    blaminhor_essentials_admin_notice( __( 'Error: "From Email" is required for the relay.', 'blaminhor-essentials' ), 'error' );
                } );
                return;
            }

            $relay = array(
                'name'       => sanitize_text_field( $data['relay_name'] ),
                'provider'   => sanitize_key( $data['relay_provider'] ),
                'host'       => sanitize_text_field( $data['relay_host'] ),
                'port'       => absint( $data['relay_port'] ),
                'encryption' => sanitize_key( $data['relay_encryption'] ),
                'username'   => sanitize_text_field( $data['relay_username'] ),
                'password'   => blaminhor_essentials_encrypt( $data['relay_password'] ),
                'from_email' => $relay_from_email,
                'from_name'  => sanitize_text_field( $data['relay_from_name'] ),
                'enabled'    => isset( $data['relay_enabled'] ),
            );

            $settings['relays'][] = $relay;
        }

        // Handle relay update
        if ( isset( $data['update_relay'] ) && isset( $data['relay_index'] ) ) {
            $relay_index      = absint( $data['relay_index'] );
            $relay_from_email = sanitize_email( $data['relay_from_email'] );

            if ( empty( $relay_from_email ) ) {
                add_action( 'admin_notices', function () {
                    blaminhor_essentials_admin_notice( __( 'Error: "From Email" is required for the relay.', 'blaminhor-essentials' ), 'error' );
                } );
                return;
            }

            // Keep existing password if field is empty
            $new_password = ! empty( $data['relay_password'] ) ? blaminhor_essentials_encrypt( $data['relay_password'] ) : '';
            if ( empty( $new_password ) && isset( $settings['relays'][ $relay_index ]['password'] ) ) {
                $new_password = $settings['relays'][ $relay_index ]['password'];
            }

            $relay = array(
                'name'       => sanitize_text_field( $data['relay_name'] ),
                'provider'   => sanitize_key( $data['relay_provider'] ),
                'host'       => sanitize_text_field( $data['relay_host'] ),
                'port'       => absint( $data['relay_port'] ),
                'encryption' => sanitize_key( $data['relay_encryption'] ),
                'username'   => sanitize_text_field( $data['relay_username'] ),
                'password'   => $new_password,
                'from_email' => $relay_from_email,
                'from_name'  => sanitize_text_field( $data['relay_from_name'] ),
                'enabled'    => isset( $data['relay_enabled'] ),
            );

            if ( isset( $settings['relays'][ $relay_index ] ) ) {
                $settings['relays'][ $relay_index ] = $relay;
            }
        }

        // Handle relay deletion via form
        if ( isset( $data['delete_relay'] ) && isset( $data['relay_index'] ) ) {
            $relay_index = absint( $data['relay_index'] );
            if ( isset( $settings['relays'][ $relay_index ] ) ) {
                unset( $settings['relays'][ $relay_index ] );
                $settings['relays'] = array_values( $settings['relays'] );
            }
        }

        // Handle general settings
        if ( isset( $data['save_general'] ) ) {
            $settings['force_from_email']   = isset( $data['force_from_email'] );
            $settings['from_email']         = sanitize_email( $data['from_email'] );
            $settings['force_from_name']    = isset( $data['force_from_name'] );
            $settings['from_name']          = sanitize_text_field( $data['from_name'] );
            $settings['enable_logging']     = isset( $data['enable_logging'] );
            $settings['log_retention_days'] = absint( $data['log_retention_days'] );
            $settings['disable_ssl_verify'] = isset( $data['disable_ssl_verify'] );
        }

        // Handle relay enable/disable toggle
        if ( isset( $data['toggle_relay'] ) && isset( $data['relay_index'] ) ) {
            $relay_index = absint( $data['relay_index'] );
            if ( isset( $settings['relays'][ $relay_index ] ) ) {
                $settings['relays'][ $relay_index ]['enabled'] = ! $settings['relays'][ $relay_index ]['enabled'];
            }
        }

        $this->save_settings( $settings );

        add_action( 'admin_notices', function () {
            blaminhor_essentials_admin_notice( __( 'Settings saved.', 'blaminhor-essentials' ), 'success' );
        } );
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        $relays = $this->get_setting( 'relays', array() );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab display, no data modification
        $current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'config';

        // Get logs for log tab
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Pagination display, no data modification
        $page      = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1;
        $logs_data = $this->get_email_logs( 20, $page );
        ?>
        <div class="wrap blaminhor-essentials-wrap blaminhor-essentials-smtp-settings">
            <div class="blaminhor-essentials-header">
                <h1><?php esc_html_e( 'SMTP Mailer', 'blaminhor-essentials' ); ?></h1>
                <p class="blaminhor-essentials-tagline">
                    <?php esc_html_e( 'Configure SMTP relay with fallback support.', 'blaminhor-essentials' ); ?>
                </p>
            </div>

            <div class="blaminhor-essentials-tabs-wrapper">
                <div class="blaminhor-essentials-tabs">
                    <button class="blaminhor-essentials-tab <?php echo 'config' === $current_tab ? 'active' : ''; ?>"
                        data-tab="config">
                        <?php esc_html_e( 'Configuration', 'blaminhor-essentials' ); ?>
                    </button>
                    <button class="blaminhor-essentials-tab <?php echo 'compare' === $current_tab ? 'active' : ''; ?>"
                        data-tab="compare">
                        <?php esc_html_e( 'Compare Providers', 'blaminhor-essentials' ); ?>
                    </button>
                    <button class="blaminhor-essentials-tab <?php echo 'test' === $current_tab ? 'active' : ''; ?>"
                        data-tab="test">
                        <?php esc_html_e( 'Test Email', 'blaminhor-essentials' ); ?>
                    </button>
                    <button class="blaminhor-essentials-tab <?php echo 'logs' === $current_tab ? 'active' : ''; ?>"
                        data-tab="logs">
                        <?php esc_html_e( 'Email Log', 'blaminhor-essentials' ); ?>
                    </button>
                    <button class="blaminhor-essentials-tab <?php echo 'import' === $current_tab ? 'active' : ''; ?>"
                        data-tab="import">
                        <?php esc_html_e( 'Import', 'blaminhor-essentials' ); ?>
                    </button>
                </div>

                <!-- Configuration Tab (merged General + Relays) -->
                <div class="blaminhor-essentials-tab-content <?php echo 'config' === $current_tab ? 'active' : ''; ?>"
                    data-tab-content="config">

                    <!-- General Settings Section (compact) -->
                    <div class="smtp-general-settings-compact">
                        <form method="post">
                            <?php $this->render_nonce_field(); ?>
                            <input type="hidden" name="save_general" value="1">

                            <h3><?php esc_html_e( 'General Settings', 'blaminhor-essentials' ); ?></h3>
                            <div class="smtp-settings-row">
                                <div class="smtp-setting-col">
                                    <label for="from_email"><?php esc_html_e( 'Default From Email', 'blaminhor-essentials' ); ?></label>
                                    <input type="email" id="from_email" name="from_email"
                                        value="<?php echo esc_attr( $this->get_setting( 'from_email' ) ); ?>"
                                        placeholder="noreply@yourdomain.com">
                                    <label class="smtp-checkbox-inline">
                                        <input type="checkbox" name="force_from_email" <?php checked( $this->get_setting( 'force_from_email' ) ); ?>>
                                        <?php esc_html_e( 'Force for all emails', 'blaminhor-essentials' ); ?>
                                    </label>
                                </div>
                                <div class="smtp-setting-col">
                                    <label for="from_name"><?php esc_html_e( 'From Name', 'blaminhor-essentials' ); ?></label>
                                    <input type="text" id="from_name" name="from_name"
                                        value="<?php echo esc_attr( $this->get_setting( 'from_name' ) ); ?>"
                                        placeholder="<?php esc_attr_e( 'Your Site Name', 'blaminhor-essentials' ); ?>">
                                    <label class="smtp-checkbox-inline">
                                        <input type="checkbox" name="force_from_name" <?php checked( $this->get_setting( 'force_from_name' ) ); ?>>
                                        <?php esc_html_e( 'Force for all emails', 'blaminhor-essentials' ); ?>
                                    </label>
                                </div>
                            </div>
                            <div class="smtp-settings-row smtp-settings-row-options">
                                <label class="smtp-checkbox-inline">
                                    <input type="checkbox" name="enable_logging" <?php checked( $this->get_setting( 'enable_logging' ) ); ?>>
                                    <?php esc_html_e( 'Enable email logging', 'blaminhor-essentials' ); ?>
                                </label>
                                <span class="smtp-option-separator">·</span>
                                <span class="smtp-retention-inline">
                                    <?php esc_html_e( 'Keep logs for', 'blaminhor-essentials' ); ?>
                                    <input type="number" name="log_retention_days" class="small-text"
                                        value="<?php echo esc_attr( $this->get_setting( 'log_retention_days', 30 ) ); ?>" min="1" max="365">
                                    <?php esc_html_e( 'days', 'blaminhor-essentials' ); ?>
                                </span>
                                <span class="smtp-option-separator">·</span>
                                <label class="smtp-checkbox-inline">
                                    <input type="checkbox" name="disable_ssl_verify" <?php checked( $this->get_setting( 'disable_ssl_verify' ) ); ?>>
                                    <?php esc_html_e( 'Disable SSL verification', 'blaminhor-essentials' ); ?>
                                </label>
                                <button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'blaminhor-essentials' ); ?></button>
                            </div>
                        </form>
                    </div>

                    <hr class="smtp-section-divider">

                    <!-- Configured Relays Section -->
                    <h3><?php esc_html_e( 'SMTP Relays', 'blaminhor-essentials' ); ?></h3>
                    <p class="description ap-mb-md">
                        <?php esc_html_e( 'Relays are tried in order. If one fails, the next one is used as fallback.', 'blaminhor-essentials' ); ?>
                    </p>

                    <?php if ( ! empty( $relays ) ) : ?>
                        <div class="smtp-relays-list smtp-relays-enhanced">
                            <?php
                            $first_active_found = false;
                            foreach ( $relays as $index => $relay ) :
                                $is_enabled = ! empty( $relay['enabled'] );
                                $is_primary = $is_enabled && ! $first_active_found;
                                if ( $is_primary ) {
                                    $first_active_found = true;
                                }
                                $item_classes = array( 'smtp-relay-item' );
                                if ( $is_primary ) {
                                    $item_classes[] = 'primary';
                                }
                                if ( ! $is_enabled ) {
                                    $item_classes[] = 'disabled';
                                }
                            ?>
                                <div class="<?php echo esc_attr( implode( ' ', $item_classes ) ); ?>"
                                    data-relay-id="<?php echo esc_attr( $index ); ?>">
                                    <span class="relay-handle dashicons dashicons-menu"></span>
                                    <div class="relay-info">
                                        <div class="relay-name">
                                            <?php echo esc_html( $relay['name'] ); ?>
                                            <?php if ( $is_primary ) : ?>
                                                <span class="relay-badge-primary"><?php esc_html_e( 'Primary', 'blaminhor-essentials' ); ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="relay-host"><?php echo esc_html( $relay['host'] . ':' . $relay['port'] ); ?></div>
                                    </div>
                                    <span class="relay-status <?php echo $is_enabled ? 'active' : 'inactive'; ?>">
                                        <?php echo $is_enabled ? esc_html__( 'Active', 'blaminhor-essentials' ) : esc_html__( 'Inactive', 'blaminhor-essentials' ); ?>
                                    </span>
                                    <div class="relay-actions">
                                        <button type="button" class="button button-secondary test-relay"
                                            title="<?php esc_attr_e( 'Test Connection', 'blaminhor-essentials' ); ?>">
                                            <span class="dashicons dashicons-email"></span>
                                            <span class="relay-action-label"><?php esc_html_e( 'Test', 'blaminhor-essentials' ); ?></span>
                                        </button>
                                        <button type="button" class="button button-secondary edit-relay"
                                            title="<?php esc_attr_e( 'Edit', 'blaminhor-essentials' ); ?>">
                                            <span class="dashicons dashicons-edit"></span>
                                            <span class="relay-action-label"><?php esc_html_e( 'Edit', 'blaminhor-essentials' ); ?></span>
                                        </button>
                                        <form method="post" class="ap-inline-form">
                                            <?php $this->render_nonce_field(); ?>
                                            <input type="hidden" name="toggle_relay" value="1">
                                            <input type="hidden" name="relay_index" value="<?php echo esc_attr( $index ); ?>">
                                            <button type="submit" class="button button-secondary"
                                                title="<?php echo $is_enabled ? esc_attr__( 'Disable', 'blaminhor-essentials' ) : esc_attr__( 'Enable', 'blaminhor-essentials' ); ?>">
                                                <span class="dashicons dashicons-<?php echo $is_enabled ? 'hidden' : 'visibility'; ?>"></span>
                                                <span class="relay-action-label"><?php echo $is_enabled ? esc_html__( 'Disable', 'blaminhor-essentials' ) : esc_html__( 'Enable', 'blaminhor-essentials' ); ?></span>
                                            </button>
                                        </form>
                                        <form method="post" class="ap-inline-form"
                                            onsubmit="return confirm('<?php esc_attr_e( 'Are you sure?', 'blaminhor-essentials' ); ?>');">
                                            <?php $this->render_nonce_field(); ?>
                                            <input type="hidden" name="delete_relay" value="1">
                                            <input type="hidden" name="relay_index" value="<?php echo esc_attr( $index ); ?>">
                                            <button type="submit" class="button button-link-delete delete-relay"
                                                title="<?php esc_attr_e( 'Delete', 'blaminhor-essentials' ); ?>">
                                                <span class="dashicons dashicons-trash"></span>
                                            </button>
                                        </form>
                                    </div>
                                    <script type="application/json" class="relay-data"><?php echo wp_json_encode( $relay ); ?></script>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else : ?>
                        <div class="blaminhor-essentials-notice info">
                            <?php esc_html_e( 'No SMTP relays configured yet. Add one below.', 'blaminhor-essentials' ); ?>
                        </div>
                    <?php endif; ?>

                    <hr class="smtp-section-divider">

                    <!-- Add/Edit Relay Form -->
                    <h3><span id="form-title"><?php esc_html_e( 'Add New SMTP Relay', 'blaminhor-essentials' ); ?></span></h3>

                    <form method="post" id="add-relay-form">
                        <?php $this->render_nonce_field(); ?>
                        <input type="hidden" name="add_relay" value="1" id="action_add_relay">
                        <input type="hidden" name="update_relay" value="0" id="action_update_relay" disabled>
                        <input type="hidden" name="relay_index" value="" id="relay_index">

                        <div class="smtp-provider-select-wrapper">
                            <label for="smtp-provider-select"><strong><?php esc_html_e( 'Provider', 'blaminhor-essentials' ); ?></strong></label>
                            <div class="ap-flex-center ap-gap-md">
                                <select id="smtp-provider-select" class="smtp-provider-select">
                                    <option value=""><?php esc_html_e( '— Select a provider —', 'blaminhor-essentials' ); ?></option>
                                    <?php foreach ( $this->providers as $key => $provider ) : ?>
                                        <option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $provider['name'] ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <a href="#compare" class="smtp-compare-link" onclick="if(typeof BlaminhorEssentialsActivateTab==='function'){BlaminhorEssentialsActivateTab('compare');return false;}">
                                    <?php esc_html_e( 'Compare SMTP providers', 'blaminhor-essentials' ); ?>
                                </a>
                            </div>
                        </div>

                        <!-- Provider Setup Tutorial -->
                        <div id="smtp-provider-tutorial" class="smtp-tutorial ap-hidden">
                            <h4 id="smtp-tutorial-title"></h4>
                            <ol id="smtp-tutorial-steps"></ol>
                            <p id="smtp-tutorial-note" class="description"></p>
                        </div>

                        <?php
                        // Output tutorials data for JavaScript
                        $tutorials = $this->get_provider_tutorials();
                        ?>
                        <script type="application/json" id="smtp-tutorials-data"><?php echo wp_json_encode( $tutorials ); ?></script>

                        <input type="hidden" id="smtp-provider" name="relay_provider" value="other">

                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="relay_name"><?php esc_html_e( 'Relay Name', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="relay_name" name="relay_name" class="regular-text" required
                                        placeholder="<?php esc_attr_e( 'e.g., Primary SMTP', 'blaminhor-essentials' ); ?>">
                                    <p class="description">
                                        <?php esc_html_e( 'A friendly name to identify this relay.', 'blaminhor-essentials' ); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="smtp-host"><?php esc_html_e( 'SMTP Host', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="smtp-host" name="relay_host" class="regular-text" required
                                        placeholder="smtp.example.com">
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="smtp-port"><?php esc_html_e( 'SMTP Port', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="smtp-port" name="relay_port" class="small-text" value="587" required>
                                    <p class="description">
                                        <?php esc_html_e( 'Common ports: 25, 465 (SSL), 587 (TLS), 2525', 'blaminhor-essentials' ); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="smtp-encryption"><?php esc_html_e( 'Encryption', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <select id="smtp-encryption" name="relay_encryption">
                                        <option value="tls"><?php esc_html_e( 'TLS', 'blaminhor-essentials' ); ?></option>
                                        <option value="ssl"><?php esc_html_e( 'SSL', 'blaminhor-essentials' ); ?></option>
                                        <option value="none"><?php esc_html_e( 'None', 'blaminhor-essentials' ); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="relay_username"><?php esc_html_e( 'Username', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="relay_username" name="relay_username" class="regular-text" autocomplete="off">
                                    <p class="description">
                                        <?php esc_html_e( 'Usually your email address or API key.', 'blaminhor-essentials' ); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="relay_password"><?php esc_html_e( 'Password', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="password" id="relay_password" name="relay_password" class="regular-text" autocomplete="new-password">
                                    <p class="description">
                                        <?php esc_html_e( 'Password or API key. Stored encrypted.', 'blaminhor-essentials' ); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="relay_from_email"><?php esc_html_e( 'From Email', 'blaminhor-essentials' ); ?>
                                        <span class="description ap-text-danger">(<?php esc_html_e( 'Required', 'blaminhor-essentials' ); ?>)</span>
                                    </label>
                                </th>
                                <td>
                                    <input type="email" id="relay_from_email" name="relay_from_email" class="regular-text" required
                                        placeholder="<?php esc_attr_e( 'e.g. newsletter@yourdomain.com', 'blaminhor-essentials' ); ?>">
                                    <p class="description">
                                        <?php esc_html_e( 'The authenticated sender email for this relay.', 'blaminhor-essentials' ); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="relay_from_name"><?php esc_html_e( 'From Name (Optional)', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="relay_from_name" name="relay_from_name" class="regular-text"
                                        placeholder="<?php esc_attr_e( 'Overrides global default', 'blaminhor-essentials' ); ?>">
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Enable', 'blaminhor-essentials' ); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="relay_enabled" value="1" checked>
                                        <?php esc_html_e( 'Activate this relay immediately', 'blaminhor-essentials' ); ?>
                                    </label>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <button type="submit" class="button button-primary" id="btn-save-relay"><?php esc_html_e( 'Add Relay', 'blaminhor-essentials' ); ?></button>
                            <button type="button" class="button button-secondary ap-hidden" id="btn-cancel-edit"><?php esc_html_e( 'Cancel', 'blaminhor-essentials' ); ?></button>
                        </p>
                    </form>
                </div>

                <!-- Compare Providers Tab -->
                <div class="blaminhor-essentials-tab-content <?php echo 'compare' === $current_tab ? 'active' : ''; ?>"
                    data-tab-content="compare">
                    <h3><?php esc_html_e( 'Free SMTP Provider Comparison', 'blaminhor-essentials' ); ?></h3>
                    <p class="description">
                        <?php esc_html_e( 'Compare the free tiers of popular SMTP providers to choose the best one for your needs.', 'blaminhor-essentials' ); ?>
                    </p>

                    <table class="widefat striped ap-mt-lg">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Provider', 'blaminhor-essentials' ); ?></th>
                                <th><?php esc_html_e( 'Free Emails/Month', 'blaminhor-essentials' ); ?></th>
                                <th><?php esc_html_e( 'Daily Limit', 'blaminhor-essentials' ); ?></th>
                                <th><?php esc_html_e( 'Requirements', 'blaminhor-essentials' ); ?></th>
                                <th><?php esc_html_e( 'Best For', 'blaminhor-essentials' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Brevo</strong></td>
                                <td>300 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>300</td>
                                <td><?php esc_html_e( 'Email verification', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Small sites, easy setup', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>SendGrid</strong></td>
                                <td>100 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>100</td>
                                <td><?php esc_html_e( 'Domain verification (DNS)', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Developers, API integration', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Mailgun</strong></td>
                                <td>1 000 (<?php esc_html_e( 'first 3 months', 'blaminhor-essentials' ); ?>)</td>
                                <td>-</td>
                                <td><?php esc_html_e( 'Credit card, domain DNS', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Transactional emails', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Amazon SES</strong></td>
                                <td>62 000 (<?php esc_html_e( 'from EC2', 'blaminhor-essentials' ); ?>)</td>
                                <td>-</td>
                                <td><?php esc_html_e( 'AWS account, domain DNS', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'High volume, AWS users', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Postmark</strong></td>
                                <td>100 / <?php esc_html_e( 'month', 'blaminhor-essentials' ); ?></td>
                                <td>-</td>
                                <td><?php esc_html_e( 'Email verification', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Transactional only', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>SparkPost</strong></td>
                                <td>500 / <?php esc_html_e( 'month', 'blaminhor-essentials' ); ?></td>
                                <td>100</td>
                                <td><?php esc_html_e( 'Domain DNS', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Small transactional', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Mailjet</strong></td>
                                <td>6 000 / <?php esc_html_e( 'month', 'blaminhor-essentials' ); ?></td>
                                <td>200</td>
                                <td><?php esc_html_e( 'Email verification', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Marketing + transactional', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>SMTP2GO</strong></td>
                                <td>1 000 / <?php esc_html_e( 'month', 'blaminhor-essentials' ); ?></td>
                                <td>-</td>
                                <td><?php esc_html_e( 'Email verification', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Simple SMTP relay', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Elastic Email</strong></td>
                                <td>100 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>100</td>
                                <td><?php esc_html_e( 'Email verification', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Budget-friendly', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Gmail / Google</strong></td>
                                <td>500 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>500</td>
                                <td><?php esc_html_e( 'App Password or OAuth', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Personal sites', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Outlook / Office 365</strong></td>
                                <td>300 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>300</td>
                                <td><?php esc_html_e( 'App Password', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Microsoft users', 'blaminhor-essentials' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Zoho Mail</strong></td>
                                <td>50 / <?php esc_html_e( 'day', 'blaminhor-essentials' ); ?></td>
                                <td>50</td>
                                <td><?php esc_html_e( 'Zoho account', 'blaminhor-essentials' ); ?></td>
                                <td><?php esc_html_e( 'Zoho users', 'blaminhor-essentials' ); ?></td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="blaminhor-essentials-notice info ap-mt-lg">
                        <strong><?php esc_html_e( 'Recommendation:', 'blaminhor-essentials' ); ?></strong>
                        <?php esc_html_e( 'For most WordPress sites, Brevo or Mailjet offer the best balance of free quota and ease of setup. For high-volume sites on AWS, Amazon SES is unbeatable.', 'blaminhor-essentials' ); ?>
                    </div>
                </div>

                <!-- Test Email Tab -->
                <div class="blaminhor-essentials-tab-content <?php echo 'test' === $current_tab ? 'active' : ''; ?>"
                    data-tab-content="test">
                    <h3><?php esc_html_e( 'Send Test Email', 'blaminhor-essentials' ); ?></h3>
                    <p class="description">
                        <?php esc_html_e( 'Send a test email to verify your SMTP configuration is working.', 'blaminhor-essentials' ); ?>
                    </p>

                    <?php if ( empty( $relays ) ) : ?>
                        <div class="blaminhor-essentials-notice warning">
                            <?php esc_html_e( 'Please configure at least one SMTP relay before testing.', 'blaminhor-essentials' ); ?>
                        </div>
                    <?php else : ?>
                        <form id="smtp-test-form">
                            <table class="form-table">
                                <tr>
                                    <th scope="row">
                                        <label for="test-email"><?php esc_html_e( 'Recipient Email', 'blaminhor-essentials' ); ?></label>
                                    </th>
                                    <td>
                                        <input type="email" id="test-email" name="test_email" class="regular-text"
                                            value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>" required>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary"><?php esc_html_e( 'Send Test Email', 'blaminhor-essentials' ); ?></button>
                            </p>

                            <div id="smtp-test-result" class="ap-mt-md"></div>
                        </form>
                    <?php endif; ?>
                </div>

                <!-- Email Log Tab -->
                <div class="blaminhor-essentials-tab-content <?php echo 'logs' === $current_tab ? 'active' : ''; ?>"
                    data-tab-content="logs">
                    <div class="ap-flex-between ap-mb-lg">
                        <h3 style="margin: 0;"><?php esc_html_e( 'Email Log', 'blaminhor-essentials' ); ?></h3>
                        <?php if ( ! empty( $logs_data['logs'] ) ) : ?>
                            <button type="button" id="clear-logs-btn" class="button button-secondary"><?php esc_html_e( 'Clear All Logs', 'blaminhor-essentials' ); ?></button>
                        <?php endif; ?>
                    </div>

                    <?php if ( ! $this->get_setting( 'enable_logging' ) ) : ?>
                        <div class="blaminhor-essentials-notice info">
                            <?php
                            printf(
                                /* translators: %s: Link to Configuration tab */
                                esc_html__( 'Email logging is currently disabled. %s to start logging emails.', 'blaminhor-essentials' ),
                                '<a href="#" class="smtp-go-to-config">' . esc_html__( 'Enable it in Configuration', 'blaminhor-essentials' ) . '</a>'
                            );
                            ?>
                        </div>
                    <?php elseif ( empty( $logs_data['logs'] ) ) : ?>
                        <div class="blaminhor-essentials-notice info">
                            <?php esc_html_e( 'No emails logged yet.', 'blaminhor-essentials' ); ?>
                        </div>
                    <?php else : ?>
                        <table class="email-log-table widefat ap-sortable-table">
                            <thead>
                                <tr>
                                    <th class="ap-sortable desc" data-sort="number"><?php esc_html_e( 'Date', 'blaminhor-essentials' ); ?> <span class="ap-sort-icon"></span></th>
                                    <th class="ap-sortable" data-sort="string"><?php esc_html_e( 'To', 'blaminhor-essentials' ); ?> <span class="ap-sort-icon"></span></th>
                                    <th class="ap-sortable" data-sort="string"><?php esc_html_e( 'Subject', 'blaminhor-essentials' ); ?> <span class="ap-sort-icon"></span></th>
                                    <th class="ap-sortable" data-sort="string"><?php esc_html_e( 'Relay', 'blaminhor-essentials' ); ?> <span class="ap-sort-icon"></span></th>
                                    <th class="ap-sortable" data-sort="string"><?php esc_html_e( 'Status', 'blaminhor-essentials' ); ?> <span class="ap-sort-icon"></span></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ( $logs_data['logs'] as $log ) : ?>
                                    <tr data-date="<?php echo esc_attr( strtotime( $log->date_sent ) ); ?>" data-to="<?php echo esc_attr( $log->to_email ); ?>" data-subject="<?php echo esc_attr( $log->subject ); ?>" data-relay="<?php echo esc_attr( $log->relay_name ? $log->relay_name : '-' ); ?>" data-status="<?php echo esc_attr( $log->status ); ?>">
                                        <td><?php echo esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $log->date_sent ) ) ); ?></td>
                                        <td><?php echo esc_html( $log->to_email ); ?></td>
                                        <td><?php echo esc_html( $log->subject ); ?></td>
                                        <td><?php echo esc_html( $log->relay_name ? $log->relay_name : '-' ); ?></td>
                                        <td class="status-<?php echo esc_attr( $log->status ); ?>">
                                            <?php echo 'sent' === $log->status ? esc_html__( 'Sent', 'blaminhor-essentials' ) : esc_html__( 'Failed', 'blaminhor-essentials' ); ?>
                                            <?php if ( $log->error_message ) : ?>
                                                <br><small><?php echo esc_html( $log->error_message ); ?></small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>

                        <?php if ( $logs_data['pages'] > 1 ) : ?>
                            <div class="tablenav bottom">
                                <div class="tablenav-pages">
                                    <?php
                                    echo wp_kses_post( paginate_links( array(
                                        'base'      => add_query_arg( 'log_page', '%#%' ),
                                        'format'    => '',
                                        'current'   => $page,
                                        'total'     => $logs_data['pages'],
                                        'prev_text' => '&laquo;',
                                        'next_text' => '&raquo;',
                                    ) ) );
                                    ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <!-- Import Tab -->
                <div class="blaminhor-essentials-tab-content <?php echo 'import' === $current_tab ? 'active' : ''; ?>"
                    data-tab-content="import">
                    <h3><?php esc_html_e( 'Import SMTP Configuration', 'blaminhor-essentials' ); ?></h3>
                    <p class="description"><?php esc_html_e( 'Import SMTP settings from other popular email plugins.', 'blaminhor-essentials' ); ?></p>

                    <?php
                    $import_sources = $this->get_available_import_sources();

                    if ( empty( $import_sources ) ) :
                    ?>
                        <div class="blaminhor-essentials-notice info">
                            <?php esc_html_e( 'No SMTP plugins with importable configuration found. Supported plugins: WP Mail SMTP, Post SMTP, Easy WP SMTP.', 'blaminhor-essentials' ); ?>
                        </div>
                    <?php else : ?>
                        <div class="ap-import-sources">
                            <?php foreach ( $import_sources as $source_id => $source ) : ?>
                                <div class="ap-import-source-card">
                                    <div class="ap-import-source-layout">
                                        <div class="ap-import-source-info">
                                            <h4 class="ap-import-source-title">
                                                <span class="dashicons dashicons-email-alt ap-icon-mr"></span>
                                                <?php echo esc_html( $source['name'] ); ?>
                                            </h4>
                                            <table class="smtp-import-preview">
                                                <?php if ( ! empty( $source['config']['from_email'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'From Email:', 'blaminhor-essentials' ); ?></td>
                                                    <td><code><?php echo esc_html( $source['config']['from_email'] ); ?></code></td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $source['config']['from_name'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'From Name:', 'blaminhor-essentials' ); ?></td>
                                                    <td><?php echo esc_html( $source['config']['from_name'] ); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $source['config']['host'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'SMTP Host:', 'blaminhor-essentials' ); ?></td>
                                                    <td><code><?php echo esc_html( $source['config']['host'] ); ?></code></td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $source['config']['port'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'Port:', 'blaminhor-essentials' ); ?></td>
                                                    <td><?php echo esc_html( $source['config']['port'] ); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $source['config']['encryption'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'Encryption:', 'blaminhor-essentials' ); ?></td>
                                                    <td><?php echo esc_html( strtoupper( $source['config']['encryption'] ) ); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $source['config']['username'] ) ) : ?>
                                                <tr>
                                                    <td><?php esc_html_e( 'Username:', 'blaminhor-essentials' ); ?></td>
                                                    <td><code><?php echo esc_html( $source['config']['username'] ); ?></code></td>
                                                </tr>
                                                <?php endif; ?>
                                            </table>
                                        </div>
                                        <div class="ap-import-source-actions">
                                            <button type="button" class="button button-primary ap-import-smtp-btn"
                                                data-source="<?php echo esc_attr( $source_id ); ?>">
                                                <?php esc_html_e( 'Import', 'blaminhor-essentials' ); ?>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="ap-import-smtp-result ap-hidden ap-mt-md" data-source="<?php echo esc_attr( $source_id ); ?>"></div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="blaminhor-essentials-notice warning ap-mt-lg">
                            <p><strong><?php esc_html_e( 'Note:', 'blaminhor-essentials' ); ?></strong> <?php esc_html_e( 'For security reasons, passwords cannot be imported. You will need to re-enter the password after importing the configuration.', 'blaminhor-essentials' ); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Get available import sources
     *
     * Detects installed SMTP plugins with importable configuration.
     *
     * @return array Array of available import sources with config.
     */
    private function get_available_import_sources() {
        $sources = array();

        // WP Mail SMTP detection.
        $wp_mail_smtp = get_option( 'wp_mail_smtp' );
        if ( ! empty( $wp_mail_smtp ) && isset( $wp_mail_smtp['smtp'] ) ) {
            $smtp = $wp_mail_smtp['smtp'];
            $mail = isset( $wp_mail_smtp['mail'] ) ? $wp_mail_smtp['mail'] : array();

            if ( ! empty( $smtp['host'] ) ) {
                $sources['wp_mail_smtp'] = array(
                    'name'   => 'WP Mail SMTP',
                    'config' => array(
                        'from_email' => isset( $mail['from_email'] ) ? $mail['from_email'] : '',
                        'from_name'  => isset( $mail['from_name'] ) ? $mail['from_name'] : '',
                        'host'       => isset( $smtp['host'] ) ? $smtp['host'] : '',
                        'port'       => isset( $smtp['port'] ) ? $smtp['port'] : 587,
                        'encryption' => isset( $smtp['encryption'] ) ? $smtp['encryption'] : 'tls',
                        'username'   => isset( $smtp['user'] ) ? $smtp['user'] : '',
                        'auth'       => isset( $smtp['auth'] ) ? $smtp['auth'] : true,
                    ),
                );
            }
        }

        // Post SMTP detection.
        $postman = get_option( 'postman_options' );
        if ( ! empty( $postman ) && ! empty( $postman['hostname'] ) ) {
            $sources['post_smtp'] = array(
                'name'   => 'Post SMTP',
                'config' => array(
                    'from_email' => isset( $postman['sender_email'] ) ? $postman['sender_email'] : '',
                    'from_name'  => isset( $postman['sender_name'] ) ? $postman['sender_name'] : '',
                    'host'       => isset( $postman['hostname'] ) ? $postman['hostname'] : '',
                    'port'       => isset( $postman['port'] ) ? $postman['port'] : 587,
                    'encryption' => isset( $postman['enc_type'] ) ? $postman['enc_type'] : 'tls',
                    'username'   => isset( $postman['basic_auth_username'] ) ? $postman['basic_auth_username'] : '',
                    'auth'       => ! empty( $postman['basic_auth_username'] ),
                ),
            );
        }

        // Easy WP SMTP detection.
        $easy_smtp = get_option( 'swpsmtp_options' );
        if ( ! empty( $easy_smtp ) && isset( $easy_smtp['smtp_settings'] ) ) {
            $smtp = $easy_smtp['smtp_settings'];

            if ( ! empty( $smtp['host'] ) ) {
                $sources['easy_wp_smtp'] = array(
                    'name'   => 'Easy WP SMTP',
                    'config' => array(
                        'from_email' => isset( $easy_smtp['from_email_field'] ) ? $easy_smtp['from_email_field'] : '',
                        'from_name'  => isset( $easy_smtp['from_name_field'] ) ? $easy_smtp['from_name_field'] : '',
                        'host'       => isset( $smtp['host'] ) ? $smtp['host'] : '',
                        'port'       => isset( $smtp['port'] ) ? $smtp['port'] : 587,
                        'encryption' => isset( $smtp['type_encryption'] ) ? $smtp['type_encryption'] : 'tls',
                        'username'   => isset( $smtp['username'] ) ? $smtp['username'] : '',
                        'auth'       => ! empty( $smtp['username'] ),
                    ),
                );
            }
        }

        return $sources;
    }

    /**
     * AJAX handler for SMTP config import
     */
    public function ajax_import_smtp() {
        check_ajax_referer( 'blaminhor_essentials_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'blaminhor-essentials' ) ) );
        }

        $source = isset( $_POST['source'] ) ? sanitize_text_field( wp_unslash( $_POST['source'] ) ) : '';

        $import_sources = $this->get_available_import_sources();

        if ( ! isset( $import_sources[ $source ] ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid import source.', 'blaminhor-essentials' ) ) );
        }

        $config = $import_sources[ $source ]['config'];

        // Save general settings.
        $settings = $this->settings;
        if ( ! empty( $config['from_email'] ) ) {
            $settings['from_email'] = sanitize_email( $config['from_email'] );
        }
        if ( ! empty( $config['from_name'] ) ) {
            $settings['from_name'] = sanitize_text_field( $config['from_name'] );
        }
        $this->save_settings( $settings );

        // Create a new relay.
        $relays = $this->get_setting( 'relays', array() );

        // Check if relay with same host already exists.
        $exists = false;
        foreach ( $relays as $relay ) {
            if ( isset( $relay['host'] ) && $relay['host'] === $config['host'] ) {
                $exists = true;
                break;
            }
        }

        if ( ! $exists && ! empty( $config['host'] ) ) {
            $new_relay = array(
                'id'         => 'relay_' . time(),
                /* translators: %s: Name of the plugin from which settings were imported */
                'name'       => sprintf( __( 'Imported from %s', 'blaminhor-essentials' ), $import_sources[ $source ]['name'] ),
                'provider'   => 'other',
                'host'       => sanitize_text_field( $config['host'] ),
                'port'       => intval( $config['port'] ),
                'encryption' => sanitize_text_field( $config['encryption'] ),
                'auth'       => ! empty( $config['auth'] ),
                'username'   => sanitize_text_field( $config['username'] ),
                'password'   => '', // Password cannot be imported for security reasons.
                'is_active'  => true,
            );

            $relays[] = $new_relay;
            $settings['relays'] = $relays;
            $this->save_settings( $settings );
        }

        wp_send_json_success(
            array(
                'message'       => __( 'Configuration imported successfully. Please enter the password to complete the setup.', 'blaminhor-essentials' ),
                'relay_created' => ! $exists,
            )
        );
    }
}
