<?php

namespace App\Jobs;

use App\Models\DiscountHostel;
use App\Models\MoneyInfo;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

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

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

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$discountId     = $this->discountId;
		$discountHostel = DiscountHostel::find( $discountId );
		if ( ! $discountHostel ) {
			return;
		}
		$hostels = $discountHostel->hostels;
		if ( ! $hostels ) {
			return;
		}

		$date = $discountHostel->date;
		if ( ! $date ) {
			return;
		}

		$moneyInfos = MoneyInfo::query()
		                       ->whereIn( 'type', [
			                       MoneyInfo::VOUCHER_CONTRACT,
			                       MoneyInfo::VOUCHER_ROOM_PRICE
		                       ] )
		                       ->whereIn( 'hostel_id', $hostels->pluck( 'id' )->toArray() )
		                       ->whereBetween( 'date_action', [
			                       $date->copy()->startOfMonth(),
			                       $date->copy()->endOfMonth()
		                       ] )
		                       ->get();
		foreach ( $moneyInfos as $moneyInfo ) {
			$moneyInfo->discount = $discountHostel->discount;
			$moneyInfo->remain   = $moneyInfo->amount - $moneyInfo->pay - $discountHostel->discount;
			$moneyInfo->save();
		}
		

	}
}
