<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_mail_settings.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_api_keys.php';

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_mail.php';

fate_admin_require_login();

$error = null;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';
$stored = fate_mail_settings_normalize(fate_mail_settings_read());
$imapHostLocked = fate_mail_imap_host_env_locked();
$imapPassSt = fate_api_key_admin_status('imap_password');
$imapExtReady = function_exists('imap_open');
$transportLocked = fate_mail_transport_locked_by_env();
$fromLocked = fate_mail_from_env_locked();
$fromNameLocked = fate_mail_from_name_env_locked();
$transportStatus = fate_mail_admin_transport_status();
$mailDiag = fate_mail_php_mail_diagnostic();
$sender = fate_mail_resolved_sender();

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_email_reverse.php';
$reverseReady = fate_reverse_imap_ready();
$manualApproval = fate_member_manual_approval_enabled();
$manualApprovalLocked = fate_member_manual_approval_locked_by_env();

$imapCfg = fate_reverse_imap_config();
$verifyMethod = fate_mail_verify_method();
$verifyMethodLocked = fate_mail_verify_method_locked_by_env();
$verifyMethodLabels = [
    'token' => '寄信驗證（PHP mail()／Brevo）',
    'reverse' => '反向 IMAP 回寄',
    'both' => '兩者並行（會員擇一）',
];
$usesTokenVerify = fate_verify_method_uses_token();
$usesReverseVerify = fate_verify_method_uses_reverse();
$verifyPreview = fate_mail_render_verify_email($stored);
$verifyPlaceholders = fate_mail_verify_placeholder_ids();
$reverseChecks = [
    ['label' => 'PHP imap 擴充', 'ok' => $imapExtReady, 'hint' => $imapExtReady ? '已啟用' : '伺服器需安裝 php-imap 並重啟'],
    ['label' => 'IMAP 主機', 'ok' => $imapCfg['host'] !== '', 'hint' => $imapCfg['host'] !== '' ? $imapCfg['host'] : '於下方填 IMAP 主機'],
    ['label' => '驗證信箱地址', 'ok' => $imapCfg['address'] !== '', 'hint' => $imapCfg['address'] !== '' ? $imapCfg['address'] : '於下方填收驗證信的信箱'],
    ['label' => 'IMAP 密碼', 'ok' => $imapCfg['pass'] !== '', 'hint' => $imapCfg['pass'] !== '' ? '已儲存' : '於下方填驗證信箱的 IMAP 密碼'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $result = fate_mail_settings_save_admin_post($_POST);
        if (!$result['ok']) {
            $error = $result['error'] ?? '儲存失敗。';
            $stored = fate_mail_settings_normalize(array_merge($stored, [
                'transport' => $_POST['transport'] ?? $stored['transport'],
                'mail_from' => $_POST['mail_from'] ?? $stored['mail_from'],
                'mail_from_name' => $_POST['mail_from_name'] ?? $stored['mail_from_name'],
                'verify_method' => $_POST['verify_method'] ?? $stored['verify_method'],
                'verify_subject' => $_POST['verify_subject'] ?? $stored['verify_subject'],
                'verify_body_plain' => $_POST['verify_body_plain'] ?? $stored['verify_body_plain'],
                'verify_body_html' => $_POST['verify_body_html'] ?? $stored['verify_body_html'],
                'imap_host' => $_POST['imap_host'] ?? $stored['imap_host'],
                'imap_port' => $_POST['imap_port'] ?? $stored['imap_port'],
                'imap_secure' => $_POST['imap_secure'] ?? $stored['imap_secure'],
                'imap_folder' => $_POST['imap_folder'] ?? $stored['imap_folder'],
                'imap_address' => $_POST['imap_address'] ?? $stored['imap_address'],
                'imap_user' => $_POST['imap_user'] ?? $stored['imap_user'],
            ]));
        } else {
            header('Location: email_settings.php?saved=1', true, 302);
            exit;
        }
    }
}

$csrf = fate_admin_csrf_token();
$jsPath = __DIR__ . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'email_settings.js';
$jsVer = is_file($jsPath) ? (string) filemtime($jsPath) : '1';

