<?php

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

class Niwa_AI_Admin_Autonomy_Email {
    const OPTION_KEY = Niwa_AI_Constants::OPT_AUTONOMY_EMAIL;
    const DEFAULT_INBOUND_POLL_INTERVAL_MINUTES = 15;

    private $contact_service;
    private $workspace;

    public function __construct( $contact_service = null, $workspace = null ) {
        $this->contact_service = $contact_service;
        $this->workspace       = $workspace;
    }

    public function get_defaults() {
        return array(
            'send_enabled'     => 1,
            'from_name'        => '',
            'from_email'       => '',
            'known_recipients' => '',
            'smtp_enabled'     => 1,
            'smtp_host'        => 'smtp.hostinger.com',
            'smtp_port'        => 465,
            'smtp_encryption'  => 'ssl',
            'smtp_username'    => '',
            'smtp_password'    => '',
            'imap_enabled'     => 0,
            'imap_host'        => '',
            'imap_port'        => 993,
            'imap_encryption'  => 'ssl',
            'imap_username'                  => '',
            'imap_password'                  => '',
            'imap_mailbox'                   => 'INBOX',
            'inbound_poll_interval_minutes' => self::DEFAULT_INBOUND_POLL_INTERVAL_MINUTES,
        );
    }

    public static function register_global_wp_mail_smtp() {
        static $registered = false;

        if ( $registered ) {
            return;
        }

        $registered = true;

        add_action( 'phpmailer_init', array( __CLASS__, 'configure_global_phpmailer' ), 900 );
        add_filter( 'wp_mail_from', array( __CLASS__, 'filter_global_wp_mail_from' ), 900 );
        add_filter( 'wp_mail_from_name', array( __CLASS__, 'filter_global_wp_mail_from_name' ), 900 );
    }

    public static function configure_global_phpmailer( $phpmailer ) {
        $smtp = self::build_global_smtp_config();

        if ( empty( $smtp['configured'] ) ) {
            return;
        }

        if ( ! is_object( $phpmailer ) || ! method_exists( $phpmailer, 'isSMTP' ) ) {
            return;
        }

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

        if ( 'none' === $smtp['encryption'] ) {
            $phpmailer->SMTPAutoTLS = false;
        }

        if ( is_email( $smtp['from_email'] ) && method_exists( $phpmailer, 'setFrom' ) ) {
            try {
                $phpmailer->setFrom( $smtp['from_email'], $smtp['from_name'], false );
            } catch ( Exception $e ) {
                // Keep PHPMailer usable; wp_mail_from filters still provide a sender.
            }
        }
    }

    public static function filter_global_wp_mail_from( $from_email ) {
        $smtp = self::build_global_smtp_config();

        return ! empty( $smtp['configured'] ) && is_email( $smtp['from_email'] ) ? $smtp['from_email'] : $from_email;
    }

    public static function filter_global_wp_mail_from_name( $from_name ) {
        $smtp = self::build_global_smtp_config();

        return ! empty( $smtp['configured'] ) && '' !== $smtp['from_name'] ? $smtp['from_name'] : $from_name;
    }

    private static function build_global_smtp_config() {
        $defaults = array(
            'send_enabled'     => 1,
            'from_name'        => '',
            'from_email'       => '',
            'smtp_enabled'     => 1,
            'smtp_host'        => 'smtp.hostinger.com',
            'smtp_port'        => 465,
            'smtp_encryption'  => 'ssl',
            'smtp_username'    => '',
            'smtp_password'    => '',
            'imap_username'    => '',
            'imap_password'    => '',
        );
        $settings = get_option( self::OPTION_KEY, array() );
        $settings = wp_parse_args( is_array( $settings ) ? $settings : array(), $defaults );

        if ( empty( $settings['smtp_enabled'] ) ) {
            return array(
                'configured' => false,
            );
        }

        $host = trim( (string) $settings['smtp_host'] );
        if ( '' === $host ) {
            $host = 'smtp.hostinger.com';
        }

        $port       = max( 1, min( 65535, intval( $settings['smtp_port'] ) ) );
        $encryption = sanitize_key( (string) $settings['smtp_encryption'] );
        if ( ! in_array( $encryption, array( 'ssl', 'tls', 'none' ), true ) ) {
            $encryption = 'ssl';
        }

        $username = trim( (string) $settings['smtp_username'] );
        if ( '' === $username ) {
            $username = trim( (string) $settings['imap_username'] );
        }
        if ( '' === $username && ! empty( $settings['from_email'] ) && is_email( $settings['from_email'] ) ) {
            $username = sanitize_email( (string) $settings['from_email'] );
        }

        $password = (string) $settings['smtp_password'];
        if ( '' === $password ) {
            $password = (string) $settings['imap_password'];
        }

        $from_email = sanitize_email( (string) $settings['from_email'] );
        if ( ! is_email( $from_email ) && is_email( $username ) ) {
            $from_email = sanitize_email( $username );
        }

        $from_name = trim( (string) $settings['from_name'] );
        if ( '' === $from_name ) {
            $from_name = function_exists( 'get_bloginfo' ) ? (string) get_bloginfo( 'name' ) : 'Niwa AI';
        }

        if ( '' === $host || '' === $username || '' === $password || ! is_email( $from_email ) ) {
            return array(
                'configured' => false,
            );
        }

        return array(
            'configured' => true,
            'host'       => $host,
            'port'       => $port,
            'encryption' => $encryption,
            'username'   => $username,
            'password'   => $password,
            'from_email' => $from_email,
            'from_name'  => $from_name,
        );
    }

    public static function get_inbound_poll_interval_choices() {
        return array(
            1  => array(
                'label'    => __( 'Every 1 minute', 'niwa-ai' ),
                'schedule' => 'niwa_ai_one_minute',
                'seconds'  => 60,
            ),
            5  => array(
                'label'    => __( 'Every 5 minutes', 'niwa-ai' ),
                'schedule' => 'niwa_ai_five_minutes',
                'seconds'  => 300,
            ),
            15 => array(
                'label'    => __( 'Every 15 minutes', 'niwa-ai' ),
                'schedule' => 'niwa_ai_fifteen_minutes',
                'seconds'  => 900,
            ),
            30 => array(
                'label'    => __( 'Every 30 minutes', 'niwa-ai' ),
                'schedule' => 'niwa_ai_thirty_minutes',
                'seconds'  => 1800,
            ),
            60 => array(
                'label'    => __( 'Every 1 hour', 'niwa-ai' ),
                'schedule' => 'hourly',
                'seconds'  => 3600,
            ),
        );
    }

