<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Services;

use Barryvdh\DomPDF\Facades\Pdf;
use Maestro\Core\Modules\Invoices\Models\Invoice;
use Symfony\Component\HttpFoundation\Response;

final class InvoicePdfExporter
{
    public static function downloadResponse(Invoice $invoice): Response
    {
        $payload = InvoiceDocumentBuilder::build($invoice);

        $slug = $invoice->document_number ?? ('draft-'.$invoice->getKey());

        return Pdf::loadView('maestro-core::invoices.document', ['doc' => $payload])
            ->setPaper('a4')
            ->setOption('isRemoteEnabled', true)
            ->download(sprintf('invoice-%s.pdf', preg_replace('/[^a-zA-Z0-9._-]/', '_', $slug)));
    }

    /**
     * Raw PDF binary for mail attachments.
     */
    public static function rawPdf(Invoice $invoice): string
    {
        $payload = InvoiceDocumentBuilder::build($invoice);

        return Pdf::loadView('maestro-core::invoices.document', ['doc' => $payload])
            ->setPaper('a4')
            ->setOption('isRemoteEnabled', true)
            ->output();
    }
}
