<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'dashboard_icons.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_masseurs.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_image.php';

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

fate_admin_require_login();

$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();
}

$msgOk = '';
$msgBad = '';
$csrf = fate_admin_csrf_token();
$rewards = fate_masseur_rewards_settings();
$genders = fate_masseur_gender_labels();
$adminProfileStatsEnabled = fate_masseur_profile_stats_enabled();
$keyword = isset($_GET['q']) && is_string($_GET['q']) ? trim($_GET['q']) : '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tok = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    $action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : '';
    if (!fate_admin_csrf_check($tok)) {
        $msgBad = '工作階段逾期，請重新整理。';
    } elseif ($action === 'save_rewards') {
        $r = fate_masseur_rewards_save([
            'feature_enabled' => !empty($_POST['feature_enabled']),
            'reviews_enabled' => !empty($_POST['reviews_enabled']),
            'store_reviews_enabled' => !empty($_POST['store_reviews_enabled']),
            'profile_stats_enabled' => !empty($_POST['profile_stats_enabled']),
            'tags_formal_only' => !empty($_POST['tags_formal_only']),
            'profile_stats_formal_only' => !empty($_POST['profile_stats_formal_only']),
            'weekly_recommend_enabled' => !empty($_POST['feature_enabled']) && !empty($_POST['weekly_recommend_enabled']),
        ]);
        if ($r['ok']) {
            header('Location: masseurs.php?tab=settings&saved=1', true, 303);
            exit;
        }
        $msgBad = $r['error'] ?? '無法儲存設定。';
    } elseif ($action === 'save_default_avatar') {
        $g = isset($_POST['gender']) && is_string($_POST['gender']) ? $_POST['gender'] : '';
        $data = isset($_POST['photo_data']) && is_string($_POST['photo_data']) ? $_POST['photo_data'] : '';
        $r = fate_masseur_save_default_avatar($g, $data);
        if ($r['ok']) {
            header('Location: masseurs.php?tab=avatars&avatar_saved=' . rawurlencode($g), true, 303);
            exit;
        }
        $msgBad = $r['error'] ?? '無法儲存預設頭像。';
    } elseif ($action === 'clear_default_avatar') {
        $g = isset($_POST['gender']) && is_string($_POST['gender']) ? $_POST['gender'] : '';
        $r = fate_masseur_clear_default_avatar($g);
        if ($r['ok']) {
            header('Location: masseurs.php?tab=avatars&avatar_cleared=' . rawurlencode($g), true, 303);
            exit;
        }
        $msgBad = $r['error'] ?? '無法清除預設頭像。';
    } elseif ($pdo instanceof PDO && $action === 'save_tag_topic') {
        $r = fate_masseur_tag_topic_save(
            $pdo,
            (int) ($_POST['topic_id'] ?? 0),
            (string) ($_POST['title'] ?? ''),
            !empty($_POST['allow_multiple']),
            !empty($_POST['is_hidden']),
            (int) ($_POST['sort'] ?? 0),
            (string) ($_POST['description'] ?? '')
        );
        if ($r['ok']) {
            header('Location: masseurs.php?tab=tags&saved=1', true, 303);
            exit;
        }
        $msgBad = $r['error'] ?? '儲存主題失敗。';
    } elseif ($pdo instanceof PDO && $action === 'save_tag') {
        $r = fate_masseur_tag_save(
            $pdo,
            (int) ($_POST['topic_id'] ?? 0),
            (string) ($_POST['label'] ?? ''),
            (int) ($_POST['sort'] ?? 0),
            (int) ($_POST['tag_id'] ?? 0)
        );
        if ($r['ok']) {
            header('Location: masseurs.php?tab=tags&saved=1', true, 303);
            exit;
        }
        $msgBad = $r['error'] ?? '儲存標籤失敗。';
    } elseif ($pdo instanceof PDO && $action === 'toggle_tag_hidden') {
        $r = fate_masseur_tag_set_hidden($pdo, (int) ($_POST['tag_id'] ?? 0), !empty($_POST['hidden']));
        $msgOk = $r['ok'] ? '已更新標籤狀態。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '更新失敗。');
    } elseif ($pdo instanceof PDO && $action === 'delete_tag') {
        $r = fate_masseur_tag_admin_delete($pdo, (int) ($_POST['tag_id'] ?? 0));
        $msgOk = $r['ok'] ? '已刪除標籤與相關點選紀錄。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '刪除失敗。');
    } elseif ($pdo instanceof PDO && $action === 'delete_tag_pick') {
        $r = fate_masseur_tag_pick_admin_delete($pdo, (int) ($_POST['pick_id'] ?? 0));
        $msgOk = $r['ok'] ? '已刪除點選紀錄並扣回獎勵（若設定啟用）。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '刪除失敗。');
    } elseif ($pdo instanceof PDO && $action === 'delete_masseur') {
        $r = fate_masseur_admin_delete($pdo, (int) ($_POST['id'] ?? 0));
        $msgOk = $r['ok'] ? '已刪除技師。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '刪除失敗。');
    } elseif ($pdo instanceof PDO && $action === 'update_masseur') {
        $profileStats = fate_masseur_profile_stats_enabled() ? fate_masseur_profile_stats_parse_post($_POST) : null;
        $r = fate_masseur_admin_update($pdo, (int) ($_POST['id'] ?? 0), (string) ($_POST['name'] ?? ''), (string) ($_POST['gender'] ?? 'female'), $profileStats);
        $msgOk = $r['ok'] ? '已更新技師。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '更新失敗。');
    } elseif ($pdo instanceof PDO && $action === 'delete_review') {
        $r = fate_masseur_admin_delete_review($pdo, (int) ($_POST['id'] ?? 0));
        $msgOk = $r['ok'] ? '已刪除評論。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '刪除失敗。');
    } elseif ($pdo instanceof PDO && $action === 'update_review') {
        $r = fate_masseur_admin_update_review($pdo, (int) ($_POST['id'] ?? 0), (string) ($_POST['body'] ?? ''));
        $msgOk = $r['ok'] ? '已更新評論。' : '';
        $msgBad = $r['ok'] ? '' : ($r['error'] ?? '更新失敗。');
    }
    $rewards = fate_masseur_rewards_settings();
}

