<?php



declare(strict_types=1);



/**

 * 郵件與驗證信範本（fate/data/fate_mail_settings.json）。

 * 環境變數 FATE_MAIL_FROM、FATE_MAIL_FROM_NAME、FATE_MAIL_TRANSPORT 優先於檔案。

 */



function fate_mail_settings_path(): string

{

    return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'fate_mail_settings.json';

}



/** @return array<string, string> */

function fate_mail_settings_default(): array

{

    return [

        'transport' => 'auto',

        'mail_from' => '',

        'mail_from_name' => 'XSPA',

        'smtp_host' => '',

        'smtp_port' => '587',

        'smtp_secure' => 'tls',

        'smtp_user' => '',

        'smtp_auth' => '1',

        'verify_method' => 'reverse',

        'imap_host' => '',

        'imap_port' => '993',

        'imap_secure' => 'ssl',

        'imap_folder' => 'INBOX',

        'imap_address' => '',

        'imap_user' => '',

        'imap_require_spf' => '0',

        'manual_approval' => '0',

        'verify_subject' => '請驗證您的 Email — {site_label}',

        'verify_body_plain' => <<<'TXT'

您好，{display_name}：



請在 {hours} 小時內完成 Email 驗證（擇一即可）：



方式一 — 開啟連結：

{verify_url}



方式二 — 至本站「我的帳號」輸入 6 位驗證碼：{verify_code}



若並非本人註冊，請忽略此信。

TXT,

        'verify_body_html' => <<<'HTML'

<p>您好，{display_name}：</p>

<p>請在 <strong>{hours}</strong> 小時內完成 Email 驗證（連結或驗證碼擇一）：</p>

<p><a href="{verify_url}">{verify_url}</a></p>

<p>驗證碼：<strong style="font-size:1.15em;letter-spacing:0.12em;">{verify_code}</strong>（請至本站「我的帳號」輸入）</p>

<p style="color:#666;font-size:13px;">若並非本人註冊，請忽略此信。</p>

HTML,

    ];

}



/** @return array<string, mixed> */

function fate_mail_settings_read(): array

{

    $p = fate_mail_settings_path();

    if (!is_file($p)) {

        return [];

    }

    $raw = file_get_contents($p);

    if ($raw === false || trim($raw) === '') {

        return [];

    }

    $j = json_decode($raw, true);



    return is_array($j) ? $j : [];

}



/** @return list<string> */

function fate_mail_verify_placeholder_ids(): array

{

    return ['display_name', 'verify_url', 'verify_code', 'site_label', 'hours'];

}



function fate_mail_settings_sanitize_transport(?string $raw): string

{

    $t = strtolower(trim((string) $raw));



    return in_array($t, ['auto', 'php_mail', 'brevo'], true) ? $t : 'auto';

}



function fate_mail_settings_sanitize_smtp_host(?string $raw): string

{

    $h = trim((string) $raw);

    if ($h === '') {

        return '';

    }

    // 去掉協定前綴與尾端斜線，僅保留主機名稱

    $h = preg_replace('#^[a-z]+://#i', '', $h) ?? $h;

    $h = rtrim($h, '/');

    if (preg_match('/^[A-Za-z0-9_.\-]{1,255}$/', $h) !== 1) {

        return '';

    }



    return $h;

}



function fate_mail_settings_sanitize_smtp_port(?string $raw): string

{

    $p = (int) trim((string) $raw);

    if ($p < 1 || $p > 65535) {

        return '587';

    }



    return (string) $p;

}



function fate_mail_settings_sanitize_smtp_secure(?string $raw): string

{

    $s = strtolower(trim((string) $raw));



    return in_array($s, ['tls', 'ssl', 'none'], true) ? $s : 'tls';

}



function fate_mail_settings_sanitize_smtp_user(?string $raw): string

{

    $u = trim((string) $raw);

    if ($u === '') {

        return '';

    }



    return strlen($u) > 254 ? substr($u, 0, 254) : $u;

}



function fate_mail_settings_sanitize_bool(?string $raw): string

{

    $v = strtolower(trim((string) $raw));



    return in_array($v, ['0', 'false', 'no', 'off', ''], true) ? '0' : '1';

}



function fate_mail_settings_sanitize_verify_method(?string $raw): string

