<?php

namespace App\Mail;

use App\Models\PaymentTransaction;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class PaymentInvoiceMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public User $user,
        public PaymentTransaction $transaction,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: trans('mail.payment_invoice.subject', [], $this->mailLocale()),
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.payment-invoice',
            with: [
                'amount' => $this->formattedAmount(),
                'credits' => $this->transaction->credits_granted ?: $this->transaction->credits_expected,
                'invoicePdfUrl' => $this->transaction->invoice_pdf_url,
                'invoiceUrl' => $this->transaction->invoice_url,
                'locale' => $this->mailLocale(),
                'productName' => $this->transaction->creditProduct?->name,
                'userName' => $this->user->name,
            ],
        );
    }

    public function attachments(): array
    {
        return [];
    }

    private function formattedAmount(): string
    {
        if ($this->transaction->amount === null) {
            return trans('mail.payment_invoice.unknown_amount', [], $this->mailLocale());
        }

        return number_format($this->transaction->amount / 100, 2, ',', ' ')
            .' '
            .strtoupper($this->transaction->currency ?: 'eur');
    }

    private function mailLocale(): string
    {
        return $this->user->preferredLocale() ?? 'en';
    }
}
