<?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_ncoin_history.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ncoin_settings.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ncoin_credit.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_rewards.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';

fate_admin_require_login();

$pageTitle = '站內貨幣設定/紀錄';
$ncoinForumInstalled = fate_forum_module_installed();

$ncoinCfg = fate_ncoin_settings();
$ncoinName = fate_ncoin_display_name();

$settingsMsgOk = '';
$settingsMsgBad = '';
$currencyMsgOk = '';
$currencyMsgBad = '';
$rewardsMsgOk = '';
$rewardsMsgBad = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'rewards_settings_save') {
    $csrfPost = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrfPost)) {
        $rewardsMsgBad = '工作階段逾期，請重新整理後再試。';
    } else {
        $r = fate_masseur_rewards_save([
            'revert_on_delete' => !empty($_POST['revert_on_delete']),
            'reward_create' => $_POST['reward_create'] ?? 0,
            'reward_review' => $_POST['reward_review'] ?? 0,
            'reward_like' => $_POST['reward_like'] ?? 0,
            'reward_tag' => $_POST['reward_tag'] ?? 0,
            'reward_crowd_store_closed' => $_POST['reward_crowd_store_closed'] ?? 0,
            'reward_crowd_store_renamed' => $_POST['reward_crowd_store_renamed'] ?? 0,
            'reward_crowd_masseur_left_store' => $_POST['reward_crowd_masseur_left_store'] ?? 0,
            'reward_store_recommend' => $_POST['reward_store_recommend'] ?? 0,
            'reward_store_mobile' => $_POST['reward_store_mobile'] ?? 0,
            'review_per_week' => $_POST['review_per_week'] ?? 1,
            'tag_reward_max_per_masseur' => $_POST['tag_reward_max_per_masseur'] ?? 5,
            'tag_reward_max_masseurs_per_day' => $_POST['tag_reward_max_masseurs_per_day'] ?? 10,
            'review_paid_enabled' => !empty($_POST['review_paid_enabled']),
            'review_paid_max_price' => $_POST['review_paid_max_price'] ?? 500,
            'review_paid_commission_pct' => $_POST['review_paid_commission_pct'] ?? 20,
            'review_paid_min_preview_chars' => $_POST['review_paid_min_preview_chars'] ?? 50,
            'review_paid_max_preview_chars' => $_POST['review_paid_max_preview_chars'] ?? 2000,
            'review_paid_default_preview_chars' => $_POST['review_paid_default_preview_chars'] ?? 200,
            'review_paid_min_body_chars' => $_POST['review_paid_min_body_chars'] ?? 500,
            'reward_weekly_recommend' => $_POST['reward_weekly_recommend'] ?? 0,
            'weekly_recommend_max_per_week' => $_POST['weekly_recommend_max_per_week'] ?? 10,
            'weekly_rank_limit' => $_POST['weekly_rank_limit'] ?? 10,
        ]);
        if ($r['ok']) {
            $rewardsMsgOk = '行為獎勵設定已儲存。';
        } else {
            $rewardsMsgBad = $r['error'] ?? '無法儲存獎勵設定。';
        }
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'currency_name_save') {
    $csrfPost = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrfPost)) {
        $currencyMsgBad = '工作階段逾期，請重新整理後再試。';
    } elseif (fate_ncoin_settings_save([
        'currency_name' => isset($_POST['currency_name']) && is_string($_POST['currency_name']) ? $_POST['currency_name'] : '',
    ])) {
        $currencyMsgOk = '站內貨幣名稱已儲存。';
        $ncoinCfg = fate_ncoin_settings();
        $ncoinName = fate_ncoin_display_name();
    } else {
        $currencyMsgBad = '設定儲存失敗，請確認 data/ 目錄可寫入。';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'transfer_settings_save') {
    $csrfPost = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrfPost)) {
        $settingsMsgBad = '工作階段逾期，請重新整理後再試。';
    } elseif (fate_ncoin_settings_save([
        'transfer_enabled' => isset($_POST['transfer_enabled']) && $_POST['transfer_enabled'] === '1',
        'transfer_fee_pct' => isset($_POST['transfer_fee_pct']) ? (int) $_POST['transfer_fee_pct'] : 0,
        'transfer_reserve' => isset($_POST['transfer_reserve']) ? (int) $_POST['transfer_reserve'] : 0,
    ])) {
        $settingsMsgOk = htmlspecialchars(fate_ncoin_display_name(), ENT_QUOTES, 'UTF-8') . '轉帳設定已儲存。';
        $ncoinName = fate_ncoin_display_name();
        $ncoinCfg = fate_ncoin_settings();
    } else {
        $settingsMsgBad = '設定儲存失敗，請確認 data/ 目錄可寫入。';
    }
}