{

    $m = strtolower(trim((string) $raw));



    return in_array($m, ['token', 'reverse', 'both'], true) ? $m : 'reverse';

}



function fate_mail_settings_sanitize_imap_secure(?string $raw): string

{

    $s = strtolower(trim((string) $raw));



    return in_array($s, ['ssl', 'tls', 'none'], true) ? $s : 'ssl';

}



function fate_mail_settings_sanitize_imap_folder(?string $raw): string

{

    $f = trim((string) $raw);

    if ($f === '') {

        return 'INBOX';

    }

    // 僅允許資料夾名稱常見字元（含階層分隔 . 與 /）

    if (preg_match('/^[A-Za-z0-9_.\/\- ]{1,128}$/', $f) !== 1) {

        return 'INBOX';

    }



    return $f;

}



/** IMAP 加密旗標字串（供 imap_open mailbox 用）。 */

function fate_mail_imap_flags_from_secure(string $secure): string

{

    switch ($secure) {

        case 'tls':

            return '/imap/tls/novalidate-cert';

        case 'none':

            return '/imap/notls';

        case 'ssl':

        default:

            return '/imap/ssl/novalidate-cert';

    }

}



function fate_mail_settings_sanitize_from_email(?string $raw): string

{

    $e = trim((string) $raw);

    if ($e === '') {

        return '';

    }



    return filter_var($e, FILTER_VALIDATE_EMAIL) ? $e : '';

}



function fate_mail_settings_sanitize_from_name(?string $raw): string

{

    $s = trim((string) $raw);

    if ($s === '') {

        return '';

    }

    if (function_exists('mb_substr')) {

        return mb_substr($s, 0, 120, 'UTF-8');

    }



    return strlen($s) > 120 ? substr($s, 0, 120) : $s;

}



function fate_mail_settings_sanitize_template_text(?string $raw, int $maxLen): string

{

    $s = str_replace(["\r\n", "\r"], "\n", (string) $raw);

    if (function_exists('mb_strlen') && mb_strlen($s, 'UTF-8') > $maxLen) {

        return mb_substr($s, 0, $maxLen, 'UTF-8');

    }

    if (strlen($s) > $maxLen) {

        return substr($s, 0, $maxLen);

    }



    return $s;

}



/**

 * @param array<string, mixed> $merge

 * @return array<string, string>

 */

function fate_mail_settings_normalize(array $merge): array

{

    $d = fate_mail_settings_default();

    foreach ($d as $k => $_) {

        if (array_key_exists($k, $merge)) {

            $d[$k] = is_string($merge[$k]) ? $merge[$k] : (string) $merge[$k];

        }

    }



    $d['transport'] = fate_mail_settings_sanitize_transport($d['transport']);

    $d['mail_from'] = fate_mail_settings_sanitize_from_email($d['mail_from']);

    $name = fate_mail_settings_sanitize_from_name($d['mail_from_name']);

    $d['mail_from_name'] = $name !== '' ? $name : fate_mail_settings_default()['mail_from_name'];

    $d['smtp_host'] = fate_mail_settings_sanitize_smtp_host($d['smtp_host']);

    $d['smtp_port'] = fate_mail_settings_sanitize_smtp_port($d['smtp_port']);

    $d['smtp_secure'] = fate_mail_settings_sanitize_smtp_secure($d['smtp_secure']);

    $d['smtp_user'] = fate_mail_settings_sanitize_smtp_user($d['smtp_user']);

    $d['smtp_auth'] = fate_mail_settings_sanitize_bool($d['smtp_auth']);

    $d['verify_method'] = fate_mail_settings_sanitize_verify_method($d['verify_method']);

    $d['imap_host'] = fate_mail_settings_sanitize_smtp_host($d['imap_host']);

    $d['imap_port'] = fate_mail_settings_sanitize_smtp_port($d['imap_port']);

    $d['imap_secure'] = fate_mail_settings_sanitize_imap_secure($d['imap_secure']);

    $d['imap_folder'] = fate_mail_settings_sanitize_imap_folder($d['imap_folder']);

    $d['imap_address'] = fate_mail_settings_sanitize_from_email($d['imap_address']);

    $d['imap_user'] = fate_mail_settings_sanitize_smtp_user($d['imap_user']);

    $d['imap_require_spf'] = fate_mail_settings_sanitize_bool($d['imap_require_spf']);

    $d['manual_approval'] = fate_mail_settings_sanitize_bool($d['manual_approval']);

    $d['verify_subject'] = fate_mail_settings_sanitize_template_text($d['verify_subject'], 200);

    $d['verify_body_plain'] = fate_mail_settings_sanitize_template_text($d['verify_body_plain'], 12000);

    $d['verify_body_html'] = fate_mail_settings_sanitize_template_text($d['verify_body_html'], 48000);



    if (trim($d['verify_subject']) === '') {

        $d['verify_subject'] = fate_mail_settings_default()['verify_subject'];

    }

    if (trim($d['verify_body_plain']) === '') {

        $d['verify_body_plain'] = fate_mail_settings_default()['verify_body_plain'];

    }



    return $d;

}



