<?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_admin_members.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_tier.php';

fate_admin_require_login();

$actingAdminId = (int) ($_SESSION['fate_admin_member_id'] ?? 0);

$pdo = null;
$dbErr = null;
try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable $e) {
    $dbErr = $e->getMessage();
}

$tableMissing = false;
$queryErr = null;
$overview = null;
$list = ['rows' => [], 'total' => 0, 'page' => 1, 'per_page' => 40, 'pages' => 1];
$flashOk = null;
$flashErr = null;

$roleFilter = isset($_GET['role']) ? strtolower(trim((string) $_GET['role'])) : '';
if (!in_array($roleFilter, ['', 'admin', 'mod', 'member'], true)) {
    $roleFilter = '';
}

$statusFilter = isset($_GET['status']) ? strtolower(trim((string) $_GET['status'])) : '';
if (!in_array($statusFilter, ['', 'active', 'inactive'], true)) {
    $statusFilter = '';
}

$reviewFilter = isset($_GET['review']) ? strtolower(trim((string) $_GET['review'])) : '';
if (!in_array($reviewFilter, ['', 'pending', 'approved'], true)) {
    $reviewFilter = '';
}

$verifyFilter = isset($_GET['verify']) ? strtolower(trim((string) $_GET['verify'])) : '';
if (!in_array($verifyFilter, ['', 'email_pending', 'email_verified'], true)) {
    $verifyFilter = '';
}

$tierFilter = isset($_GET['tier']) ? strtolower(trim((string) $_GET['tier'])) : '';
if (!in_array($tierFilter, ['', 'formal', 'register', 'blacklist'], true)) {
    $tierFilter = '';
}

$q = isset($_GET['q']) ? trim((string) $_GET['q']) : '';
if (strlen($q) > 80) {
    $q = substr($q, 0, 80);
}

$page = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$editId = isset($_GET['edit']) ? max(0, (int) $_GET['edit']) : 0;

$buildListUrl = static function (int $p, ?int $edit = null, ?array $filterOverrides = null) use ($roleFilter, $statusFilter, $reviewFilter, $verifyFilter, $tierFilter, $q): string {
    $rf = $roleFilter;
    $sf = $statusFilter;
    $rv = $reviewFilter;
    $vf = $verifyFilter;
    $tf = $tierFilter;
    $qq = $q;
    if (is_array($filterOverrides)) {
        if (array_key_exists('role', $filterOverrides)) {
            $rf = (string) $filterOverrides['role'];
        }
        if (array_key_exists('status', $filterOverrides)) {
            $sf = (string) $filterOverrides['status'];
        }
        if (array_key_exists('review', $filterOverrides)) {
            $rv = (string) $filterOverrides['review'];
        }
        if (array_key_exists('verify', $filterOverrides)) {
            $vf = (string) $filterOverrides['verify'];
        }
        if (array_key_exists('tier', $filterOverrides)) {
            $tf = (string) $filterOverrides['tier'];
        }
        if (array_key_exists('q', $filterOverrides)) {
            $qq = (string) $filterOverrides['q'];
        }
    }

    $qs = ['page' => (string) $p];
    if ($rf !== '') {
        $qs['role'] = $rf;
    }
    if ($sf !== '') {
        $qs['status'] = $sf;
    }
    if ($rv !== '') {
        $qs['review'] = $rv;
    }
    if ($vf !== '') {
        $qs['verify'] = $vf;
    }
    if ($tf !== '') {
        $qs['tier'] = $tf;
    }
    if ($qq !== '') {
        $qs['q'] = $qq;
    }
    if ($edit !== null && $edit > 0) {
        $qs['edit'] = (string) $edit;
    }

    return 'members.php?' . http_build_query($qs);
};

$redirectAfterPost = static function (int $editMemberId, ?string $flash = null, ?string $err = null) use ($buildListUrl, $page): void {
    $qs = [];
    if ($flash === 'saved') {
        $qs['saved'] = '1';
    }
    if ($err !== null && $err !== '') {
        $qs['err'] = $err;
    }
    if ($editMemberId > 0) {
        $qs['edit'] = (string) $editMemberId;
    }
    $base = $buildListUrl($page, null);
    $join = str_contains($base, '?') ? '&' : '?';
    $extra = $qs !== [] ? $join . http_build_query($qs) : '';

    header('Location: ' . $base . $extra, true, 303);
    exit;
};

