<?php

namespace App\Jobs;

use App\Mail\CharacteristicApprovalMail;
use App\Models\CharacteristicApproverMaster;
use App\Models\RequestCharacteristic;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;

class SendApprover1MailJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(public RequestCharacteristic $request) {

    }

    /**
     * Execute the job.
     */
     public function handle()
    {
        // Already approved? stop
        if (!is_null($this->request->approver_status1)) return;

        if ($this->request->approver1_mail_sent) return;

        $approver = CharacteristicApproverMaster::where('plant_id', $this->request->plant_id)
            ->where('machine_id', $this->request->machine_id)
            ->first();

        if (! $approver || ! $approver->mail1) return;

        Mail::to($approver->mail1)
            ->queue(new CharacteristicApprovalMail(
                $this->request,
                $approver->name1,
                1
            ));

        $this->request->update(['approver1_mail_sent' => 1]);

        SendApprover2MailJob::dispatch($this->request)
            ->delay(now()->addMinutes(5));
    }
}
