<?php
/**
 * Plugin Name: Mail Baby SMTP
 * Plugin URI: https://www.mail.baby/
 * Description: MailBaby is an email smart host that offers outbound filtering
 * Version: 3.2.13
 * Tested up to: 6.9.1
 * Requires PHP: 7.4
 * Author: Mail.Baby
 * Author URI: https://www.mail.baby
 **/

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

// 1. --- ACTIVATION AND ERROR HOOKS ---

function mbs_plugin_activated()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'mbs_mail_log';
    $wpdb_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table_name} (
        `id` int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
        `error_log` VARCHAR(1000) NOT NULL
    ) $wpdb_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql, true);
}
register_activation_hook(__FILE__, 'mbs_plugin_activated');

function onMailError($wp_error)
{
    $mbsmtp_options = get_option('MAIL_BABY_SMTP_options');
    if (empty($mbsmtp_options) || empty($mbsmtp_options['mailer'])) {
        return;
    }

    $errors = $wp_error->errors['wp_mail_failed'];
    $mailer = $mbsmtp_options['mailer'];

    if ($mailer != 'othersmtp') {
        update_option('smtp_error_log', $errors);
    }
}
add_action('wp_mail_failed', 'onMailError', 10, 1);

// 2. --- PHPMAILER CONFIGURATION (SMTP ONLY) ---

function mbs_configure_phpmailer($phpmailer)
{
    $options = MAIL_BABY_SMTP_get_option();

    if (
        empty($options) || 
        empty($options['mailer']) || 
        $options['mailer'] === 'php' ||
        $options['mailer'] === 'mailbaby'
    ) {
        return;
    }

    $phpmailer->isSMTP();
    
    $from_email = '';
    $from_name = '';

    switch ($options['mailer']) {
        case 'smtp':
            $from_email = $options['from_email1'] ?? '';
            $from_name = $options['from_name1'] ?? '';
            break;
        case 'sendinblue':
            $from_email = $options['from_email2'] ?? '';
            break;
        case 'mailgun':
            $from_email = $options['from_email3'] ?? '';
            $from_name = $options['from_name2'] ?? '';
            break;
        case 'sendgrid':
            $from_email = $options['from_email4'] ?? '';
            $from_name = $options['from_name3'] ?? '';
            break;
        case 'gmail':
            $from_email = $options['from_email5'] ?? '';
            $from_name = $options['from_name4'] ?? '';
            break;
        case 'othersmtp':
            $from_email = $options['from_email6'] ?? '';
            $from_name = $options['from_name5'] ?? '';
            break;
    }
    
    if (!empty($from_email)) {
        $phpmailer->From = $from_email;
    }
    if (!empty($from_name)) {
        $phpmailer->FromName = $from_name;
    }

    switch ($options['mailer']) {
        case 'smtp':
            $phpmailer->Host = 'smtp.smtp.com';
            $phpmailer->Port = 2525;
            $phpmailer->SMTPSecure = 'tls';
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = $options['mail_baby_smtp_smtpcom_sender_name'] ?? '';
            $phpmailer->Password = $options['mail_baby_smtp_smtpcom_api_key'] ?? '';
            break;
        case 'othersmtp':
            $phpmailer->Host = $options['smtp_host'] ?? '';
            $phpmailer->Port = $options['smtp_port'] ?? 587;
            $phpmailer->SMTPSecure = ($options['type_of_encryption'] == 'none') ? '' : $options['type_of_encryption'];
            $phpmailer->SMTPAuth = ($options['smtp_auth'] == 'true');
            $phpmailer->SMTPAutoTLS = ($options['smtp_auto_tls'] == 'true');
            $phpmailer->Username = $options['smtp_username'] ?? '';
            $phpmailer->Password = $options['smtp_password'] ?? '';
            break;
        case 'sendgrid':
            $phpmailer->Host = 'smtp.sendgrid.net';
            $phpmailer->Port = 587;
            $phpmailer->SMTPSecure = 'tls';
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = 'apikey';
            $phpmailer->Password = $options['mail_baby_smtp_sendgrid_api_key'] ?? '';
            break;
        case 'mailgun':
            $host = 'smtp.mailgun.org';
            if(isset($options['mail_baby_smtp_mailgun_region']) && $options['mail_baby_smtp_mailgun_region'] === 'EU'){
                $host = 'smtp.eu.mailgun.org';
            }
            $phpmailer->Host = $host;
            $phpmailer->Port = 587;
            $phpmailer->SMTPSecure = 'tls';
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = $options['mail_baby_smtp_mailgun_domain'] ?? '';
            $phpmailer->Password = $options['mail_baby_smtp_mailgun_api_key'] ?? '';
            break;
        case 'sendinblue':
            $phpmailer->Host = 'smtp-relay.brevo.com';
            $phpmailer->Port = 587;
            $phpmailer->SMTPSecure = 'tls';
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = $options['from_email2'] ?? '';
            $phpmailer->Password = $options['mail_baby_smtp_sendinblue_api_key'] ?? '';
            break;
        case 'gmail':
            $phpmailer->Host = 'smtp.gmail.com';
            $phpmailer->Port = $options['smtp_port'] ?? 587;
            $phpmailer->SMTPSecure = $options['type_of_encryption'] ?? 'tls';
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = $options['oauth_user_email'] ?? '';
            $phpmailer->Password = $options['oauth_client_secret'] ?? '';
            break;
    }

    if (!empty($options['dkim_enable']) && $options['dkim_enable'] === 'on') {
        if (!empty($options['dkim_domain']) && !empty($options['dkim_selector']) && !empty($options['dkim_private_key'])) {
            $phpmailer->DKIM_domain = $options['dkim_domain'];
            $phpmailer->DKIM_selector = $options['dkim_selector'];
            $phpmailer->DKIM_private_string = $options['dkim_private_key'];
            $phpmailer->DKIM_identity = $phpmailer->From;
            $phpmailer->DKIM_passphrase = $options['dkim_passphrase'] ?? '';
        }
    }
}
add_action('phpmailer_init', 'mbs_configure_phpmailer', 10, 1);

