<?php

/**
 * 文件功能：全站留言板与站内悄悄信控制器
 * (替代原版 Guestbook 系列功能)
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers;

use App\Http\Requests\StoreGuestbookRequest;
use App\Models\Guestbook;
use App\Models\User;
use App\Services\MessageFilterService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class GuestbookController extends Controller
{
    public function __construct(
        private readonly MessageFilterService $filter
    ) {}

    /**
     * 留言簿主面板 (支持分类 Tab: public/inbox/outbox)
     */
    public function index(Request $request): View
    {
        $tab = $request->input('tab', 'public');
        $user = Auth::user();

        $query = Guestbook::query()->orderByDesc('id');

        // 根据 Tab 拆分查询逻辑
        if ($tab === 'inbox') {
            // 收件箱：发给自己的，无论公私
            $query->where('towho', $user->username);
        } elseif ($tab === 'outbox') {
            // 发件箱：自己发出去的，无论公私
            $query->where('who', $user->username);
        } else {
            // 默认公共墙：
            // 条件 = (公开留言) 或者 (悄悄话但发件人是自己) 或者 (悄悄话但收件人是自己)
            $query->where(function ($q) use ($user) {
                $q->where('secret', 0)
                    ->orWhere('who', $user->username)
                    ->orWhere('towho', $user->username);
            });
        }

        $messages = $query->paginate(15)->appends(['tab' => $tab]);

        // 获取收件人默认值 (比如点击他人名片的"写私信"转跳过来)
        $defaultTo = $request->input('to', '');

        // 获取所有用户名列表（供写信弹窗的收件人选择器使用）
        $users = User::where('username', '!=', $user->username)
            ->orderBy('username')
            ->pluck('username');

        return view('guestbook.index', compact('messages', 'tab', 'defaultTo', 'users'));

    }

    /**
     * 创建一条新留言或私信
     */
    public function store(StoreGuestbookRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $user = Auth::user();

        // 强力消毒文本
        $pureBody = $this->filter->filter($data['text_body']);
        if (empty($pureBody)) {
            return back()->withInput()->with('error', '留言内容不合法或全为敏感词被过滤！');
        }

        // 处理目标人，如果没填或者填写了"大家"，则默认是 null (公共留言)
        $towho = trim($data['towho'] ?? '');
        if ($towho === '大家' || empty($towho)) {
            $towho = null;
        }

        // 如果明确指定了人，检查一下这人存不存在 (原版可不查，但查一下体验更好)
        if ($towho && ! User::where('username', $towho)->exists()) {
            return back()->withInput()->with('error', "目标收件人 [{$towho}] 不存在于系统中。");
        }

        Guestbook::create([
            'who' => $user->username,
            'towho' => $towho,
            'secret' => isset($data['secret']) ? 1 : 0,
            'text_title' => mb_substr(trim($data['text_title'] ?? ''), 0, 50),
            'text_body' => $pureBody,
            'ip' => $request->ip(),
            'post_time' => now(), // 原数据库可能用 post_time 代替了 created_at，这里两个都写保证兼容
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return back()->with('success', '飞鸽传书已成功发送！');
    }

    /**
     * 删除留言
     */
    public function destroy(int $id): RedirectResponse
    {
        $msg = Guestbook::findOrFail($id);
        $user = Auth::user();

        // 权限校验：只能删除自己发的、发给自己的，或者自己是15级以上超管
        $canDelete = $user->username === $msg->who
                  || $user->username === $msg->towho
                  || $user->user_level >= 15;

        if (! $canDelete) {
            abort(403, '越权操作：您无权擦除此留言记录！');
        }

        $msg->delete();

        return back()->with('success', '该行留言已被抹除。');
    }
}