$rewardsCfg = fate_masseur_rewards_settings();
$adminCsrf = fate_admin_csrf_token();

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

$grantMsgOk = '';
$grantMsgBad = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_grant') {
    $csrfPost = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrfPost)) {
        $grantMsgBad = '工作階段逾期，請重新整理後再試。';
    } else {
        $grantMemberId = isset($_POST['grant_member_id']) ? (int) $_POST['grant_member_id'] : 0;
        $grantAmount = isset($_POST['grant_amount']) ? (int) $_POST['grant_amount'] : 0;
        $grantNote = isset($_POST['grant_note']) && is_string($_POST['grant_note']) ? $_POST['grant_note'] : '';
        $adminId = isset($_SESSION['fate_admin_member_id']) ? (int) $_SESSION['fate_admin_member_id'] : 0;

        if ($pdo instanceof PDO) {
            $grantResult = fate_ncoin_admin_grant($pdo, $grantMemberId, $grantAmount, $grantNote, $adminId);
            if ($grantResult['ok']) {
                $grantMsgOk = '已成功發放 ' . number_format((int) $grantResult['amount']) . ' ' . htmlspecialchars($ncoinName, ENT_QUOTES, 'UTF-8') . '給 '
                    . htmlspecialchars((string) ($grantResult['member_label'] ?? '會員 #' . $grantMemberId), ENT_QUOTES, 'UTF-8')
                    . '（帳本 #' . (int) $grantResult['ledger_id'] . '）。';
            } else {
                $grantMsgBad = '發放失敗：' . htmlspecialchars((string) $grantResult['error'], ENT_QUOTES, 'UTF-8');
            }
        } else {
            $grantMsgBad = '資料庫連線失敗，無法發放。';
        }
    }
}

$keyword = isset($_GET['q']) && is_string($_GET['q']) ? trim($_GET['q']) : '';
$actionFilter = isset($_GET['action']) && is_string($_GET['action']) ? trim($_GET['action']) : '';
$actionLabels = fate_ncoin_action_labels();

$perPageOpt = (int) ($_GET['pp'] ?? 50);
$perPage = in_array($perPageOpt, [25, 50, 100], true) ? $perPageOpt : 50;
$page = isset($_GET['p']) ? max(1, (int) $_GET['p']) : 1;
$matchCount = $pdo instanceof PDO ? fate_ncoin_history_all_count($pdo, $keyword, $actionFilter) : 0;
$pageCount = max(1, (int) ceil($matchCount / $perPage));
if ($page > $pageCount) {
    $page = $pageCount;
}
$rows = $pdo instanceof PDO ? fate_ncoin_history_all($pdo, $keyword, $actionFilter, $perPage, ($page - 1) * $perPage) : [];
$totals = $pdo instanceof PDO ? fate_ncoin_history_totals($pdo) : ['earned' => 0, 'reverted' => 0, 'spent' => 0, 'net' => 0, 'count' => 0];