// 3. --- TEST EMAIL HANDLER ---

function mbs_handle_test_email()
{
    if (
        !isset($_POST['MAIL_BABY_SMTP_send_test_email']) ||
        !isset($_GET['page']) ||
        $_GET['page'] !== 'mail-baby-smtp-settings' ||
        !isset($_GET['action']) ||
        $_GET['action'] !== 'test-email'
    ) {
        return;
    }

    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have permission to send test emails.', 'mail-baby-smtp'));
    }

    check_admin_referer('mbs_test_email_action', 'mbs_test_email_nonce');

    $to = sanitize_email(wp_unslash($_POST['MAIL_BABY_SMTP_to_email']));
    $subject = sanitize_text_field(wp_unslash($_POST['MAIL_BABY_SMTP_email_subject']));
    $body = sanitize_textarea_field(wp_unslash($_POST['MAIL_BABY_SMTP_email_body']));

    if (empty($to) || empty($subject) || empty($body)) {
        set_transient('mbs_test_email_status', ['success' => false, 'message' => 'Error: Please fill in all fields for the test email.']);
        return;
    }

    $result = wp_mail($to, $subject, $body);

    if ($result) {
        set_transient('mbs_test_email_status', ['success' => true, 'message' => 'Test email sent successfully! Please check your inbox.']);
    } else {
        $api_log = get_transient('mbs_test_email_debug_log');
        if ($api_log && $api_log['type'] === 'API') {
            $error_message = 'Mailbaby API Error. See Debug Log tab.';
            set_transient('mbs_test_email_status', ['success' => false, 'message' => $error_message]);
        } else {
            global $phpmailer;
            $error_info = 'SMTP Error: Unknown error. Check Debug Log.';
            if (isset($phpmailer) && !empty($phpmailer->ErrorInfo)) {
                $error_info = $phpmailer->ErrorInfo;
            }
            set_transient('mbs_test_email_status', ['success' => false, 'message' => $error_info]);
        }
    }
}
add_action('admin_init', 'mbs_handle_test_email');