if (isset($_GET['saved'])) {
    $savedTab = isset($_GET['tab']) && is_string($_GET['tab']) ? strtolower(trim($_GET['tab'])) : '';
    $msgOk = $savedTab === 'tags' ? '已儲存標籤設定。' : '已儲存功能設定。';
}
if (isset($_GET['avatar_saved']) && is_string($_GET['avatar_saved'])) {
    $gl = fate_masseur_default_avatar_gender_norm($_GET['avatar_saved']);
    $msgOk = '已儲存' . ($gl === 'male' ? '男' : ($gl === 'female' ? '女' : '其他')) . '技師預設頭像。';
}
if (isset($_GET['avatar_cleared']) && is_string($_GET['avatar_cleared'])) {
    $gl = fate_masseur_default_avatar_gender_norm($_GET['avatar_cleared']);
    $msgOk = '已清除' . ($gl === 'male' ? '男' : ($gl === 'female' ? '女' : '其他')) . '技師預設頭像。';
}

$masseurPage = max(1, (int) ($_GET['mp'] ?? 1));
$reviewPage = max(1, (int) ($_GET['rp'] ?? 1));
$mppOpt = (int) ($_GET['mpp'] ?? 25);
$masseurPerPage = in_array($mppOpt, [25, 50, 100], true) ? $mppOpt : 25;
$rppOpt = (int) ($_GET['rpp'] ?? 20);
$reviewPerPage = in_array($rppOpt, [20, 50, 100], true) ? $rppOpt : 20;
$tabRaw = isset($_GET['tab']) && is_string($_GET['tab']) ? strtolower(trim($_GET['tab'])) : 'list';
if ($tabRaw === 'masseurs' || $tabRaw === 'reviews') {
    $activeTab = 'list';
    $listView = $tabRaw === 'reviews' ? 'reviews' : 'masseurs';
} else {
    $activeTab = in_array($tabRaw, ['settings', 'avatars', 'tags', 'list'], true) ? $tabRaw : 'list';
    $listView = ($activeTab === 'list' && isset($_GET['list']) && $_GET['list'] === 'reviews') ? 'reviews' : 'masseurs';
}

$emptyList = ['rows' => [], 'total' => 0, 'page' => 1, 'per_page' => 25, 'pages' => 1, 'from' => 0, 'to' => 0];
$masseurList = $pdo instanceof PDO
    ? fate_admin_masseurs_page($pdo, $keyword, $masseurPage, $masseurPerPage)
    : $emptyList;
$reviewList = $pdo instanceof PDO
    ? fate_admin_masseur_reviews_page($pdo, $reviewPage, $reviewPerPage)
    : array_merge($emptyList, ['per_page' => 20]);

