<?php

namespace App\Jobs;

use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\RenterRoom;
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 SendMailRentersMoney implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    protected $moneyInfoId;

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

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

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

        $room = $moneyInfo->room;
        if (!$room) {
            return;
        }

        $details = MoneyDetail::query()->where('money_info_id', $moneyInfoId)->get();
        if ($details->count() <= 0) {
            return;
        }

        $renters = RenterRoom::query()->where('room_id', $room->id)->get();

        if ($renters->count() <= 0) {
            return;
        }


        foreach ($renters as $renter) {
            $renterId = $renter->user_id;
            $user = User::find($renterId);
            if (!$user) {
                continue;
            }

            $email = $user->email;
            if (empty($email)) {
                continue;
            }

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                continue;
            }
            \Mail::send('frontend3.mail.mail_remind_renter_money', compact('moneyInfo', 'details'), function ($message) use ($user, $moneyInfo) {
                $message->from('support@itro.vn', 'iTro.vn');
                $message->subject('Thông báo đóng tiền hóa đơn ' .' '. $moneyInfo->name . ', tháng '.$moneyInfo->date_action->format('m/Y').' - iTro.vn');
                $message->to($user->email);
                //$message->to('huynt57@gmail.com');
            });
        }
    }
}