// 4. --- ADMIN SETTINGS CLASS ---

class MAIL_BABY_SMTP {

    var $plugin_version = '3.2.13';
    var $plugin_url;
    var $plugin_path;
    var $assets_url;

    function __construct() {
        define('MAIL_BABY_SMTP_VERSION', $this->plugin_version);
        define('MAIL_BABY_SMTP_URL', $this->plugin_url());
        define('MAIL_BABY_SMTP_PATH', $this->plugin_path());

        $this->assets_url = plugins_url('/inc/assets', __FILE__);
        $this->loader_operations();
    }

    function loader_operations() {
        if (is_admin()) {
            add_filter('plugin_action_links', array($this, 'add_plugin_action_links'), 10, 2);
        }
        add_action('plugins_loaded', array($this, 'plugins_loaded_handler'));
        add_action('admin_menu', array($this, 'options_menu'));
        add_action('admin_enqueue_scripts', [ $this, 'enqueue_assets' ]);
        add_filter('pre_wp_mail', array($this, 'mbs_send_via_api'), 10, 2);
    }
    
    public function mbs_send_via_api($null, $atts) {
        $options = MAIL_BABY_SMTP_get_option();
        
        if (empty($options['mailer']) || $options['mailer'] !== 'mailbaby') {
            return $null; 
        }

        delete_transient('mbs_test_email_debug_log');

        $api_key = $options['mail_baby_api_key'] ?? '';
        if (empty($api_key)) {
            return false; 
        }
        
        $from_email = $options['from_email'] ?? '';
        if (empty($from_email) || !is_email($from_email)) {
            $from_email = get_option('admin_email');
        }
        $from_email = apply_filters('wp_mail_from', $from_email);
        
        $from_name = $options['from_name'] ?? '';
        if (empty($from_name)) {
            $from_name = apply_filters('wp_mail_from_name', 'WordPress');
        }

        $to = $atts['to'];
        $subject = $atts['subject'];
        $message = $atts['message'];

        if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
            require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
            require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
            require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
        }

        $signer = new \PHPMailer\PHPMailer\PHPMailer();
        $signer->CharSet = 'UTF-8';
        $signer->setFrom($from_email, $from_name);
        $signer->Subject = $subject;

        if ($message !== strip_tags($message)) {
            $signer->isHTML(true);
        }
        $signer->Body = $message;

        if (is_array($to)) {
            foreach ($to as $recipient) $signer->addAddress($recipient);
        } else {
            $signer->addAddress($to);
        }

        // CC / BCC / Reply-To Logic
        $custom_headers = $atts['headers'] ?? array();
        if (!empty($custom_headers)) {
            if (!is_array($custom_headers)) {
                $custom_headers = explode("\n", str_replace("\r", "", $custom_headers));
            }
            foreach ($custom_headers as $header) {
                $header = trim($header);
                if (stripos($header, 'Cc:') === 0) {
                    $signer->addCC(trim(substr($header, 3)));
                } elseif (stripos($header, 'Bcc:') === 0) {
                    $signer->addBCC(trim(substr($header, 4)));
                } elseif (stripos($header, 'Reply-To:') === 0) {
                    $signer->addReplyTo(trim(substr($header, 9)));
                }
            }
        }

        $dkim_enabled = !empty($options['dkim_enable']) && ($options['dkim_enable'] === 'on') && !empty($options['dkim_private_key']);
        if ($dkim_enabled) {
            $signer->DKIM_domain = $options['dkim_domain'];
            $signer->DKIM_selector = $options['dkim_selector'];
            $signer->DKIM_private_string = $options['dkim_private_key'];
            $signer->DKIM_identity = $signer->From;
            $signer->DKIM_passphrase = $options['dkim_passphrase'] ?? '';
        }