fate_admin_layout_start(['page' => 'Email 驗證', 'active' => 'email', 'body_class' => 'admin-body--email-settings']);
?>
        <style>
        .verify-badge { display:inline-block; margin-left:.4rem; padding:.05rem .5rem; border-radius:999px; font-size:.78rem; font-weight:600; vertical-align:middle; }
        .verify-badge--ok { background:rgba(34,197,94,.15); color:#16a34a; border:1px solid rgba(34,197,94,.4); }
        .verify-badge--warn { background:rgba(234,179,8,.15); color:#b45309; border:1px solid rgba(234,179,8,.45); }
        .verify-check { margin-top:.85rem; padding:.75rem .85rem; border:1px dashed var(--line,rgba(128,128,128,.3)); border-radius:10px; }
        .verify-check__head { font-weight:600; margin-bottom:.5rem; }
        .verify-check__list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:.4rem; }
        .verify-check__item { display:grid; grid-template-columns:1.4rem auto; grid-template-areas:"icon label" ". hint"; align-items:center; gap:.1rem .3rem; }
        .verify-check__icon { grid-area:icon; font-weight:700; width:1.25rem; height:1.25rem; display:inline-flex; align-items:center; justify-content:center; border-radius:50%; font-size:.8rem; }
        .verify-check__item--ok .verify-check__icon { background:rgba(34,197,94,.18); color:#16a34a; }
        .verify-check__item--no .verify-check__icon { background:rgba(239,68,68,.18); color:#dc2626; }
        .verify-check__label { grid-area:label; font-weight:500; }
        .verify-check__hint { grid-area:hint; font-size:.8rem; opacity:.75; }
        .verify-check__item--no .verify-check__hint { color:#dc2626; opacity:.9; }
        </style>
        <header class="page-head">
            <h1 class="page-title">Email 驗證（XSPA）</h1>
            <p class="sub">
                管理員可選會員 Email 驗證方式：寄出驗證信（PHP mail()／Brevo）、反向 IMAP 回寄，或兩者並行。
                設定檔：<code>data/fate_mail_settings.json</code>；IMAP 密碼存於 <code>data/fate_secrets.json</code>。
            </p>
        </header>

        <?php if ($saved): ?>
            <div class="msg ok">已儲存。</div>
        <?php endif; ?>
        <?php if ($error !== null): ?>
            <div class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <div class="card">
            <h2 class="card-title">目前狀態</h2>
            <dl class="row">
                <div class="stat">
                    <dt>驗證方式</dt>
                    <dd><?= htmlspecialchars($verifyMethodLabels[$verifyMethod] ?? $verifyMethod, ENT_QUOTES, 'UTF-8') ?>
                        <?php if ($usesReverseVerify): ?>
                            <span class="verify-badge verify-badge--<?= $reverseReady ? 'ok' : 'warn' ?>"><?= $reverseReady ? 'IMAP 就緒' : 'IMAP 未就緒' ?></span>
                        <?php endif; ?>
                        <?php if ($usesTokenVerify): ?>
                            <span class="verify-badge verify-badge--<?= $transportStatus['can_send'] ? 'ok' : 'warn' ?>"><?= $transportStatus['can_send'] ? '可寄信' : '發信未就緒' ?></span>
                        <?php endif; ?>
                    </dd>
                </div>
                <?php if ($usesReverseVerify): ?>
                <div class="stat">
                    <dt>驗證信箱</dt>
                    <dd><code><?= htmlspecialchars($imapCfg['address'] !== '' ? $imapCfg['address'] : '（未設定）', ENT_QUOTES, 'UTF-8') ?></code></dd>
                </div>
                <?php endif; ?>
                <div class="stat">
                    <dt>人工審核</dt>
                    <dd><?= $manualApproval ? '開啟（須管理員核准後登入）' : '關閉（Email 驗證把關）' ?></dd>
                </div>
                <div class="stat">
                    <dt>系統發信</dt>
                    <dd><?= htmlspecialchars($transportStatus['label'], ENT_QUOTES, 'UTF-8') ?>
                        <span class="verify-badge verify-badge--<?= $transportStatus['can_send'] ? 'ok' : 'warn' ?>">
                            <?= $transportStatus['can_send'] ? '可發信' : '未就緒' ?>
                        </span>
                    </dd>
                </div>
            </dl>
            <p class="sub" style="margin-bottom:0;">
                <?php if ($usesTokenVerify && $usesReverseVerify): ?>
                    會員註冊後可收驗證信，或從註冊信箱回寄到驗證信箱（擇一完成即可）。
                <?php elseif ($usesReverseVerify): ?>
                    <?= $reverseReady
                        ? '會員註冊後可登入，並依「我的帳號」回寄驗證。'
                        : '⚠ IMAP 設定尚未完成或 php-imap 未啟用，會員無法完成反向驗證。' ?>
                <?php elseif ($usesTokenVerify): ?>
                    <?= $transportStatus['can_send']
                        ? '會員註冊後會寄出驗證信（連結或 6 位驗證碼擇一）。'
                        : '⚠ 發信設定尚未就緒，無法寄出驗證信。' ?>
                <?php else: ?>
                    請於下方選擇驗證方式。
                <?php endif; ?>
            </p>
        </div>

        <form method="post" action="email_settings.php" class="stack-form" id="email-settings-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

            <div class="card">
                <h2 class="card-title">Email 驗證方式</h2>
                <p class="sub" style="margin-top:0;">選擇會員完成 Email 驗證的管道；環境變數 <code>FATE_VERIFY_METHOD</code> 可鎖定（<code>token</code>／<code>reverse</code>／<code>both</code>）。</p>
                <fieldset class="field field--full" style="border:none;padding:0;margin:0;">
                    <legend class="field-label">驗證方式</legend>
                    <?php foreach ($verifyMethodLabels as $val => $lab): ?>
                        <label class="radio-line">
                            <input type="radio" name="verify_method" value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>"
                                <?= $stored['verify_method'] === $val ? 'checked' : '' ?>
                                <?= $verifyMethodLocked ? 'disabled' : '' ?>>
                            <span><?= htmlspecialchars($lab, ENT_QUOTES, 'UTF-8') ?></span>
                        </label>
                    <?php endforeach; ?>
                    <?php if ($verifyMethodLocked): ?>
                        <input type="hidden" name="verify_method" value="<?= htmlspecialchars($stored['verify_method'], ENT_QUOTES, 'UTF-8') ?>">
                        <p class="sub">已由環境變數 <code>FATE_VERIFY_METHOD</code> 鎖定。</p>
                    <?php endif; ?>
                </fieldset>
            </div>

            <div class="card">
                <h2 class="card-title">會員登入把關</h2>
                <label class="radio-line">
                    <input type="checkbox" name="manual_approval" value="1" <?= $manualApproval ? 'checked' : '' ?> <?= $manualApprovalLocked ? 'disabled' : '' ?>>
                    <span>新會員須管理員人工審核後才能登入
                        <?php if ($manualApprovalLocked): ?>
                            （已由環境變數 <code>FATE_MEMBER_MANUAL_APPROVAL</code> 鎖定）
                        <?php else: ?>
                            （不勾＝註冊後即可登入，改由 Email 驗證把關）
                        <?php endif; ?>
                    </span>
                </label>
            </div>

            <div class="card js-verify-token-panel" data-verify-panel="token">
                <h2 class="card-title">寄信驗證（PHP mail()／Brevo）</h2>
                <p class="sub" style="margin-top:0;">
                    選「寄信驗證」或「兩者並行」時，註冊／重寄會寄出含<strong>驗證連結</strong>與<strong>6 位驗證碼</strong>的信件。
                    管道 <code>auto</code>：有 Brevo 金鑰則走 API，否則用主機 <code>mail()</code>。Brevo 金鑰於「網站與模版」設定。
                </p>
                <p class="sub"><?= htmlspecialchars($transportStatus['detail'], ENT_QUOTES, 'UTF-8') ?></p>

                <fieldset class="field field--full" style="border:none;padding:0;margin:0;">
                    <legend class="field-label">發信管道</legend>
                    <?php
                    $transports = [
                        'auto' => '自動（有 Brevo 金鑰則用 API，否則 PHP mail()）',
                        'brevo' => '強制 Brevo API',
                        'php_mail' => '強制 PHP mail()（主機內建）',
                    ];
                    foreach ($transports as $val => $lab):
                        ?>
                        <label class="radio-line">
                            <input type="radio" name="transport" value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>"
                                <?= $stored['transport'] === $val ? 'checked' : '' ?>
                                <?= $transportLocked ? 'disabled' : '' ?>>
                            <span><?= htmlspecialchars($lab, ENT_QUOTES, 'UTF-8') ?></span>
                        </label>
                    <?php endforeach; ?>
                    <?php if ($transportLocked): ?>
                        <input type="hidden" name="transport" value="<?= htmlspecialchars($stored['transport'], ENT_QUOTES, 'UTF-8') ?>">
                        <p class="sub">已由環境變數 <code>FATE_MAIL_TRANSPORT</code> 鎖定。</p>
                    <?php endif; ?>
                </fieldset>

                <div class="field-grid">
                    <div class="field">
                        <label for="mail_from">寄件人 Email</label>
                        <input type="email" name="mail_from" id="mail_from" maxlength="254" autocomplete="off"
                               value="<?= htmlspecialchars($sender['mail_from'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="noreply@xspa.tw"
                            <?= $fromLocked ? 'readonly' : '' ?>>
                        <?php if ($fromLocked): ?>
                            <p class="sub">已由 <code>FATE_MAIL_FROM</code> 鎖定。</p>
                        <?php endif; ?>
                    </div>
                    <div class="field">
                        <label for="mail_from_name">寄件人名稱</label>
                        <input type="text" name="mail_from_name" id="mail_from_name" maxlength="120"
                               value="<?= htmlspecialchars($sender['mail_from_name'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="XSPA"
                            <?= $fromNameLocked ? 'readonly' : '' ?>>
                        <?php if ($fromNameLocked): ?>
                            <p class="sub">已由 <code>FATE_MAIL_FROM_NAME</code> 鎖定。</p>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($stored['transport'] === 'php_mail' || ($stored['transport'] === 'auto' && fate_api_key('brevo_email') === '')): ?>
                    <div class="verify-check" style="margin-top:0.75rem;">
                        <div class="verify-check__head">PHP mail() 環境</div>
                        <ul class="verify-check__list">
                            <li class="verify-check__item verify-check__item--<?= $mailDiag['mail_disabled_in_ini'] ? 'no' : 'ok' ?>">
                                <span class="verify-check__icon" aria-hidden="true"><?= $mailDiag['mail_disabled_in_ini'] ? '✗' : '✓' ?></span>
                                <span class="verify-check__label">mail() 函式</span>
                                <span class="verify-check__hint"><?= $mailDiag['mail_disabled_in_ini'] ? 'php.ini disable_functions 已停用' : '可用' ?></span>
                            </li>
                            <?php if ($mailDiag['platform'] === 'linux'): ?>
                                <li class="verify-check__item verify-check__item--<?= $mailDiag['sendmail_path'] !== '' ? 'ok' : 'no' ?>">
                                    <span class="verify-check__icon" aria-hidden="true"><?= $mailDiag['sendmail_path'] !== '' ? '✓' : '✗' ?></span>
                                    <span class="verify-check__label">sendmail_path</span>
                                    <span class="verify-check__hint"><?= $mailDiag['sendmail_path'] !== '' ? htmlspecialchars($mailDiag['sendmail_path'], ENT_QUOTES, 'UTF-8') : '未設定' ?></span>
                                </li>
                            <?php endif; ?>
                        </ul>
                        <p class="sub" style="margin:0.5rem 0 0;"><?= htmlspecialchars($mailDiag['hint'], ENT_QUOTES, 'UTF-8') ?></p>
                    </div>
                <?php endif; ?>
            </div>

            <div class="card js-verify-token-panel" data-verify-panel="token">
                <h2 class="card-title">驗證信範本</h2>
                <p class="sub" style="margin-top:0;">
                    可用變數：<code>{<?= implode('}</code>、<code>{', $verifyPlaceholders) ?>}</code>。
                    測試信會套用範例值（連結與驗證碼為示意，無法真正完成驗證）。
                </p>
                <div class="field field--full">
                    <label for="verify_subject">主旨</label>
                    <input type="text" name="verify_subject" id="verify_subject" maxlength="200"
                           value="<?= htmlspecialchars($stored['verify_subject'], ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div class="field field--full">
                    <label for="verify_body_plain">純文字內文</label>
                    <textarea name="verify_body_plain" id="verify_body_plain" rows="8" maxlength="12000"><?= htmlspecialchars($stored['verify_body_plain'], ENT_QUOTES, 'UTF-8') ?></textarea>
                </div>
                <div class="field field--full">
                    <label for="verify_body_html">HTML 內文（選填）</label>
                    <textarea name="verify_body_html" id="verify_body_html" rows="8" maxlength="48000"><?= htmlspecialchars($stored['verify_body_html'], ENT_QUOTES, 'UTF-8') ?></textarea>
                </div>

                <div class="field-actions" style="margin-top:0.5rem;">
                    <button type="button" class="btn btn--secondary" data-preview-verify>更新預覽</button>
                </div>

                <div class="verify-check" style="margin-top:0.75rem;" id="verify-mail-preview">
                    <div class="verify-check__head">預覽（範例變數）</div>
                    <p class="preview-subject" id="preview-subject"><?= htmlspecialchars($verifyPreview['subject'], ENT_QUOTES, 'UTF-8') ?></p>
                    <div class="preview-tabs" role="tablist">
                        <button type="button" class="preview-tab on" data-preview-tab="plain">純文字</button>
                        <button type="button" class="preview-tab" data-preview-tab="html">HTML</button>
                    </div>
                    <pre class="preview-plain" id="preview-plain"><?= htmlspecialchars($verifyPreview['plaintext'], ENT_QUOTES, 'UTF-8') ?></pre>
                    <iframe class="preview-html-frame" id="preview-html-frame" title="HTML 預覽" hidden sandbox=""
                        <?php if ($verifyPreview['html'] !== ''): ?>srcdoc="<?= htmlspecialchars($verifyPreview['html'], ENT_QUOTES, 'UTF-8') ?>"<?php endif; ?>></iframe>
                </div>

                <div class="field field--full" style="margin-top:0.75rem;">
                    <label for="test_email">測試收件信箱</label>
                    <input type="email" name="test_email" id="test_email" maxlength="254" autocomplete="off"
                           placeholder="your@email.com">
                </div>
                <div class="field-actions">
                    <button type="button" class="btn btn--secondary" data-test-send>寄送管道測試信</button>
                    <button type="button" class="btn" data-test-send-verify>寄送驗證信測試</button>
                    <p class="sub" style="margin-top:0.35rem;">會以<strong>已儲存</strong>的設定發信，請先按下方「儲存設定」再測試。</p>
                    <p class="msg" id="test-send-result" style="display:none;"></p>
                    <p class="msg" id="test-send-verify-result" style="display:none;"></p>
                </div>
            </div>

            <div class="card js-verify-reverse-panel" data-verify-panel="reverse">
                <h2 class="card-title">反向 IMAP 回寄驗證</h2>
                <p class="sub" style="margin-top:0;">
                    選「反向 IMAP」或「兩者並行」時，會員從註冊信箱寄信到驗證信箱，系統以 IMAP 收信比對寄件者後完成驗證。
                    <?php if (!$imapExtReady): ?>
                        <br><strong style="color:#b91c1c;">本機尚未啟用 PHP <code>imap</code> 擴充（請安裝 php-imap 並重啟）。</strong>
                    <?php endif; ?>
                    <?php if ($imapHostLocked): ?>
                        <br><strong>主機已由環境變數 <code>FATE_IMAP_HOST</code> 鎖定。</strong>
                    <?php endif; ?>
                </p>

                <div class="verify-check">
                    <div class="verify-check__head">
                        就緒檢查
                        <span class="verify-badge verify-badge--<?= $reverseReady ? 'ok' : 'warn' ?>"><?= $reverseReady ? '✅ 已就緒' : '⚠ 尚缺設定' ?></span>
                    </div>
                    <ul class="verify-check__list">
                        <?php foreach ($reverseChecks as $item): ?>
                            <li class="verify-check__item verify-check__item--<?= $item['ok'] ? 'ok' : 'no' ?>">
                                <span class="verify-check__icon" aria-hidden="true"><?= $item['ok'] ? '✓' : '✗' ?></span>
                                <span class="verify-check__label"><?= htmlspecialchars($item['label'], ENT_QUOTES, 'UTF-8') ?></span>
                                <span class="verify-check__hint"><?= htmlspecialchars($item['hint'], ENT_QUOTES, 'UTF-8') ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <div class="field-grid">
                    <div class="field">
                        <label for="imap_host">IMAP 主機</label>
                        <input type="text" name="imap_host" id="imap_host" maxlength="255"
                               value="<?= htmlspecialchars($stored['imap_host'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="mail.example.com"
                            <?= $imapHostLocked ? 'readonly' : '' ?>>
                    </div>
                    <div class="field">
                        <label for="imap_port">連接埠</label>
                        <input type="number" name="imap_port" id="imap_port" min="1" max="65535"
                               value="<?= htmlspecialchars($stored['imap_port'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="993">
                    </div>
                    <div class="field">
                        <label for="imap_secure">加密方式</label>
                        <select name="imap_secure" id="imap_secure">
                            <?php
                            $imapSecureOpts = [
                                'ssl' => 'SSL／TLS（連接埠常為 993）',
                                'tls' => 'STARTTLS（連接埠常為 143）',
                                'none' => '不加密（僅本機 localhost）',
                            ];
                            foreach ($imapSecureOpts as $val => $lab):
                                ?>
                                <option value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>"
                                    <?= $stored['imap_secure'] === $val ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($lab, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="field-grid">
                    <div class="field">
                        <label for="imap_address">驗證信箱地址</label>
                        <input type="email" name="imap_address" id="imap_address" maxlength="254" autocomplete="off"
                               value="<?= htmlspecialchars($stored['imap_address'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="verify@xspa.tw">
                    </div>
                    <div class="field">
                        <label for="imap_folder">收信資料夾</label>
                        <input type="text" name="imap_folder" id="imap_folder" maxlength="128"
                               value="<?= htmlspecialchars($stored['imap_folder'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="INBOX">
                    </div>
                    <div class="field">
                        <label for="imap_user">IMAP 帳號（留空＝驗證信箱地址）</label>
                        <input type="text" name="imap_user" id="imap_user" maxlength="254" autocomplete="off"
                               value="<?= htmlspecialchars($stored['imap_user'], ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="verify@xspa.tw">
                    </div>
                </div>
                <div class="field field--full">
                    <label for="imap_password">IMAP 密碼</label>
                    <?php if ($imapPassSt['state'] === 'env'): ?>
                        <input type="text" id="imap_password_env" value="<?= htmlspecialchars($imapPassSt['label'], ENT_QUOTES, 'UTF-8') ?>" readonly>
                    <?php else: ?>
                        <input type="password" name="imap_password" id="imap_password" maxlength="255" autocomplete="new-password"
                               placeholder="<?= $imapPassSt['state'] === 'file' ? '已儲存（' . htmlspecialchars($imapPassSt['masked'], ENT_QUOTES, 'UTF-8') . '）— 留空不變更' : '輸入驗證信箱的 IMAP 密碼' ?>">
                        <?php if ($imapPassSt['state'] === 'file'): ?>
                            <label class="radio-line" style="margin-top:0.35rem;">
                                <input type="checkbox" name="imap_password_clear" value="1">
                                <span>清除已儲存的 IMAP 密碼</span>
                            </label>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <label class="radio-line" style="margin-top:0.5rem;">
                    <input type="checkbox" name="imap_require_spf" value="1" <?= $stored['imap_require_spf'] === '1' ? 'checked' : '' ?>>
                    <span>額外要求通過 SPF（拒絕標頭 spf=fail／softfail 的來信）</span>
                </label>
                <div class="field-actions" style="margin-top:0.75rem;">
                    <button type="button" class="btn" data-test-imap>測試 IMAP 連線</button>
                    <p class="sub" style="margin-top:0.35rem;">會以<strong>已儲存</strong>的設定測試，請先按下方「儲存設定」再測試。</p>
                    <p class="msg" id="test-imap-result" style="display:none;"></p>
                </div>
            </div>

            <div class="btn-row">
                <button type="submit">儲存設定</button>
            </div>
        </form>

        <div class="page-actions"><a class="btn" href="index.php">返回概覽</a></div>
        <script src="<?= htmlspecialchars(fate_admin_asset_url('static/email_settings.js'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($jsVer, ENT_QUOTES, 'UTF-8') ?>"></script>
<?php
fate_admin_layout_end();