if ($pdo instanceof PDO && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $flashErr = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } elseif (!fate_admin_members_table_exists($pdo)) {
        $flashErr = '會員表不存在';
    } else {
        $memberId = isset($_POST['member_id']) ? (int) $_POST['member_id'] : 0;
        $action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : '';

        if ($action === 'create') {
            $createRes = fate_admin_members_create($pdo, fate_admin_members_create_input_from_request($_POST), $actingAdminId);
            if ($createRes['ok'] && (int) ($createRes['id'] ?? 0) > 0) {
                $newId = (int) $createRes['id'];
                header('Location: members.php?page=1&edit=' . $newId . '&created=1', true, 303);
                exit;
            }
            $flashErr = $createRes['err'] ?? '新增失敗';
        } elseif ($memberId <= 0) {
            $flashErr = '無效的會員 ID';
        } elseif ($action === 'toggle_active') {
            $res = fate_admin_members_toggle_active($pdo, $memberId, $actingAdminId);
            if ($res['ok']) {
                $redirectAfterPost($memberId, 'saved');
            } else {
                $redirectAfterPost($memberId, null, $res['err'] ?? '更新失敗');
            }
        } elseif ($action === 'approve') {
            $res = fate_admin_members_approve($pdo, $memberId, $actingAdminId);
            if ($res['ok']) {
                $redirectAfterPost($memberId, 'saved');
            } else {
                $redirectAfterPost($memberId, null, $res['err'] ?? '審核失敗');
            }
        } elseif ($action === 'verify_email') {
            $res = fate_admin_members_update($pdo, $memberId, ['email_verified' => true], $actingAdminId);
            if ($res['ok']) {
                $redirectAfterPost($memberId, 'saved');
            } else {
                $redirectAfterPost($memberId, null, $res['err'] ?? '更新失敗');
            }
        } elseif ($action === 'clear_email_verify') {
            $res = fate_admin_members_update($pdo, $memberId, ['email_verified' => false], $actingAdminId);
            if ($res['ok']) {
                $redirectAfterPost($memberId, 'saved');
            } else {
                $redirectAfterPost($memberId, null, $res['err'] ?? '更新失敗');
            }
        } elseif ($action === 'save') {
            $roleIn = isset($_POST['role']) && is_string($_POST['role']) ? $_POST['role'] : 'member';
            $statusIn = isset($_POST['status']) && is_string($_POST['status']) ? $_POST['status'] : '1';
            $displayName = isset($_POST['display_name']) && is_string($_POST['display_name']) ? $_POST['display_name'] : '';
            $res = fate_admin_members_update($pdo, $memberId, [
                'display_name' => $displayName,
                'role' => $roleIn,
                'member_tier' => isset($_POST['member_tier']) && is_string($_POST['member_tier']) ? $_POST['member_tier'] : 'register',
                'active' => $statusIn === '1',
            ], $actingAdminId);
            if ($res['ok']) {
                $redirectAfterPost($memberId, 'saved');
            } else {
                $redirectAfterPost($memberId, null, $res['err'] ?? '儲存失敗');
            }
        } else {
            $flashErr = '未知的操作';
        }
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1') {
    $flashOk = '已儲存變更。';
}
if (isset($_GET['created']) && $_GET['created'] === '1' && $flashOk === null) {
    $flashOk = '已新增會員。';
}
if (isset($_GET['err']) && is_string($_GET['err']) && $_GET['err'] !== '') {
    $flashErr = (string) $_GET['err'];
}

/** @var array<string,mixed>|null */
$editMember = null;

if ($pdo instanceof PDO) {
    if (!fate_admin_members_table_exists($pdo)) {
        $tableMissing = true;
    } else {
        try {
            $overview = fate_admin_members_overview($pdo);
            $list = fate_admin_members_list($pdo, [
                'role' => $roleFilter,
                'status' => $statusFilter,
                'review' => $reviewFilter,
                'verify' => $verifyFilter,
                'tier' => $tierFilter,
                'q' => $q,
                'page' => $page,
            ]);
            if ($editId > 0) {
                $editMember = fate_admin_members_fetch_by_id($pdo, $editId);
            }
        } catch (Throwable $e) {
            $queryErr = $e->getMessage();
        }
    }
}

$memberTableLabel = fate_admin_member_auth_ready()
    ? FATE_MEMBER_DATABASE . '.' . FATE_MEMBER_TABLE
    : '（未設定）';

