<?php

namespace App\Mail;

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

class NotaServiceMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly ServiceTicket $ticket
    ) {}

    // ── Envelope ──────────────────────────────────────────────

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: "Nota Servis #{$this->ticket->ticket_code} — Service Center",
        );
    }

    // ── Content ───────────────────────────────────────────────

    public function content(): Content
    {
        return new Content(
            view: 'emails.nota',
            with: [
                'ticket'   => $this->ticket,
                'notaUrl'  => route('nota.show', $this->ticket->ticket_code),
            ],
        );
    }

    // ── Attachments ───────────────────────────────────────────

    public function attachments(): array
    {
        // Generate PDF in-memory and attach
        $pdf = Pdf::loadView('nota.pdf', ['ticket' => $this->ticket])
            ->setPaper('a4', 'portrait');

        return [
            \Illuminate\Mail\Mailables\Attachment::fromData(
                fn () => $pdf->output(),
                "Nota-{$this->ticket->ticket_code}.pdf"
            )->withMime('application/pdf'),
        ];
    }
}
