<?php

namespace App\Services;

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

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

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

    /**
     * @param  array<string, mixed>  $data
     */
    private function make(PurchaseOrder $debitNote, 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);
        $data['logoSrc'] = null;
        $data['signatureSrc'] = null;
        $data['layout'] = 'a4';

        $tempDir = storage_path('framework/dompdf');
        if (! is_dir($tempDir)) {
            @mkdir($tempDir, 0755, true);
        }

        return Pdf::loadView('admin.purchase-orders.pdf', $data)
            ->setPaper('a4', 'portrait')
            ->setOption('isHtml5ParserEnabled', true)
            ->setOption('isRemoteEnabled', false)
            ->setOption('defaultFont', 'DejaVu Sans')
            ->setOption('tempDir', $tempDir)
            ->setOption('chroot', realpath(base_path()) ?: base_path());
    }

    private function filename(PurchaseOrder $debitNote): string
    {
        $safe = preg_replace('/[^a-zA-Z0-9._-]+/', '_', $debitNote->purchase_order_number) ?: 'purchase-order';

        return $safe.'_'.now()->format('Y-m-d').'.pdf';
    }
}
