<?php

namespace App\Jobs;

use App\Notifications\SearchHostel;
use App\Notifications\SearchHostelManageApp;
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 SendSearchNotification implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

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

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$params        = $this->params;
		$owners        = $params['owners'];
		$districtsName = $params['district_name'];
		$findSession   = $params['find_session'];
		$provinceId    = $params['province_id'];
		$districtId    = $params['district_id'];
		$user          = $params['user'];
		$ownersVip     = $params['owners_vip'];
		$hostels       = $params['hostels'];

		\Notification::send( $owners, new SearchHostel(
			$user,
			$districtsName,
			$findSession->id,
			$provinceId,
			$districtId
		) );

		\Notification::send( $owners, new SearchHostelManageApp(
			$user,
			$districtsName,
			$findSession->id,
			$provinceId,
			$districtId
		) );

		if ( $ownersVip->count() > 0 ) {
			$itroStaffs = User::query()->where( 'is_agent', true )
			                           //->whereHas('agentDistricts', )
			                           ->get();
			\Notification::send( $itroStaffs, new SearchHostel(
				$user,
				$districtsName,
				$findSession->id,
				$provinceId,
				$districtId
			) );

			\Notification::send( $itroStaffs, new SearchHostelManageApp(
				$user,
				$districtsName,
				$findSession->id,
				$provinceId,
				$districtId
			) );
		}

		//bắn cho nhân viên của từng nhà trọ
		foreach ( $hostels as $hostel ) {
			$staffs = $hostel->staffs;
			if ( ! empty( $staffs ) ) {
				\Notification::send( $staffs, new SearchHostel(
					$user,
					$districtsName,
					$findSession->id,
					$provinceId,
					$districtId
				) );

				\Notification::send( $staffs, new SearchHostelManageApp(
					$user,
					$districtsName,
					$findSession->id,
					$provinceId,
					$districtId
				) );
			}
		}
	}
}