        try {
            $signer->preSend();
            $full_message = $signer->getSentMIMEMessage();
            if ($dkim_enabled) {
                $dkim_signature_value = $signer->DKIM_Sign($full_message);
                if (!empty($dkim_signature_value)) {
                    $full_message = "DKIM-Signature: $dkim_signature_value\r\n" . $full_message;
                }
            }
        } catch (\Exception $e) {
            error_log('Mail Baby SMTP: Message creation failed: ' . $e->getMessage());
        }

        $url = 'https://api.mailbaby.net/mail/rawsend';
        if (empty($full_message)) return false;

        // CRITICAL FIX: Explicitly gather envelope recipients for the API
        $envelope_recipients = array();
        if (is_array($to)) { $envelope_recipients = array_merge($envelope_recipients, $to); } else { $envelope_recipients[] = $to; }
        foreach ($signer->getCcAddresses() as $cc) { $envelope_recipients[] = $cc[0]; }
        foreach ($signer->getBccAddresses() as $bcc) { $envelope_recipients[] = $bcc[0]; }

        $payload = array(
            'raw_email' => $full_message,
            'recipients' => implode(',', array_unique($envelope_recipients))
        );

        $postdata = array(
            'timeout' => 45, 'blocking' => true, 'sslverify' => true, 'httpversion' => '1.0',
            'headers' => array('Accept' => 'application/json', 'Content-Type' => 'application/json', 'X-API-KEY' => $api_key),
            'body' => wp_json_encode($payload),
        );

        $response = wp_remote_post($url, $postdata);
        
        $debug_log = [
            'timestamp' => current_time('mysql'),
            'type' => 'API', 
            'request' => ['url' => $url, 'payload' => $payload],
            'response' => [
                'is_wp_error' => is_wp_error($response), 'response_code' => wp_remote_retrieve_response_code($response), 
                'response_body' => wp_remote_retrieve_body($response)
            ]
        ];
        set_transient('mbs_test_email_debug_log', $debug_log, HOUR_IN_SECONDS);

