<?php

namespace App\Jobs;

use App\Models_v2\Conversation;
use App\Models_v2\FindSession;
use App\Models_v2\Message;
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 SendNotificationUserNotReply implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

	public function __construct( $conversationId ) {
		//
		$this->conversationId = $conversationId;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$conversation = Conversation::find( $this->conversationId );
		if ( ! $conversation ) {
			return;
		}

		if ( $conversation->findSession ) {
			$findSession = $conversation->findSession;
			if ( $findSession->status != FindSession::SEARCHING ) {
				return;
			}
		}

		$userSend = Message::query()
		                   ->where( 'conversation_id', $conversation->id )
		                   ->pluck( 'from' )
		                   ->toArray();

		$userSend = array_unique( $userSend );

		if ( empty( $userSend ) ) {
			return;
		}

		if ( count( $userSend ) > 1 ) {
			return;
		}

		$userFrom  = $userSend[0];
		$otherUser = \DB::table( 'user_conversation_find_hostels' )
		                ->where( 'conversation_id', $conversation->id )
		                ->where( 'user_id', '<>', $userFrom )
		                ->first();
		if ( $otherUser ) {
			$user = User::find( $otherUser->user_id );
			if ( ! $user ) {
				return;
			}

			\Mail::send( 'frontend3.mail.info_user', [
				'user' => $user
			], function ( $message ) {
				// $message->to('huynt57@gmail.com');
				$message->to( 'team@itro.vn' );
				$message->subject( 'Thông báo user quá 30 phút chưa trả lời hội thoại' );
			} );
		}

	}
}
