<?php

namespace App\Jobs;

use App\Models\Comment;
use App\Models\Notification;
use App\Models\SocialPost;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendNotificationSocial implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $comment;
    protected $post;

    public function __construct(Comment $comment, SocialPost $post)
    {
        //
	    $this->comment = $comment;
	    $this->post = $post;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
	    $comment = $this->comment;
	    $post = $this->post;


	    $images = json_decode($comment->images, true);

	    if(!empty($images))
	    {
		    $content = $comment->account->name.' vừa bình luận 1 ảnh vào bài viết';
	    } else {
		    $content = $comment->account->name.' vừa bình luận: '.$comment->content;
	    }
	    $payload = json_encode([
		    'id' => $post->id,
		    'type' => config('constants.SOCIAL_POST')
	    ]);

	    $likes = \DB::table('user_posts')->where('social_post_id', $post->id)->pluck('user_id')->toArray();

        $comments = Comment::where('social_post_id', $post->id)->where('user_id', '<>', $comment->user_id)
            ->groupBy('user_id')
            ->pluck('user_id')
            ->toArray();

        $arrs = array_merge($likes, $comments);
        $arrs[] = $post->user_id;
        $arrs = array_unique($arrs);

        if (($key = array_search($comment->user_id, $arrs)) !== false) {
            unset($arrs[$key]);
        }


	    foreach ($arrs as $arr)
	    {
		    Notification::create( [
			    'to_user' => $arr,
			    'title'   => 'Thông báo từ itro.vn',
			    'user_id' => $arr,
			    'content' => $content,
			    'payload' => $payload,
                'image' => $comment->account->image
		    ] );
	    }

    }
}
