<?php

namespace App\Http\Controllers;

use App\Models\Document;
use App\Models\User;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function store(Request $request, Document $document)
    {
        $comment = $document->comments()->create([
            'user_id' => auth()->id(),
            'content' => $request->content,
            'parent_id' => $request->parent_id
        ]);
        
        $this->processMentions($comment);
        
        return back();
    }
    
    private function processMentions(Comment $comment)
    {
        preg_match_all('/@([\w\-]+)/', $comment->content, $matches);
        
        foreach ($matches[1] as $username) {
            $user = User::where('username', $username)->first();
            if ($user) {
                $user->notify(new MentionNotification($comment));
            }
        }
    }
}