$from = $matchCount > 0 ? ($page - 1) * $perPage + 1 : 0;
$to = min($matchCount, $page * $perPage);
$dbOk = $pdo instanceof PDO && $dbErr === null;
$hasFilter = $keyword !== '' || $actionFilter !== '';
$ncoinNameEsc = htmlspecialchars($ncoinName, ENT_QUOTES, 'UTF-8');

$buildUrl = static function (?int $p = null, ?string $q = null, ?string $action = null, ?int $pp = null) use ($page, $keyword, $actionFilter, $perPage): string {
    $qs = [
        'p' => $p ?? $page,
        'pp' => $pp ?? $perPage,
    ];
    $kw = $q ?? $keyword;
    if ($kw !== '') {
        $qs['q'] = $kw;
    }
    $act = $action ?? $actionFilter;
    if ($act !== '') {
        $qs['action'] = $act;
    }

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

fate_admin_layout_start(['page' => $pageTitle, 'active' => 'ncoin', 'body_class' => 'admin-body--ncoin']);
?>
        <div class="ncoin-admin">
            <header class="ncoin-hero" aria-label="<?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?>">
                <div class="ncoin-hero__glow" aria-hidden="true"></div>
                <div class="ncoin-hero__inner">
                    <div class="ncoin-hero__lead">
                        <span class="ncoin-hero__icon" aria-hidden="true"><?= fate_admin_dashboard_icon('ncoin') ?></span>
                        <div class="ncoin-hero__copy">
                            <h1 class="ncoin-hero__title"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                            <p class="ncoin-hero__sub"><?= $ncoinNameEsc ?>轉帳、行為獎勵、手動發放與全站帳本紀錄（<code>fate_reward_ledger</code>）。</p>
                        </div>
                    </div>
                    <span class="sync-pill<?= $dbOk ? ' sync-pill--ok' : ' sync-pill--bad' ?>">
                        <?= $dbOk ? number_format((int) $totals['count']) . ' 筆紀錄' : '資料庫異常' ?>
                    </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; ?>

            <section class="sync-panel ncoin-settings-panel" aria-label="站內貨幣名稱">
                <h2 class="ncoin-settings-panel__title">站內貨幣名稱</h2>
                <p class="ncoin-settings-panel__hint">自訂前台／後台顯示的貨幣名稱（例如「星幣」「點數」）。留空或還原預設時為「N 幣」。資料庫欄位仍為 <code>ncoin</code>，僅改變使用者看見的文字。</p>
                <?php if ($currencyMsgOk !== ''): ?>
                    <div class="sync-banner sync-banner--ok" role="status"><?= htmlspecialchars($currencyMsgOk, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <?php if ($currencyMsgBad !== ''): ?>
                    <div class="sync-banner sync-banner--bad" role="alert"><?= htmlspecialchars($currencyMsgBad, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <form method="post" action="ncoin.php" class="ncoin-settings-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($adminCsrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="currency_name_save">
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">顯示名稱</span>
                        <input type="text" name="currency_name" maxlength="20" required value="<?= $ncoinNameEsc ?>" placeholder="N 幣">
                        <span class="ncoin-settings-form__hint">最多 20 字；儲存後全站介面（側欄、會員頁、論壇獎勵等）會同步更新。</span>
                    </label>
                    <button type="submit" class="sync-btn">儲存貨幣名稱</button>
                </form>
            </section>

            <section class="sync-panel ncoin-settings-panel" aria-label="行為獎勵設定">
                <h2 class="ncoin-settings-panel__title">行為獎勵設定</h2>
                <p class="ncoin-settings-panel__hint">推薦技師相關獎勵於會員操作後即時發放；推薦店家獎勵僅在管理員<strong>審核通過</strong>時發放（見下方「推薦店家獎勵」）。推薦技師功能開關請至「推薦技師 → 功能設定」。</p>
                <?php if ($rewardsMsgOk !== ''): ?>
                    <div class="sync-banner sync-banner--ok" role="status"><?= htmlspecialchars($rewardsMsgOk, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <?php if ($rewardsMsgBad !== ''): ?>
                    <div class="sync-banner sync-banner--bad" role="alert"><?= htmlspecialchars($rewardsMsgBad, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <form method="post" action="ncoin.php" class="ncoin-settings-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($adminCsrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="rewards_settings_save">

                    <h3 class="ncoin-rewards-subtitle">推薦技師</h3>
                    <p class="ncoin-settings-panel__hint ncoin-settings-panel__hint--tight">建檔、評論、點讚、標籤點選完成後立即發放 <?= $ncoinNameEsc ?>（若該行為有設定獎勵金額）。</p>
                    <div class="masseur-rewards-grid ncoin-rewards-grid">
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">推薦技師建檔（<?= $ncoinNameEsc ?>）</span>
                            <input type="number" name="reward_create" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_create'] ?? 0) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">文字評論（<?= $ncoinNameEsc ?>）</span>
                            <input type="number" name="reward_review" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_review'] ?? 0) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">同會員每週可評論次數（同一技師）</span>
                            <input type="number" name="review_per_week" min="1" max="50" value="<?= (int) ($rewardsCfg['review_per_week'] ?? 1) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">技師點讚（<?= $ncoinNameEsc ?>）</span>
                            <input type="number" name="reward_like" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_like'] ?? 0) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">本週推薦技師（<?= $ncoinNameEsc ?>）</span>
                            <input type="number" name="reward_weekly_recommend" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_weekly_recommend'] ?? 0) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">同會員每週可推薦技師數上限</span>
                            <input type="number" name="weekly_recommend_max_per_week" min="1" max="50" value="<?= (int) ($rewardsCfg['weekly_recommend_max_per_week'] ?? 10) ?>">
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">週榜／側欄 TOP 筆數</span>
                            <input type="number" name="weekly_rank_limit" min="1" max="50" value="<?= (int) ($rewardsCfg['weekly_rank_limit'] ?? 10) ?>">
                        </label>
                    </div>

                    <div class="ncoin-review-paid-panel">
                        <label class="ncoin-review-paid-panel__toggle">
                            <input type="checkbox" name="review_paid_enabled" value="1"<?= !empty($rewardsCfg['review_paid_enabled']) ? ' checked' : '' ?>>
                            <span class="ncoin-review-paid-panel__toggle-label">開放技師評論付費文</span>
                        </label>
                        <p class="ncoin-settings-panel__hint ncoin-settings-panel__hint--tight ncoin-review-paid-panel__hint">
                            會員發表評論時可勾選「設為付費評論」以 <?= $ncoinNameEsc ?>販售全文；需達「啟用付費最少字數」才可勾選（與論壇 Summernote 編輯器相同）。
                        </p>
                        <div class="masseur-rewards-grid ncoin-rewards-grid ncoin-review-paid-panel__grid">
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">售價上限（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="review_paid_max_price" min="1" max="100000" value="<?= (int) ($rewardsCfg['review_paid_max_price'] ?? 500) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">平台抽成（%）</span>
                                <input type="number" name="review_paid_commission_pct" min="0" max="100" value="<?= (int) ($rewardsCfg['review_paid_commission_pct'] ?? 20) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">啟用付費最少字數</span>
                                <input type="number" name="review_paid_min_body_chars" min="0" max="50000" value="<?= (int) ($rewardsCfg['review_paid_min_body_chars'] ?? 500) ?>">
                                <span class="ncoin-settings-form__hint">正文純文字未達此字數時，前台無法勾選付費。</span>
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">預讀字數下限</span>
                                <input type="number" name="review_paid_min_preview_chars" min="0" max="5000" value="<?= (int) ($rewardsCfg['review_paid_min_preview_chars'] ?? 50) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">預讀字數上限</span>
                                <input type="number" name="review_paid_max_preview_chars" min="50" max="10000" value="<?= (int) ($rewardsCfg['review_paid_max_preview_chars'] ?? 2000) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">預設預讀字數</span>
                                <input type="number" name="review_paid_default_preview_chars" min="0" max="5000" value="<?= (int) ($rewardsCfg['review_paid_default_preview_chars'] ?? 200) ?>">
                            </label>
                        </div>
                    </div>

                    <div class="ncoin-rewards-store-block">
                        <h3 class="ncoin-rewards-subtitle">技師標籤獎勵</h3>
                        <p class="ncoin-settings-panel__hint ncoin-settings-panel__hint--tight">
                            會員<strong>點選標籤次數不受限制</strong>；下列僅限制 <?= $ncoinNameEsc ?> 發放，不影響標籤紀錄與統計。
                        </p>
                        <div class="masseur-rewards-grid ncoin-rewards-grid">
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">每次標籤點選（<?= $ncoinNameEsc ?>）</span>
                            <input type="number" name="reward_tag" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_tag'] ?? 0) ?>">
                            <span class="ncoin-settings-form__hint">填 0 表示點選標籤不發 <?= $ncoinNameEsc ?>。</span>
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">同一技師可獲標籤獎勵次數</span>
                            <input type="number" name="tag_reward_max_per_masseur" min="0" max="50" value="<?= (int) ($rewardsCfg['tag_reward_max_per_masseur'] ?? 5) ?>">
                            <span class="ncoin-settings-form__hint">0＝不限制；取消已點標籤且扣回獎勵後釋出名額。</span>
                        </label>
                        <label class="ncoin-settings-form__field">
                            <span class="ncoin-settings-form__label">每日可獲標籤獎勵的技師數</span>
                            <input type="number" name="tag_reward_max_masseurs_per_day" min="0" max="100" value="<?= (int) ($rewardsCfg['tag_reward_max_masseurs_per_day'] ?? 10) ?>">
                            <span class="ncoin-settings-form__hint">0＝不限制；每日 00:00 重置；當日已在某技師領過獎勵，後續標籤不另占新技師名額。</span>
                        </label>
                        </div>
                    </div>

                    <div class="ncoin-rewards-store-block">
                        <h3 class="ncoin-rewards-subtitle">會員回報獎勵</h3>
                        <p class="ncoin-settings-panel__hint ncoin-settings-panel__hint--tight">
                            會員於探索列表、店家頁<?= $ncoinForumInstalled ? '或<strong>討論區</strong>' : '' ?>回報店況／技師狀態後立即發放；取消回報時若已開啟「扣回」設定，將扣回該次 <?= $ncoinNameEsc ?>。
                            不受「推薦技師」功能開關影響。
                        </p>
                        <div class="masseur-rewards-grid ncoin-rewards-grid ncoin-rewards-grid--store">
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">回報店家歇業（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="reward_crowd_store_closed" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_crowd_store_closed'] ?? 0) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">回報店家更名（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="reward_crowd_store_renamed" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_crowd_store_renamed'] ?? 0) ?>">
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">回報技師已離店（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="reward_crowd_masseur_left_store" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_crowd_masseur_left_store'] ?? 0) ?>">
                            </label>
                        </div>
                    </div>

                    <div class="ncoin-rewards-store-block">
                        <h3 class="ncoin-rewards-subtitle">推薦店家獎勵</h3>
                        <p class="ncoin-settings-panel__hint ncoin-settings-panel__hint--tight">
                            會員於前台「定點店家」或「非定點服務」送審後<strong>不會</strong>立即發幣；
                            須至後台 <a href="approve_stores.php">審核推薦店家</a> 按「核准」通過後，才依下列金額發放給推薦人（每筆店家僅發一次）。
                        </p>
                        <div class="masseur-rewards-grid ncoin-rewards-grid ncoin-rewards-grid--store">
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">定點店家核准（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="reward_store_recommend" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_store_recommend'] ?? 0) ?>">
                                <span class="ncoin-settings-form__hint">有完整地址的定點店家推薦。</span>
                            </label>
                            <label class="ncoin-settings-form__field">
                                <span class="ncoin-settings-form__label">非定點服務核准（<?= $ncoinNameEsc ?>）</span>
                                <input type="number" name="reward_store_mobile" min="0" max="100000" value="<?= (int) ($rewardsCfg['reward_store_mobile'] ?? 0) ?>">
                                <span class="ncoin-settings-form__hint">不公開路名地址的服務類推薦。</span>
                            </label>
                        </div>
                    </div>

                    <label class="ncoin-settings-form__row">
                        <input type="checkbox" name="revert_on_delete" value="1"<?= !empty($rewardsCfg['revert_on_delete']) ? ' checked' : '' ?>>
                        <span>管理員刪除技師／評論／標籤點選／會員回報／已核准推薦店家時，<strong>扣回</strong>當初發放的 <?= $ncoinNameEsc ?></span>
                    </label>
                    <button type="submit" class="sync-btn">儲存獎勵設定</button>
                </form>
            </section>

            <section class="sync-panel ncoin-settings-panel" aria-label="<?= $ncoinNameEsc ?>轉帳設定">
                <h2 class="ncoin-settings-panel__title">會員轉帳設定</h2>
                <p class="ncoin-settings-panel__hint">會員可將 <?= $ncoinNameEsc ?>轉給其他會員；留底金額同時為啟用門檻與不可轉出之保留額。關閉後會員仍可看見「<?= $ncoinNameEsc ?>轉帳」分頁，但無法送出轉帳。</p>
                <?php if ($settingsMsgOk !== ''): ?>
                    <div class="sync-banner sync-banner--ok" role="status"><?= htmlspecialchars($settingsMsgOk, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <?php if ($settingsMsgBad !== ''): ?>
                    <div class="sync-banner sync-banner--bad" role="alert"><?= htmlspecialchars($settingsMsgBad, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <form method="post" action="ncoin.php" class="ncoin-settings-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($adminCsrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="transfer_settings_save">
                    <label class="ncoin-settings-form__row">
                        <input type="checkbox" name="transfer_enabled" value="1"<?= !empty($ncoinCfg['transfer_enabled']) ? ' checked' : '' ?>>
                        <span>開啟會員 <?= $ncoinNameEsc ?>轉帳</span>
                    </label>
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">轉帳手續費（%）</span>
                        <input type="number" name="transfer_fee_pct" min="0" max="100" step="1" required value="<?= (int) ($ncoinCfg['transfer_fee_pct'] ?? 0) ?>">
                        <span class="ncoin-settings-form__hint">自轉出金額內扣除；例如 5 表示轉 100 時對方收 95。</span>
                    </label>
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">留底金額（<?= $ncoinNameEsc ?>）</span>
                        <input type="number" name="transfer_reserve" min="0" max="9999999" step="1" required value="<?= (int) ($ncoinCfg['transfer_reserve'] ?? 100) ?>">
                        <span class="ncoin-settings-form__hint">餘額須達此門檻才可轉帳，且此金額不可轉出（僅能自用）。</span>
                    </label>
                    <button type="submit" class="sync-btn">儲存轉帳設定</button>
                </form>
            </section>

            <section class="sync-panel ncoin-settings-panel" aria-label="管理員手動發放 <?= $ncoinNameEsc ?>">
                <h2 class="ncoin-settings-panel__title">手動發放 <?= $ncoinNameEsc ?></h2>
                <p class="ncoin-settings-panel__hint">管理員可直接對指定會員發放 <?= $ncoinNameEsc ?>（無中生有），不受留底與手續費限制。發放紀錄會記入帳本（項目：管理員發放）。</p>
                <?php if ($grantMsgOk !== ''): ?>
                    <div class="sync-banner sync-banner--ok" role="status"><?= $grantMsgOk ?></div>
                <?php endif; ?>
                <?php if ($grantMsgBad !== ''): ?>
                    <div class="sync-banner sync-banner--bad" role="alert"><?= $grantMsgBad ?></div>
                <?php endif; ?>
                <form method="post" action="ncoin.php" class="ncoin-settings-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($adminCsrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="admin_grant">
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">會員編號（ID）</span>
                        <input type="number" name="grant_member_id" min="1" step="1" required placeholder="輸入會員 ID">
                        <span class="ncoin-settings-form__hint">可至「會員管理」查詢會員編號。</span>
                    </label>
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">發放金額（<?= $ncoinNameEsc ?>）</span>
                        <input type="number" name="grant_amount" min="1" max="9999999" step="1" required placeholder="輸入金額">
                        <span class="ncoin-settings-form__hint">將直接加入該會員的 <?= $ncoinNameEsc ?>餘額，單次上限 9,999,999。</span>
                    </label>
                    <label class="ncoin-settings-form__field">
                        <span class="ncoin-settings-form__label">備註（選填）</span>
                        <input type="text" name="grant_note" maxlength="120" placeholder="例如：活動獎勵、補償、測試">
                        <span class="ncoin-settings-form__hint">會顯示在帳本紀錄的備註欄。</span>
                    </label>
                    <button type="submit" class="sync-btn" onclick="return confirm('確定要發放 <?= $ncoinNameEsc ?>嗎？此操作不可自動撤銷。');">發放 <?= $ncoinNameEsc ?></button>
                </form>
            </section>

            <div class="ncoin-stats" aria-label="全站統計">
                <div class="ncoin-stat">
                    <span class="ncoin-stat__label">紀錄筆數</span>
                    <span class="ncoin-stat__value"><?= number_format((int) $totals['count']) ?></span>
                </div>
                <div class="ncoin-stat ncoin-stat--earn">
                    <span class="ncoin-stat__label">累計發放</span>
                    <span class="ncoin-stat__value">+<?= number_format((int) $totals['earned']) ?></span>
                </div>
                <?php if (($totals['spent'] ?? 0) > 0): ?>
                <div class="ncoin-stat ncoin-stat--spent">
                    <span class="ncoin-stat__label">累計支出</span>
                    <span class="ncoin-stat__value">-<?= number_format((int) $totals['spent']) ?></span>
                </div>
                <?php endif; ?>
                <div class="ncoin-stat ncoin-stat--revert">
                    <span class="ncoin-stat__label">累計扣回</span>
                    <span class="ncoin-stat__value">-<?= number_format((int) $totals['reverted']) ?></span>
                </div>
                <div class="ncoin-stat ncoin-stat--net">
                    <span class="ncoin-stat__label">淨發放</span>
                    <span class="ncoin-stat__value"><?= number_format((int) $totals['net']) ?></span>
                </div>
            </div>

            <section class="sync-panel ncoin-list-panel" aria-label="站內貨幣紀錄列表">
                    <div class="ncoin-toolbar">
                        <form method="get" action="ncoin.php" class="ncoin-search">
                            <input type="hidden" name="p" value="1">
                            <input type="hidden" name="pp" value="<?= (int) $perPage ?>">
                            <input type="search" name="q" value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>" placeholder="搜尋會員名稱或 ID" class="ncoin-search__input">
                            <select name="action" class="ncoin-search__select">
                                <option value="">全部項目</option>
                                <?php foreach ($actionLabels as $ak => $al): ?>
                                    <option value="<?= htmlspecialchars($ak, ENT_QUOTES, 'UTF-8') ?>"<?= $actionFilter === $ak ? ' selected' : '' ?>><?= htmlspecialchars($al, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="sync-btn">查詢</button>
                            <?php if ($hasFilter): ?>
                                <a href="ncoin.php" class="btn btn--ghost">清除</a>
                            <?php endif; ?>
                        </form>
                        <form method="get" action="ncoin.php" class="ncoin-per-page">
                            <input type="hidden" name="q" value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="action" value="<?= htmlspecialchars($actionFilter, ENT_QUOTES, 'UTF-8') ?>">
                            <input type="hidden" name="p" value="1">
                            <label class="ncoin-per-page__label">
                                每頁
                                <select name="pp" onchange="this.form.submit()">
                                    <?php foreach ([25, 50, 100] as $n): ?>
                                        <option value="<?= $n ?>"<?= $perPage === $n ? ' selected' : '' ?>><?= $n ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                        </form>
                    </div>

                    <?php if ($rows === []): ?>
                        <p class="ncoin-empty">查無紀錄<?= $hasFilter ? '（無符合篩選結果）' : '' ?>。</p>
                    <?php else: ?>
                        <p class="ncoin-range" role="status">
                            顯示第 <?= number_format($from) ?>–<?= number_format($to) ?> 筆，共 <?= number_format($matchCount) ?> 筆
                        </p>
                        <?php if ($pageCount > 1): ?>
                            <nav class="pagination ncoin-pager" aria-label="站內貨幣紀錄分頁">
                                <?php if ($page > 1): ?>
                                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildUrl($page - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                                <?php endif; ?>
                                <span class="ncoin-pager__meta">第 <?= $page ?>／<?= $pageCount ?> 頁</span>
                                <?php if ($page < $pageCount): ?>
                                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildUrl($page + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                                <?php endif; ?>
                            </nav>
                        <?php endif; ?>

                        <div class="ncoin-scroll-table" role="region" aria-label="站內貨幣紀錄表格" tabindex="0">
                            <table class="data-table ncoin-table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>時間</th>
                                        <th>會員</th>
                                        <th>項目</th>
                                        <th>備註</th>
                                        <th class="ncoin-table__amount"><?= $ncoinNameEsc ?></th>
                                        <th>入帳</th>
                                        <th>狀態</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rows as $r): ?>
                                        <?php $reverted = !empty($r['reverted']); ?>
                                        <tr<?= $reverted ? ' class="ncoin-row--reverted"' : '' ?>>
                                            <td class="ncoin-table__id"><?= (int) ($r['id'] ?? 0) ?></td>
                                            <td class="ncoin-table__time"><?= htmlspecialchars(substr((string) ($r['created_at'] ?? ''), 0, 16), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td>
                                                <span class="ncoin-table__primary"><?= htmlspecialchars((string) ($r['member_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                                <span class="ncoin-table__sub">#<?= (int) ($r['member_id'] ?? 0) ?></span>
                                            </td>
                                            <td><?= htmlspecialchars(fate_ncoin_action_label((string) ($r['action'] ?? '')), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td class="ncoin-table__note"><?= htmlspecialchars((string) ($r['note'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td class="ncoin-table__amount ncoin-table__amount--<?= htmlspecialchars(fate_ncoin_ledger_amount_kind($r), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars(fate_ncoin_format_ledger_amount($r), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><span class="ncoin-table__sub"><?= htmlspecialchars(fate_ncoin_applied_label($r), ENT_QUOTES, 'UTF-8') ?></span></td>
                                            <td>
                                                <?php if ($reverted): ?>
                                                    <span class="ncoin-badge ncoin-badge--reverted">已扣回</span>
                                                    <span class="ncoin-table__sub"><?= htmlspecialchars(substr((string) ($r['reverted_at'] ?? ''), 0, 16), ENT_QUOTES, 'UTF-8') ?></span>
                                                <?php else: ?>
                                                    <span class="ncoin-badge ncoin-badge--ok">有效</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($pageCount > 1): ?>
                            <nav class="pagination ncoin-pager" aria-label="站內貨幣紀錄分頁">
                                <?php if ($page > 1): ?>
                                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildUrl($page - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                                <?php endif; ?>
                                <span class="ncoin-pager__meta">第 <?= $page ?>／<?= $pageCount ?> 頁</span>
                                <?php if ($page < $pageCount): ?>
                                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildUrl($page + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                                <?php endif; ?>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </section>
        </div>
<?php
fate_admin_layout_end();
