<?php
 namespace App\Listeners; use App\Events\InvoiceCreated; use App\Jobs\SendEmailJob; use App\Services\InvoicePdfService; use App\Services\NotificationService; use App\Traits\ChecksNotificationPreference; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class SendInvoiceCreatedNotification implements ShouldQueue { use InteractsWithQueue, ChecksNotificationPreference; protected InvoicePdfService $pdfService; public function __construct(InvoicePdfService $pdfService) { $this->pdfService = $pdfService; } public function handle(InvoiceCreated $event): void { $invoice = $event->invoice; if (! $invoice->client) { return; } if (! $this->shouldSendNotification($invoice->client, 'invoice_created')) { return; } $pdfAttachment = null; try { $pdfAttachment = $this->pdfService->prepareAttachment($invoice); } catch (\Throwable $e) { \Illuminate\Support\Facades\Log::error('Invoice PDF attachment skipped — email sent without PDF', [ 'invoice_id' => $invoice->id, 'error' => $e->getMessage(), ]); } SendEmailJob::dispatch( 'Invoice Created', 'invoice', $invoice->id, null, null, null, $pdfAttachment ? [$pdfAttachment] : [] ); if (setting('notify_admin_on_invoice_created', false)) { app(NotificationService::class)->notifyAdmins( type: 'Admin Invoice Created Notification', subject: __('admin/billing.notify_admin_invoice_created_subject', ['number' => $invoice->invoice_number]), message: __('admin/billing.notify_admin_invoice_created_message', [ 'number' => $invoice->invoice_number, 'client' => $invoice->client->first_name.' '.$invoice->client->last_name, 'total' => number_format($invoice->total_amount, 2), ]), data: [ 'entity_type' => 'invoice', 'entity_id' => $invoice->id, 'invoice_number' => $invoice->invoice_number, 'client_id' => $invoice->client_id, 'total' => $invoice->total_amount, 'url' => route('admin.invoices.show', $invoice->id), ] ); } } } 