/** @param array<string, string> $normalized */

function fate_mail_settings_persist(array $normalized): bool

{

    $dir = dirname(fate_mail_settings_path());

    if (!is_dir($dir)) {

        if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {

            return false;

        }

    }

    $payload = json_encode($normalized, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    if ($payload === false) {

        return false;

    }



    return file_put_contents(fate_mail_settings_path(), $payload . "\n", LOCK_EX) !== false;

}



function fate_mail_transport_from_env(): string

{

    $v = trim((string) (getenv('FATE_MAIL_TRANSPORT') ?: ''));



    return fate_mail_settings_sanitize_transport($v !== '' ? $v : 'auto');

}



function fate_mail_transport_locked_by_env(): bool

{

    return trim((string) (getenv('FATE_MAIL_TRANSPORT') ?: '')) !== '';

}



function fate_mail_from_env_locked(): bool

{

    $e = trim((string) (getenv('FATE_MAIL_FROM') ?: ''));



    return $e !== '' && filter_var($e, FILTER_VALIDATE_EMAIL) !== false;

}



function fate_mail_from_name_env_locked(): bool

{

    return trim((string) (getenv('FATE_MAIL_FROM_NAME') ?: '')) !== '';

}



/**
 * SMTP 連線設定（環境變數 FATE_SMTP_* 優先於檔案；密碼走金鑰庫 smtp_password）。
 *
 * @return array{host:string, port:int, secure:string, user:string, pass:string, auth:bool}
 */
function fate_mail_resolved_smtp(): array

{

    $file = fate_mail_settings_normalize(fate_mail_settings_read());



    $envHost = trim((string) (getenv('FATE_SMTP_HOST') ?: ''));

    $host = $envHost !== ''

        ? fate_mail_settings_sanitize_smtp_host($envHost)

        : $file['smtp_host'];



    $envPort = trim((string) (getenv('FATE_SMTP_PORT') ?: ''));

    $port = $envPort !== ''

        ? fate_mail_settings_sanitize_smtp_port($envPort)

        : $file['smtp_port'];



    $envSecure = trim((string) (getenv('FATE_SMTP_SECURE') ?: ''));

    $secure = $envSecure !== ''

        ? fate_mail_settings_sanitize_smtp_secure($envSecure)

        : $file['smtp_secure'];



    $envUser = trim((string) (getenv('FATE_SMTP_USER') ?: ''));

    $user = $envUser !== ''

        ? fate_mail_settings_sanitize_smtp_user($envUser)

        : $file['smtp_user'];



    if (!function_exists('fate_api_key')) {

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_api_keys.php';

    }

    $pass = fate_api_key('smtp_password');



    $auth = $file['smtp_auth'] === '1';



    return [

        'host' => $host,

        'port' => (int) $port,

        'secure' => $secure,

        'user' => $user,

        'pass' => $pass,

        'auth' => $auth,

    ];

}



/** SMTP 是否已具備可發信的最低設定（至少有主機）。 */
function fate_mail_smtp_configured(): bool

{

    return fate_mail_resolved_smtp()['host'] !== '';

}



function fate_mail_smtp_host_env_locked(): bool

{

    return trim((string) (getenv('FATE_SMTP_HOST') ?: '')) !== '';

}



/**
 * 反向 Email 驗證的 IMAP 設定（環境變數 FATE_IMAP_* 優先於檔案；密碼走金鑰庫 imap_password）。
 *
 * @return array{host:string,port:int,secure:string,flags:string,folder:string,address:string,user:string,pass:string,require_spf:bool}
 */
function fate_mail_resolved_imap(): array

{

    $file = fate_mail_settings_normalize(fate_mail_settings_read());



    $envHost = trim((string) (getenv('FATE_IMAP_HOST') ?: ''));

    $host = $envHost !== '' ? fate_mail_settings_sanitize_smtp_host($envHost) : $file['imap_host'];



    $envPort = trim((string) (getenv('FATE_IMAP_PORT') ?: ''));

    $port = $envPort !== '' ? fate_mail_settings_sanitize_smtp_port($envPort) : $file['imap_port'];



    $envSecure = trim((string) (getenv('FATE_IMAP_SECURE') ?: ''));

    $secure = $envSecure !== '' ? fate_mail_settings_sanitize_imap_secure($envSecure) : $file['imap_secure'];



    // 旗標：FATE_IMAP_FLAGS 可直接覆寫，否則由 secure 推導

    $envFlags = trim((string) (getenv('FATE_IMAP_FLAGS') ?: ''));

    $flags = $envFlags !== '' ? $envFlags : fate_mail_imap_flags_from_secure($secure);



    $envFolder = trim((string) (getenv('FATE_IMAP_FOLDER') ?: ''));

    $folder = $envFolder !== '' ? fate_mail_settings_sanitize_imap_folder($envFolder) : $file['imap_folder'];



    $envAddr = trim((string) (getenv('FATE_IMAP_VERIFY_ADDRESS') ?: ''));

    $address = $envAddr !== '' ? fate_mail_settings_sanitize_from_email($envAddr) : $file['imap_address'];



    $envUser = trim((string) (getenv('FATE_IMAP_USER') ?: ''));

    $user = $envUser !== '' ? fate_mail_settings_sanitize_smtp_user($envUser) : $file['imap_user'];

    if ($user === '') {

        $user = $address;

    }



    if (!function_exists('fate_api_key')) {

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_api_keys.php';

    }

    $pass = fate_api_key('imap_password');



    $envSpf = strtolower(trim((string) (getenv('FATE_IMAP_REQUIRE_SPF') ?: '')));

    $requireSpf = $envSpf !== ''

        ? in_array($envSpf, ['1', 'true', 'yes', 'on'], true)

        : $file['imap_require_spf'] === '1';



    return [

        'host' => $host,

        'port' => (int) $port,

        'secure' => $secure,

        'flags' => $flags,

        'folder' => $folder,

        'address' => $address,

        'user' => $user,

        'pass' => $pass,

        'require_spf' => $requireSpf,

    ];

}



function fate_mail_imap_host_env_locked(): bool

{

    return trim((string) (getenv('FATE_IMAP_HOST') ?: '')) !== '';

}



/** 會員 Email 驗證方式：token｜reverse｜both（環境變數 FATE_VERIFY_METHOD 優先）。 */
function fate_mail_verify_method(): string

{

    $env = strtolower(trim((string) (getenv('FATE_VERIFY_METHOD') ?: '')));

    if (in_array($env, ['token', 'reverse', 'both'], true)) {

        return $env;

    }



    return fate_mail_settings_normalize(fate_mail_settings_read())['verify_method'];

}



function fate_mail_verify_method_locked_by_env(): bool

{

    $env = strtolower(trim((string) (getenv('FATE_VERIFY_METHOD') ?: '')));



    return in_array($env, ['token', 'reverse', 'both'], true);

}



/** 是否啟用「寄碼／連結」驗證（token 或 both）。 */
function fate_verify_method_uses_token(): bool

{

    return in_array(fate_mail_verify_method(), ['token', 'both'], true);

}



/** 是否啟用「反向 IMAP」驗證（reverse 或 both）。 */
function fate_verify_method_uses_reverse(): bool

{

    return in_array(fate_mail_verify_method(), ['reverse', 'both'], true);

}



/** 實際寄信管道：auto | php_mail | brevo | smtp */

function fate_mail_effective_transport(): string

{

    if (fate_mail_transport_locked_by_env()) {

        return fate_mail_transport_from_env();

    }



    return fate_mail_settings_normalize(fate_mail_settings_read())['transport'];

}



/**

 * @return array{transport:string, mail_from:string, mail_from_name:string}

 */

function fate_mail_resolved_sender(): array

{

    $file = fate_mail_settings_normalize(fate_mail_settings_read());



    $from = fate_mail_from_env_locked()

        ? trim((string) getenv('FATE_MAIL_FROM'))

        : $file['mail_from'];



    $name = fate_mail_from_name_env_locked()

        ? trim((string) getenv('FATE_MAIL_FROM_NAME'))

        : $file['mail_from_name'];



    return [

        'transport' => fate_mail_effective_transport(),

        'mail_from' => fate_mail_settings_sanitize_from_email($from),

        'mail_from_name' => fate_mail_settings_sanitize_from_name($name) !== ''

            ? fate_mail_settings_sanitize_from_name($name)

            : fate_mail_settings_default()['mail_from_name'],

    ];

}



/**

 * @param array<string, string> $vars

 */

function fate_mail_apply_placeholders(string $template, array $vars): string

{

    return (string) preg_replace_callback(

        '/\{([a-z_][a-z0-9_]*)\}/i',

        static function (array $m) use ($vars): string {

            $key = strtolower($m[1]);



            return array_key_exists($key, $vars) ? $vars[$key] : $m[0];

        },

        $template

    );

}



/**

 * 預覽／測試用變數（verify_url 為範例連結）。

 *

 * @return array<string, string>

 */

function fate_mail_verify_sample_vars(): array

{

    if (!function_exists('fate_public_site_branding')) {

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';

    }

    if (!function_exists('fate_absolute_url')) {

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_member_email.php';

    }



    $brand = fate_public_site_branding();

    $base = fate_public_site_absolute_base();

    $label = $brand['title_main'] !== '' ? $brand['title_main'] : ($base['label'] !== '' ? $base['label'] : 'FATE');



    return [

        'display_name' => '測試會員',

        'verify_url' => fate_absolute_url('verify_email.php?token=' . str_repeat('a', 48)),

        'verify_code' => '123456',

        'site_label' => $label,

        'hours' => '48',

    ];

}



/**

 * @param array<string, string>|null $draft 未儲存表單內容（覆寫檔案設定）

 * @return array{subject:string, plaintext:string, html:string}

 */

function fate_mail_render_verify_email(?array $draft = null, ?array $sampleVars = null): array

{

    $cfg = fate_mail_settings_normalize($draft ?? fate_mail_settings_read());

    $vars = $sampleVars ?? fate_mail_verify_sample_vars();



    $html = trim($cfg['verify_body_html']);



    return [

        'subject' => fate_mail_apply_placeholders($cfg['verify_subject'], $vars),

        'plaintext' => fate_mail_apply_placeholders($cfg['verify_body_plain'], $vars),

        'html' => $html !== '' ? fate_mail_apply_placeholders($html, $vars) : '',

    ];

}



/**

 * @param array<string, mixed> $post

 * @return array{ok:bool, error:?string}

 */

function fate_mail_settings_save_admin_post(array $post): array

{

    $patch = fate_mail_settings_normalize(fate_mail_settings_read());

    if (!fate_mail_verify_method_locked_by_env()) {

        $patch['verify_method'] = isset($post['verify_method']) ? (string) $post['verify_method'] : $patch['verify_method'];

    }

    if (!fate_mail_transport_locked_by_env()) {

        $patch['transport'] = isset($post['transport']) ? (string) $post['transport'] : $patch['transport'];

    }

    if (!fate_mail_from_env_locked()) {

        $patch['mail_from'] = isset($post['mail_from']) ? (string) $post['mail_from'] : $patch['mail_from'];

    }

    if (!fate_mail_from_name_env_locked()) {

        $patch['mail_from_name'] = isset($post['mail_from_name']) ? (string) $post['mail_from_name'] : $patch['mail_from_name'];

    }

    if (!fate_mail_imap_host_env_locked()) {

        $patch['imap_host'] = isset($post['imap_host']) ? (string) $post['imap_host'] : $patch['imap_host'];

    }

    $patch['imap_port'] = isset($post['imap_port']) ? (string) $post['imap_port'] : $patch['imap_port'];

    $patch['imap_secure'] = isset($post['imap_secure']) ? (string) $post['imap_secure'] : $patch['imap_secure'];

    $patch['imap_folder'] = isset($post['imap_folder']) ? (string) $post['imap_folder'] : $patch['imap_folder'];

    $patch['imap_address'] = isset($post['imap_address']) ? (string) $post['imap_address'] : $patch['imap_address'];

    $patch['imap_user'] = isset($post['imap_user']) ? (string) $post['imap_user'] : $patch['imap_user'];

    $patch['imap_require_spf'] = isset($post['imap_require_spf']) ? '1' : '0';

    if (!function_exists('fate_member_manual_approval_locked_by_env') || !fate_member_manual_approval_locked_by_env()) {

        $patch['manual_approval'] = isset($post['manual_approval']) ? '1' : '0';

    }

    $patch['verify_subject'] = isset($post['verify_subject']) ? (string) $post['verify_subject'] : $patch['verify_subject'];

    $patch['verify_body_plain'] = isset($post['verify_body_plain']) ? (string) $post['verify_body_plain'] : $patch['verify_body_plain'];

    $patch['verify_body_html'] = isset($post['verify_body_html']) ? (string) $post['verify_body_html'] : $patch['verify_body_html'];

    $norm = fate_mail_settings_normalize($patch);

    if (!fate_mail_settings_persist($norm)) {

        return ['ok' => false, 'error' => '無法寫入 fate/data/fate_mail_settings.json（請檢查目錄權限）。'];

    }

    // IMAP 密碼存入金鑰庫（fate_secrets.json）；空白＝保留原值，勾選清除＝刪除。

    if (!function_exists('fate_api_key_from_env')) {

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_api_keys.php';

    }

    // IMAP 密碼（反向驗證）存入金鑰庫；空白＝保留原值，勾選清除＝刪除。

    if (fate_api_key_from_env('imap_password') === '') {

        $clearImap = !empty($post['imap_password_clear']);

        $newImap = isset($post['imap_password']) ? trim((string) $post['imap_password']) : '';

        if ($clearImap || $newImap !== '') {

            $secrets = fate_api_keys_read_file();

            if ($clearImap) {

                unset($secrets['imap_password']);

            } else {

                $secrets['imap_password'] = $newImap;

            }

            if (!fate_api_keys_persist($secrets)) {

                return ['ok' => false, 'error' => 'IMAP 主機等已儲存，但無法寫入 fate/data/fate_secrets.json（密碼未更新，請檢查權限）。'];

            }

        }

    }



    return ['ok' => true, 'error' => null];

}



/**

 * @return array{label:string, detail:string, can_send:bool}

 */

function fate_mail_admin_transport_status(): array

{

    require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_api_keys.php';



    $t = fate_mail_effective_transport();

    $key = fate_api_key('brevo_email');

    $keySt = fate_api_key_admin_status('brevo_email');



    if ($t === 'brevo') {

        if ($key === '') {

            return [

                'label' => 'Brevo（第三方 API）',

                'detail' => '已選 Brevo，但尚未設定 API 金鑰（請至「網站與模版」→ 郵件）。',

                'can_send' => false,

            ];

        }



        return [

            'label' => 'Brevo（第三方 API）',

            'detail' => '使用 Brevo Transactional API 發信。金鑰：' . $keySt['label'],

            'can_send' => true,

        ];

    }



    if ($t === 'php_mail') {

        return [

            'label' => 'PHP mail()',

            'detail' => '強制使用主機 mail()；回傳成功僅表示交給本機 MTA，無法保證收件匣送達。',

            'can_send' => true,

        ];

    }



    // auto：Brevo > PHP mail()

    if ($key !== '') {

        return [

            'label' => '自動（目前：Brevo）',

            'detail' => '已設定 Brevo 金鑰，優先走 API。金鑰：' . $keySt['label'],

            'can_send' => true,

        ];

    }



    return [

        'label' => '自動（目前：PHP mail()）',

        'detail' => '未設定 Brevo 金鑰，改以主機 mail()；回傳成功僅表示交給本機 MTA，不保證送達。',

        'can_send' => true,

    ];

}


