<?php

namespace App\Services;

use App\Helpers\CompanyMedia;
use App\Models\Payment;
use Barryvdh\DomPDF\Facade\Pdf;
use Symfony\Component\HttpFoundation\Response;

class PaymentPdfGenerator
{
    /**
     * @param  array<string, mixed>  $data
     */
    public function download(Payment $payment, array $data, ?string $documentCopyLabel = null): Response
    {
        return $this->make($payment, $data, $documentCopyLabel)->download($this->filename($payment));
    }

    public function stream(Payment $payment, array $data, ?string $documentCopyLabel = null): Response
    {
        return $this->make($payment, $data, $documentCopyLabel)
            ->stream($this->filename($payment))
            ->withHeaders([
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                'Pragma' => 'no-cache',
            ]);
    }

    /**
     * @param  array<string, mixed>  $data
     */
    private function make(Payment $payment, array $data, ?string $documentCopyLabel): \Barryvdh\DomPDF\PDF
    {
        $company = $data['company'];
        $data['documentCopyLabel'] = $documentCopyLabel
            ?? ($data['documentCopies']['original'] ?? 'Original Copy');
        $data['forPdf'] = true;
        $data['logoPath'] = CompanyMedia::pdfImagePath($company->logo_path);
        $data['signaturePath'] = CompanyMedia::pdfImagePath($company->signature_image_path);

        return Pdf::loadView('admin.payments.pdf', $data)
            ->setPaper('a4', 'portrait');
    }

    private function filename(Payment $payment): string
    {
        $num = preg_replace('/[^a-zA-Z0-9_-]+/', '-', $payment->payment_number ?? 'payment');

        return 'payment-'.$num.'.pdf';
    }
}
