<?php

namespace App\Jobs;

use App\Components\Functions;
use App\Models\Notification;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	protected $name;
	protected $facebookId;
	protected $token;
	protected $user;

	public function __construct(User $user, $name, $facebookId, $token ) {
		//
		$this->name       = $name;
		$this->facebookId = $facebookId;
		$this->token      = $token;
		$this->user = $user;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$facebookId = $this->facebookId;
		$token      = $this->token;
		$friends    = Functions::sendNotificationFacebookLogin( $facebookId, $token );

		$this->user->is_fb_first = true;
		$this->user->save();

		foreach ( $friends as $friend ) {
			$check = User::where( 'facebook_id', $friend )->first();

			if ( $check ) {
				Notification::create( [
					'to_user' => $check->id,
					'title'   => 'Thông báo từ itro.vn',
					'user_id' => $check->id,
					'content' => 'Bạn của bạn (' . $this->name . ') vừa tham gia itro'
				] );
			}
		}
	}
}