    public static function normalize_inbound_poll_interval_minutes( $value ) {
        $minutes = intval( $value );
        $choices = self::get_inbound_poll_interval_choices();

        return isset( $choices[ $minutes ] ) ? $minutes : self::DEFAULT_INBOUND_POLL_INTERVAL_MINUTES;
    }

    public static function get_inbound_poll_schedule_for_interval( $value ) {
        $minutes = self::normalize_inbound_poll_interval_minutes( $value );
        $choices = self::get_inbound_poll_interval_choices();

        return $choices[ $minutes ];
    }

    public function get_settings() {
        $saved = get_option( self::OPTION_KEY, array() );
        return wp_parse_args( is_array( $saved ) ? $saved : array(), $this->get_defaults() );
    }

    public function configure_imap_mailbox_from_existing_smtp() {
        $credentials = $this->get_existing_smtp_mailbox_credentials();
        if ( empty( $credentials['success'] ) ) {
            return $credentials;
        }

        return $this->configure_mailbox_settings(
            array(
                'source'        => isset( $credentials['source'] ) ? (string) $credentials['source'] : 'fluent_smtp',
                'mailbox_email' => (string) $credentials['username'],
                'password'      => (string) $credentials['password'],
            )
        );
    }

    public function configure_mailbox_settings( $args ) {
        $args          = is_array( $args ) ? $args : array();
        $mailbox_email = isset( $args['mailbox_email'] ) ? sanitize_email( (string) $args['mailbox_email'] ) : '';
        $password      = isset( $args['password'] ) ? (string) $args['password'] : '';
        if ( ! is_email( $mailbox_email ) || '' === $password ) {
            return array(
                'success'        => false,
                'configured'     => false,
                'error'          => 'Valid mailbox_email and password are required.',
                'missing_secret' => true,
            );
        }

        $settings = $this->get_settings();
        $settings['imap_enabled']    = 1;
        $settings['imap_host']       = isset( $args['imap_host'] ) && '' !== trim( (string) $args['imap_host'] )
            ? sanitize_text_field( (string) $args['imap_host'] )
            : 'imap.hostinger.com';
        $settings['imap_port']       = isset( $args['imap_port'] ) ? max( 1, min( 65535, intval( $args['imap_port'] ) ) ) : 993;
        $settings['imap_encryption'] = isset( $args['imap_encryption'] ) ? sanitize_key( (string) $args['imap_encryption'] ) : 'ssl';
        if ( ! in_array( $settings['imap_encryption'], array( 'ssl', 'tls', 'notls' ), true ) ) {
            $settings['imap_encryption'] = 'ssl';
        }
        $settings['imap_username'] = $mailbox_email;
        $settings['imap_password'] = $password;
        $settings['imap_mailbox']  = isset( $args['imap_mailbox'] ) && '' !== trim( (string) $args['imap_mailbox'] )
            ? sanitize_text_field( (string) $args['imap_mailbox'] )
            : 'INBOX';
        $settings['send_enabled']  = 1;
        if ( empty( $settings['from_email'] ) || ! is_email( $settings['from_email'] ) ) {
            $settings['from_email'] = $mailbox_email;
        }
        $settings['smtp_enabled']    = 1;
        $settings['smtp_host']       = isset( $args['smtp_host'] ) && '' !== trim( (string) $args['smtp_host'] )
            ? sanitize_text_field( (string) $args['smtp_host'] )
            : 'smtp.hostinger.com';
        $settings['smtp_port']       = isset( $args['smtp_port'] ) ? max( 1, min( 65535, intval( $args['smtp_port'] ) ) ) : 465;
        $settings['smtp_encryption'] = isset( $args['smtp_encryption'] ) ? sanitize_key( (string) $args['smtp_encryption'] ) : 'ssl';
        if ( ! in_array( $settings['smtp_encryption'], array( 'ssl', 'tls', 'none' ), true ) ) {
            $settings['smtp_encryption'] = 'ssl';
        }
        $settings['smtp_username'] = isset( $args['smtp_username'] ) && '' !== trim( (string) $args['smtp_username'] )
            ? sanitize_text_field( (string) $args['smtp_username'] )
            : $mailbox_email;
        $settings['smtp_password'] = isset( $args['smtp_password'] ) && '' !== (string) $args['smtp_password']
            ? (string) $args['smtp_password']
            : $password;

        update_option( self::OPTION_KEY, $settings, false );

        $test = $this->test_imap_settings( $settings );
        if ( empty( $test['success'] ) ) {
            return array(
                'success'        => false,
                'configured'     => true,
                'error'          => isset( $test['error'] ) ? $test['error'] : 'IMAP connection test failed.',
                'source'         => isset( $args['source'] ) ? sanitize_text_field( (string) $args['source'] ) : 'explicit_credentials',
                'missing_secret' => false,
                'imap'           => array(
                    'host'            => $settings['imap_host'],
                    'port'            => $settings['imap_port'],
                    'encryption'      => $settings['imap_encryption'],
                    'mailbox'         => $settings['imap_mailbox'],
                    'username_masked' => $this->mask_mailbox_identifier( $settings['imap_username'] ),
                ),
                'test'           => $test,
            );
        }

        return array(
            'success'    => true,
            'configured' => true,
            'source'     => isset( $args['source'] ) ? sanitize_text_field( (string) $args['source'] ) : 'explicit_credentials',
            'smtp'       => array(
                'host'            => isset( $args['smtp_host'] ) && '' !== trim( (string) $args['smtp_host'] ) ? sanitize_text_field( (string) $args['smtp_host'] ) : 'smtp.hostinger.com',
                'port'            => isset( $args['smtp_port'] ) ? max( 1, min( 65535, intval( $args['smtp_port'] ) ) ) : 465,
                'encryption'      => isset( $args['smtp_encryption'] ) ? sanitize_key( (string) $args['smtp_encryption'] ) : 'ssl',
                'username_masked' => $this->mask_mailbox_identifier( $mailbox_email ),
            ),
            'imap'       => array(
                'host'            => $settings['imap_host'],
                'port'            => $settings['imap_port'],
                'encryption'      => $settings['imap_encryption'],
                'mailbox'         => $settings['imap_mailbox'],
                'username_masked' => $this->mask_mailbox_identifier( $settings['imap_username'] ),
            ),
            'test'       => $test,
        );
    }