$csrf = fate_admin_csrf_token();
$hasEmailVerified = is_array($overview) && !empty($overview['features']['email_verified']);
$hasMemberTier = is_array($overview) && !empty($overview['features']['member_tier']);
$hasManualReview = is_array($overview) && !empty($overview['features']['manual_review']);
$reviewPendingCount = $hasManualReview ? (int) ($overview['review_pending'] ?? 0) : 0;
$emailPendingCount = $hasEmailVerified ? (int) ($overview['email_pending'] ?? 0) : 0;
$hasActiveFilters = $q !== '' || $roleFilter !== '' || $statusFilter !== '' || $reviewFilter !== '' || $verifyFilter !== '' || $tierFilter !== '';

fate_admin_layout_start(['page' => '會員管理', 'active' => 'members']);
?>
        <header class="page-head page-head--compact">
            <h1 class="page-title">會員管理</h1>
            <p class="sub">
                <code><?= htmlspecialchars($memberTableLabel, ENT_QUOTES, 'UTF-8') ?></code> · 啟用欄位 <code><?= htmlspecialchars(FATE_MEMBER_ACTIVE_COLUMN, ENT_QUOTES, 'UTF-8') ?></code>
            </p>
        </header>

        <div id="member-ajax-flash" class="msg" hidden aria-live="polite"></div>
        <?php if ($flashOk !== null): ?>
            <div class="msg ok"><?= htmlspecialchars($flashOk, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>
        <?php if ($flashErr !== null): ?>
            <div class="msg bad"><?= htmlspecialchars($flashErr, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <?php if ($dbErr !== null || !$pdo instanceof PDO): ?>
            <div class="msg bad">無法連線資料庫<?= $dbErr !== null ? '：<code>' . htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') . '</code>' : '' ?>。</div>
        <?php elseif ($tableMissing): ?>
            <div class="msg warn">
                找不到會員資料表。請先執行 <code>fate/sql/install.sql</code>。
            </div>
        <?php elseif ($queryErr !== null): ?>
            <div class="msg bad">讀取會員資料失敗：<code><?= htmlspecialchars($queryErr, ENT_QUOTES, 'UTF-8') ?></code></div>
        <?php else: ?>

            <?php if (is_array($overview)):
                $summarySegs = fate_admin_members_summary_segments($overview);
            ?>
                <p class="member-summary">
                    <?php foreach ($summarySegs as $i => $seg): ?>
                        <?php if ($i > 0): ?><span class="member-summary__sep" aria-hidden="true"> · </span><?php endif; ?>
                        <span><?= htmlspecialchars($seg, ENT_QUOTES, 'UTF-8') ?></span>
                    <?php endforeach; ?>
                </p>
            <?php endif; ?>

            <?php if ($hasManualReview || $hasEmailVerified): ?>
                <nav class="member-quick-filters" aria-label="快速篩選">
                    <?php if ($hasManualReview): ?>
                        <a class="member-quick-filters__chip<?= $reviewFilter === 'pending' ? ' is-active' : '' ?>"
                           href="<?= htmlspecialchars($buildListUrl(1, null, ['review' => 'pending', 'verify' => '', 'status' => '']), ENT_QUOTES, 'UTF-8') ?>">
                            待審核<?php if ($reviewPendingCount > 0): ?> <span class="member-quick-filters__count"><?= htmlspecialchars(number_format($reviewPendingCount), ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?>
                        </a>
                    <?php endif; ?>
                    <?php if ($hasEmailVerified): ?>
                        <a class="member-quick-filters__chip<?= $verifyFilter === 'email_pending' ? ' is-active' : '' ?>"
                           href="<?= htmlspecialchars($buildListUrl(1, null, ['verify' => 'email_pending', 'review' => '']), ENT_QUOTES, 'UTF-8') ?>">
                            待驗證信箱<?php if ($emailPendingCount > 0): ?> <span class="member-quick-filters__count"><?= htmlspecialchars(number_format($emailPendingCount), ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?>
                        </a>
                    <?php endif; ?>
                    <?php if ($hasMemberTier): ?>
                        <a class="member-quick-filters__chip<?= $tierFilter === 'formal' ? ' is-active' : '' ?>"
                           href="<?= htmlspecialchars($buildListUrl(1, null, ['tier' => 'formal', 'review' => '', 'verify' => '']), ENT_QUOTES, 'UTF-8') ?>">
                            正式會員
                        </a>
                    <?php endif; ?>
                    <a class="member-quick-filters__chip<?= !$hasActiveFilters ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildListUrl(1, null, ['role' => '', 'status' => '', 'review' => '', 'verify' => '', 'tier' => '', 'q' => '']), ENT_QUOTES, 'UTF-8') ?>">
                        全部會員
                    </a>
                </nav>
            <?php endif; ?>

            <details class="member-create card" id="member-create-panel">
                <summary class="member-create__summary">手動新增會員</summary>
                <p class="sub member-create__hint">建立後預設已通過審核並啟用（可取消勾選）；密碼至少 8 字元。Email 選填，勾選「標記信箱已驗證」須填寫 Email。</p>
                <form method="post" action="members.php" class="member-create__form member-ajax-form" id="member-create-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="create">
                    <div class="member-create__grid">
                        <div>
                            <label for="create_username">帳號 <span class="member-create__req">*</span></label>
                            <input type="text" name="username" id="create_username" required maxlength="80" autocomplete="off"
                                   placeholder="至少 3 字，可含中文">
                        </div>
                        <div>
                            <label for="create_password">密碼 <span class="member-create__req">*</span></label>
                            <input type="password" name="password" id="create_password" required minlength="8" maxlength="72" autocomplete="new-password">
                        </div>
                        <div>
                            <label for="create_display_name">顯示名稱</label>
                            <input type="text" name="display_name" id="create_display_name" maxlength="120" placeholder="留空則同帳號">
                        </div>
                        <?php if (is_array($overview) && !empty($overview['features']['email'])): ?>
                        <div>
                            <label for="create_email">Email</label>
                            <input type="email" name="email" id="create_email" maxlength="254" autocomplete="off" placeholder="選填">
                        </div>
                        <?php endif; ?>
                        <div>
                            <label for="create_role">層級 (role)</label>
                            <select name="role" id="create_role">
                                <option value="member" selected>一般會員</option>
                                <option value="mod">版主 (mod)</option>
                                <option value="admin">管理員 (admin)</option>
                            </select>
                        </div>
                        <?php if ($hasMemberTier): ?>
                        <div>
                            <label for="create_member_tier">會員分級</label>
                            <select name="member_tier" id="create_member_tier">
                                <option value="register" selected>註冊會員</option>
                                <option value="formal">正式會員</option>
                                <option value="blacklist">黑名單</option>
                            </select>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="member-create__checks">
                        <label class="member-create__check">
                            <input type="hidden" name="status" value="0">
                            <input type="checkbox" name="status" value="1" checked>
                            帳號啟用（可登入）
                        </label>
                        <?php if ($hasManualReview): ?>
                        <label class="member-create__check">
                            <input type="hidden" name="approve" value="0">
                            <input type="checkbox" name="approve" value="1" checked>
                            視為已通過審核
                        </label>
                        <?php endif; ?>
                        <?php if ($hasEmailVerified): ?>
                        <label class="member-create__check">
                            <input type="checkbox" name="email_verified" value="1">
                            標記信箱已驗證
                        </label>
                        <?php endif; ?>
                    </div>
                    <div class="member-create__actions">
                        <button type="submit" class="btn btn--primary">新增會員</button>
                    </div>
                </form>
            </details>

            <?php if (is_array($editMember)): ?>
                <?php
                $eid = (int) ($editMember['id'] ?? 0);
                $eActive = (int) ($editMember['_mem_active'] ?? 0) === 1;
                $eRole = fate_admin_members_role_input_value(isset($editMember['role']) ? (string) $editMember['role'] : '');
                $eEmail = isset($editMember['email']) ? trim((string) $editMember['email']) : '';
                $eVerified = isset($editMember['email_verified_at']) && trim((string) $editMember['email_verified_at']) !== '';
                $eTier = fate_member_tier_from_row($editMember);
                $ePendingReview = $hasManualReview && fate_admin_members_is_pending_review($editMember);
                $eReviewLabel = fate_admin_members_review_status_label($editMember);
                $isSelf = $actingAdminId > 0 && $actingAdminId === $eid;
                ?>
                <section id="member-edit-panel" class="member-edit card" aria-labelledby="member-edit-title"
                         data-member-id="<?= $eid ?>">
                    <h2 id="member-edit-title" class="section-title section-title--list">詳細編輯 · 會員 #<?= $eid ?></h2>
                    <p class="sub member-edit__meta">
                        帳號 <code><?= htmlspecialchars((string) ($editMember['username'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code>
                        <?php if ($isSelf): ?><span class="badge badge--admin">目前登入帳號</span><?php endif; ?>
                        <span data-edit-review-badge class="<?= htmlspecialchars(fate_admin_members_review_badge_class($editMember), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($eReviewLabel, ENT_QUOTES, 'UTF-8') ?></span>
                        · <a href="<?= htmlspecialchars($buildListUrl($page), ENT_QUOTES, 'UTF-8') ?>">關閉</a>
                    </p>
                    <p class="sub member-edit__hint">顯示名稱、層級與分級可直接在下方列表修改；此處用於信箱驗證、審核與進階設定。</p>
                    <?php if ($hasManualReview): ?>
                        <form method="post" action="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>"
                              class="member-edit__approve member-ajax-form" data-edit-approve-form<?= !$ePendingReview ? ' hidden' : '' ?>>
                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="action" value="approve">
                            <input type="hidden" name="member_id" value="<?= $eid ?>">
                            <input type="hidden" name="edit_url" value="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>">
                            <button type="submit" class="btn btn--approve">通過審核並啟用</button>
                        </form>
                    <?php endif; ?>
                    <form method="post" action="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>" class="member-edit__form member-ajax-form">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="action" value="save">
                        <input type="hidden" name="member_id" value="<?= $eid ?>">
                        <input type="hidden" name="edit_url" value="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>">
                        <div class="member-edit__grid">
                            <div>
                                <label for="display_name">顯示名稱</label>
                                <input type="text" name="display_name" id="display_name" maxlength="120"
                                       value="<?= htmlspecialchars((string) ($editMember['display_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                            </div>
                            <div>
                                <label for="role">層級 (role)</label>
                                <select name="role" id="role">
                                    <option value="member"<?= $eRole === 'member' ? ' selected' : '' ?>>一般會員</option>
                                    <option value="mod"<?= $eRole === 'mod' ? ' selected' : '' ?>>版主 (mod)</option>
                                    <option value="admin"<?= $eRole === 'admin' ? ' selected' : '' ?>>管理員 (admin)</option>
                                </select>
                            </div>
                            <?php if ($hasMemberTier): ?>
                            <div>
                                <label for="member_tier">會員分級</label>
                                <select name="member_tier" id="member_tier">
                                    <option value="register"<?= $eTier === 'register' ? ' selected' : '' ?>>註冊會員</option>
                                    <option value="formal"<?= $eTier === 'formal' ? ' selected' : '' ?>>正式會員</option>
                                    <option value="blacklist"<?= $eTier === 'blacklist' ? ' selected' : '' ?>>黑名單</option>
                                </select>
                                <p class="sub" style="margin:0.25rem 0 0;">完成信箱驗證僅會將「註冊會員」升為正式會員；黑名單須由管理員手動解除。停權與黑名單不同。</p>
                            </div>
                            <?php endif; ?>
                            <div>
                                <label for="status">帳號啟用</label>
                                <select name="status" id="status"<?= $isSelf ? ' disabled' : '' ?>>
                                    <option value="1"<?= $eActive ? ' selected' : '' ?>>啟用（可登入）</option>
                                    <option value="0"<?= !$eActive ? ' selected' : '' ?>><?= $ePendingReview ? '待審核（未啟用）' : '停權（未啟用）' ?></option>
                                </select>
                                <?php if ($isSelf): ?>
                                    <input type="hidden" name="status" value="1">
                                    <p class="sub" style="margin:0.25rem 0 0;">無法停用自己的帳號。</p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php if ($eEmail !== ''): ?>
                            <p class="sub member-edit__email">
                                Email：<code><?= htmlspecialchars($eEmail, ENT_QUOTES, 'UTF-8') ?></code>
                                <?php if ($hasEmailVerified): ?>
                                    · <span data-edit-email-meta><?= $eVerified ? '已驗證' : '待驗證' ?></span>
                                <?php endif; ?>
                            </p>
                        <?php endif; ?>
                        <div class="member-edit__actions">
                            <button type="submit">儲存</button>
                        </div>
                    </form>
                    <?php if ($hasEmailVerified && $eEmail !== ''): ?>
                        <div class="member-edit__sideform">
                            <form method="post" action="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>" class="member-ajax-form"<?= $eVerified ? ' hidden' : '' ?> data-edit-verify-form>
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="verify_email">
                                <input type="hidden" name="member_id" value="<?= $eid ?>">
                                <input type="hidden" name="edit_url" value="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>">
                                <button type="submit" class="btn btn--ghost" data-edit-verify-btn>標記信箱已驗證</button>
                            </form>
                            <form method="post" action="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>" class="member-ajax-form"<?= !$eVerified ? ' hidden' : '' ?> data-edit-clear-form>
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="clear_email_verify">
                                <input type="hidden" name="member_id" value="<?= $eid ?>">
                                <input type="hidden" name="edit_url" value="<?= htmlspecialchars($buildListUrl($page, $eid), ENT_QUOTES, 'UTF-8') ?>">
                                <button type="submit" class="btn btn--ghost" data-edit-clear-verify-btn>清除驗證狀態</button>
                            </form>
                        </div>
                    <?php endif; ?>
                </section>
            <?php elseif ($editId > 0): ?>
                <div class="msg warn">找不到會員 #<?= $editId ?>。<a href="<?= htmlspecialchars($buildListUrl($page), ENT_QUOTES, 'UTF-8') ?>">返回列表</a></div>
            <?php endif; ?>

            <h2 class="section-title section-title--list">會員列表</h2>
            <p class="sub member-list-hint">可直接在列表修改顯示名稱、層級與分級；變更會自動儲存。信箱驗證、審核與其他進階設定請點「詳細」。</p>
            <div class="card card--filter">
                <form method="get" action="members.php" class="member-filter-form">
                    <div class="member-filter-form__row">
                        <div>
                            <label for="q">搜尋帳號／顯示名稱</label>
                            <input type="search" name="q" id="q" value="<?= htmlspecialchars($q, ENT_QUOTES, 'UTF-8') ?>" maxlength="80" placeholder="關鍵字">
                        </div>
                        <div>
                            <label for="role">層級</label>
                            <select name="role" id="role">
                                <option value=""<?= $roleFilter === '' ? ' selected' : '' ?>>全部</option>
                                <option value="admin"<?= $roleFilter === 'admin' ? ' selected' : '' ?>>管理員</option>
                                <option value="mod"<?= $roleFilter === 'mod' ? ' selected' : '' ?>>版主</option>
                                <option value="member"<?= $roleFilter === 'member' ? ' selected' : '' ?>>一般會員</option>
                            </select>
                        </div>
                        <div>
                            <label for="status">啟用</label>
                            <select name="status" id="status">
                                <option value=""<?= $statusFilter === '' ? ' selected' : '' ?>>全部</option>
                                <option value="active"<?= $statusFilter === 'active' ? ' selected' : '' ?>>已啟用</option>
                                <option value="inactive"<?= $statusFilter === 'inactive' ? ' selected' : '' ?>>未啟用</option>
                            </select>
                        </div>
                        <?php if ($hasManualReview): ?>
                        <div>
                            <label for="review">審核</label>
                            <select name="review" id="review">
                                <option value=""<?= $reviewFilter === '' ? ' selected' : '' ?>>全部</option>
                                <option value="pending"<?= $reviewFilter === 'pending' ? ' selected' : '' ?>>待審核</option>
                                <option value="approved"<?= $reviewFilter === 'approved' ? ' selected' : '' ?>>已通過</option>
                            </select>
                        </div>
                        <?php endif; ?>
                        <?php if ($hasEmailVerified): ?>
                        <div>
                            <label for="verify">信箱</label>
                            <select name="verify" id="verify">
                                <option value=""<?= $verifyFilter === '' ? ' selected' : '' ?>>全部</option>
                                <option value="email_pending"<?= $verifyFilter === 'email_pending' ? ' selected' : '' ?>>待驗證</option>
                                <option value="email_verified"<?= $verifyFilter === 'email_verified' ? ' selected' : '' ?>>已驗證</option>
                            </select>
                        </div>
                        <?php endif; ?>
                        <?php if ($hasMemberTier): ?>
                        <div>
                            <label for="tier">分級</label>
                            <select name="tier" id="tier">
                                <option value=""<?= $tierFilter === '' ? ' selected' : '' ?>>全部</option>
                                <option value="formal"<?= $tierFilter === 'formal' ? ' selected' : '' ?>>正式會員</option>
                                <option value="register"<?= $tierFilter === 'register' ? ' selected' : '' ?>>註冊會員</option>
                                <option value="blacklist"<?= $tierFilter === 'blacklist' ? ' selected' : '' ?>>黑名單</option>
                            </select>
                        </div>
                        <?php endif; ?>
                        <div class="member-filter-form__actions">
                            <button type="submit">篩選</button>
                            <?php if ($hasActiveFilters): ?>
                                <a class="btn btn--ghost" href="members.php">清除</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
            </div>

            <p class="sub member-list-meta">
                共 <strong><?= htmlspecialchars(number_format($list['total']), ENT_QUOTES, 'UTF-8') ?></strong> 筆
                <?php if ($list['pages'] > 1): ?>
                    · 第 <?= (int) $list['page'] ?> / <?= (int) $list['pages'] ?> 頁
                <?php endif; ?>
            </p>

            <?php if ($list['rows'] === []): ?>
                <div class="msg warn">沒有符合條件的會員。</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="table table--members">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">帳號</th>
                                <th scope="col">顯示名稱</th>
                                <?php if ($hasMemberTier): ?>
                                <th scope="col">分級</th>
                                <?php endif; ?>
                                <th scope="col">層級</th>
                                <th scope="col"><?= $hasManualReview ? '審核' : '狀態' ?></th>
                                <?php if (is_array($overview) && $overview['features']['email']): ?>
                                <th scope="col">Email</th>
                                <th scope="col">信箱</th>
                                <?php endif; ?>
                                <?php if (is_array($overview) && $overview['features']['last_login']): ?>
                                <th scope="col">最後登入</th>
                                <?php endif; ?>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($list['rows'] as $row): ?>
                                <?php
                                if (!is_array($row)) {
                                    continue;
                                }
                                $mid = (int) ($row['id'] ?? 0);
                                $active = (int) ($row['_mem_active'] ?? 0) === 1;
                                $roleRaw = isset($row['role']) ? (string) $row['role'] : '';
                                $isSelfRow = $actingAdminId > 0 && $actingAdminId === $mid;
                                $rowEditUrl = $buildListUrl($page, $mid);
                                $rowPendingReview = $hasManualReview && fate_admin_members_is_pending_review($row);
                                $rowNeedsEmailVerify = $hasEmailVerified
                                    && fate_admin_members_email_status_label($row) === '待驗證';
                                $rowClasses = ['member-row'];
                                if ($editId === $mid) {
                                    $rowClasses[] = 'row--highlight';
                                }
                                if ($rowPendingReview) {
                                    $rowClasses[] = 'member-row--pending';
                                }
                                $rowRoleInput = fate_admin_members_role_input_value($roleRaw);
                                $rowTier = $hasMemberTier ? fate_member_tier_from_row($row) : '';
                                ?>
                                <tr class="<?= htmlspecialchars(implode(' ', $rowClasses), ENT_QUOTES, 'UTF-8') ?>"
                                    data-member-id="<?= $mid ?>"
                                    data-edit-url="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>"
                                    data-is-self="<?= $isSelfRow ? '1' : '0' ?>">
                                    <td class="col-id"><?= $mid ?></td>
                                    <td><code><?= htmlspecialchars((string) ($row['username'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code></td>
                                    <td class="col-inline-edit">
                                        <input type="text" class="member-inline-input" name="display_name" maxlength="120"
                                               value="<?= htmlspecialchars((string) ($row['display_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                               data-member-id="<?= $mid ?>" data-field="display_name" aria-label="顯示名稱 #<?= $mid ?>">
                                    </td>
                                    <?php if ($hasMemberTier): ?>
                                    <td class="col-inline-edit">
                                        <select class="member-inline-select" name="member_tier" data-member-id="<?= $mid ?>" data-field="member_tier" aria-label="會員分級 #<?= $mid ?>">
                                            <option value="register"<?= $rowTier === 'register' ? ' selected' : '' ?>>註冊會員</option>
                                            <option value="formal"<?= $rowTier === 'formal' ? ' selected' : '' ?>>正式會員</option>
                                            <option value="blacklist"<?= $rowTier === 'blacklist' ? ' selected' : '' ?>>黑名單</option>
                                        </select>
                                    </td>
                                    <?php endif; ?>
                                    <td class="col-inline-edit">
                                        <select class="member-inline-select" name="role" data-member-id="<?= $mid ?>" data-field="role" aria-label="層級 #<?= $mid ?>">
                                            <option value="member"<?= $rowRoleInput === 'member' ? ' selected' : '' ?>>一般會員</option>
                                            <option value="mod"<?= $rowRoleInput === 'mod' ? ' selected' : '' ?>>版主</option>
                                            <option value="admin"<?= $rowRoleInput === 'admin' ? ' selected' : '' ?>>管理員</option>
                                        </select>
                                    </td>
                                    <td data-cell-review>
                                        <span class="<?= htmlspecialchars(fate_admin_members_review_badge_class($row), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars(fate_admin_members_review_status_label($row), ENT_QUOTES, 'UTF-8') ?></span>
                                    </td>
                                    <?php if (is_array($overview) && $overview['features']['email']): ?>
                                    <td class="col-email" title="<?= htmlspecialchars((string) ($row['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars(fate_admin_members_mask_email(isset($row['email']) ? (string) $row['email'] : null), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td data-cell-email-status><?= htmlspecialchars(fate_admin_members_email_status_label($row), ENT_QUOTES, 'UTF-8') ?></td>
                                    <?php endif; ?>
                                    <?php if (is_array($overview) && $overview['features']['last_login']): ?>
                                    <td class="col-time"><?= htmlspecialchars(fate_admin_members_format_dt(isset($row['last_login_at']) ? (string) $row['last_login_at'] : null), ENT_QUOTES, 'UTF-8') ?></td>
                                    <?php endif; ?>
                                    <td class="col-actions" data-row-actions>
                                        <div class="member-action-btns">
                                            <?php if ($rowPendingReview): ?>
                                                <form method="post" action="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>" class="member-inline-form member-ajax-form">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="approve">
                                                    <input type="hidden" name="member_id" value="<?= $mid ?>">
                                                    <input type="hidden" name="edit_url" value="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>">
                                                    <button type="submit" class="btn btn--sm btn--approve">通過審核</button>
                                                </form>
                                            <?php endif; ?>
                                            <?php if ($rowNeedsEmailVerify): ?>
                                                <form method="post" action="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>" class="member-inline-form member-ajax-form">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="verify_email">
                                                    <input type="hidden" name="member_id" value="<?= $mid ?>">
                                                    <input type="hidden" name="edit_url" value="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>">
                                                    <button type="submit" class="btn btn--sm btn--ghost">驗證信箱</button>
                                                </form>
                                            <?php endif; ?>
                                            <a class="btn btn--sm btn--ghost" href="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>">詳細</a>
                                            <?php if (!$isSelfRow && !$rowPendingReview): ?>
                                                <form method="post" action="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>" class="member-inline-form member-ajax-form">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="toggle_active">
                                                    <input type="hidden" name="member_id" value="<?= $mid ?>">
                                                    <input type="hidden" name="edit_url" value="<?= htmlspecialchars($rowEditUrl, ENT_QUOTES, 'UTF-8') ?>">
                                                    <button type="submit" class="btn btn--sm btn--ghost"><?= $active ? '停權' : '啟用' ?></button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($list['pages'] > 1): ?>
                    <nav class="pagination" aria-label="會員列表分頁">
                        <?php if ($list['page'] > 1): ?>
                            <a class="btn btn--ghost" href="<?= htmlspecialchars($buildListUrl($list['page'] - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                        <?php endif; ?>
                        <?php if ($list['page'] < $list['pages']): ?>
                            <a class="btn btn--ghost" href="<?= htmlspecialchars($buildListUrl($list['page'] + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                        <?php endif; ?>
                    </nav>
                <?php endif; ?>
            <?php endif; ?>

        <?php endif; ?>
        <?php if (!$dbErr && $pdo instanceof PDO && !$tableMissing && $queryErr === null):
            $membersJsPath = __DIR__ . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'members.js';
            $membersJsVer = is_file($membersJsPath) ? (string) filemtime($membersJsPath) : '1';
            $pageConfig = [
                'csrf' => $csrf,
                'actingAdminId' => $actingAdminId,
                'hasEmail' => is_array($overview) && !empty($overview['features']['email']),
                'hasEmailVerified' => $hasEmailVerified,
                'hasMemberTier' => $hasMemberTier,
                'hasLastLogin' => is_array($overview) && !empty($overview['features']['last_login']),
                'reviewFilter' => $reviewFilter,
                'verifyFilter' => $verifyFilter,
                'statusFilter' => $statusFilter,
                'tierFilter' => $tierFilter,
            ];
        ?>
        <script type="application/json" id="members-page-config"><?= json_encode(
            $pageConfig,
            JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE
        ) ?></script>
        <script src="<?= htmlspecialchars(fate_admin_asset_url('static/members.js'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($membersJsVer, ENT_QUOTES, 'UTF-8') ?>" defer></script>
        <?php endif; ?>
<?php
fate_admin_layout_end();
