<?php namespace App\Services; use App\Mail\BulkTemplateMail; use App\Models\Customer; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Visualbuilder\EmailTemplates\Models\EmailTemplate; class BulkEmailService { public function sendEmail( Customer $customer, EmailTemplate $template, array $replacements, string $logContext = '' ): bool { try { Log::channel('email')->info("Preparing email for customer", [ 'customer_id' => $customer->id, 'email' => $customer->email, 'template_id' => $template->id, 'context' => $logContext ]); $emailContent = $this->replaceTemplateVariables($template->content, $replacements); Mail::to($customer->email) ->send(new BulkTemplateMail($emailContent, $template->subject)); Log::channel('email')->info("Email sent successfully", [ 'customer_id' => $customer->id, 'email' => $customer->email, 'template_id' => $template->id, 'context' => $logContext ]); return true; } catch (\Exception $e) { Log::channel('email')->error("Failed to send email", [ 'customer_id' => $customer->id, 'email' => $customer->email, 'template_id' => $template->id, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'context' => $logContext ]); return false; } } private function replaceTemplateVariables(string $content, array $replacements): string { return str_replace( array_keys($replacements), array_values($replacements), $content ); } }