<?php

namespace App\Mail;

use App\Models\Booking;
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 BookingReceiptMail extends Mailable
{
    use Queueable, SerializesModels;

    private readonly string $pdfBase64;

    /**
     * The PDF is base64-encoded before being stored on the mailable — the
     * database queue driver JSON-encodes the whole job payload, and raw
     * binary PDF bytes fail json_encode() with a "Malformed UTF-8" error.
     */
    public function __construct(public readonly Booking $booking, string $pdfContent)
    {
        $this->pdfBase64 = base64_encode($pdfContent);
    }

    public function envelope(): Envelope
    {
        return new Envelope(subject: 'Your receipt — booking '.$this->booking->booking_number);
    }

    public function content(): Content
    {
        return new Content(
            markdown: 'emails.booking-receipt',
            with: ['booking' => $this->booking],
        );
    }

    public function attachments(): array
    {
        return [
            Attachment::fromData(fn () => base64_decode($this->pdfBase64), 'receipt-'.$this->booking->booking_number.'.pdf')
                ->withMime('application/pdf'),
        ];
    }
}
