Files
fotospiel-app/app/Mail/PurchaseConfirmation.php

95 lines
2.6 KiB
PHP

<?php
namespace App\Mail;
use App\Models\PackagePurchase;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class PurchaseConfirmation extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public PackagePurchase $purchase)
{
//
}
public function envelope(): Envelope
{
return new Envelope(
subject: __('emails.purchase.subject', ['package' => $this->localizedPackageName()]),
);
}
public function content(): Content
{
return new Content(
view: 'emails.purchase',
with: [
'purchase' => $this->purchase,
'user' => $this->purchase->tenant->user,
'package' => $this->purchase->package,
'packageName' => $this->localizedPackageName(),
'priceFormatted' => $this->formattedTotal(),
],
);
}
public function attachments(): array
{
return [];
}
private function localizedPackageName(): string
{
$locale = $this->locale ?? app()->getLocale();
return optional($this->purchase->package)->getNameForLocale($locale) ?? '';
}
private function formattedTotal(): string
{
$totals = $this->purchase->metadata['paddle_totals'] ?? [];
$currency = $totals['currency']
?? $this->purchase->metadata['currency']
?? $this->purchase->package?->currency
?? 'EUR';
$amount = array_key_exists('total', $totals) ? (float) $totals['total'] : (float) $this->purchase->price;
$locale = $this->locale ?? app()->getLocale();
$formatter = class_exists(\NumberFormatter::class)
? new \NumberFormatter($this->mapLocale($locale), \NumberFormatter::CURRENCY)
: null;
if ($formatter) {
$formatted = $formatter->formatCurrency($amount, $currency);
if ($formatted !== false) {
return $formatted;
}
}
$symbol = match ($currency) {
'EUR' => '€',
'USD' => '$',
default => $currency,
};
return number_format($amount, 2, ',', '.').' '.$symbol;
}
private function mapLocale(string $locale): string
{
$normalized = strtolower(str_replace('_', '-', $locale));
return match (true) {
str_starts_with($normalized, 'de') => 'de_DE',
str_starts_with($normalized, 'en') => 'en_US',
default => 'de_DE',
};
}
}