<?php

declare(strict_types=1);

/**
 * 會員頁 — 個人資料分頁。
 *
 * @var string $csrf
 * @var array{id:int,username:string,display_name:string,avatar_rel:string} $member
 * @var array{enabled:bool,email:string,masked:string,verified:bool,verified_at:?string} $emailStatus
 * @var bool $needsVerify
 * @var bool $verifyUsesToken
 * @var bool $verifyUsesReverse
 */

?>
<div class="member-profile-tab-panel__inner">
    <form method="post" action="member_profile.php?tab=profile" enctype="multipart/form-data" class="member-profile-form">
        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="action" value="save_profile">
        <label class="member-profile-label" for="display_name">顯示名稱</label>
        <input type="text" name="display_name" id="display_name" class="member-profile-input" maxlength="<?= (int) fate_member_display_name_max_chars() ?>"
               value="<?= htmlspecialchars($member['display_name'], ENT_QUOTES, 'UTF-8') ?>" autocomplete="nickname">
        <p class="sub member-profile-hint">最多 <?= (int) fate_member_display_name_max_chars() ?> 個字（中文、英文、數字各算 1 字）。留空則以帳號顯示。</p>
        <label class="member-profile-label" for="avatar">頭像（JPEG／PNG／WebP／GIF，最大 3MB）</label>
        <div class="member-profile-avatar-pick">
            <input type="file" name="avatar" id="avatar" class="member-profile-input member-profile-input--file" accept="image/jpeg,image/png,image/webp,image/gif">
            <img id="avatar-crop-preview" class="member-profile-avatar-preview" hidden alt="剪裁預覽" width="64" height="64">
        </div>
        <input type="hidden" name="avatar_crop" id="avatar_crop" value="">
        <div id="avatar-crop-panel" class="member-profile-crop-panel" hidden>
            <p class="member-profile-crop-hint">拖曳調整位置，滑桿縮放；滿意後按「套用剪裁」，再按下方「儲存」上傳。</p>
            <div class="member-profile-crop-canvas-wrap">
                <canvas id="avatar-crop-canvas" width="280" height="280" aria-label="頭像剪裁區"></canvas>
            </div>
            <label class="member-profile-crop-zoom" for="avatar-crop-zoom">縮放
                <input type="range" id="avatar-crop-zoom" min="1" max="3" step="0.02" value="1">
            </label>
            <div class="member-profile-crop-actions">
                <button type="button" class="member-profile-btn" id="avatar-crop-apply">套用剪裁</button>
                <button type="button" class="member-profile-btn member-profile-btn--ghost" id="avatar-crop-cancel">取消</button>
            </div>
        </div>
        <div class="member-profile-form-actions">
            <button type="submit" class="member-profile-btn member-profile-btn--primary">儲存</button>
        </div>
    </form>

    <?php if ($emailStatus['enabled']): ?>
        <div class="member-profile-tab-divider" aria-hidden="true"></div>
        <h3 class="member-profile-tab-subtitle" id="member-email-title">Email</h3>
        <div class="member-profile-email-block<?= $needsVerify ? ' member-profile-email-block--warn' : '' ?>">
            <?php if ($emailStatus['verified']): ?>
                <p class="member-profile-email">
                    <code class="inline"><?= htmlspecialchars($emailStatus['email'] !== '' ? $emailStatus['email'] : '—', ENT_QUOTES, 'UTF-8') ?></code>
                    <span class="member-profile-meta-inline">已驗證</span>
                    <?php if ($emailStatus['verified_at'] !== null): ?>
                        <span class="member-profile-meta-block"><?= htmlspecialchars($emailStatus['verified_at'], ENT_QUOTES, 'UTF-8') ?></span>
                    <?php endif; ?>
                </p>
                <p class="sub member-profile-hint">驗證完成後無法自行修改；若填錯請聯絡管理員。</p>
            <?php else:
                if (!isset($verifyUsesToken, $verifyUsesReverse)) {
                    if (!function_exists('fate_verify_method_uses_token')) {
                        require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_mail_settings.php';
                    }
                    if (!function_exists('fate_reverse_imap_ready')) {
                        require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_email_reverse.php';
                    }
                    $verifyUsesToken = fate_verify_method_uses_token();
                    $verifyUsesReverse = fate_verify_method_uses_reverse();
                    if (!$verifyUsesToken && !$verifyUsesReverse) {
                        $verifyUsesToken = true;
                    }
                }
                $reverseReady = $verifyUsesReverse && fate_reverse_imap_ready();
                ?>
                <p class="sub member-profile-hint">目前：<strong><?= $emailStatus['masked'] !== '' ? htmlspecialchars($emailStatus['masked'], ENT_QUOTES, 'UTF-8') : '（未填）' ?></strong></p>
                <form method="post" action="member_profile.php?tab=profile" class="member-profile-form member-profile-form--spaced">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="change_email">
                    <label class="member-profile-label" for="new_email">更正 Email</label>
                    <input type="email" name="new_email" id="new_email" class="member-profile-input" required maxlength="254" autocomplete="email"
                           value="<?= htmlspecialchars($emailStatus['email'], ENT_QUOTES, 'UTF-8') ?>">
                    <p class="sub member-profile-hint"><?= $verifyUsesToken ? '更新後會重寄驗證信。' : '更新後請依下方指示完成驗證。' ?></p>
                    <div class="member-profile-form-actions">
                        <button type="submit" class="member-profile-btn">更新 Email</button>
                    </div>
                </form>

                <?php if ($verifyUsesToken): ?>
                    <div class="member-profile-tab-divider" aria-hidden="true"></div>
                    <h3 class="member-profile-tab-subtitle">驗證信／驗證碼</h3>
                    <p class="sub member-profile-hint">請至信箱查收驗證信，點信內連結或於下方輸入 6 位驗證碼（擇一）。</p>
                    <form method="post" action="member_profile.php?tab=profile" class="member-profile-form member-profile-form--spaced">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="action" value="verify_code">
                        <label class="member-profile-label" for="verify_code">6 位驗證碼</label>
                        <input type="text" name="verify_code" id="verify_code" class="member-profile-input" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" autocomplete="one-time-code" required>
                        <div class="member-profile-form-actions">
                            <button type="submit" class="member-profile-btn member-profile-btn--primary">送出驗證碼</button>
                        </div>
                    </form>
                    <form method="post" action="member_profile.php?tab=profile" class="member-profile-form member-profile-form--spaced">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="action" value="resend_verify">
                        <div class="member-profile-form-actions">
                            <button type="submit" class="member-profile-btn">重寄驗證信</button>
                        </div>
                    </form>
                <?php endif; ?>

                <?php if ($verifyUsesReverse):
                    if ($reverseReady):
                    $reverseAddr = fate_reverse_imap_verify_address();
                    $reverseMemberEmail = $emailStatus['email'] !== '' ? $emailStatus['email'] : '';
                    $reverseSubject = 'Email 驗證';
                    $reverseBody = '您好，我要完成 Email 驗證，謝謝。';
                    $reverseMailto = 'mailto:' . $reverseAddr
                        . '?subject=' . rawurlencode($reverseSubject)
                        . '&body=' . rawurlencode($reverseBody);
                    ?>
                    <div class="member-profile-tab-divider" aria-hidden="true"></div>
                    <h3 class="member-profile-tab-subtitle">回寄驗證</h3>
                    <p class="sub member-profile-hint">
                        請從您的註冊信箱<?php if ($reverseMemberEmail !== ''): ?>
                        <code class="inline"><?= htmlspecialchars($reverseMemberEmail, ENT_QUOTES, 'UTF-8') ?></code><?php endif; ?>
                        寄一封信到下方<strong>驗證信箱</strong>（主旨與內容可直接複製，內容不限），寄出後約數秒按「我已寄出，立即驗證」。
                    </p>
                    <div class="member-profile-reverse-copy">
                        <div class="member-profile-copy-row">
                            <span class="member-profile-copy-key">驗證信箱</span>
                            <code class="member-profile-copy-val" data-copy="<?= htmlspecialchars($reverseAddr, ENT_QUOTES, 'UTF-8') ?>" title="點一下複製"><?= htmlspecialchars($reverseAddr, ENT_QUOTES, 'UTF-8') ?></code>
                            <button type="button" class="member-profile-btn member-profile-btn--ghost" data-copy="<?= htmlspecialchars($reverseAddr, ENT_QUOTES, 'UTF-8') ?>">複製</button>
                        </div>
                        <div class="member-profile-copy-row">
                            <span class="member-profile-copy-key">主旨</span>
                            <code class="member-profile-copy-val" data-copy="<?= htmlspecialchars($reverseSubject, ENT_QUOTES, 'UTF-8') ?>" title="點一下複製"><?= htmlspecialchars($reverseSubject, ENT_QUOTES, 'UTF-8') ?></code>
                            <button type="button" class="member-profile-btn member-profile-btn--ghost" data-copy="<?= htmlspecialchars($reverseSubject, ENT_QUOTES, 'UTF-8') ?>">複製</button>
                        </div>
                        <div class="member-profile-copy-row">
                            <span class="member-profile-copy-key">內容</span>
                            <code class="member-profile-copy-val" data-copy="<?= htmlspecialchars($reverseBody, ENT_QUOTES, 'UTF-8') ?>" title="點一下複製"><?= htmlspecialchars($reverseBody, ENT_QUOTES, 'UTF-8') ?></code>
                            <button type="button" class="member-profile-btn member-profile-btn--ghost" data-copy="<?= htmlspecialchars($reverseBody, ENT_QUOTES, 'UTF-8') ?>">複製</button>
                        </div>
                    </div>
                    <p class="sub member-profile-hint member-profile-copy-toast" data-copy-toast aria-live="polite" hidden>已複製到剪貼簿</p>
                    <div class="member-profile-form-actions">
                        <a class="member-profile-btn member-profile-btn--primary" href="<?= htmlspecialchars($reverseMailto, ENT_QUOTES, 'UTF-8') ?>">一鍵開啟郵件（自動填好收件者／主旨／內容）</a>
                        <button type="button" class="member-profile-btn" data-reverse-verify>我已寄出，立即驗證</button>
                    </div>
                    <p class="sub member-profile-hint">
                        手機：點上方按鈕會開啟郵件 App 並自動填好，按「寄出」後再回來按「我已寄出，立即驗證」即可。
                        若手機有多個郵件帳號，請確認<strong>寄件者是您的註冊信箱</strong>。
                        按鈕若沒反應（未設定郵件 App），請改用上方「複製」手動貼上寄出。
                    </p>
                    <p class="sub member-profile-hint" data-reverse-msg aria-live="polite" hidden></p>
                    <style>
                    .member-profile-reverse-copy { display:flex; flex-direction:column; gap:.45rem; margin:.5rem 0; }
                    .member-profile-copy-row { display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; }
                    .member-profile-copy-key { min-width:4.5em; font-size:.82rem; opacity:.75; }
                    .member-profile-copy-val { flex:1 1 12rem; padding:.35rem .55rem; border-radius:8px; background:rgba(128,128,128,.12); cursor:pointer; word-break:break-all; }
                    .member-profile-copy-toast { color:#16a34a; }
                    </style>
                    <script>
                    (function () {
                        var toast = document.querySelector('[data-copy-toast]');
                        var toastTimer = null;
                        function showToast(t) {
                            if (!toast) { return; }
                            toast.textContent = t || '已複製到剪貼簿';
                            toast.hidden = false;
                            clearTimeout(toastTimer);
                            toastTimer = setTimeout(function () { toast.hidden = true; }, 1800);
                        }
                        function copyText(text) {
                            if (navigator.clipboard && navigator.clipboard.writeText) {
                                navigator.clipboard.writeText(text).then(function () { showToast(); }).catch(fallback);
                            } else {
                                fallback();
                            }
                            function fallback() {
                                try {
                                    var ta = document.createElement('textarea');
                                    ta.value = text;
                                    ta.style.position = 'fixed';
                                    ta.style.opacity = '0';
                                    document.body.appendChild(ta);
                                    ta.select();
                                    document.execCommand('copy');
                                    document.body.removeChild(ta);
                                    showToast();
                                } catch (e) {
                                    showToast('複製失敗，請手動選取');
                                }
                            }
                        }
                        document.querySelectorAll('[data-copy]').forEach(function (el) {
                            el.addEventListener('click', function () {
                                copyText(el.getAttribute('data-copy') || '');
                            });
                        });

                        var btn = document.querySelector('[data-reverse-verify]');
                        var msg = document.querySelector('[data-reverse-msg]');
                        if (!btn || !msg) { return; }
                        btn.addEventListener('click', function () {
                            btn.disabled = true;
                            msg.hidden = false;
                            msg.textContent = '檢查中…';
                            fetch('verify_inbox.php', { method: 'POST', credentials: 'same-origin' })
                                .then(function (r) { return r.json(); })
                                .then(function (j) {
                                    if (j && j.verified) {
                                        msg.textContent = j.message || '驗證成功';
                                        window.location.href = (j.redirect || './member_profile.php');
                                    } else {
                                        msg.textContent = (j && j.error) ? j.error : '尚未收到來信，請稍後再試。';
                                        btn.disabled = false;
                                    }
                                })
                                .catch(function () {
                                    msg.textContent = '網路或伺服器錯誤，請稍後再試。';
                                    btn.disabled = false;
                                });
                        });
                    })();
                    </script>
                    <?php else: ?>
                    <div class="member-profile-msg member-profile-msg--warn" style="margin-top:.75rem;">
                        反向 Email 驗證尚未就緒（IMAP 設定未完成），請稍後再試或聯絡站方。
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>
