<?php
declare(strict_types=1);

namespace App\Jobs;

use App\Mail\PaymentRequestMail;
use App\Models\Job;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

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

    public int $jobId;
    public ?string $note;

    public function __construct(int $jobId, ?string $note = null)
    {
        $this->jobId = $jobId;
        $this->note  = $note;
        // $this->onQueue('emails'); // optional queue name
    }

    public function handle(): void
    {
        /** @var \App\Models\Job $job */
        $job = Job::query()->findOrFail($this->jobId); // ✅ use $this->jobId

        // ✅ Use on-row columns (no nonexistent `customer` relation)
        $recipientEmail = $job->customer_email;
        $recipientName  = $job->customer_name ?? 'Customer';

        if (empty($recipientEmail)) {
            // Avoid failing the job if no email; log for visibility
            Log::warning('PaymentRequestEmail not sent: missing customer_email on Job', [
                'job_id' => $this->jobId,
                'reference' => $job->reference ?? null,
            ]);
            return;
        }

        Mail::to($recipientEmail, $recipientName)->send(
            new PaymentRequestMail($job, $this->note)
        );
    }
}