        return (wp_remote_retrieve_response_code($response) === 200);
    }

    function plugins_loaded_handler() {
        load_plugin_textdomain('mail-baby-smtp', false, dirname(plugin_basename(__FILE__)) . '/languages/');
    }

    function plugin_url() {
        if ($this->plugin_url) return $this->plugin_url;
        return $this->plugin_url = plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__));
    }

    function plugin_path() {
        if ($this->plugin_path) return $this->plugin_path;
        return $this->plugin_path = untrailingslashit(plugin_dir_path(__FILE__));
    }

    function enqueue_assets( $hook ) {
        if ($hook !== 'settings_page_mail-baby-smtp-settings') return;
        $assets_url_inc = plugins_url( '', __FILE__ ). '/inc/assets';
        wp_enqueue_style('bootstrap-ui-css', $assets_url_inc . '/css/bootstrap/bootstrap/css/bootstrap.min.css');
        wp_enqueue_script('mbsmtp_js_bootstrap_bundle', $assets_url_inc . '/js/bootstrap/js/bootstrap.bundle.min.js', ['jquery'], false, true);
        wp_enqueue_script('mbsmtp_popper', $assets_url_inc . '/js/popper.min.js', ['mbsmtp_js_bootstrap_bundle'], false, true);
        wp_enqueue_script('mbsmtp_js_bootstrap_min', $assets_url_inc . '/js/bootstrap/js/bootstrap.min.js', ['mbsmtp_js_bootstrap_bundle'], false, true);
        wp_enqueue_script('mail-baby-smtp-admin', $this->assets_url . '/js/mbsmtp-new.js', array( 'jquery' ), MAIL_BABY_SMTP_VERSION, true);
        wp_enqueue_style('mail-baby-smtp', $this->assets_url . '/css/customstyle.css', false, MAIL_BABY_SMTP_VERSION);
    }

    function add_plugin_action_links($links, $file) {
        if ($file == plugin_basename(__FILE__)) {
            $links[] = '<a href="options-general.php?page=mail-baby-smtp-settings">' . __('Settings', 'mail-baby-smtp') . '</a>';
        }
        return $links;
    }

    function options_menu() {
        add_options_page(__('Mail Baby SMTP', 'mail-baby-smtp'), __('Mail Baby SMTP', 'mail-baby-smtp'), 'manage_options', 'mail-baby-smtp-settings', array($this, 'options_page'));
    }

    function options_page() {
        $plugin_tabs = array(
            'mail-baby-smtp-settings' => __('General', 'mail-baby-smtp'),
            'mail-baby-smtp-settings&action=test-email' => __('Test Email', 'mail-baby-smtp'),
            'mail-baby-smtp-settings&action=debug-log' => __('Debug Log', 'mail-baby-smtp'),
            'mail-baby-smtp-settings&action=server-info' => __('Server Info', 'mail-baby-smtp'),
        );
        
        $url = "https://www.mail.baby/";
        $link_text = sprintf(wp_kses(__('Please visit the <a target="_blank" href="%s">Mail Baby SMTP</a> documentation page for usage instructions.', 'mail-baby-smtp'), array('a' => array('href' => array(), 'target' => array()))), esc_url($url));
        
        echo '<div class="wrap" id="mail-baby-smtp">';
        echo '<div class="card"><h3 class="h3">Mail Baby SMTP v' . esc_html(MAIL_BABY_SMTP_VERSION) . '</h3>';
        echo '<div class="update-nag">'.$link_text.'</div>';
        echo '<div id="poststuff"><div id="post-body">';

        $current = $_GET['page'] . (isset($_GET['action']) ? "&action=" . $_GET['action'] : '');

        echo '<ul class="nav nav-tabs">';
        foreach ($plugin_tabs as $location => $tabname) {
            $class = ($current == $location) ? ' active' : '';
            echo '<li class="nav-item"><a class="nav-link' . $class . '" href="' . esc_url('?page=' . $location) . '">' . esc_html($tabname) . '</a></li>';
        }
        echo '</ul>';

        if (isset($_GET['action'])) {
            switch($_GET['action']) {
                case 'test-email': $this->test_email_settings(); break;
                case 'debug-log': $this->debug_log_page(); break;
                case 'server-info': $this->server_info_settings(); break;
                default: $this->general_settings(); break;
            }
        } else { $this->general_settings(); }

        echo '</div></div></div>';
    }

    function debug_log_page() {
        $debug_log = get_transient('mbs_test_email_debug_log');
        if (isset($_GET['clear_log'])) { delete_transient('mbs_test_email_debug_log'); wp_redirect(admin_url('options-general.php?page=mail-baby-smtp-settings&action=debug-log')); exit; }
        ?>
        <div class="p-4">
            <h3>Latest Delivery Log</h3>
            <?php if ($debug_log) : ?>
                <div class="alert alert-info">Generated: <?php echo esc_html($debug_log['timestamp']); ?></div>
                <div style="background: #272822; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: monospace; overflow-x: auto;">
                    <pre><?php echo esc_html(json_encode($debug_log, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); ?></pre>
                </div>
                <a href="?page=mail-baby-smtp-settings&action=debug-log&clear_log=1" class="btn btn-outline-danger btn-sm mt-3">Clear Log</a>
            <?php else : ?>
                <div class="alert alert-warning">No log found. Send a test email first.</div>
            <?php endif; ?>
        </div>
        <?php
    }

    function test_email_settings() {
        $status = get_transient('mbs_test_email_status');
        if ($status) { delete_transient('mbs_test_email_status'); $class = $status['success'] ? 'notice-success' : 'notice-error';
            echo '<div class="notice ' . $class . ' is-dismissible" style="margin-top: 15px;"><p><strong>' . esc_html($status['message']) . '</strong></p></div>';
        }
        ?>
        <br>
        <form method="post" action="?page=mail-baby-smtp-settings&action=test-email">
            <?php wp_nonce_field('mbs_test_email_action', 'mbs_test_email_nonce'); ?>
            <div class="my-3"><label class="form-label">To</label><input name="MAIL_BABY_SMTP_to_email" type="text" class="mb-2 form-control"></div>
            <div class="my-3"><label class="form-label">Subject</label><input name="MAIL_BABY_SMTP_email_subject" type="text" value="Mail Baby Test" class="mb-2 form-control"></div>
            <div class="my-3"><label class="form-label">Message</label><textarea name="MAIL_BABY_SMTP_email_body" rows="3" class="mb-2 form-control">Testing CC/BCC delivery with the new recipient envelope logic.</textarea></div>
            <div class="my-3"><input type="submit" name="MAIL_BABY_SMTP_send_test_email" class="btn btn-primary btn-sm" value="Send Email"></div>
        </form>
        <?php
    }

    function server_info_settings() {
        $server_info = sprintf("OS: %s\nPHP: %s\nWP: %s", php_uname(), PHP_VERSION, get_bloginfo('version'));
        echo '<br><textarea rows="10" cols="50" class="large-text code" readonly="readonly">' . esc_textarea($server_info) . '</textarea>';
    }
    
    function general_settings() {
        if (isset($_POST['MAIL_BABY_SMTP_update_settings'])) {
            check_admin_referer('MAIL_BABY_SMTP_general_settings');
            $options = MAIL_BABY_SMTP_get_empty_options_array();
            $new_options = array();
            foreach ($options as $key => $value) {
                if (isset($_POST[$key])) {
                    $raw_value = wp_unslash($_POST[$key]);
                    if (in_array($key, ['from_email', 'from_email1', 'from_email2', 'from_email3', 'from_email4', 'from_email5', 'from_email6', 'oauth_user_email'])) {
                        $sanitized_email = sanitize_email($raw_value);
                        $new_options[$key] = (empty($sanitized_email) || !is_email($sanitized_email)) ? get_option('admin_email') : $sanitized_email;
                    } elseif (in_array($key, ['from_name', 'from_name1', 'from_name2', 'from_name3', 'from_name4', 'from_name5'])) {
                        $sanitized_name = sanitize_text_field($raw_value);
                        $new_options[$key] = empty($sanitized_name) ? get_bloginfo('name') : $sanitized_name;
                    } else {
                        $new_options[$key] = sanitize_text_field($raw_value);
                    }
                }
            }
            $new_options['dkim_enable'] = isset($_POST['dkim_enable']) ? 'on' : 'off';
            $new_options['disable_ssl_verification'] = isset($_POST['disable_ssl_verification']) ? '1' : '0';
            MAIL_BABY_SMTP_update_option($new_options);
            echo '<div id="message" class="alert alert-success d-block">Settings Saved!</div>';
        }

        $options = MAIL_BABY_SMTP_get_option();
        ?>
        <div class="wrap" id="mail-baby-smtp">
            <div class="mail-baby-smtp-page mail-baby-smtp-page-general mail-baby-smtp-tab-settings">
                <div class="mail-baby-smtp-page-content">
                    <form method="post" action="">
                        <?php wp_nonce_field('MAIL_BABY_SMTP_general_settings'); ?>
                        
                        <div class="mb-5 ml-2">
                            <label class="my-3 form-label" style="font-weight: 600;">Select Mailer:</label>
                            <section>
                                <div class="mailer-section"><input class="mailer" type="radio" id="m1" name="mailer" value="mailbaby" <?php checked($options['mailer'], 'mailbaby'); ?> /><label class="mailer-label mailbaby" for="m1"><h1 class="mailer-title">Mail Baby</h1></label></div>
                                <div class="mailer-section"><input class="mailer" type="radio" id="m2" name="mailer" value="php" <?php checked($options['mailer'], 'php'); ?> /><label class="mailer-label php" for="m2"><h1 class="mailer-title">PHP</h1></label></div>
                                <div class="mailer-section"><input class="mailer" type="radio" id="m3" name="mailer" value="smtp" <?php checked($options['mailer'], 'smtp'); ?> /><label class="mailer-label smtp-com" for="m3"><h1 class="mailer-title">SMTP.com</h1></label></div>
                                <div class="mailer-section"><input class="mailer" type="radio" id="m4" name="mailer" value="sendinblue" <?php checked($options['mailer'], 'sendinblue'); ?> /><label class="mailer-label sendinblue" for="m4"><h1 class="mailer-title">SendInBlue</h1></label></div>
                                <div class="mailer-section"><input class="mailer" type="radio" id="m8" name="mailer" value="othersmtp" <?php checked($options['mailer'], 'othersmtp'); ?> /><label class="mailer-label smtp" for="m8"><h1 class="mailer-title">Other SMTP</h1></label></div>
                            </section>
                        </div>
                        
                        <div class="mail-baby-smtp-mailer-option mail-baby-smtp-mailer-option-mailbaby <?php echo $options['mailer'] === 'mailbaby' ? 'active' : 'hidden'; ?>">
                            <div class="my-3"><label class="form-label">From Email Address</label><input class="form-control" name="from_email" type="text" value="<?php echo esc_attr($options['from_email']); ?>"></div>
                            <div class="my-3"><label class="form-label">From Name</label><input class="form-control" name="from_name" type="text" value="<?php echo esc_attr($options['from_name']); ?>"></div>
                            <div class="my-3"><label class="form-label">API Key</label><input class="form-control" type="password" name="mail_baby_api_key" value="<?php echo esc_attr($options['mail_baby_api_key']); ?>"></div>
                        </div>

                        <div class="dkim-settings-section" style="margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 4px;">
                            <h2>DKIM Settings</h2>
                            <label><input name="dkim_enable" type="checkbox" <?php checked($options['dkim_enable'], 'on'); ?>> Enable DKIM</label>
                            <div class="my-3"><label class="form-label">Domain</label><input class="form-control" name="dkim_domain" type="text" value="<?php echo esc_attr($options['dkim_domain']); ?>"></div>
                            <div class="my-3"><label class="form-label">Selector</label><input class="form-control" name="dkim_selector" type="text" value="<?php echo esc_attr($options['dkim_selector']); ?>"></div>
                            <div class="my-3"><label class="form-label">Private Key</label><textarea name="dkim_private_key" rows="5" class="form-control"><?php echo esc_textarea($options['dkim_private_key']); ?></textarea></div>
                        </div>
                        <p class="submit"><input type="submit" name="MAIL_BABY_SMTP_update_settings" class="btn btn-primary btn-sm" value="Save Changes"></p>
                    </form>
                </div>
            </div>
        </div>
        <?php
    }
}

