<?php

namespace App\Mail;

use App\Models\PlatformPayment;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class SubscriptionInvoiceMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly PlatformPayment $payment
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Your Invoice ' . $this->payment->invoice_number . ' — ' . config('app.name'),
        );
    }

    public function content(): Content
    {
        return new Content(view: 'emails.subscription-invoice');
    }

    public function attachments(): array
    {
        $payment = $this->payment->load('organization', 'subscription');

        $pdf = Pdf::loadView('invoices.subscription', [
            'payment' => $payment,
            'org'     => $payment->organization,
        ])->setPaper('a4', 'portrait');

        return [
            Attachment::fromData(
                fn () => $pdf->output(),
                "invoice-{$payment->invoice_number}.pdf"
            )->withMime('application/pdf'),
        ];
    }
}