    private function get_existing_smtp_mailbox_credentials() {
        $smtp_settings = array();
        $used_helper   = false;

        if ( function_exists( 'fluentMailGetSettings' ) ) {
            $smtp_settings = fluentMailGetSettings( array(), false );
            $used_helper   = true;
        }

        if ( empty( $smtp_settings ) || ! is_array( $smtp_settings ) ) {
            $smtp_settings = get_option( 'fluentmail-settings', array() );
        }

        if ( empty( $smtp_settings ) || ! is_array( $smtp_settings ) ) {
            return array(
                'success'        => false,
                'error'          => 'FluentSMTP settings were not found.',
                'missing_secret' => true,
            );
        }

        $connection = $this->get_fluent_smtp_provider_settings( $smtp_settings );
        if ( empty( $connection ) ) {
            return array(
                'success'        => false,
                'error'          => 'No SMTP mailbox connection was found in FluentSMTP settings.',
                'missing_secret' => true,
            );
        }

        $username = '';
        if ( isset( $connection['settings']['username'] ) ) {
            $username = trim( (string) $connection['settings']['username'] );
        }
        if ( '' === $username && defined( 'FLUENTMAIL_SMTP_USERNAME' ) ) {
            $username = trim( (string) constant( 'FLUENTMAIL_SMTP_USERNAME' ) );
        }
        if ( '' === $username && ! empty( $connection['settings']['sender_email'] ) ) {
            $username = sanitize_email( (string) $connection['settings']['sender_email'] );
        }

        $password = isset( $connection['settings']['password'] ) ? $connection['settings']['password'] : '';
        if ( '' === (string) $password && defined( 'FLUENTMAIL_SMTP_PASSWORD' ) ) {
            $password = (string) constant( 'FLUENTMAIL_SMTP_PASSWORD' );
        }

        if ( '' === $username ) {
            return array(
                'success'        => false,
                'error'          => 'FluentSMTP mailbox username is unavailable.',
                'missing_secret' => true,
            );
        }

        if ( false === $password || '' === (string) $password ) {
            return array(
                'success'        => false,
                'error'          => ! $used_helper && ! empty( $smtp_settings['use_encrypt'] ) ? 'FluentSMTP password is encrypted and the decryptor is unavailable in this runtime.' : 'FluentSMTP mailbox password is unavailable.',
                'missing_secret' => true,
            );
        }

        return array(
            'success'  => true,
            'username' => $username,
            'password' => (string) $password,
            'source'   => 'fluent_smtp:' . (string) $connection['key'],
        );
    }

    private function get_fluent_smtp_provider_settings( $smtp_settings ) {
        $connections = isset( $smtp_settings['connections'] ) && is_array( $smtp_settings['connections'] ) ? $smtp_settings['connections'] : array();
        if ( empty( $connections ) ) {
            return array();
        }

        $default_key = isset( $smtp_settings['misc']['default_connection'] ) ? (string) $smtp_settings['misc']['default_connection'] : '';
        if ( '' !== $default_key && isset( $connections[ $default_key ]['provider_settings'] ) ) {
            $settings = $connections[ $default_key ]['provider_settings'];
            if ( isset( $settings['provider'] ) && 'smtp' === (string) $settings['provider'] ) {
                return array(
                    'key'      => $default_key,
                    'settings' => $settings,
                );
            }
        }

        foreach ( $connections as $key => $connection ) {
            $settings = isset( $connection['provider_settings'] ) && is_array( $connection['provider_settings'] ) ? $connection['provider_settings'] : array();
            if ( isset( $settings['provider'] ) && 'smtp' === (string) $settings['provider'] ) {
                return array(
                    'key'      => $key,
                    'settings' => $settings,
                );
            }
        }

        return array();
    }

    private function test_imap_settings( $settings ) {
        if ( ! function_exists( 'imap_open' ) ) {
            return array(
                'success' => false,
                'error'   => 'PHP IMAP extension is not available.',
            );
        }

        $mailbox = $this->build_imap_mailbox_string( $settings );
        $stream  = @imap_open( $mailbox, (string) $settings['imap_username'], (string) $settings['imap_password'], OP_READONLY, 1 );
        if ( ! $stream ) {
            $errors = function_exists( 'imap_errors' ) ? imap_errors() : array();
            return array(
                'success' => false,
                'error'   => 'IMAP connection failed.' . ( ! empty( $errors ) ? ' ' . implode( ' ', array_map( 'sanitize_text_field', (array) $errors ) ) : '' ),
            );
        }

        $check       = @imap_check( $stream );
        $unseen      = @imap_search( $stream, 'UNSEEN', SE_UID );
        $last_header = array();

        if ( $check && ! empty( $check->Nmsgs ) ) {
            $header = @imap_headerinfo( $stream, intval( $check->Nmsgs ) );
            if ( $header ) {
                $subject = $this->decode_imap_header_value( isset( $header->subject ) ? (string) $header->subject : '' );
                $from    = '';
                if ( ! empty( $header->from[0] ) ) {
                    $from_part = $header->from[0];
                    $from      = ( isset( $from_part->mailbox ) ? (string) $from_part->mailbox : '' ) . ( isset( $from_part->host ) ? '@' . (string) $from_part->host : '' );
                }
                $last_header = array(
                    'subject' => sanitize_text_field( $subject ),
                    'from'    => sanitize_email( $from ),
                    'date'    => isset( $header->date ) ? sanitize_text_field( (string) $header->date ) : '',
                );
            }
        }

        @imap_close( $stream );

        return array(
            'success'       => true,
            'messages'      => $check && isset( $check->Nmsgs ) ? intval( $check->Nmsgs ) : 0,
            'recent'        => $check && isset( $check->Recent ) ? intval( $check->Recent ) : 0,
            'unread'        => is_array( $unseen ) ? count( $unseen ) : 0,
            'last_header'   => $last_header,
            'status_source' => 'imap_check',
        );
    }

