<?php

namespace App\Mail\Reminders;

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;

/**
 * Single mailable for all smart billing reminders; body is admin-editable HTML.
 */
class DynamicReminderMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * @param  list<array{content: string, as: string, mime: string}>  $binaryAttachments
     */
    public function __construct(
        public string $subjectLine,
        public string $htmlBody,
        public string $textBody,
        public array $binaryAttachments = [],
        public array $ccAddresses = []
    ) {}

    public function envelope(): Envelope
    {
        $envelope = new Envelope(
            subject: $this->subjectLine,
        );

        if ($this->ccAddresses !== []) {
            $envelope = $envelope->cc($this->ccAddresses);
        }

        return $envelope;
    }

    public function content(): Content
    {
        return new Content(
            htmlString: $this->htmlBody,
            text: $this->textBody,
        );
    }

    /**
     * @return array<int, Attachment>
     */
    public function attachments(): array
    {
        $out = [];
        foreach ($this->binaryAttachments as $row) {
            if (empty($row['content'])) {
                continue;
            }
            $out[] = Attachment::fromData(
                fn () => $row['content'],
                $row['as'] ?? 'attachment.pdf',
                ['mime' => $row['mime'] ?? 'application/pdf']
            );
        }

        return $out;
    }
}
