<?php

namespace App\Jobs;

use App\Models\RenterRoom;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */

	protected $room;
	protected $dateAction;

    public function onConnection($connection)
    {
        $this->connection = 'redis';
        return $this;
    }

	public function __construct( $room, $dateAction ) {
		//
		$this->room       = $room;
		$this->dateAction = $dateAction;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$room       = $this->room;
		$dateAction = $this->dateAction;
		$renters    = RenterRoom::where( 'room_id', $room->id )->get();

		if ( empty( $dateAction ) ) {
			$startDate = Carbon::now()->startOfMonth()->toDateString();
			$endDate   = Carbon::now()->endOfMonth()->toDateString();
		} else {
			$startDate = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->startOfMonth()->toDateString();
			$endDate   = Carbon::createFromFormat( 'd/m/Y', '01/'.$dateAction )->endOfMonth()->toDateString();
		}

		$moneyInfo = MoneyInfo::where( 'room_id', $room->id )->where( 'date_action', '>=', $startDate )->where( 'date_action', '<=', $endDate )->first();
		if ( $moneyInfo ) {
			if ( $moneyInfo->remain > 0 ) {
				foreach ( $renters as $renter ) {
					Notification::create( [
						'to_user' => $renter->user_id,
						'title'   => 'Thông báo từ itro.vn',
						'user_id' => $renter->user_id,
						'content' => 'Thông báo thu tiền phòng tháng ' . $dateAction . ': số tiền ' . number_format( $moneyInfo->remain, 0, '.', '.' ) . ' đ'
					] );
				}

				$remindJob = ( new RemindCharge( $room, $dateAction ) )->delay( Carbon::now()->addDay( 1 ) );

				dispatch( $remindJob );
			}
		}

	}
}