    public function send_email( $to_email, $subject, $body, $headers = array() ) {
        $settings = $this->get_settings();
        $to_email = sanitize_email( (string) $to_email );
        $subject  = trim( (string) $subject );
        $body     = (string) $body;
        $headers  = is_array( $headers ) ? $headers : array();

        if ( empty( $settings['send_enabled'] ) ) {
            return array(
                'success' => false,
                'error'   => 'Niwa outbound email je iskljucen u settings.',
            );
        }

        if ( ! is_email( $to_email ) ) {
            return array(
                'success' => false,
                'error'   => 'Treba mi validna email adresa primaoca.',
            );
        }

        if ( '' === $subject ) {
            return array(
                'success' => false,
                'error'   => 'Email subject je obavezan.',
            );
        }

        if ( '' === trim( wp_strip_all_tags( $body ) ) ) {
            return array(
                'success' => false,
                'error'   => 'Email body je obavezan.',
            );
        }

        $from_name  = trim( (string) $settings['from_name'] );
        $from_email = sanitize_email( (string) $settings['from_email'] );
        $smtp       = $this->build_smtp_config( $settings );
        $filters    = array();

        if ( ! is_email( $from_email ) && ! empty( $smtp['username'] ) && is_email( $smtp['username'] ) ) {
            $from_email = sanitize_email( (string) $smtp['username'] );
        }

        if ( is_email( $from_email ) ) {
            $filters['from_email'] = function () use ( $from_email ) {
                return $from_email;
            };
            add_filter( 'wp_mail_from', $filters['from_email'] );
        }

        if ( '' !== $from_name ) {
            $filters['from_name'] = function () use ( $from_name ) {
                return $from_name;
            };
            add_filter( 'wp_mail_from_name', $filters['from_name'] );
        }

        $is_html = (bool) preg_match( '/<\/?[a-z][\s\S]*>/i', $body );
        if ( $is_html ) {
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
        }

        if ( ! empty( $smtp['enabled'] ) && ! empty( $smtp['configured'] ) ) {
            $filters['phpmailer_init'] = function ( $phpmailer ) use ( $smtp, $from_email, $from_name ) {
                $this->configure_phpmailer_for_smtp( $phpmailer, $smtp, $from_email, $from_name );
            };
            add_action( 'phpmailer_init', $filters['phpmailer_init'], 1000 );
        }

        try {
            $sent = wp_mail( $to_email, $subject, $body, $headers );
        } finally {
            if ( ! empty( $filters['phpmailer_init'] ) ) {
                remove_action( 'phpmailer_init', $filters['phpmailer_init'], 1000 );
            }
            if ( ! empty( $filters['from_email'] ) ) {
                remove_filter( 'wp_mail_from', $filters['from_email'] );
            }
            if ( ! empty( $filters['from_name'] ) ) {
                remove_filter( 'wp_mail_from_name', $filters['from_name'] );
            }
        }

        if ( ! $sent ) {
            $last_error = $this->get_last_wp_mail_error_message();
            $error      = ! empty( $smtp['enabled'] ) && empty( $smtp['configured'] )
                ? 'Niwa SMTP nije kompletno podesen: ' . ( isset( $smtp['error'] ) ? (string) $smtp['error'] : 'nedostaju SMTP credentials.' )
                : 'Niwa SMTP/wp_mail nije uspeo da posalje poruku.';
            if ( '' !== $last_error ) {
                $error .= ' ' . $last_error;
            }

            return array(
                'success' => false,
                'error'   => $error,
            );
        }

        return array(
            'success'   => true,
            'to_email'  => $to_email,
            'subject'   => $subject,
            'sent_via'  => ! empty( $smtp['enabled'] ) && ! empty( $smtp['configured'] ) ? 'niwa_smtp' : 'wp_mail',
            'smtp_host' => ! empty( $smtp['enabled'] ) && ! empty( $smtp['configured'] ) ? $smtp['host'] : '',
            'from_name' => $from_name,
            'from_email'=> $from_email,
        );
    }

    private function build_smtp_config( $settings ) {
        $settings = is_array( $settings ) ? $settings : array();
        if ( empty( $settings['smtp_enabled'] ) ) {
            return array(
                'enabled'    => false,
                'configured' => false,
            );
        }

        $host = trim( (string) ( isset( $settings['smtp_host'] ) ? $settings['smtp_host'] : '' ) );
        if ( '' === $host ) {
            $host = 'smtp.hostinger.com';
        }

        $port       = max( 1, min( 65535, intval( isset( $settings['smtp_port'] ) ? $settings['smtp_port'] : 465 ) ) );
        $encryption = sanitize_key( isset( $settings['smtp_encryption'] ) ? (string) $settings['smtp_encryption'] : 'ssl' );
        if ( ! in_array( $encryption, array( 'ssl', 'tls', 'none' ), true ) ) {
            $encryption = 'ssl';
        }

        $username = trim( (string) ( isset( $settings['smtp_username'] ) ? $settings['smtp_username'] : '' ) );
        if ( '' === $username ) {
            $username = trim( (string) ( isset( $settings['imap_username'] ) ? $settings['imap_username'] : '' ) );
        }
        if ( '' === $username && ! empty( $settings['from_email'] ) && is_email( $settings['from_email'] ) ) {
            $username = sanitize_email( (string) $settings['from_email'] );
        }

        $password = (string) ( isset( $settings['smtp_password'] ) ? $settings['smtp_password'] : '' );
        if ( '' === $password ) {
            $password = (string) ( isset( $settings['imap_password'] ) ? $settings['imap_password'] : '' );
        }

        if ( '' === $host || '' === $username || '' === $password ) {
            return array(
                'enabled'    => true,
                'configured' => false,
                'error'      => 'nedostaju SMTP host, username ili password. Ako su IMAP username/password vec podeseni, Niwa ih koristi kao fallback.',
            );
        }

        return array(
            'enabled'    => true,
            'configured' => true,
            'host'       => $host,
            'port'       => $port,
            'encryption' => $encryption,
            'username'   => $username,
            'password'   => $password,
        );
    }

