<?php

use App\Http\Controllers\Admin\AdminAuthController;
use App\Http\Controllers\AdminCommandController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ChangelogController;
use App\Http\Controllers\ChatBotController;
use App\Http\Controllers\ChatController;
use App\Http\Controllers\FeedbackController;
use App\Http\Controllers\FishingController;
use App\Http\Controllers\PasswordResetController;
use App\Http\Controllers\RoomController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

// 聊天室首页 (即登录/注册页面)
Route::get('/', function () {
    if (Auth::check()) {
        // 通过隐藏入口登录的站长，首页统一回到后台而不是聊天室大厅
        if (Auth::id() === 1 && session('admin_login_via_hidden')) {
            return redirect()->route('admin.dashboard');
        }

        return redirect()->route('rooms.index');
    }

    // 获取可用房间列表供登录页选择（原版风格）
    $rooms = \App\Models\Room::orderBy('id')->get();

    return view('index', compact('rooms'));
})->name('home');

// 站长隐藏登录入口（仅 id=1 可使用，成功后直接进入后台控制台）
Route::get('/lkddi', [AdminAuthController::class, 'create'])->name('admin.login');
Route::post('/lkddi', [AdminAuthController::class, 'store'])
    ->middleware('throttle:admin-hidden-login')
    ->name('admin.login.store');

// 处理登录/自动注册请求
Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:chat-login')
    ->name('login.post');

// 前台邮箱找回密码页面与提交流程
Route::middleware('guest')->group(function () {
    Route::get('/forgot-password', [PasswordResetController::class, 'create'])->name('password.request');
    Route::post('/forgot-password', [PasswordResetController::class, 'storeLink'])->name('password.email');
    Route::get('/reset-password/{token}', [PasswordResetController::class, 'edit'])->name('password.reset');
    Route::post('/reset-password', [PasswordResetController::class, 'update'])->name('password.update');
});

// 处理退出登录
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// 登录失效后用于收口离场清理的签名地址，不依赖当前会话。
Route::get('/room/{id}/leave-expired/{user}', [ChatController::class, 'expiredLeave'])
    ->middleware('signed')
    ->name('chat.leave.expired');

