<?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 SendApprover2MailJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    // public function __construct()
    // {
    //     //
    // }

    /**
     * Execute the job.
     */
    public function __construct(public RequestCharacteristic $request) {}

    public function handle()
    {
        // If approver-1 approved → STOP
        if (!is_null($this->request->approver_status1)) return;

        // If approver-2 already approved → STOP
        if (!is_null($this->request->approver_status2)) return;

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

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

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

        Mail::to($approver->mail2)
            ->queue(new CharacteristicApprovalMail(
                $this->request,
                $approver->name2,
                2
            ));

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

        // Schedule Approver-3 after 5 minutes
        SendApprover3MailJob::dispatch($this->request)
            ->delay(now()->addMinutes(5));
    }
}
