<?php

/**
 * 文件功能：房间管理器
 * 接管原版 ROOMLIST.ASP, NEWROOM.ASP, ROOMSET.ASP, CUTROOM.ASP, OVERROOM.ASP 的职责
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers;

use App\Events\RoomTitleUpdated;
use App\Http\Requests\StoreRoomRequest;
use App\Http\Requests\UpdateRoomRequest;
use App\Models\Room;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class RoomController extends Controller
{
    /**
     * 显示房间大厅列表 (对应 ROOMLIST.ASP)
     */
    public function index(): View
    {
        $rooms = Room::with('masterUser')
            ->orderByDesc('room_keep')  // 系统房间排在最前面
            ->orderByDesc('id')
            ->get();

        return view('rooms.index', compact('rooms'));
    }

    /**
     * 创建房间 (对应 NEWROOM.ASP)
     */
    public function store(StoreRoomRequest $request): RedirectResponse
    {
        $data = $request->validated();

        $room = Room::create([
            'room_name' => $data['name'],
            'room_des' => $data['description'] ?? '',
            'room_owner' => Auth::user()->username,
            'room_keep' => false, // 用户自建均为非系统房
        ]);

        return redirect()->route('rooms.index')->with('success', "聊天室 [{$room->name}] 创建成功！");
    }

    /**
     * 更新房间属性 (对应 ROOMSET.ASP)
     */
    public function update(UpdateRoomRequest $request, int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);

        // 鉴权：必须是该房间的主人或者是高管 (系统级 > 15)
        $user = Auth::user();
        if ($room->master !== $user->username && $user->user_level < 15) {
            abort(403, '只有房主或超级管理员才能修改此房间设置。');
        }

        $data = $request->validated();
        $room->update([
            'room_name' => $data['name'],
            'room_des' => $data['description'] ?? '',
        ]);

        // 广播房间信息更新 (所有人立即可以在聊天框顶部看到)
        broadcast(new RoomTitleUpdated($room->id, $room->name.($room->description ? ' - '.$room->description : '')));

        return back()->with('success', '房间设置更新成功！');
    }

    /**
     * 解散/删除房间 (对应 CUTROOM.ASP)
     */
    public function destroy(int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);

        // 鉴权：系统自带房不能被任何人删除
        if ($room->is_system) {
            abort(403, '系统固定聊天室无法被删除。');
        }

        $user = Auth::user();
        if ($room->master !== $user->username && $user->user_level < 15) {
            abort(403, '只有房主或超级管理员才能解散该房间。');
        }

        $room->delete();
        // 备注：如果该房间内还有人，他们应该会被前端由于 channel 无法维系而被请出，或者可以在这里再发送一个专门的踢出事件。

        return redirect()->route('rooms.index')->with('success', "聊天室 [{$room->name}] 已被彻底解散。");
    }

    /**
     * 转让房主 (对应 OVERROOM.ASP)
     */
    public function transfer(int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);
        $user = Auth::user();

        if ($room->master !== $user->username && $user->user_level < 15) {
            abort(403, '只有当前房主可以进行转让。');
        }

        $targetUsername = request('target_username');
        if (empty($targetUsername)) {
            return back()->with('error', '请输入目标用户的昵称。');
        }

        $targetUser = User::where('username', $targetUsername)->first();
        if (! $targetUser) {
            return back()->with('error', '该用户不存在，无法转让。');
        }

        $room->update(['room_owner' => $targetUser->username]);

        return back()->with('success', "房间已成功转让给 [{$targetUser->username}]。");
    }
}