    private function configure_phpmailer_for_smtp( $phpmailer, $smtp, $from_email, $from_name ) {
        if ( ! is_object( $phpmailer ) || ! method_exists( $phpmailer, 'isSMTP' ) || empty( $smtp['configured'] ) ) {
            return;
        }

        $phpmailer->isSMTP();
        $phpmailer->Host       = (string) $smtp['host'];
        $phpmailer->Port       = (int) $smtp['port'];
        $phpmailer->SMTPAuth   = true;
        $phpmailer->Username   = (string) $smtp['username'];
        $phpmailer->Password   = (string) $smtp['password'];
        $phpmailer->SMTPSecure = 'none' === $smtp['encryption'] ? '' : (string) $smtp['encryption'];
        if ( 'none' === $smtp['encryption'] ) {
            $phpmailer->SMTPAutoTLS = false;
        }

        if ( is_email( $from_email ) && method_exists( $phpmailer, 'setFrom' ) ) {
            try {
                $phpmailer->setFrom( $from_email, $from_name, false );
            } catch ( Exception $e ) {
                // Keep PHPMailer usable; wp_mail_from filters still provide a sender.
            }
        }
    }

    private function get_last_wp_mail_error_message() {
        global $phpmailer;

        if ( is_object( $phpmailer ) && ! empty( $phpmailer->ErrorInfo ) ) {
            return 'PHPMailer: ' . sanitize_text_field( (string) $phpmailer->ErrorInfo );
        }

        return '';
    }

    public function resolve_recipient( $query = '', $explicit_email = '', $limit = 8 ) {
        $limit          = max( 1, min( 20, intval( $limit ) ) );
        $explicit_email = sanitize_email( (string) $explicit_email );
        if ( is_email( $explicit_email ) ) {
            return array(
                'success' => true,
                'match'   => array(
                    'label'  => $explicit_email,
                    'email'  => $explicit_email,
                    'source' => 'explicit',
                    'score'  => 100,
                ),
                'matches' => array(),
            );
        }

        $query = trim( (string) $query );
        if ( is_email( $query ) ) {
            return array(
                'success' => true,
                'match'   => array(
                    'label'  => $query,
                    'email'  => $query,
                    'source' => 'query_email',
                    'score'  => 100,
                ),
                'matches' => array(),
            );
        }

        $matches = array();
        $matches = array_merge( $matches, $this->find_known_recipient_matches( $query ) );
        $matches = array_merge( $matches, $this->find_workspace_recipient_matches( $query ) );
        $matches = array_merge( $matches, $this->find_contact_recipient_matches( $query, $limit ) );
        $matches = $this->dedupe_recipient_matches( $matches );

        usort(
            $matches,
            function ( $a, $b ) {
                return intval( isset( $b['score'] ) ? $b['score'] : 0 ) <=> intval( isset( $a['score'] ) ? $a['score'] : 0 );
            }
        );

        $matches = array_slice( $matches, 0, $limit );

        return array(
            'success' => ! empty( $matches ),
            'match'   => ! empty( $matches[0] ) ? $matches[0] : array(),
            'matches' => $matches,
            'query'   => $query,
        );
    }

    public function get_followup_candidates( $limit = 20, $search = '', $days = 90 ) {
        if ( ! $this->contact_service || ! method_exists( $this->contact_service, 'search_contacts' ) ) {
            return array(
                'success' => false,
                'error'   => 'Lead contact service nije ucitan.',
            );
        }

        $limit   = max( 1, min( 100, intval( $limit ) ) );
        $days    = max( 1, min( 365, intval( $days ) ) );
        $search  = trim( (string) $search );
        $results = $this->contact_service->search_contacts( $search, max( $limit * 5, 80 ), 0 );
        $items   = isset( $results['items'] ) && is_array( $results['items'] ) ? $results['items'] : array();
        $cutoff  = strtotime( '-' . $days . ' days', current_time( 'timestamp' ) );

        $candidates = array();
        foreach ( $items as $item ) {
            if ( ! is_array( $item ) ) {
                continue;
            }

            $email = isset( $item['email'] ) ? strtolower( trim( (string) $item['email'] ) ) : '';
            if ( '' === $email || 0 === strpos( $email, 'phone_only_' ) || ! is_email( $email ) ) {
                continue;
            }

            $created_at = isset( $item['created_at'] ) ? strtotime( (string) $item['created_at'] ) : 0;
            if ( $created_at > 0 && $created_at < $cutoff ) {
                continue;
            }

            if ( $this->has_orders_for_email( $email ) ) {
                continue;
            }

            $candidates[] = array(
                'email'      => $email,
                'name'       => isset( $item['name'] ) ? (string) $item['name'] : '',
                'phone'      => isset( $item['phone'] ) ? (string) $item['phone'] : '',
                'created_at' => isset( $item['created_at'] ) ? (string) $item['created_at'] : '',
                'source'     => 'lead_capture',
            );

            if ( count( $candidates ) >= $limit ) {
                break;
            }
        }

        return array(
            'success'    => true,
            'count'      => count( $candidates ),
            'candidates' => $candidates,
        );
    }

    public function read_inbox( $limit = 5, $unread_only = true, $from_filter = '', $subject_filter = '', $body_chars = 1200 ) {
        $settings = $this->get_settings();
        if ( empty( $settings['imap_enabled'] ) ) {
            return array(
                'success' => false,
                'error'   => 'IMAP inbox citanje nije ukljuceno.',
            );
        }

        if ( ! function_exists( 'imap_open' ) ) {
            return array(
                'success' => false,
                'error'   => 'PHP IMAP ekstenzija nije dostupna na ovom serveru.',
            );
        }

        $stream_result = $this->open_imap_stream();
        if ( empty( $stream_result['success'] ) ) {
            return $stream_result;
        }
        $stream = $stream_result['stream'];

        try {
            $limit          = max( 1, min( 50, intval( $limit ) ) );
            $body_chars     = max( 0, min( 5000, intval( $body_chars ) ) );
            $from_filter    = trim( (string) $from_filter );
            $subject_filter = trim( (string) $subject_filter );
            $criteria       = array();
            if ( $unread_only ) {
                $criteria[] = 'UNSEEN';
            }
            if ( '' !== $from_filter ) {
                $criteria[] = 'FROM "' . addslashes( $from_filter ) . '"';
            }
            if ( '' !== $subject_filter ) {
                $criteria[] = 'SUBJECT "' . addslashes( $subject_filter ) . '"';
            }

            $search  = empty( $criteria ) ? 'ALL' : implode( ' ', $criteria );
            $message_numbers = @imap_search( $stream, $search, SE_UID );
            if ( ! is_array( $message_numbers ) ) {
                $message_numbers = array();
            }

            rsort( $message_numbers, SORT_NUMERIC );
            $messages = array();
            foreach ( array_slice( $message_numbers, 0, $limit ) as $uid ) {
                $overview = imap_fetch_overview( $stream, (string) $uid, FT_UID );
                $row      = is_array( $overview ) && ! empty( $overview[0] ) ? $overview[0] : null;
                if ( ! is_object( $row ) ) {
                    continue;
                }

                $body_text = $this->extract_imap_message_text( $stream, intval( $uid ), $body_chars );

                $messages[] = array(
                    'uid'        => intval( $uid ),
                    'message_id' => isset( $row->message_id ) ? $this->decode_imap_header_value( $row->message_id ) : '',
                    'subject'    => $this->decode_imap_header_value( isset( $row->subject ) ? $row->subject : '' ),
                    'from'       => $this->decode_imap_header_value( isset( $row->from ) ? $row->from : '' ),
                    'date'       => isset( $row->date ) ? (string) $row->date : '',
                    'seen'       => ! empty( $row->seen ),
                    'excerpt'    => $this->truncate_text_value( $body_text, 280 ),
                    'body_text'  => $body_text,
                );
            }

            return array(
                'success'  => true,
                'messages' => $messages,
                'count'    => count( $messages ),
            );
        } finally {
            imap_close( $stream );
        }
    }

