messageId = $event->message->id; $this->sender = $sender; $this->recipient = $recipient; $this->participant = $participant; } /** * Execute the job. * * @return void */ public function handle() { try { Log::info('SendDelayedEmail job starting', [ 'recipient_id' => $this->recipient->id, 'recipient_type' => get_class($this->recipient), 'participant_id' => $this->participant->id ?? 'null', 'message_id' => $this->messageId, ]); // Re-fetch the message fresh from the DB to avoid stale serialized data $message = Message::with('conversation.participants')->find($this->messageId); if (!$message) { Log::info('Message no longer exists, skipping email', ['message_id' => $this->messageId]); return; } // Refresh the participant to get the latest read state $this->participant->refresh(); // Check if the message has been read since it was sent $lastRead = $this->participant->conversation_read_at ? Carbon::parse($this->participant->conversation_read_at) : null; $messageCreatedAt = Carbon::parse($message->created_at); Log::info('Read status check', [ 'conversation_read_at' => $lastRead ? $lastRead->toDateTimeString() : 'null', 'message_created' => $messageCreatedAt->toDateTimeString(), ]); if ($lastRead && $lastRead->greaterThanOrEqualTo($messageCreatedAt)) { Log::info('Recipient has already read the message', [ 'recipient_id' => $this->recipient->id, 'message_id' => $this->messageId, ]); return; } // Build a fresh event wrapper with the re-fetched message $freshEvent = new MessageCreated($message); // Get the recipient's language preference $language = $this->recipient->lang_preference ?? config('app.locale', 'en'); Log::info('Language detection', [ 'recipient_lang_preference' => $this->recipient->lang_preference ?? 'null', 'selected_language' => $language, ]); // Send the email with the appropriate language Mail::to($this->recipient->email) ->locale($language) ->send(new NewMessageMail( $freshEvent, $this->sender, $this->recipient, $language )); Log::info('Email sent to recipient', [ 'recipient_id' => $this->recipient->id, 'recipient_type' => get_class($this->recipient), 'email' => $this->recipient->email, 'language' => $language, 'message_id' => $this->messageId, ]); } catch (\Exception $e) { Log::error('Error sending SendDelayedEmail', [ 'recipient_id' => $this->recipient->id, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); // Re-throw the exception so the job can be retried throw $e; } } /** * The job failed to process. * * @param \Throwable $exception * @return void */ public function failed(\Throwable $exception) { Log::error('SendDelayedEmail job failed', [ 'recipient_id' => $this->recipient->id, 'recipient_type' => get_class($this->recipient), 'message_id' => $this->messageId, 'error' => $exception->getMessage(), ]); } }