<?php

namespace App\Jobs;

use App\Mail\PaymentReceived;
use App\Models\Invoice;
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\Mail;
use Illuminate\Support\Facades\Log;

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

    public int $tries   = 3;
    public int $backoff = 60;

    public function __construct(public Invoice $invoice) {}

    public function handle(): void
    {
        // Email to client
        if ($this->invoice->client->email) {
            Mail::to($this->invoice->client->email)
                ->send(new PaymentReceived($this->invoice, 'client'));

            Log::info("Payment confirmation (client): {$this->invoice->invoice_number}");
        }

        // Email to business owner
        if ($this->invoice->user->notify_payment_received) {
            Mail::to($this->invoice->user->email)
                ->send(new PaymentReceived($this->invoice, 'owner'));

            Log::info("Payment confirmation (owner): {$this->invoice->invoice_number}");
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error("SendPaymentConfirmation failed for {$this->invoice->invoice_number}: " . $exception->getMessage());
    }
}