// 5. --- HELPER FUNCTIONS ---
function MAIL_BABY_SMTP_get_option() {
    $defaults = MAIL_BABY_SMTP_get_empty_options_array();
    $options = get_option('MAIL_BABY_SMTP_options');
    return array_merge($defaults, is_array($options) ? $options : []);
}
function MAIL_BABY_SMTP_update_option($new_options) {
    update_option('MAIL_BABY_SMTP_options', array_merge(MAIL_BABY_SMTP_get_option(), $new_options));
}
function MAIL_BABY_SMTP_get_empty_options_array() {
    return ['from_email' => '', 'from_name' => '', 'from_email1' => '', 'from_name1' => '', 'from_email2' => '', 'from_name2' => '', 'from_email3' => '', 'from_name3' => '', 'from_email4' => '', 'from_name4' => '', 'from_email5' => '', 'from_name5' => '', 'from_email6' => '', 'from_name6' => '', 'mailer' => 'php', 'smtp_host' => '', 'smtp_auth' => 'true', 'smtp_username' => '', 'smtp_password' => '', 'type_of_encryption' => 'tls', 'smtp_port' => '587', 'smtp_auto_tls' => 'true', 'disable_ssl_verification' => '0', 'mail_baby_api_key' => '', 'mail_baby_sender_name' => '', 'dkim_enable' => 'off', 'dkim_domain' => '', 'dkim_selector' => '', 'dkim_private_key' => '', 'dkim_passphrase' => ''];
}
$GLOBALS['mail-baby-smtp'] = new MAIL_BABY_SMTP();
