/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
$user = auth()->check() ? auth()->user() : null;
$xhr = $request->ajax();
if (is_null($user)) {
return $xhr ? "Not logged in" : redirect()->back()->with('error', 'Not logged in');
}
if (!$request->has('comment')) {
return $xhr ? "You need to enter a comment" : redirect()->back()->with('error', 'You need to enter a comment');
}
if (mb_strlen(trim($request->get('comment'))) > 1000) {
return $xhr ? "Comment to long" : redirect()->back()->with('error', 'Comment to long');
}
$video = Video::findOrFail($id);
$com = new Comment();
$com->content = trim($request->get('comment'));
$com->user()->associate($user);
$com->video()->associate($video);
$com->save();
$sent = [];
foreach ($com->getMentioned() as $mentioned) {
Message::send($user->id, $mentioned->id, $user->username . ' mentioned you in a comment', view('messages.commentmention', ['video' => $video, 'user' => $user, 'comment' => $com]));
$sent[] = $mentioned;
}
foreach ($com->answered() as $answered) {
if (array_search($answered, $sent) !== false) {
continue;
}
Message::send($user->id, $answered->id, $user->username . ' answered on your comment', view('messages.commentanswer', ['video' => $video, 'user' => $user, 'comment' => $com]));
$sent[] = $answered;
}
if ($user->id != $video->user->id) {
if (array_search($video->user, $sent) === false) {
Message::send($user->id, $video->user->id, $user->username . ' commented on your video', view('messages.videocomment', ['video' => $video, 'user' => $user, 'comment' => $com]));
}
}
return $xhr ? view('partials.comment', ['comment' => $com, 'mod' => $user->can('delete_comment')]) : redirect()->back()->with('success', 'Comment successfully saved');
}