$buildUrl = static function (
    ?int $mp = null,
    ?int $rp = null,
    ?string $q = null,
    ?string $tab = null,
    ?string $list = null
) use (
    $masseurPage,
    $reviewPage,
    $masseurPerPage,
    $reviewPerPage,
    $keyword,
    $activeTab,
    $listView
): string {
    $tabVal = $tab ?? $activeTab;
    $qs = [
        'tab' => $tabVal,
        'mp' => $mp ?? $masseurPage,
        'rp' => $rp ?? $reviewPage,
        'mpp' => $masseurPerPage,
        'rpp' => $reviewPerPage,
    ];
    if ($tabVal === 'list') {
        $qs['list'] = $list ?? $listView;
    }
    $kw = $q ?? $keyword;
    if ($kw !== '') {
        $qs['q'] = $kw;
    }

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

$formAction = $buildUrl();
$dbOk = $pdo instanceof PDO && $dbErr === null;
$masseurs = $masseurList['rows'];
$recentReviews = $reviewList['rows'];
$largeCatalog = $masseurList['total'] >= 100 || $reviewList['total'] >= 100;
$tagTopics = $pdo instanceof PDO ? fate_masseur_tag_topics_all($pdo, true) : [];
$tagPicksRecent = $pdo instanceof PDO ? fate_masseur_tag_picks_recent($pdo, 50) : [];

$pager = static function (array $list, string $which) use ($buildUrl): void {
    if (($list['pages'] ?? 1) <= 1) {
        return;
    }
    $isMasseur = $which === 'masseur';
    $view = $isMasseur ? 'masseurs' : 'reviews';
    $prev = $isMasseur
        ? $buildUrl((int) $list['page'] - 1, null, null, 'list', $view)
        : $buildUrl(null, (int) $list['page'] - 1, null, 'list', $view);
    $next = $isMasseur
        ? $buildUrl((int) $list['page'] + 1, null, null, 'list', $view)
        : $buildUrl(null, (int) $list['page'] + 1, null, 'list', $view);
    ?>
    <nav class="pagination masseur-pager" aria-label="<?= $isMasseur ? '技師列表分頁' : '評論列表分頁' ?>">
        <?php if ((int) $list['page'] > 1): ?>
            <a class="btn btn--ghost" href="<?= htmlspecialchars($prev, ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
        <?php endif; ?>
        <span class="masseur-pager__meta">第 <?= (int) $list['page'] ?>／<?= (int) $list['pages'] ?> 頁</span>
        <?php if ((int) $list['page'] < (int) $list['pages']): ?>
            <a class="btn btn--ghost" href="<?= htmlspecialchars($next, ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
        <?php endif; ?>
    </nav>
    <?php
};

fate_admin_layout_start(['page' => '推薦技師', 'active' => 'masseurs', 'body_class' => 'admin-body--masseurs']);
?>
        <div class="masseur-admin" id="masseur-admin" data-density="comfortable">
            <header class="masseur-hero" aria-label="推薦技師">
                <div class="masseur-hero__glow" aria-hidden="true"></div>
                <div class="masseur-hero__inner">
                    <div class="masseur-hero__lead">
                        <span class="masseur-hero__icon" aria-hidden="true"><?= fate_admin_dashboard_icon('masseurs') ?></span>
                        <div class="masseur-hero__copy">
                            <h1 class="masseur-hero__title">推薦技師</h1>
                            <p class="masseur-hero__sub">管理會員推薦的技師、評論與標籤；N 幣獎勵金額請至<a href="ncoin.php">站內貨幣設定/紀錄</a>。</p>
                        </div>
                    </div>
                    <span class="sync-pill<?= $dbOk ? ' sync-pill--ok' : ' sync-pill--bad' ?>">
                        技師 <?= number_format((int) $masseurList['total']) ?> · 評論 <?= number_format((int) $reviewList['total']) ?>
                    </span>
                </div>
            </header>

            <?php if ($dbErr !== null): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text">資料庫：<?= htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>
            <?php if ($msgOk !== ''): ?>
                <div class="sync-banner sync-banner--ok" role="status">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('check') ?></span>
                    <p class="sync-banner__text"><?= htmlspecialchars($msgOk, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>
            <?php if ($msgBad !== ''): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text"><?= htmlspecialchars($msgBad, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>

            <div class="masseur-tabs-col sync-panel" id="masseur-tabs">
                <nav class="masseur-tabs masseur-tabs--main" role="tablist" aria-label="主題切換">
                    <a class="masseur-tabs__btn<?= $activeTab === 'settings' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'settings'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'settings' ? 'true' : 'false' ?>"
                       id="tab-btn-settings">功能設定</a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'avatars' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'avatars'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'avatars' ? 'true' : 'false' ?>"
                       id="tab-btn-avatars">預設頭像</a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'tags' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'tags' ? 'true' : 'false' ?>"
                       id="tab-btn-tags">技師標籤</a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'list' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'list', 'masseurs'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'list' ? 'true' : 'false' ?>"
                       id="tab-btn-list">
                        列表管理
                        <span class="masseur-tabs__count"><?= number_format((int) $masseurList['total']) ?>／<?= number_format((int) $reviewList['total']) ?></span>
                    </a>
                </nav>

                <?php if ($activeTab === 'settings'): ?>
                <div class="masseur-tab-panel is-active" id="tab-panel-settings" role="tabpanel" aria-labelledby="tab-btn-settings">
            <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'settings'), ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="action" value="save_rewards">
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:.4rem 0 .5rem;font-weight:600;">
                    <input type="checkbox" id="masseur-feature-enabled" name="feature_enabled" value="1" <?= $rewards['feature_enabled'] ? 'checked' : '' ?>>
                    啟用推薦技師功能（關閉後前台不顯示此區）
                </label>
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .85rem;">
                    <input type="checkbox" name="store_reviews_enabled" value="1" <?= !empty($rewards['store_reviews_enabled']) ? 'checked' : '' ?>>
                    開放<strong>店家文字評論</strong>（店家頁「店家評論」區；可獨立於推薦技師）
                </label>
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .85rem;">
                    <input type="checkbox" name="reviews_enabled" value="1" <?= $rewards['reviews_enabled'] ? 'checked' : '' ?>>
                    開放<strong>技師文字評論</strong>（關閉後前台不顯示技師評論、不可發表；點讚／建檔不受影響）
                </label>
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .85rem;">
                    <input type="checkbox" name="profile_stats_enabled" value="1" <?= !empty($rewards['profile_stats_enabled']) ? 'checked' : '' ?>>
                    啟用技師<strong>年齡／三圍／罩杯</strong>欄位（建檔與編輯可選「無資料」；關閉後前台與討論區不顯示）
                </label>
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .85rem;">
                    <input type="checkbox" name="tags_formal_only" value="1" <?= !empty($rewards['tags_formal_only']) ? 'checked' : '' ?>>
                    技師<strong>標籤</strong>僅<strong>正式會員</strong>可見與點選（站方人員豁免；未勾選則完成驗證即可）
                </label>
                <label class="checkbox-label masseur-weekly-settings-label" style="display:flex;align-items:flex-start;gap:.45rem;margin:0 0 .85rem;<?= !$rewards['feature_enabled'] ? ' opacity:.55;' : '' ?>">
                    <input type="checkbox" id="masseur-weekly-settings-input" name="weekly_recommend_enabled" value="1"<?= !empty($rewards['weekly_recommend_enabled']) ? ' checked' : '' ?><?= !$rewards['feature_enabled'] ? ' disabled' : '' ?>>
                    <span>開放<strong>本週推薦／週推榜</strong>（sidebar TOP5、獨立週榜頁；須先啟用上方推薦技師功能）</span>
                </label>
                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .85rem;">
                    <input type="checkbox" name="profile_stats_formal_only" value="1" <?= !empty($rewards['profile_stats_formal_only']) ? 'checked' : '' ?>>
                    技師<strong>年齡／身材</strong>僅<strong>正式會員</strong>可見（站方人員豁免；須先啟用上方進階欄位）
                </label>
                <p class="masseur-note" style="margin:0 0 .85rem;">N 幣獎勵金額、扣回規則與推薦店家核准獎勵，請至 <a href="ncoin.php">站內貨幣設定/紀錄</a> 統一設定。</p>
                <button type="submit" class="sync-btn sync-btn--primary" style="margin-top:.25rem;">儲存功能設定</button>
            </form>
            <script>
            (function () {
                var feat = document.getElementById('masseur-feature-enabled');
                var weekly = document.getElementById('masseur-weekly-settings-input');
                var weeklyLabel = document.querySelector('.masseur-weekly-settings-label');
                if (!feat || !weekly) return;
                function syncWeeklySettings() {
                    var on = feat.checked;
                    weekly.disabled = !on;
                    if (!on) weekly.checked = false;
                    if (weeklyLabel) weeklyLabel.style.opacity = on ? '' : '0.55';
                }
                feat.addEventListener('change', syncWeeklySettings);
                syncWeeklySettings();
            })();
            </script>
                    <p class="masseur-note masseur-tab-foot">互動功能須<strong>完成信箱驗證</strong>；黑名單與未驗證會員相同不得參與。標籤／身材若啟用「正式會員專區」，須為正式會員（完成驗證後自動升級）方可查看。停權無法登入；黑名單可登入但完成驗證後仍不得互動，須管理員解除。</p>
                </div>

                <?php elseif ($activeTab === 'tags'): ?>
                <div class="masseur-tab-panel is-active" id="tab-panel-tags" role="tabpanel" aria-labelledby="tab-btn-tags">
                    <p class="masseur-note">兩個預設主題為「技師情報」「服務」。可設定各主題是否允許會員<strong>多選</strong>標籤；各分區可撰寫<strong>說明</strong>供前台點開查看（適合解釋縮寫標籤）。前台顯示於店家技師卡；<strong>標籤點選次數不限</strong>，N 幣發放上限請至 <a href="ncoin.php">站內貨幣設定</a>「技師標籤獎勵」區調整。</p>
                    <?php foreach ($tagTopics as $topic): ?>
                        <?php
                        $topicId = (int) ($topic['id'] ?? 0);
                        $topicTags = $pdo instanceof PDO ? fate_masseur_tags_for_topic($pdo, $topicId, true) : [];
                        ?>
                        <div class="card" style="margin-bottom:1rem;padding:1rem;">
                            <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" class="masseur-tag-topic-form">
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="save_tag_topic">
                                <input type="hidden" name="topic_id" value="<?= $topicId ?>">
                                <h3 class="h3" style="margin:0 0 .65rem;">主題：<?= htmlspecialchars((string) ($topic['slug'] ?? ''), ENT_QUOTES, 'UTF-8') ?></h3>
                                <div class="masseur-rewards-grid" style="margin-bottom:.65rem;">
                                    <label style="display:flex;flex-direction:column;gap:.25rem;">
                                        <span class="sub">顯示名稱</span>
                                        <input type="text" name="title" maxlength="80" required value="<?= htmlspecialchars((string) ($topic['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                                    </label>
                                    <label style="display:flex;flex-direction:column;gap:.25rem;">
                                        <span class="sub">排序（小在前）</span>
                                        <input type="number" name="sort" value="<?= (int) ($topic['sort'] ?? 0) ?>">
                                    </label>
                                </div>
                                <label style="display:flex;flex-direction:column;gap:.25rem;margin:0 0 .65rem;">
                                    <span class="sub">分區說明（選填，前台可點「說明」查看；適合解釋縮寫，例：DF＝深層筋膜）</span>
                                    <textarea name="description" rows="4" maxlength="2000" placeholder="可逐條列出縮寫含義，支援換行。"><?= htmlspecialchars(fate_masseur_tag_normalize_topic_description((string) ($topic['description'] ?? '')), ENT_QUOTES, 'UTF-8') ?></textarea>
                                </label>
                                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .45rem;">
                                    <input type="checkbox" name="allow_multiple" value="1"<?= (int) ($topic['allow_multiple'] ?? 0) === 1 ? ' checked' : '' ?>>
                                    允許會員在此主題<strong>多選</strong>標籤（未勾選則同一技師僅能選一個）
                                </label>
                                <label class="checkbox-label" style="display:flex;align-items:center;gap:.45rem;margin:0 0 .65rem;">
                                    <input type="checkbox" name="is_hidden" value="1"<?= (int) ($topic['is_hidden'] ?? 0) === 1 ? ' checked' : '' ?>>
                                    隱藏此主題（前台不顯示）
                                </label>
                                <button type="submit" class="btn btn--secondary btn--sm">儲存主題設定</button>
                            </form>

                            <table class="data-table" style="margin-top:.85rem;">
                                <thead>
                                    <tr><th>標籤</th><th>全站點選</th><th>排序</th><th>狀態</th><th>操作</th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topicTags as $tg): ?>
                                        <?php $tgId = (int) ($tg['id'] ?? 0); ?>
                                        <tr>
                                            <td>
                                                <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" style="display:flex;gap:.35rem;align-items:center;flex-wrap:wrap;">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="save_tag">
                                                    <input type="hidden" name="topic_id" value="<?= $topicId ?>">
                                                    <input type="hidden" name="tag_id" value="<?= $tgId ?>">
                                                    <input type="text" name="label" maxlength="48" required value="<?= htmlspecialchars((string) ($tg['label'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" style="min-width:8rem;">
                                                    <input type="number" name="sort" value="<?= (int) ($tg['sort'] ?? 0) ?>" style="width:4.5rem;">
                                                    <button type="submit" class="btn btn--ghost btn--sm">更新</button>
                                                </form>
                                            </td>
                                            <td><?= (int) ($tg['pick_total'] ?? 0) ?></td>
                                            <td><?= (int) ($tg['sort'] ?? 0) ?></td>
                                            <td><?= (int) ($tg['is_hidden'] ?? 0) === 1 ? '隱藏' : '顯示' ?></td>
                                            <td style="white-space:nowrap;">
                                                <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" style="display:inline;">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="toggle_tag_hidden">
                                                    <input type="hidden" name="tag_id" value="<?= $tgId ?>">
                                                    <input type="hidden" name="hidden" value="<?= (int) ($tg['is_hidden'] ?? 0) === 1 ? '0' : '1' ?>">
                                                    <button type="submit" class="btn btn--ghost btn--sm"><?= (int) ($tg['is_hidden'] ?? 0) === 1 ? '顯示' : '隱藏' ?></button>
                                                </form>
                                                <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" style="display:inline;" onsubmit="return confirm('刪除此標籤？所有點選紀錄與相關 N 幣將一併處理。');">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="delete_tag">
                                                    <input type="hidden" name="tag_id" value="<?= $tgId ?>">
                                                    <button type="submit" class="btn btn--danger btn--sm">刪除</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" style="margin-top:.75rem;display:flex;flex-wrap:wrap;gap:.45rem;align-items:flex-end;">
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="save_tag">
                                <input type="hidden" name="topic_id" value="<?= $topicId ?>">
                                <input type="hidden" name="tag_id" value="0">
                                <label style="display:flex;flex-direction:column;gap:.2rem;">
                                    <span class="sub">新增標籤</span>
                                    <input type="text" name="label" maxlength="48" required placeholder="例：親切、深層按摩">
                                </label>
                                <label style="display:flex;flex-direction:column;gap:.2rem;">
                                    <span class="sub">排序</span>
                                    <input type="number" name="sort" value="0" style="width:5rem;">
                                </label>
                                <button type="submit" class="btn btn--primary btn--sm">新增</button>
                            </form>
                        </div>
                    <?php endforeach; ?>

                    <div class="card" style="padding:1rem;">
                        <h3 class="h3" style="margin:0 0 .65rem;">最近點選紀錄（可刪除並扣回 N 幣）</h3>
                        <?php if ($tagPicksRecent === []): ?>
                            <p class="sub" style="margin:0;">尚無點選紀錄。</p>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr><th>ID</th><th>技師</th><th>標籤</th><th>會員</th><th>時間</th><th></th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($tagPicksRecent as $pk): ?>
                                        <tr>
                                            <td><?= (int) ($pk['id'] ?? 0) ?></td>
                                            <td><?= htmlspecialchars((string) ($pk['masseur_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?> <span class="masseur-table__sub">#<?= (int) ($pk['masseur_id'] ?? 0) ?></span></td>
                                            <td><?= htmlspecialchars((string) ($pk['topic_title'] ?? ''), ENT_QUOTES, 'UTF-8') ?>／<?= htmlspecialchars((string) ($pk['tag_label'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td>#<?= (int) ($pk['member_id'] ?? 0) ?></td>
                                            <td class="masseur-table__meta"><?= htmlspecialchars(substr((string) ($pk['created_at'] ?? ''), 0, 16), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td>
                                                <form method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'tags'), ENT_QUOTES, 'UTF-8') ?>" onsubmit="return confirm('刪除此點選紀錄？');">
                                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="delete_tag_pick">
                                                    <input type="hidden" name="pick_id" value="<?= (int) ($pk['id'] ?? 0) ?>">
                                                    <button type="submit" class="btn btn--danger btn--sm">刪除</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>

                <?php elseif ($activeTab === 'avatars'): ?>
                <div class="masseur-tab-panel is-active" id="tab-panel-avatars" role="tabpanel" aria-labelledby="tab-btn-avatars">
                    <p class="masseur-note">會員未上傳相片時，依性別顯示預設圖；可剪裁並遮蔽五官。</p>
            <div class="masseur-avatar-grid">
                <?php foreach (['female' => '女', 'male' => '男'] as $defG => $defLabel): ?>
                    <?php
                    $defRel = fate_masseur_default_avatar_rel($defG);
                    $defPreview = $defRel !== null ? fate_masseur_photo_admin_url($defRel, true) : null;
                    $pfx = 'admin-avatar-' . $defG;
                    $hasDef = $defPreview !== null;
                    ?>
                    <div id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-block" class="admin-default-avatar-block masseur-avatar-card">
                        <h3 class="h3" style="margin:0 0 .65rem;font-size:.95rem;"><?= htmlspecialchars($defLabel, ENT_QUOTES, 'UTF-8') ?>技師預設</h3>
                        <div class="admin-avatar-current" style="margin-bottom:.65rem;">
                            <p class="sub admin-avatar-empty" style="margin:0 0 .65rem;"<?= $hasDef ? ' hidden' : '' ?>>尚未設定（前台顯示符號頭像）。</p>
                            <p class="sub admin-avatar-current-label" style="margin:0 0 .5rem;<?= $hasDef ? '' : 'display:none;' ?>">目前預設：</p>
                            <img class="admin-avatar-current-img" src="<?= $hasDef ? htmlspecialchars($defPreview, ENT_QUOTES, 'UTF-8') : '' ?>" alt="" width="96" height="96" style="width:96px;height:96px;object-fit:cover;border-radius:50%;border:1px solid var(--line);margin-bottom:.45rem;<?= $hasDef ? '' : 'display:none;' ?>"<?= $hasDef ? '' : ' hidden' ?>>
                            <div style="display:flex;flex-wrap:wrap;gap:.45rem;margin-bottom:.35rem;">
                                <button type="button" class="btn btn--secondary btn--sm admin-avatar-edit-btn" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-edit" data-src="<?= $hasDef ? htmlspecialchars($defPreview, ENT_QUOTES, 'UTF-8') : '' ?>"<?= $hasDef ? '' : ' hidden' ?>>編輯目前預設</button>
                                <button type="button" class="btn btn--danger btn--sm admin-avatar-clear-btn" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-clear" data-label="<?= htmlspecialchars($defLabel, ENT_QUOTES, 'UTF-8') ?>"<?= $hasDef ? '' : ' hidden' ?>>清除預設</button>
                            </div>
                        </div>
                        <form id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-form" method="post" action="<?= htmlspecialchars($buildUrl(null, null, null, 'avatars'), ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="action" value="save_default_avatar">
                            <input type="hidden" name="gender" value="<?= htmlspecialchars($defG, ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="photo_data" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-data" value="">
                            <label class="sub" for="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-file"><?= $hasDef ? '或上傳新圖' : '選擇圖片' ?>（JPEG／PNG／WebP）</label>
                            <input type="file" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-file" accept="image/jpeg,image/png,image/webp" style="display:block;margin:.35rem 0 .5rem;max-width:100%;">
                            <div id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-panel" class="masseur-photo-editor" hidden style="margin:.4rem 0;">
                                <div id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-crop-stage" class="masseur-photo-stage">
                                    <canvas id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-crop-canvas" class="masseur-photo-canvas masseur-photo-canvas--crop" style="max-width:100%;"></canvas>
                                    <div class="masseur-photo-tools" style="display:flex;flex-wrap:wrap;gap:.45rem;align-items:center;margin-top:.45rem;">
                                        <label class="sub">縮放 <input type="range" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-crop-zoom" min="1" max="3" value="1" step="0.02"></label>
                                        <button type="button" class="btn btn--primary btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-crop-apply">完成剪裁</button>
                                        <button type="button" class="btn btn--ghost btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-cancel">取消</button>
                                    </div>
                                </div>
                                <div id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-edit-stage" class="masseur-photo-stage" hidden>
                                    <canvas id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-canvas" class="masseur-photo-canvas" style="max-width:100%;"></canvas>
                                    <div class="masseur-photo-tools" style="display:flex;flex-wrap:wrap;gap:.45rem;align-items:center;margin-top:.45rem;">
                                        <label class="sub">筆刷 <input type="range" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-brush" min="10" max="120" value="40" step="2"></label>
                                        <button type="button" class="btn btn--secondary btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-recrop">重新剪裁</button>
                                        <button type="button" class="btn btn--secondary btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-reset">還原</button>
                                        <button type="button" class="btn btn--primary btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-apply">套用相片</button>
                                        <button type="button" class="btn btn--ghost btn--sm" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-cancel-edit">取消</button>
                                    </div>
                                </div>
                            </div>
                            <img id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-preview" alt="待儲存預覽" hidden style="max-width:120px;border-radius:10px;margin:.35rem 0;display:block;">
                            <p class="sub" id="<?= htmlspecialchars($pfx, ENT_QUOTES, 'UTF-8') ?>-hint" style="min-height:1.2em;margin:.25rem 0 .5rem;"></p>
                            <div style="display:flex;flex-wrap:wrap;gap:.45rem;">
                                <button type="submit" class="btn btn--primary btn--sm">儲存預設頭像</button>
                            </div>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
                </div>
        <script src="<?= htmlspecialchars(fate_site_static_url('fate-masseur-photo.js'), ENT_QUOTES, 'UTF-8') ?>?v=4"></script>
        <script src="<?= htmlspecialchars(fate_admin_asset_url('static/masseur_default_avatar.js'), ENT_QUOTES, 'UTF-8') ?>?v=2"></script>
        <script>
        (function () {
            if (typeof fateInitDefaultAvatarAdmin !== 'function') return;
            fateInitDefaultAvatarAdmin({
                csrf: <?= json_encode($csrf, JSON_UNESCAPED_UNICODE) ?>,
                apiUrl: 'masseur_avatar_api.php',
                genders: ['female', 'male']
            });
        })();
        </script>

                <?php else: ?>
                <nav class="masseur-subtabs" role="tablist" aria-label="列表切換">
                    <a class="masseur-subtabs__btn<?= $listView === 'masseurs' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'list', 'masseurs'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $listView === 'masseurs' ? 'true' : 'false' ?>"
                       id="tab-btn-masseurs">
                        技師列表
                        <span class="masseur-tabs__count"><?= number_format((int) $masseurList['total']) ?></span>
                    </a>
                    <a class="masseur-subtabs__btn<?= $listView === 'reviews' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl(null, null, null, 'list', 'reviews'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $listView === 'reviews' ? 'true' : 'false' ?>"
                       id="tab-btn-reviews">
                        評論列表
                        <span class="masseur-tabs__count"><?= number_format((int) $reviewList['total']) ?></span>
                    </a>
                </nav>

                    <?php if ($listView === 'masseurs'): ?>
                    <div class="masseur-tab-panel is-active" id="masseur-list" role="tabpanel" aria-labelledby="tab-btn-masseurs">
                        <div class="masseur-toolbar">
                            <form method="get" action="masseurs.php" class="masseur-search">
                                <input type="hidden" name="tab" value="list">
                                <input type="hidden" name="list" value="masseurs">
                                <input type="hidden" name="mp" value="1">
                                <input type="hidden" name="rp" value="<?= (int) $reviewPage ?>">
                                <input type="hidden" name="mpp" value="<?= (int) $masseurPerPage ?>">
                                <input type="hidden" name="rpp" value="<?= (int) $reviewPerPage ?>">
                                <input type="search" name="q" value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>" placeholder="搜尋技師或店名" class="masseur-search__input">
                                <button type="submit" class="sync-btn">搜尋</button>
                            </form>
                            <form method="get" action="masseurs.php" class="masseur-per-page">
                                <input type="hidden" name="tab" value="list">
                                <input type="hidden" name="list" value="masseurs">
                                <input type="hidden" name="q" value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="mp" value="1">
                                <input type="hidden" name="rp" value="<?= (int) $reviewPage ?>">
                                <input type="hidden" name="rpp" value="<?= (int) $reviewPerPage ?>">
                                <label class="masseur-per-page__label">
                                    每頁
                                    <select name="mpp" onchange="this.form.submit()">
                                        <?php foreach ([25, 50, 100] as $n): ?>
                                            <option value="<?= $n ?>"<?= $masseurPerPage === $n ? ' selected' : '' ?>><?= $n ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                            </form>
                            <label class="masseur-per-page__label">
                                密度
                                <select id="masseur-density">
                                    <option value="comfortable">標準</option>
                                    <option value="compact">緊湊</option>
                                </select>
                            </label>
                        </div>

                        <?php if ($masseurList['total'] > 0): ?>
                            <p class="masseur-range" role="status">
                                顯示第 <?= (int) $masseurList['from'] ?>–<?= (int) $masseurList['to'] ?> 筆
                                <?php if ($largeCatalog): ?>
                                    <span class="masseur-range__hint">· 資料量大，已分頁並固定表頭捲動</span>
                                <?php endif; ?>
                            </p>
                            <?php $pager($masseurList, 'masseur'); ?>
                        <?php endif; ?>

                        <?php if ($masseurs === []): ?>
                            <p class="masseur-empty">尚無技師資料<?= $keyword !== '' ? '（無符合搜尋結果）' : '' ?>。</p>
                        <?php else: ?>
                            <div class="masseur-scroll-table" role="region" aria-label="技師列表表格" tabindex="0">
                                <table class="data-table masseur-table">
                                    <thead>
                                        <tr><th>#</th><th>店家</th><th>技師／性別</th><th>讚／不讚</th><th>評論</th><th>建檔</th><th>操作</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($masseurs as $m): ?>
                                            <?php $mid = (int) $m['id']; ?>
                                            <tr>
                                                <td class="masseur-table__id"><?= $mid ?></td>
                                                <td class="masseur-table__store">
                                                    <span class="masseur-table__primary"><?= htmlspecialchars((string) ($m['store_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                                    <span class="masseur-table__sub">#<?= (int) ($m['spa_store_id'] ?? 0) ?> · <a href="<?= htmlspecialchars('../store.php?id=' . (int) ($m['spa_store_id'] ?? 0), ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">前台</a></span>
                                                </td>
                                                <td>
                                                    <form method="post" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" class="masseur-inline-form">
                                                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="action" value="update_masseur">
                                                        <input type="hidden" name="id" value="<?= $mid ?>">
                                                        <input type="text" name="name" value="<?= htmlspecialchars((string) ($m['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" maxlength="40" class="masseur-inline-form__name">
                                                        <select name="gender" class="masseur-inline-form__gender">
                                                            <?php foreach ($genders as $gk => $gl): ?>
                                                                <option value="<?= htmlspecialchars($gk, ENT_QUOTES, 'UTF-8') ?>"<?= ($m['gender'] ?? '') === $gk ? ' selected' : '' ?>><?= htmlspecialchars($gl, ENT_QUOTES, 'UTF-8') ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                        <button type="submit" class="btn btn--secondary btn--sm">存</button>
                                                        <?php if ($adminProfileStatsEnabled): ?>
                                                            <details class="masseur-admin-profile-stats" style="margin-top:.45rem;">
                                                                <summary class="sub" style="cursor:pointer;">年齡／三圍／罩杯</summary>
                                                                <?php
                                                                $mprefix = 'admin-m-' . $mid . '-';
                                                                $masseur = $m;
                                                                $fieldClass = 'masseur-field';
                                                                require dirname(__DIR__) . '/includes/partials/masseur_profile_stats_form.inc.php';
                                                                ?>
                                                            </details>
                                                        <?php endif; ?>
                                                    </form>
                                                </td>
                                                <td class="masseur-table__num"><?= (int) ($m['like_count'] ?? 0) ?>／<?= (int) ($m['dislike_count'] ?? 0) ?></td>
                                                <td class="masseur-table__num"><?= (int) ($m['review_count'] ?? 0) ?></td>
                                                <td class="masseur-table__meta">
                                                    <span class="masseur-table__primary"><?= htmlspecialchars((string) ($m['creator_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                                    <span class="masseur-table__sub"><?= htmlspecialchars(substr((string) ($m['created_at'] ?? ''), 0, 10), ENT_QUOTES, 'UTF-8') ?></span>
                                                </td>
                                                <td>
                                                    <form method="post" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" onsubmit="return confirm('確定刪除此技師？相關評論與評分將一併刪除。');">
                                                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="action" value="delete_masseur">
                                                        <input type="hidden" name="id" value="<?= $mid ?>">
                                                        <button type="submit" class="btn btn--danger btn--sm">刪除</button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php $pager($masseurList, 'masseur'); ?>
                        <?php endif; ?>
                    </div>
                    <?php else: ?>
                    <div class="masseur-tab-panel is-active" id="masseur-reviews" role="tabpanel" aria-labelledby="tab-btn-reviews">
                        <div class="masseur-toolbar">
                            <form method="get" action="masseurs.php" class="masseur-per-page">
                                <input type="hidden" name="tab" value="list">
                                <input type="hidden" name="list" value="reviews">
                                <input type="hidden" name="q" value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="mp" value="<?= (int) $masseurPage ?>">
                                <input type="hidden" name="mpp" value="<?= (int) $masseurPerPage ?>">
                                <input type="hidden" name="rp" value="1">
                                <label class="masseur-per-page__label">
                                    每頁
                                    <select name="rpp" onchange="this.form.submit()">
                                        <?php foreach ([20, 50, 100] as $n): ?>
                                            <option value="<?= $n ?>"<?= $reviewPerPage === $n ? ' selected' : '' ?>><?= $n ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                            </form>
                        </div>

                        <?php if ($reviewList['total'] > 0): ?>
                            <p class="masseur-range" role="status">
                                顯示第 <?= (int) $reviewList['from'] ?>–<?= (int) $reviewList['to'] ?> 筆
                                <?php if ($reviewList['total'] >= 200): ?>
                                    <span class="masseur-range__hint">· 長評論預設折疊，可展開編輯</span>
                                <?php endif; ?>
                            </p>
                            <?php $pager($reviewList, 'review'); ?>
                        <?php endif; ?>

                        <?php if ($recentReviews === []): ?>
                            <p class="masseur-empty">尚無評論。</p>
                        <?php else: ?>
                            <div class="masseur-scroll-table masseur-scroll-table--reviews" role="region" aria-label="評論列表表格" tabindex="0">
                                <table class="data-table masseur-table masseur-table--reviews">
                                    <thead>
                                        <tr><th>#</th><th>技師</th><th>會員</th><th>內容</th><th>日期</th><th>操作</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recentReviews as $rv): ?>
                                            <?php
                                            $rid = (int) $rv['id'];
                                            $body = (string) ($rv['body'] ?? '');
                                            $snippet = fate_admin_masseur_review_snippet($body);
                                            ?>
                                            <tr class="masseur-review-row<?= $snippet['truncated'] ? ' is-collapsed' : '' ?>">
                                                <td class="masseur-table__id"><?= $rid ?></td>
                                                <td><?= htmlspecialchars((string) ($rv['masseur_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                                <td><?= htmlspecialchars((string) ($rv['author_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                                <td class="masseur-review-cell">
                                                    <?php if ($snippet['truncated']): ?>
                                                        <p class="masseur-review-preview"><?= htmlspecialchars($snippet['preview'], ENT_QUOTES, 'UTF-8') ?></p>
                                                        <button type="button" class="btn-link masseur-review-expand" data-review-expand aria-expanded="false">展開全文</button>
                                                    <?php endif; ?>
                                                    <form method="post" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" class="masseur-review-form">
                                                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="action" value="update_review">
                                                        <input type="hidden" name="id" value="<?= $rid ?>">
                                                        <textarea name="body" rows="<?= $snippet['truncated'] ? 1 : 2 ?>" class="masseur-review-form__body"><?= htmlspecialchars($body, ENT_QUOTES, 'UTF-8') ?></textarea>
                                                        <button type="submit" class="btn btn--secondary btn--sm">存</button>
                                                    </form>
                                                    <?php if (!empty($rv['edited_by_admin'])): ?><span class="masseur-table__sub">（已編輯）</span><?php endif; ?>
                                                </td>
                                                <td class="masseur-table__meta"><?= htmlspecialchars(substr((string) ($rv['created_at'] ?? ''), 0, 10), ENT_QUOTES, 'UTF-8') ?></td>
                                                <td>
                                                    <form method="post" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" onsubmit="return confirm('確定刪除此評論？');">
                                                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="action" value="delete_review">
                                                        <input type="hidden" name="id" value="<?= $rid ?>">
                                                        <button type="submit" class="btn btn--danger btn--sm">刪除</button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php $pager($reviewList, 'review'); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
        $masseursJs = __DIR__ . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'masseurs.js';
        $masseursJsVer = is_file($masseursJs) ? (string) filemtime($masseursJs) : '1';
        ?>
        <script src="<?= htmlspecialchars(fate_admin_asset_url('static/masseurs.js'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($masseursJsVer, ENT_QUOTES, 'UTF-8') ?>"></script>
        <?php if ($adminProfileStatsEnabled): ?>
        <script src="<?= htmlspecialchars(fate_site_static_url('fate-masseur-profile-stats.js'), ENT_QUOTES, 'UTF-8') ?>?v=1" defer></script>
        <?php endif; ?>
<?php
fate_admin_layout_end();