// 聊天室系统内部路由 (需要鉴权)
Route::middleware(['chat.auth'])->group(function () {
    // ---- 第六阶段：大厅与房间管理 ----
    Route::get('/guide', fn () => view('rooms.guide'))->name('guide');
    Route::get('/vip-center', [\App\Http\Controllers\VipCenterController::class, 'index'])->name('vip.center');
    Route::put('/vip-center/presence-settings', [\App\Http\Controllers\VipCenterController::class, 'updatePresenceSettings'])->name('vip.center.presence.update');

    // ---- VIP 在线支付 ----
    Route::post('/vip/payment', [\App\Http\Controllers\VipPaymentController::class, 'store'])->name('vip.payment.store');
    Route::get('/rooms', [RoomController::class, 'index'])->name('rooms.index');
    Route::post('/rooms', [RoomController::class, 'store'])->name('rooms.store');
    Route::put('/rooms/{id}', [RoomController::class, 'update'])->name('rooms.update');
    Route::delete('/rooms/{id}', [RoomController::class, 'destroy'])->name('rooms.destroy');
    Route::post('/rooms/{id}/transfer', [RoomController::class, 'transfer'])->name('rooms.transfer');

    // ═══════════════════════════════════════════════════════════════════
    // 排行榜系统 (风云榜、土豪榜等)
    // ═══════════════════════════════════════════════════════════════════
    Route::get('/leaderboard', [\App\Http\Controllers\LeaderboardController::class, 'index'])->name('leaderboard.index');
    Route::get('/leaderboard/today', [\App\Http\Controllers\LeaderboardController::class, 'todayIndex'])->name('leaderboard.today');

    // ═══════════════════════════════════════════════════════════════════
    // 邀请排行达人榜
    // ═══════════════════════════════════════════════════════════════════
    Route::get('/invites/leaderboard', [\App\Http\Controllers\InviteController::class, 'leaderboard'])->name('invite.leaderboard');

    // ═══════════════════════════════════════════════════════════════════用户个人积分流水日志（查询自己的经验/金币/魅力历史）
    Route::get('/my/currency-logs', [\App\Http\Controllers\LeaderboardController::class, 'myLogs'])->name('currency.my-logs');

    // ---- 勤务台（展示四榜）----
    Route::get('/duty-hall', [\App\Http\Controllers\DutyHallController::class, 'index'])->name('duty-hall.index');

    // ---- 第十阶段：站内信与留言板系统 ----
    Route::get('/guestbook', [\App\Http\Controllers\GuestbookController::class, 'index'])->name('guestbook.index');
    Route::post('/guestbook', [\App\Http\Controllers\GuestbookController::class, 'store'])->middleware('throttle:10,1')->name('guestbook.store');
    Route::delete('/guestbook/{id}', [\App\Http\Controllers\GuestbookController::class, 'destroy'])->name('guestbook.destroy');

    // ---- 第七阶段：用户资料与特权管理 ----
    Route::get('/user/{username}', [UserController::class, 'show'])->name('user.show');
    Route::put('/user/profile', [UserController::class, 'updateProfile'])->name('user.update_profile');
    Route::put('/user/chat-preferences', [UserController::class, 'updateChatPreferences'])->name('user.update_chat_preferences');
    Route::put('/user/daily-status', [UserController::class, 'updateDailyStatus'])->name('user.update_daily_status');
    Route::get('/daily-sign-in/status', [\App\Http\Controllers\DailySignInController::class, 'status'])->name('daily-sign-in.status');
    Route::get('/daily-sign-in/calendar', [\App\Http\Controllers\DailySignInController::class, 'calendar'])->name('daily-sign-in.calendar');
    Route::post('/daily-sign-in/claim', [\App\Http\Controllers\DailySignInController::class, 'claim'])->name('daily-sign-in.claim');
    Route::post('/daily-sign-in/makeup', [\App\Http\Controllers\DailySignInController::class, 'makeup'])->name('daily-sign-in.makeup');
    Route::post('/user/generate-wechat-code', [UserController::class, 'generateWechatCode'])->name('user.generate_wechat_code');
    Route::post('/user/unbind-wechat', [UserController::class, 'unbindWechat'])->name('user.unbind_wechat');
    Route::post('/user/send-email-code', [\App\Http\Controllers\Api\VerificationController::class, 'sendEmailCode'])->name('user.send_email_code');
    Route::put('/user/password', [UserController::class, 'changePassword'])->name('user.update_password');
    Route::post('/user/{username}/kick', [UserController::class, 'kick'])->name('user.kick');
    Route::post('/user/{username}/mute', [UserController::class, 'mute'])->name('user.mute');
    Route::post('/user/{username}/ban', [UserController::class, 'ban'])->name('user.ban');
    Route::post('/user/{username}/banip', [UserController::class, 'banIp'])->name('user.banip');

    // ---- 好友系统 ----
    Route::get('/friends', [\App\Http\Controllers\FriendController::class, 'index'])->name('friend.index');
    Route::get('/friend/{username}/status', [\App\Http\Controllers\FriendController::class, 'status'])->name('friend.status');
    Route::post('/friend/{username}/add', [\App\Http\Controllers\FriendController::class, 'addFriend'])->name('friend.add');
    Route::delete('/friend/{username}/remove', [\App\Http\Controllers\FriendController::class, 'removeFriend'])->name('friend.remove');

    // ── 婚姻系统（前台）──────────────────────────────────────────────
    Route::prefix('marriage')->name('marriage.')->group(function () {
        // 全站已婚列表
        Route::get('/list', [\App\Http\Controllers\MarriageController::class, 'list'])->name('list');
        // 查询当前用户婚姻状态
        Route::get('/status', [\App\Http\Controllers\MarriageController::class, 'status'])->name('status');
        // 查询目标用户婚姻信息（名片用）
        Route::get('/target', [\App\Http\Controllers\MarriageController::class, 'targetStatus'])->name('target-status');
        // 当前用户持有的戒指列表
        Route::get('/rings', [\App\Http\Controllers\MarriageController::class, 'myRings'])->name('rings');
        // 发起求婚
        Route::post('/propose', [\App\Http\Controllers\MarriageController::class, 'propose'])->name('propose');
        // 接受/拒绝求婚
        Route::post('/{marriage}/accept', [\App\Http\Controllers\MarriageController::class, 'accept'])->name('accept');
        Route::post('/{marriage}/reject', [\App\Http\Controllers\MarriageController::class, 'reject'])->name('reject');
        // 申请离婚（type: mutual|forced）
        Route::post('/{marriage}/divorce', [\App\Http\Controllers\MarriageController::class, 'divorce'])->name('divorce');
        // 离婚惩罚配置查询（前端展示风险提示用）
        Route::get('/divorce-config', [\App\Http\Controllers\MarriageController::class, 'divorceConfig'])->name('divorce-config');
        // 确认协议离婚
        Route::post('/{marriage}/confirm-divorce', [\App\Http\Controllers\MarriageController::class, 'confirmDivorce'])->name('confirm-divorce');
        // 拒绝离婚申请（被申请方选择不同意→弹强制离婚）
        Route::post('/{marriage}/reject-divorce', [\App\Http\Controllers\MarriageController::class, 'rejectDivorce'])->name('reject-divorce');
    });

    // ── 婚礼系统（前台）──────────────────────────────────────────────
    Route::prefix('wedding')->name('wedding.')->group(function () {
        // 婚礼档位列表
        Route::get('/tiers', [\App\Http\Controllers\WeddingController::class, 'tiers'])->name('tiers');
        // 设置并发起婚礼
        Route::post('/{marriage}/setup', [\App\Http\Controllers\WeddingController::class, 'setup'])->name('setup');
        // 领取婚礼红包
        Route::post('/ceremony/{ceremony}/claim', [\App\Http\Controllers\WeddingController::class, 'claim'])->name('claim');
        // 查询是否有待领取红包（单个婚礼）
        Route::get('/ceremony/{ceremony}/envelope', [\App\Http\Controllers\WeddingController::class, 'envelopeStatus'])->name('envelope-status');
        // 查询当前用户所有待领取婚礼红包（页面加载时恢复按钮）
        Route::get('/pending-envelopes', [\App\Http\Controllers\WeddingController::class, 'pendingEnvelopes'])->name('pending-envelopes');
    });

    // ── 节日福利（前台）──────────────────────────────────────────────
    Route::prefix('holiday')->name('holiday.')->group(function () {
        // 领取指定发放批次的节日福利红包。
        Route::post('/runs/{run}/claim', [\App\Http\Controllers\HolidayController::class, 'claim'])->name('claim');
        // 查询当前用户在某个发放批次中的领取状态。
        Route::get('/runs/{run}/status', [\App\Http\Controllers\HolidayController::class, 'status'])->name('status');
    });

    // ── 百家乐（前台）────────────────────────────────────────────────
    Route::prefix('baccarat')->name('baccarat.')->group(function () {
        Route::get('/current', [\App\Http\Controllers\BaccaratController::class, 'currentRound'])->name('current');
        Route::post('/bet', [\App\Http\Controllers\BaccaratController::class, 'bet'])->name('bet');
        Route::get('/history', [\App\Http\Controllers\BaccaratController::class, 'history'])->name('history');
    });

    // ── 百家乐买单活动（前台）───────────────────────────────────────
    Route::prefix('baccarat-loss-cover')->name('baccarat-loss-cover.')->group(function () {
        Route::get('/summary', [\App\Http\Controllers\BaccaratLossCoverController::class, 'summary'])->name('summary');
        Route::get('/history', [\App\Http\Controllers\BaccaratLossCoverController::class, 'history'])->name('history');
        Route::post('/{event}/claim', [\App\Http\Controllers\BaccaratLossCoverController::class, 'claim'])->name('claim');
    });

    // ── 老虎机（前台）────────────────────────────────────────────────
    Route::prefix('slot')->name('slot.')->group(function () {
        // 获取配置及今日剩余次数
        Route::get('/info', [\App\Http\Controllers\SlotMachineController::class, 'info'])->name('info');
        // 执行一次转动
        Route::post('/spin', [\App\Http\Controllers\SlotMachineController::class, 'spin'])->name('spin');
        // 个人历史记录
        Route::get('/history', [\App\Http\Controllers\SlotMachineController::class, 'history'])->name('history');
    });

    // ── 神秘箱子（前台）──────────────────────────────────────────────
    Route::prefix('mystery-box')->name('mystery-box.')->group(function () {
        // 查询当前可领取的箱子（前端轮询/显示悬浮提示用）
        Route::get('/status', [\App\Http\Controllers\MysteryBoxController::class, 'status'])->name('status');
        // 用户发送暗号领取箱子
        Route::post('/claim', [\App\Http\Controllers\MysteryBoxController::class, 'claim'])->name('claim');
    });

    // ── 赛马竞猜（前台）─────────────────────────────────────────
    Route::prefix('horse-race')->name('horse-race.')->group(function () {
        // 获取当前赛事信息（马匹、注池、赔率）
        Route::get('/current', [\App\Http\Controllers\HorseRaceController::class, 'currentRace'])->name('current');
        // 提交下注
        Route::post('/bet', [\App\Http\Controllers\HorseRaceController::class, 'bet'])->name('bet');
        // 最近10场历史记录
        Route::get('/history', [\App\Http\Controllers\HorseRaceController::class, 'history'])->name('history');
    });

    // ── 神秘占卜（前台）─────────────────────────────────────────
    Route::prefix('fortune')->name('fortune.')->group(function () {
        // 查询今日占卜状态（已占卜签文 / 剩余免费次数）
        Route::get('/today', [\App\Http\Controllers\FortuneTellingController::class, 'todayStatus'])->name('today');
        // 执行占卜（免费或付费）
        Route::post('/tell', [\App\Http\Controllers\FortuneTellingController::class, 'tell'])->name('tell');
        // 个人历史记录
        Route::get('/history', [\App\Http\Controllers\FortuneTellingController::class, 'history'])->name('history');
    });

    // ── 双色球彩票（前台）──────────────────────────────────────
    Route::prefix('lottery')->name('lottery.')->group(function () {
        // 当期状态：奖池金额 / 剩余购票时间 / 我的购票
        Route::get('/current', [\App\Http\Controllers\LotteryController::class, 'current'])->name('current');
        // 购票（自选或机选）
        Route::post('/buy', [\App\Http\Controllers\LotteryController::class, 'buy'])->name('buy');
        // 服务端机选号码生成（不扣费，俩前端展示后确认购买）
        Route::get('/quick-pick', [\App\Http\Controllers\LotteryController::class, 'quickPick'])->name('quick-pick');
        // 历史期次（最近20期）
        Route::get('/history', [\App\Http\Controllers\LotteryController::class, 'history'])->name('history');
        // 我的购票记录
        Route::get('/my', [\App\Http\Controllers\LotteryController::class, 'my'])->name('my');
    });

    // ── 五子棋（前台）───────────────────────────────────────────────
    Route::prefix('gomoku')->name('gomoku.')->group(function () {
        // 获取五子棋配置（入场费、奖励，对外暴露给前端面板）
        Route::get('/config', function () {
            $c = \App\Models\GameConfig::query()->where('game_key', 'gomoku')->first();
            $p = $c?->params ?? [];

            return response()->json([
                'ok' => true,
                'pvp_reward' => (int) ($p['pvp_reward'] ?? 80),
                'pve_levels' => [
                    ['level' => 1, 'name' => '简单', 'fee' => (int) ($p['pve_easy_fee'] ?? 0),   'reward' => (int) ($p['pve_easy_reward'] ?? 20)],
                    ['level' => 2, 'name' => '普通', 'fee' => (int) ($p['pve_normal_fee'] ?? 10),  'reward' => (int) ($p['pve_normal_reward'] ?? 50)],
                    ['level' => 3, 'name' => '困难', 'fee' => (int) ($p['pve_hard_fee'] ?? 30),  'reward' => (int) ($p['pve_hard_reward'] ?? 120)],
                    ['level' => 4, 'name' => '专家', 'fee' => (int) ($p['pve_expert_fee'] ?? 80), 'reward' => (int) ($p['pve_expert_reward'] ?? 300)],
                ],
            ]);
        })->name('config');
        // 查询当前用户是否有进行中的对局（用于重进时恢复）
        Route::get('/active', [\App\Http\Controllers\GomokuController::class, 'active'])->name('active');
        // 创建对局（pvp=随机邀请 | pve=人机对战）
        Route::post('/create', [\App\Http\Controllers\GomokuController::class, 'create'])->name('create');
        // 加入 PvP 对战
        Route::post('/{game}/join', [\App\Http\Controllers\GomokuController::class, 'join'])->name('join');
        // 落子
        Route::post('/{game}/move', [\App\Http\Controllers\GomokuController::class, 'move'])->name('move');
        // 认输
        Route::post('/{game}/resign', [\App\Http\Controllers\GomokuController::class, 'resign'])->name('resign');
        // 取消等待中的邀请
        Route::post('/{game}/cancel', [\App\Http\Controllers\GomokuController::class, 'cancel'])->name('cancel');
        // 获取当前棋盘状态
        Route::get('/{game}/state', [\App\Http\Controllers\GomokuController::class, 'state'])->name('state');
    });

    // ── 游戏大厅：实时开关状态接口 ────────────────────────────────────
    Route::get('/games/enabled', function () {
        return response()->json([
            'baccarat' => \App\Models\GameConfig::isEnabled('baccarat'),
            'slot_machine' => \App\Models\GameConfig::isEnabled('slot_machine'),
            'mystery_box' => \App\Models\GameConfig::isEnabled('mystery_box'),
            'horse_racing' => \App\Models\GameConfig::isEnabled('horse_racing'),
            'fortune_telling' => \App\Models\GameConfig::isEnabled('fortune_telling'),
            'fishing' => \App\Models\GameConfig::isEnabled('fishing'),
            'lottery' => \App\Models\GameConfig::isEnabled('lottery'),
            'gomoku' => \App\Models\GameConfig::isEnabled('gomoku'),
        ]);
    })->name('games.enabled');

    // ---- 第五阶段：具体房间内部聊天核心 ----
    // 进入具体房间界面的初始化
    Route::get('/room/{id}', [ChatController::class, 'init'])->name('chat.room');

    // 发送消息
    Route::post('/room/{id}/send', [ChatController::class, 'send'])
        ->middleware('throttle:chat-send')
        ->name('chat.send');

    // 挂机心跳存点 (限制每分钟最多调用 6 次防止挂机脚本滥用)
    Route::post('/room/{id}/heartbeat', [ChatController::class, 'heartbeat'])
        ->middleware('throttle:6,1')
        ->name('chat.heartbeat');

    // 退出房间
    Route::post('/room/{id}/leave', [ChatController::class, 'leave'])->name('chat.leave');

    // 所有房间在线人数（右侧房间面板用）
    Route::get('/rooms/online-status', [ChatController::class, 'roomsOnlineStatus'])->name('chat.rooms-online-status');

    // 头像列表（供选择）
    Route::get('/headface/list', [ChatController::class, 'headfaceList'])->name('headface.list');

    // 修改头像
    Route::post('/headface/change', [ChatController::class, 'changeAvatar'])->name('headface.change');

    // 上传自定义头像
    Route::post('/headface/upload', [ChatController::class, 'uploadAvatar'])->name('headface.upload');

    // 设置房间公告/祝福语
    Route::post('/room/{id}/announcement', [ChatController::class, 'setAnnouncement'])->name('chat.announcement');

    // ---- 钓鱼小游戏（复刻原版 diaoyu/ 功能）----
    Route::post('/room/{id}/fish/cast', [FishingController::class, 'cast'])->name('fishing.cast');
    Route::post('/room/{id}/fish/reel', [FishingController::class, 'reel'])->name('fishing.reel');

    // ---- AI 聊天机器人 ----
    Route::post('/chatbot/chat', [ChatBotController::class, 'chat'])->name('chatbot.chat');
    Route::post('/chatbot/clear', [ChatBotController::class, 'clearContext'])->name('chatbot.clear');

    // ---- 送花/礼物互动 ----
    Route::post('/gift/flower', [ChatController::class, 'sendFlower'])->name('gift.flower');
    Route::post('/gift/gold', [ChatController::class, 'giftGold'])->name('gift.gold');

    // ---- 管理员命令（聊天室内实时操作）----
    Route::post('/command/warn', [AdminCommandController::class, 'warn'])->name('command.warn');
    Route::post('/command/kick', [AdminCommandController::class, 'kick'])->name('command.kick');
    Route::post('/command/mute', [AdminCommandController::class, 'mute'])->name('command.mute');
    Route::post('/command/freeze', [AdminCommandController::class, 'freeze'])->name('command.freeze');
    Route::post('/command/reward', [AdminCommandController::class, 'reward'])->name('command.reward');
    Route::get('/command/reward-quota', [AdminCommandController::class, 'rewardQuota'])->name('command.reward_quota');
    Route::get('/command/whispers/{username}', [AdminCommandController::class, 'viewWhispers'])->name('command.whispers');
    Route::post('/command/announce', [AdminCommandController::class, 'announce'])->name('command.announce');
    Route::post('/command/clear-screen', [AdminCommandController::class, 'clearScreen'])->name('command.clear_screen');
    Route::post('/command/refresh-all', [AdminCommandController::class, 'refreshAll'])->name('command.refresh_all');
    Route::post('/command/effect', [AdminCommandController::class, 'effect'])
        ->middleware('throttle:chat-effect')
        ->name('command.effect');
    Route::post('/command/baccarat-loss-cover', [\App\Http\Controllers\Admin\BaccaratLossCoverEventController::class, 'store'])->name('command.baccarat_loss_cover.store');
    Route::post('/command/baccarat-loss-cover/{event}/close', [\App\Http\Controllers\Admin\BaccaratLossCoverEventController::class, 'close'])->name('command.baccarat_loss_cover.close');

    // ---- 礼包红包（superlevel 发包 / 所有登录用户可抢）----
    Route::get('/command/red-packet/config', [\App\Http\Controllers\RedPacketController::class, 'config'])->name('command.red_packet.config');
    Route::post('/command/red-packet/send', [\App\Http\Controllers\RedPacketController::class, 'send'])->name('command.red_packet.send');
    Route::get('/red-packet/{envelopeId}/status', [\App\Http\Controllers\RedPacketController::class, 'status'])->name('red_packet.status');
    Route::post('/red-packet/{envelopeId}/claim', [\App\Http\Controllers\RedPacketController::class, 'claim'])->name('red_packet.claim');

    // ---- 商店（购买特效卡/改名卡）----
    Route::get('/shop/items', [\App\Http\Controllers\ShopController::class, 'items'])->name('shop.items');
    Route::post('/shop/buy', [\App\Http\Controllers\ShopController::class, 'buy'])
        ->middleware('throttle:chat-shop-buy')
        ->name('shop.buy');
    Route::post('/shop/rename', [\App\Http\Controllers\ShopController::class, 'rename'])->name('shop.rename');

    // ---- 银行资金接口 ----
    Route::get('/bank', [\App\Http\Controllers\BankController::class, 'info'])->name('bank.info');
    Route::get('/bank/ranking', [\App\Http\Controllers\BankController::class, 'ranking'])->name('bank.ranking');
    Route::post('/bank/deposit', [\App\Http\Controllers\BankController::class, 'deposit'])->name('bank.deposit');
    Route::post('/bank/withdraw', [\App\Http\Controllers\BankController::class, 'withdraw'])->name('bank.withdraw');

    // ---- 开发日志（独立前台页面 /changelog）----
    Route::get('/changelog', [ChangelogController::class, 'index'])->name('changelog.index');
    // 懒加载接口：scroll 到底追加更多日志
    Route::get('/changelog/more', [ChangelogController::class, 'loadMoreChangelogs'])->name('changelog.more');

    // ---- 用户反馈（独立前台页面 /feedback）----
    // 反馈列表页
    Route::get('/feedback', [FeedbackController::class, 'index'])->name('feedback.index');
    // 懒加载接口：scroll 到底追加更多反馈
    Route::get('/feedback/more', [FeedbackController::class, 'loadMore'])->name('feedback.more');
    // 提交新反馈
    Route::post('/feedback', [FeedbackController::class, 'store'])->middleware('throttle:5,1')->name('feedback.store');
    // 赞同/取消赞同（Toggle）
    Route::post('/feedback/{id}/vote', [FeedbackController::class, 'vote'])->name('feedback.vote');
    // 提交补充评论
    Route::post('/feedback/{id}/reply', [FeedbackController::class, 'reply'])->middleware('throttle:10,1')->name('feedback.reply');
    // 删除反馈（本人24小时内或管理员）
    Route::delete('/feedback/{id}', [FeedbackController::class, 'destroy'])->name('feedback.destroy');

    // ---- 赚金币看视频等任务 ----
    Route::post('/earn/video-reward', [\App\Http\Controllers\EarnController::class, 'claimVideoReward'])->name('earn.video_reward');
});

