campaignId); $customer = Customer::find($this->customerId); if (!$campaign || !$customer || !$customer->email) { $this->markSent($campaign, failed: true); return; } try { $mailer = Mail::to($customer->email); if ($cc = $this->parseRecipients($this->cc)) { $mailer->cc($cc); } if ($bcc = $this->parseRecipients($this->bcc)) { $mailer->bcc($bcc); } $mailer->send(new ManualCustomerEmail($this->subject, $this->message)); \App\Models\Mail::create([ 'campaign_id' => $campaign->id, 'template_id' => $campaign->template_id ?? 0, 'subject' => $this->subject, 'to' => $customer->email, 'customer_id' => $customer->id, 'message' => $this->message, 'status' => 'sent', ]); $this->markSent($campaign, failed: false); } catch (\Throwable) { \App\Models\Mail::create([ 'campaign_id' => $campaign->id, 'template_id' => $campaign->template_id ?? 0, 'subject' => $this->subject, 'to' => $customer->email, 'customer_id' => $customer->id, 'message' => $this->message, 'status' => 'failed', ]); $this->markSent($campaign, failed: true); } } private function parseRecipients(?string $value): array { if (!$value) { return []; } return collect(preg_split('/[,;]+/', $value) ?: []) ->map(fn ($email) => trim((string) $email)) ->filter(fn ($email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ->unique() ->values() ->all(); } private function markSent(?MailCampaign $campaign, bool $failed): void { if (!$campaign) { return; } $campaign->increment($failed ? 'failed_count' : 'sent_count'); $campaign->refresh(); if ($campaign->sent_count + $campaign->failed_count >= $campaign->total_recipients) { $campaign->update([ 'status' => $campaign->failed_count > 0 && $campaign->sent_count === 0 ? 'failed' : 'completed', 'completed_at' => now(), ]); } } }