    private function has_orders_for_email( $email ) {
        if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'wc_get_orders' ) || ! is_email( $email ) ) {
            return false;
        }

        $orders = wc_get_orders(
            array(
                'billing_email' => $email,
                'status'        => array( 'wc-pending', 'wc-on-hold', 'wc-processing', 'wc-completed' ),
                'limit'         => 1,
                'return'        => 'ids',
            )
        );

        return is_array( $orders ) && ! empty( $orders );
    }

    private function find_known_recipient_matches( $query ) {
        $query    = $this->normalize_query( $query );
        $settings = $this->get_settings();
        $items    = $this->parse_known_recipients( isset( $settings['known_recipients'] ) ? (string) $settings['known_recipients'] : '' );
        $results  = array();

        $admin_email = get_option( 'admin_email' );
        if ( is_email( $admin_email ) ) {
            $items[] = array(
                'label'  => 'admin',
                'email'  => $admin_email,
                'source' => 'site_admin',
            );
        }

        foreach ( $items as $item ) {
            $label = isset( $item['label'] ) ? (string) $item['label'] : '';
            $email = isset( $item['email'] ) ? (string) $item['email'] : '';
            if ( ! is_email( $email ) ) {
                continue;
            }
            $score = $this->score_recipient_match( $query, $label, $email );
            if ( $score <= 0 ) {
                continue;
            }
            $results[] = array(
                'label'  => $label,
                'email'  => $email,
                'source' => isset( $item['source'] ) ? (string) $item['source'] : 'known',
                'score'  => $score,
            );
        }

        return $results;
    }

    private function find_workspace_recipient_matches( $query ) {
        if ( '' === $query || ! $this->workspace || ! method_exists( $this->workspace, 'read_bootstrap_file' ) ) {
            return array();
        }

        $files   = array( 'USER.md', 'MEMORY.md', 'IDENTITY.md' );
        $matches = array();
        foreach ( $files as $file ) {
            $record = $this->workspace->read_bootstrap_file( $file );
            if ( empty( $record['success'] ) || empty( $record['content'] ) ) {
                continue;
            }
            $lines = preg_split( '/\r\n|\r|\n/', (string) $record['content'] );
            foreach ( (array) $lines as $line ) {
                if ( false === strpos( strtolower( remove_accents( $line ) ), $query ) ) {
                    continue;
                }
                if ( ! preg_match( '/([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})/i', $line, $email_match ) ) {
                    continue;
                }
                $email = sanitize_email( (string) $email_match[1] );
                if ( ! is_email( $email ) ) {
                    continue;
                }
                $matches[] = array(
                    'label'  => trim( preg_replace( '/([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})/i', '', $line ) ),
                    'email'  => $email,
                    'source' => 'workspace:' . $file,
                    'score'  => 70,
                );
            }
        }

        return $matches;
    }

    private function find_contact_recipient_matches( $query, $limit ) {
        if ( '' === $query || ! $this->contact_service || ! method_exists( $this->contact_service, 'search_contacts' ) ) {
            return array();
        }

        $results = $this->contact_service->search_contacts( $query, $limit, 0 );
        $items   = isset( $results['items'] ) && is_array( $results['items'] ) ? $results['items'] : array();
        $matches = array();

        foreach ( $items as $item ) {
            $email = isset( $item['email'] ) ? strtolower( trim( (string) $item['email'] ) ) : '';
            if ( '' === $email || 0 === strpos( $email, 'phone_only_' ) || ! is_email( $email ) ) {
                continue;
            }

            $label = trim(
                implode(
                    ' ',
                    array_filter(
                        array(
                            isset( $item['name'] ) ? (string) $item['name'] : '',
                            isset( $item['phone'] ) ? (string) $item['phone'] : '',
                        )
                    )
                )
            );
            $matches[] = array(
                'label'  => '' !== $label ? $label : $email,
                'email'  => $email,
                'source' => 'lead_capture',
                'score'  => $this->score_recipient_match( $query, $label, $email ),
            );
        }

        return array_values(
            array_filter(
                $matches,
                function ( $match ) {
                    return intval( isset( $match['score'] ) ? $match['score'] : 0 ) > 0;
                }
            )
        );
    }

    private function parse_known_recipients( $raw ) {
        $raw   = trim( (string) $raw );
        $items = array();
        if ( '' === $raw ) {
            return $items;
        }

        foreach ( preg_split( '/\r\n|\r|\n/', $raw ) as $line ) {
            $line = trim( (string) $line );
            if ( '' === $line ) {
                continue;
            }

            if ( preg_match( '/^(.+?)(?:\||,|:|=>)\s*<?([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})>?$/i', $line, $matches ) ) {
                $label = trim( (string) $matches[1] );
                $email = sanitize_email( (string) $matches[2] );
            } elseif ( preg_match( '/<?([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})>?$/i', $line, $matches ) ) {
                $email = sanitize_email( (string) $matches[1] );
                $label = $email;
            } else {
                continue;
            }

            if ( ! is_email( $email ) ) {
                continue;
            }

            $items[] = array(
                'label'  => $label,
                'email'  => $email,
                'source' => 'known',
            );
        }

        return $items;
    }

    private function dedupe_recipient_matches( $matches ) {
        $deduped = array();
        foreach ( (array) $matches as $match ) {
            if ( ! is_array( $match ) || empty( $match['email'] ) ) {
                continue;
            }
            $email = strtolower( trim( (string) $match['email'] ) );
            if ( ! isset( $deduped[ $email ] ) || intval( $match['score'] ) > intval( isset( $deduped[ $email ]['score'] ) ? $deduped[ $email ]['score'] : 0 ) ) {
                $deduped[ $email ] = $match;
            }
        }

        return array_values( $deduped );
    }

    private function score_recipient_match( $query, $label, $email ) {
        $query = $this->normalize_query( $query );
        $label = $this->normalize_query( $label );
        $email = strtolower( trim( (string) $email ) );

        if ( '' === $query ) {
            return 0;
        }
        if ( $query === $email || false !== strpos( $email, $query ) ) {
            return 95;
        }
        if ( '' !== $label && $query === $label ) {
            return 90;
        }
        if ( '' !== $label && false !== strpos( $label, $query ) ) {
            return 80;
        }
        if ( preg_match( '/\b' . preg_quote( $query, '/' ) . '\b/u', $label ) ) {
            return 85;
        }

        return 0;
    }

    private function normalize_query( $text ) {
        $text = trim( strtolower( remove_accents( wp_strip_all_tags( (string) $text ) ) ) );
        $text = preg_replace( '/\s+/', ' ', (string) $text );
        return trim( (string) $text );
    }

    public function fetch_message_by_uid( $uid, $body_chars = 2000 ) {
        $uid = (int) $uid;
        if ( $uid <= 0 ) {
            return array( 'success' => false, 'error' => 'Invalid IMAP UID.' );
        }

        $stream_result = $this->open_imap_stream();
        if ( empty( $stream_result['success'] ) ) {
            return $stream_result;
        }
        $stream = $stream_result['stream'];

        try {
            $message = $this->format_imap_message( $stream, $uid, $body_chars );
            @imap_close( $stream );
            if ( empty( $message ) ) {
                return array( 'success' => false, 'error' => 'Message not found.' );
            }
            return array( 'success' => true, 'message' => $message );
        } catch ( Exception $e ) {
            @imap_close( $stream );
            return array( 'success' => false, 'error' => $e->getMessage() );
        }
    }

    public function move_message_to_trash( $uid ) {
        $uid = (int) $uid;
        if ( $uid <= 0 ) {
            return array( 'success' => false, 'error' => 'Invalid IMAP UID.' );
        }

        $stream_result = $this->open_imap_stream();
        if ( empty( $stream_result['success'] ) ) {
            return $stream_result;
        }
        $stream = $stream_result['stream'];

        $mailboxes = array( 'Trash', 'INBOX.Trash', '[Gmail]/Trash', 'Deleted Messages' );
        $moved = false;
        $last_error = '';
        foreach ( $mailboxes as $trash ) {
            if ( function_exists( 'imap_mail_move' ) && @imap_mail_move( $stream, (string) $uid, $trash, CP_UID ) ) {
                $moved = true;
                break;
            }
            $last_error = function_exists( 'imap_last_error' ) ? (string) imap_last_error() : '';
        }

        if ( ! $moved && function_exists( 'imap_delete' ) && @imap_delete( $stream, (string) $uid, FT_UID ) ) {
            $moved = true;
        }

        if ( $moved && function_exists( 'imap_expunge' ) ) {
            @imap_expunge( $stream );
        }
        @imap_close( $stream );

        return $moved ? array( 'success' => true, 'uid' => $uid ) : array( 'success' => false, 'error' => ( '' !== $last_error ? $last_error : 'Could not move message to Trash.' ) );
    }

    private function open_imap_stream() {
        $settings = $this->get_settings();
        if ( empty( $settings['imap_enabled'] ) ) {
            return array( 'success' => false, 'error' => 'IMAP inbox citanje nije ukljuceno.' );
        }
        if ( ! function_exists( 'imap_open' ) ) {
            return array( 'success' => false, 'error' => 'PHP IMAP ekstenzija nije dostupna na ovom serveru.' );
        }
        $mailbox = $this->build_imap_mailbox_string( $settings );
        if ( '' === $mailbox ) {
            return array( 'success' => false, 'error' => 'IMAP konfiguracija nije potpuna.' );
        }
        $stream = @imap_open( $mailbox, (string) $settings['imap_username'], (string) $settings['imap_password'] );
        if ( ! $stream ) {
            $last_error = function_exists( 'imap_last_error' ) ? imap_last_error() : '';
            return array( 'success' => false, 'error' => 'IMAP konekcija nije uspela' . ( $last_error ? ': ' . $last_error : '.' ) );
        }
        return array( 'success' => true, 'stream' => $stream );
    }

    private function format_imap_message( $stream, $uid, $body_chars = 1200 ) {
        $overview = function_exists( 'imap_fetch_overview' ) ? @imap_fetch_overview( $stream, (string) $uid, FT_UID ) : array();
        $ov = is_array( $overview ) && ! empty( $overview ) ? $overview[0] : null;
        if ( ! $ov ) {
            return array();
        }
        $subject = isset( $ov->subject ) ? $this->decode_imap_header_value( $ov->subject ) : '';
        $from = isset( $ov->from ) ? $this->decode_imap_header_value( $ov->from ) : '';
        $body = $this->extract_imap_message_text( $stream, $uid, $body_chars );
        return array(
            'uid'        => $uid,
            'message_id' => isset( $ov->message_id ) ? $this->decode_imap_header_value( $ov->message_id ) : '',
            'date'       => isset( $ov->date ) ? (string) $ov->date : '',
            'from'       => $from,
            'subject'    => $subject,
            'body_text'  => $body,
            'excerpt'    => $this->truncate_text_value( $body, 300 ),
        );
    }

    private function build_imap_mailbox_string( $settings ) {
        $host      = trim( (string) ( isset( $settings['imap_host'] ) ? $settings['imap_host'] : '' ) );
        $port      = max( 1, intval( isset( $settings['imap_port'] ) ? $settings['imap_port'] : 993 ) );
        $mailbox   = trim( (string) ( isset( $settings['imap_mailbox'] ) ? $settings['imap_mailbox'] : 'INBOX' ) );
        $username  = trim( (string) ( isset( $settings['imap_username'] ) ? $settings['imap_username'] : '' ) );
        $password  = (string) ( isset( $settings['imap_password'] ) ? $settings['imap_password'] : '' );
        $encryption= sanitize_key( isset( $settings['imap_encryption'] ) ? (string) $settings['imap_encryption'] : 'ssl' );

        if ( '' === $host || '' === $mailbox || '' === $username || '' === $password ) {
            return '';
        }

        $flags = '/imap';
        if ( 'ssl' === $encryption ) {
            $flags .= '/ssl';
        } elseif ( 'tls' === $encryption ) {
            $flags .= '/tls';
        } elseif ( 'notls' === $encryption ) {
            $flags .= '/notls';
        }
        $flags .= '/novalidate-cert';

        return '{' . $host . ':' . $port . $flags . '}' . $mailbox;
    }

    private function mask_mailbox_identifier( $value ) {
        $value = (string) $value;
        if ( false !== strpos( $value, '@' ) ) {
            list( $local, $domain ) = explode( '@', $value, 2 );
            return substr( $local, 0, 2 ) . str_repeat( '*', max( 2, strlen( $local ) - 2 ) ) . '@' . $domain;
        }

        return substr( $value, 0, 2 ) . str_repeat( '*', max( 2, strlen( $value ) - 2 ) );
    }

    private function decode_imap_header_value( $value ) {
        $value = (string) $value;
        if ( '' === $value ) {
            return '';
        }
        if ( function_exists( 'iconv_mime_decode' ) ) {
            $decoded = @iconv_mime_decode( $value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8' );
            if ( is_string( $decoded ) && '' !== $decoded ) {
                return $decoded;
            }
        }
        return $value;
    }

    private function extract_imap_message_text( $stream, $uid, $limit = 1200 ) {
        $limit     = max( 0, min( 5000, intval( $limit ) ) );
        $structure = function_exists( 'imap_fetchstructure' ) ? @imap_fetchstructure( $stream, $uid, FT_UID ) : null;
        $plain     = '';
        $html      = '';

        if ( $structure ) {
            foreach ( $this->collect_imap_text_parts( $stream, $uid, $structure ) as $part ) {
                if ( empty( $part['text'] ) ) {
                    continue;
                }
                if ( 'text/plain' === $part['mime'] && '' === $plain ) {
                    $plain = (string) $part['text'];
                } elseif ( 'text/html' === $part['mime'] && '' === $html ) {
                    $html = (string) $part['text'];
                }
            }
        }

        if ( '' === $plain && '' === $html ) {
            $plain = (string) @imap_body( $stream, $uid, FT_UID | FT_PEEK );
        }

        $text = '' !== $plain ? $plain : wp_strip_all_tags( $html );
        $text = $this->normalize_imap_body_text( $text );

        if ( $limit > 0 ) {
            return $this->truncate_text_value( $text, $limit );
        }

        return '';
    }

    private function collect_imap_text_parts( $stream, $uid, $structure, $prefix = '' ) {
        $parts = array();
        if ( ! empty( $structure->parts ) && is_array( $structure->parts ) ) {
            foreach ( $structure->parts as $index => $child ) {
                $part_number = '' === $prefix ? (string) ( $index + 1 ) : $prefix . '.' . ( $index + 1 );
                $parts       = array_merge( $parts, $this->collect_imap_text_parts( $stream, $uid, $child, $part_number ) );
            }
            return $parts;
        }

        $type    = isset( $structure->type ) ? intval( $structure->type ) : -1;
        $subtype = isset( $structure->subtype ) ? strtolower( (string) $structure->subtype ) : '';
        if ( 0 !== $type || ! in_array( $subtype, array( 'plain', 'html' ), true ) ) {
            return $parts;
        }

        $part_number = '' === $prefix ? '1' : $prefix;
        $body        = @imap_fetchbody( $stream, $uid, $part_number, FT_UID | FT_PEEK );
        if ( ( ! is_string( $body ) || '' === trim( $body ) ) && '1' === $part_number ) {
            $body = @imap_body( $stream, $uid, FT_UID | FT_PEEK );
        }

        $parts[] = array(
            'mime' => 'text/' . $subtype,
            'text' => $this->decode_imap_part_body(
                is_string( $body ) ? $body : '',
                isset( $structure->encoding ) ? intval( $structure->encoding ) : 0,
                $this->get_imap_part_charset( $structure )
            ),
        );

        return $parts;
    }

    private function decode_imap_part_body( $body, $encoding = 0, $charset = '' ) {
        $body = (string) $body;
        if ( 3 === intval( $encoding ) ) {
            $decoded = base64_decode( $body, true );
            if ( false !== $decoded ) {
                $body = $decoded;
            }
        } elseif ( 4 === intval( $encoding ) ) {
            $body = quoted_printable_decode( $body );
        }

        $charset = trim( (string) $charset );
        if ( '' !== $charset && function_exists( 'iconv' ) && 0 !== strcasecmp( $charset, 'UTF-8' ) ) {
            $converted = @iconv( $charset, 'UTF-8//IGNORE', $body );
            if ( is_string( $converted ) && '' !== $converted ) {
                $body = $converted;
            }
        }

        return $body;
    }

    private function get_imap_part_charset( $structure ) {
        foreach ( array( 'parameters', 'dparameters' ) as $property ) {
            if ( empty( $structure->{$property} ) || ! is_array( $structure->{$property} ) ) {
                continue;
            }
            foreach ( $structure->{$property} as $parameter ) {
                if ( isset( $parameter->attribute, $parameter->value ) && 0 === strcasecmp( (string) $parameter->attribute, 'charset' ) ) {
                    return (string) $parameter->value;
                }
            }
        }

        return '';
    }

    private function normalize_imap_body_text( $body ) {
        $body = trim( html_entity_decode( wp_strip_all_tags( (string) $body ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
        $body = preg_replace( '/\s+/', ' ', (string) $body );
        return trim( (string) $body );
    }

    private function truncate_text_value( $text, $limit ) {
        $text  = (string) $text;
        $limit = max( 0, intval( $limit ) );
        if ( 0 === $limit || '' === $text ) {
            return '';
        }

        if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) {
            return mb_strlen( $text ) > $limit ? mb_substr( $text, 0, max( 0, $limit - 3 ) ) . '...' : $text;
        }

        return strlen( $text ) > $limit ? substr( $text, 0, max( 0, $limit - 3 ) ) . '...' : $text;
    }
}