// ═══════════════════════════════════════════════════════════════════
// 后台管理路由（三层权限）
// 层级 1｜chat.has_position  ── 有在职职务即可（id=1 始终通过）
// 层级 2｜chat.site_owner    ── 仅站长（id=1）
// 聊天室内快速任命/撤销（需登录 + 有在职职务）
Route::middleware(['chat.auth', 'chat.has_position'])->prefix('chat-appoint')->name('chat.appoint.')->group(function () {
    Route::get('/positions', [\App\Http\Controllers\ChatAppointmentController::class, 'positions'])->name('positions');
    Route::post('/appoint', [\App\Http\Controllers\ChatAppointmentController::class, 'appoint'])->name('appoint');
    Route::post('/revoke', [\App\Http\Controllers\ChatAppointmentController::class, 'revoke'])->name('revoke');
});

// ═══════════════════════════════════════════════════════════════════
Route::middleware(['chat.auth', 'chat.has_position'])->prefix('admin')->name('admin.')->group(function () {

    // ──────────────────────────────────────────────────────────────
    // 层级 1：有在职职务即可访问
    // ──────────────────────────────────────────────────────────────

    // 后台首页概览
    Route::get('/', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');

    // 积分流水统计
    Route::get('/currency-stats', [\App\Http\Controllers\Admin\CurrencyStatsController::class, 'index'])->name('currency-stats.index');

    // 用户管理：有职务的人只能查看（index），update/destroy 仅站长
    Route::get('/users', [\App\Http\Controllers\Admin\UserManagerController::class, 'index'])->name('users.index');

    // 秘语查看（耳语记录）
    Route::get('/whispers', function () {
        return view('admin.whispers');
    })->name('whispers.index');

    // 我的履职记录（当前登录者自己的权限操作记录）
    Route::get('/my-duty-logs', [\App\Http\Controllers\Admin\AppointmentController::class, 'myDutyLogs'])->name('appointments.my-duty-logs');

    // 任命管理（任命权限由 AppointmentService 内部校验）
    Route::get('/appointments', [\App\Http\Controllers\Admin\AppointmentController::class, 'index'])->name('appointments.index');
    Route::post('/appointments', [\App\Http\Controllers\Admin\AppointmentController::class, 'store'])->name('appointments.store');
    Route::delete('/appointments/{userPosition}/revoke', [\App\Http\Controllers\Admin\AppointmentController::class, 'revoke'])->name('appointments.revoke');
    Route::get('/appointments/{userPosition}/duty-logs', [\App\Http\Controllers\Admin\AppointmentController::class, 'dutyLogs'])->name('appointments.duty-logs');
    Route::get('/appointments/{userPosition}/authority-logs', [\App\Http\Controllers\Admin\AppointmentController::class, 'authorityLogs'])->name('appointments.authority-logs');
    Route::get('/appointments/history', [\App\Http\Controllers\Admin\AppointmentController::class, 'history'])->name('appointments.history');
    Route::get('/appointments/search-users', [\App\Http\Controllers\Admin\AppointmentController::class, 'searchUsers'])->name('appointments.search-users');

    // ── 层级 1.5：superlevel 及以上可完整操作以下模块 ──
    Route::middleware(['chat.level:super'])->group(function () {
        // 部门 / 职务列表 + 编辑（删除仍限 id=1）
        Route::get('/departments', [\App\Http\Controllers\Admin\DepartmentController::class, 'index'])->name('departments.index');
        Route::get('/positions', [\App\Http\Controllers\Admin\PositionController::class, 'index'])->name('positions.index');
        Route::put('/departments/{department}', [\App\Http\Controllers\Admin\DepartmentController::class, 'update'])->name('departments.update');
        Route::put('/positions/{position}', [\App\Http\Controllers\Admin\PositionController::class, 'update'])->name('positions.update');
        Route::patch('/positions/{position}/patch', [\App\Http\Controllers\Admin\PositionController::class, 'quickPatch'])->name('positions.quick_patch');
        Route::post('/positions/reward-config', [\App\Http\Controllers\Admin\PositionController::class, 'saveRewardConfig'])->name('positions.reward_config');

        // 大卡片通知广播（仅超级管理员，安全隔离：普通用户无此接口）
        Route::post('/banner/broadcast', [\App\Http\Controllers\Admin\BannerBroadcastController::class, 'send'])->name('admin.banner.broadcast');

        // 聊天室参数（含保存）
        Route::get('/system', [\App\Http\Controllers\Admin\SystemController::class, 'edit'])->name('system.edit');
        Route::put('/system', [\App\Http\Controllers\Admin\SystemController::class, 'update'])->name('system.update');

        // 微信机器人配置
        Route::get('/wechat-bot', [\App\Http\Controllers\Admin\WechatBotController::class, 'edit'])->name('wechat_bot.edit');
        Route::put('/wechat-bot', [\App\Http\Controllers\Admin\WechatBotController::class, 'update'])->name('wechat_bot.update');
        Route::post('/wechat-bot/announcement', [\App\Http\Controllers\Admin\WechatBotController::class, 'sendAnnouncement'])->name('wechat_bot.send_announcement');

        // 运维工具（仅 id=1 超管可用）
        Route::get('/ops', [\App\Http\Controllers\Admin\OpsController::class, 'index'])->name('ops.index');
        Route::post('/ops/clear-cache', [\App\Http\Controllers\Admin\OpsController::class, 'clearCache'])->name('ops.clear-cache');
        Route::post('/ops/clear-routes', [\App\Http\Controllers\Admin\OpsController::class, 'clearRoutes'])->name('ops.clear-routes');
        Route::post('/ops/clear-views', [\App\Http\Controllers\Admin\OpsController::class, 'clearViews'])->name('ops.clear-views');
        Route::post('/ops/clear-room-online', [\App\Http\Controllers\Admin\OpsController::class, 'clearRoomOnline'])->name('ops.clear-room-online');

        // 房间管理（含新增/编辑/删除）
        Route::get('/rooms', [\App\Http\Controllers\Admin\RoomManagerController::class, 'index'])->name('rooms.index');
        Route::post('/rooms', [\App\Http\Controllers\Admin\RoomManagerController::class, 'store'])->name('rooms.store');
        Route::put('/rooms/{room}', [\App\Http\Controllers\Admin\RoomManagerController::class, 'update'])->name('rooms.update');
        Route::delete('/rooms/{room}', [\App\Http\Controllers\Admin\RoomManagerController::class, 'destroy'])->name('rooms.destroy');

        // 随机事件（含新增/编辑/删除/切换）
        Route::get('/autoact', [\App\Http\Controllers\Admin\AutoactController::class, 'index'])->name('autoact.index');
        Route::post('/autoact', [\App\Http\Controllers\Admin\AutoactController::class, 'store'])->name('autoact.store');
        Route::put('/autoact/{autoact}', [\App\Http\Controllers\Admin\AutoactController::class, 'update'])->name('autoact.update');
        Route::delete('/autoact/{autoact}', [\App\Http\Controllers\Admin\AutoactController::class, 'destroy'])->name('autoact.destroy');
        Route::post('/autoact/{autoact}/toggle', [\App\Http\Controllers\Admin\AutoactController::class, 'toggle'])->name('autoact.toggle');

        // 每日签到奖励规则管理
        Route::get('/sign-in-rules', [\App\Http\Controllers\Admin\SignInRewardRuleController::class, 'index'])->name('sign-in-rules.index');
        Route::post('/sign-in-rules', [\App\Http\Controllers\Admin\SignInRewardRuleController::class, 'store'])->name('sign-in-rules.store');
        Route::put('/sign-in-rules/{signInRewardRule}', [\App\Http\Controllers\Admin\SignInRewardRuleController::class, 'update'])->name('sign-in-rules.update');
        Route::post('/sign-in-rules/{signInRewardRule}/toggle', [\App\Http\Controllers\Admin\SignInRewardRuleController::class, 'toggle'])->name('sign-in-rules.toggle');
        Route::delete('/sign-in-rules/{signInRewardRule}', [\App\Http\Controllers\Admin\SignInRewardRuleController::class, 'destroy'])->name('sign-in-rules.destroy');

        // VIP 会员等级（含新增/编辑/删除）
        Route::get('/vip', [\App\Http\Controllers\Admin\VipController::class, 'index'])->name('vip.index');
        Route::get('/vip/{vip}/members', [\App\Http\Controllers\Admin\VipController::class, 'members'])->name('vip.members');
        Route::post('/vip', [\App\Http\Controllers\Admin\VipController::class, 'store'])->name('vip.store');
        Route::put('/vip/{vip}', [\App\Http\Controllers\Admin\VipController::class, 'update'])->name('vip.update');
        Route::delete('/vip/{vip}', [\App\Http\Controllers\Admin\VipController::class, 'destroy'])->name('vip.destroy');
        Route::get('/vip-payment-logs', [\App\Http\Controllers\Admin\VipPaymentLogController::class, 'index'])->name('vip-payment-logs.index');

        // 全局用户金币/积分流水
        Route::get('/currency-logs', [\App\Http\Controllers\Admin\CurrencyLogController::class, 'index'])->name('currency-logs.index');

        // 🛒 商店商品管理（查看/编辑所有 superlevel 可用，新增/删除仅 id=1）
        Route::get('/shop', [\App\Http\Controllers\Admin\ShopItemController::class, 'index'])->name('shop.index');
        Route::post('/shop', [\App\Http\Controllers\Admin\ShopItemController::class, 'store'])->name('shop.store');
        Route::put('/shop/{shopItem}', [\App\Http\Controllers\Admin\ShopItemController::class, 'update'])->name('shop.update');
        Route::patch('/shop/{shopItem}/toggle', [\App\Http\Controllers\Admin\ShopItemController::class, 'toggle'])->name('shop.toggle');
        Route::delete('/shop/{shopItem}', [\App\Http\Controllers\Admin\ShopItemController::class, 'destroy'])->name('shop.destroy');

        // 💒 婚姻管理（superlevel 及以上）
        Route::prefix('marriages')->name('marriages.')->group(function () {
            // 总览统计
            Route::get('/', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'index'])->name('index');
            // 婚姻列表（支持筛选）
            Route::get('/list', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'list'])->name('list');
            // 求婚记录
            Route::get('/proposals', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'proposals'])->name('proposals');
            // 婚礼红包记录
            Route::get('/ceremonies', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'ceremonies'])->name('ceremonies');
            // 红包领取明细
            Route::get('/ceremonies/{ceremony}/claims', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'claimDetail'])->name('claim-detail');
            // 亲密度日志
            Route::get('/intimacy-logs', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'intimacyLogs'])->name('intimacy-logs');
            // 参数配置（GET=页面，POST=保存）
            Route::get('/configs', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'configs'])->name('configs');
            Route::post('/configs', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'updateConfigs'])->name('configs.update');
            // 婚礼档位（GET=页面，PUT=保存）
            Route::get('/tiers', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'tiers'])->name('tiers');
            Route::put('/tiers/{tier}', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'updateTier'])->name('tiers.update');
            // 强制离婚
            Route::post('/{marriage}/force-dissolve', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'forceDissolve'])->name('force-dissolve');
            Route::post('/{marriage}/cancel-proposal', [\App\Http\Controllers\Admin\MarriageManagerController::class, 'cancelProposal'])->name('cancel-proposal');
        });

        // 📅 节日福利活动管理
        Route::prefix('holiday-events')->name('holiday-events.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\HolidayEventController::class, 'index'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\HolidayEventController::class, 'create'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\HolidayEventController::class, 'store'])->name('store');
            Route::get('/{holidayEvent}/edit', [\App\Http\Controllers\Admin\HolidayEventController::class, 'edit'])->name('edit');
            Route::put('/{holidayEvent}', [\App\Http\Controllers\Admin\HolidayEventController::class, 'update'])->name('update');
            Route::post('/{holidayEvent}/toggle', [\App\Http\Controllers\Admin\HolidayEventController::class, 'toggle'])->name('toggle');
            Route::post('/{holidayEvent}/trigger-now', [\App\Http\Controllers\Admin\HolidayEventController::class, 'triggerNow'])->name('trigger-now');
            Route::delete('/{holidayEvent}', [\App\Http\Controllers\Admin\HolidayEventController::class, 'destroy'])->name('destroy');
        });

        // 🎮 游戏管理（开关 + 核心参数配置）
        Route::prefix('game-configs')->name('game-configs.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\GameConfigController::class, 'index'])->name('index');
            Route::post('/{gameConfig}/toggle', [\App\Http\Controllers\Admin\GameConfigController::class, 'toggle'])->name('toggle');
            Route::post('/{gameConfig}/params', [\App\Http\Controllers\Admin\GameConfigController::class, 'updateParams'])->name('params');
        });

        // 📊 游戏历史记录查询（各游戏历史 + 实时统计摘要）
        Route::prefix('game-history')->name('game-history.')->group(function () {
            // 各游戏实时统计摘要（JSON 接口，供游戏管理页 AJAX 加载）
            Route::get('/stats', [\App\Http\Controllers\Admin\GameHistoryController::class, 'stats'])->name('stats');
            // 百家乐局次历史
            Route::get('/baccarat', [\App\Http\Controllers\Admin\GameHistoryController::class, 'baccarat'])->name('baccarat');
            Route::get('/baccarat/{round}', [\App\Http\Controllers\Admin\GameHistoryController::class, 'baccaratRound'])->name('baccarat.round');
            // 老虎机历史
            Route::get('/slot', [\App\Http\Controllers\Admin\GameHistoryController::class, 'slot'])->name('slot');
            // 赛马场次历史
            Route::get('/horse', [\App\Http\Controllers\Admin\GameHistoryController::class, 'horse'])->name('horse');
            Route::get('/horse/{race}', [\App\Http\Controllers\Admin\GameHistoryController::class, 'horseRace'])->name('horse.race');
            // 神秘箱子投放历史
            Route::get('/mystery-box', [\App\Http\Controllers\Admin\GameHistoryController::class, 'mysteryBox'])->name('mystery-box');
            // 神秘占卜历史
            Route::get('/fortune', [\App\Http\Controllers\Admin\GameHistoryController::class, 'fortune'])->name('fortune');
            // 彩票场次历史
            Route::get('/lottery', [\App\Http\Controllers\Admin\GameHistoryController::class, 'lottery'])->name('lottery');
            Route::get('/lottery/{issue}', [\App\Http\Controllers\Admin\GameHistoryController::class, 'lotteryIssue'])->name('lottery.issue');
            // 五子棋历史
            Route::get('/gomoku', [\App\Http\Controllers\Admin\GameHistoryController::class, 'gomoku'])->name('gomoku');
        });

        // 📦 神秘箱子：管理员手动投放
        Route::post('/mystery-box/drop', [\App\Http\Controllers\Admin\GameConfigController::class, 'dropMysteryBox'])->name('mystery-box.drop');

        // 🎟️ 双色球彩票：管理员手动操作
        Route::post('/lottery/open-issue', [\App\Http\Controllers\Admin\GameConfigController::class, 'openLotteryIssue'])->name('lottery.open-issue');
        Route::post('/lottery/force-draw', [\App\Http\Controllers\Admin\GameConfigController::class, 'forceLotteryDraw'])->name('lottery.force-draw');

        // 🎣 钓鱼事件管理
        Route::prefix('fishing')->name('fishing.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\FishingEventController::class, 'index'])->name('index');
            Route::post('/', [\App\Http\Controllers\Admin\FishingEventController::class, 'store'])->name('store');
            Route::put('/{fishing}', [\App\Http\Controllers\Admin\FishingEventController::class, 'update'])->name('update');
            Route::post('/{fishing}/toggle', [\App\Http\Controllers\Admin\FishingEventController::class, 'toggle'])->name('toggle');
            Route::delete('/{fishing}', [\App\Http\Controllers\Admin\FishingEventController::class, 'destroy'])->name('destroy');
        });
    });

    // ──────────────────────────────────────────────────────────────
    // 层级 2：仅站长（id=1）可进行以下操作
    // ──────────────────────────────────────────────────────────────
    Route::middleware(['chat.site_owner'])->group(function () {

        // 用户编辑 & 删除
        Route::put('/users/{user}', [\App\Http\Controllers\Admin\UserManagerController::class, 'update'])->name('users.update');
        Route::delete('/users/{user}', [\App\Http\Controllers\Admin\UserManagerController::class, 'destroy'])->name('users.destroy');

        // 发信配置管理
        Route::get('/smtp', [\App\Http\Controllers\Admin\SmtpController::class, 'edit'])->name('smtp.edit');
        Route::put('/smtp', [\App\Http\Controllers\Admin\SmtpController::class, 'update'])->name('smtp.update');
        Route::post('/smtp/test', [\App\Http\Controllers\Admin\SmtpController::class, 'test'])->name('smtp.test');

        // VIP 支付配置管理
        Route::get('/vip-payment', [\App\Http\Controllers\Admin\VipPaymentConfigController::class, 'edit'])->name('vip-payment.edit');
        Route::put('/vip-payment', [\App\Http\Controllers\Admin\VipPaymentConfigController::class, 'update'])->name('vip-payment.update');

        // 部门新增/删除（编辑已在 superlevel 层）
        Route::post('/departments', [\App\Http\Controllers\Admin\DepartmentController::class, 'store'])->name('departments.store');
        Route::delete('/departments/{department}', [\App\Http\Controllers\Admin\DepartmentController::class, 'destroy'])->name('departments.destroy');

        // 职务新增/删除（编辑已在 superlevel 层）
        Route::post('/positions', [\App\Http\Controllers\Admin\PositionController::class, 'store'])->name('positions.store');
        Route::delete('/positions/{position}', [\App\Http\Controllers\Admin\PositionController::class, 'destroy'])->name('positions.destroy');

        // AI 厂商配置管理
        Route::get('/ai-providers', [\App\Http\Controllers\Admin\AiProviderController::class, 'index'])->name('ai-providers.index');
        Route::post('/ai-providers', [\App\Http\Controllers\Admin\AiProviderController::class, 'store'])->name('ai-providers.store');
        Route::put('/ai-providers/{id}', [\App\Http\Controllers\Admin\AiProviderController::class, 'update'])->name('ai-providers.update');
        Route::post('/ai-providers/{id}/toggle', [\App\Http\Controllers\Admin\AiProviderController::class, 'toggleEnabled'])->name('ai-providers.toggle');
        Route::post('/ai-providers/{id}/default', [\App\Http\Controllers\Admin\AiProviderController::class, 'setDefault'])->name('ai-providers.default');
        Route::post('/ai-providers/{id}/test', [\App\Http\Controllers\Admin\AiProviderController::class, 'testConnection'])->name('ai-providers.test');
        Route::post('/ai-providers/toggle-chatbot', [\App\Http\Controllers\Admin\AiProviderController::class, 'toggleChatBot'])->name('ai-providers.toggle-chatbot');
        Route::post('/ai-providers/update-settings', [\App\Http\Controllers\Admin\AiProviderController::class, 'updateSettings'])->name('ai-providers.update-settings');
        Route::delete('/ai-providers/{id}', [\App\Http\Controllers\Admin\AiProviderController::class, 'destroy'])->name('ai-providers.destroy');

        // 开发日志管理
        Route::resource('changelogs', \App\Http\Controllers\Admin\ChangelogController::class)->except(['show']);

        // 用户反馈管理
        Route::get('/feedback', [\App\Http\Controllers\Admin\FeedbackManagerController::class, 'index'])->name('feedback.index');
        Route::put('/feedback/{id}', [\App\Http\Controllers\Admin\FeedbackManagerController::class, 'update'])->name('feedback.update');

        // 禁用用户名管理（永久禁止注册/改名的词语：领导人名称、攻击性词汇等）
        Route::get('/forbidden-usernames', [\App\Http\Controllers\Admin\ForbiddenUsernameController::class, 'index'])->name('forbidden-usernames.index');
        Route::post('/forbidden-usernames', [\App\Http\Controllers\Admin\ForbiddenUsernameController::class, 'store'])->name('forbidden-usernames.store');
        Route::post('/forbidden-usernames/batch', [\App\Http\Controllers\Admin\ForbiddenUsernameController::class, 'batchStore'])->name('forbidden-usernames.batch');
        Route::put('/forbidden-usernames/{id}', [\App\Http\Controllers\Admin\ForbiddenUsernameController::class, 'update'])->name('forbidden-usernames.update');
        Route::delete('/forbidden-usernames/{id}', [\App\Http\Controllers\Admin\ForbiddenUsernameController::class, 'destroy'])->name('forbidden-usernames.destroy');
    });
});

// ---- VIP 支付回调（公开入口） ----
Route::get('/vip/payment/return', [\App\Http\Controllers\VipPaymentController::class, 'handleReturn'])->name('vip.payment.return');
Route::post('/vip/payment/notify', [\App\Http\Controllers\VipPaymentController::class, 'notify'])
    ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class])
    ->name('vip.payment.notify');

// ═══════════════════════════════════════════════════════════════════
// 邀请链接路由 (严格纯数字)
// 必须放在最后以避免与其他如 /admin 路由冲突
// ═══════════════════════════════════════════════════════════════════
Route::get('/{inviter_id}', [\App\Http\Controllers\InviteController::class, 'handle'])
    ->where('inviter_id', '[0-9]+')
    ->name('invite.link');
