<?php

namespace App\Core\Services\Invoice;

use App\Models\Invoice;
use App\Support\InvoicePdfViewVariables;
use App\Support\InvoiceTemplateResolver;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Support\Facades\View;

/**
 * PDF Service
 * Generates PDF invoices for download, email, and previews.
 */
class PdfService
{
    /**
     * Generate PDF for invoice
     */
    public function generate(Invoice $invoice): string
    {
        $options = new Options;
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');

        $dompdf = new Dompdf($options);

        $invoice->load(['customer', 'items']);

        $templateKey = InvoiceTemplateResolver::resolveKeyForInvoice($invoice);
        $pdfView = InvoiceTemplateResolver::pdfView($templateKey);

        $html = View::make($pdfView, array_merge(
            InvoicePdfViewVariables::forInvoice($invoice),
            [
                'invoice' => $invoice,
                'showWatermark' => false,
            ]
        ))->render();

        $dompdf->loadHtml($html);
        // Explicit A4 in points (72 dpi) so page size is always correct in viewers
        $dompdf->setPaper([0.0, 0.0, 595.28, 841.89], 'portrait');
        $dompdf->render();

        return $dompdf->output();
    }

    /**
     * Download PDF
     */
    public function download(Invoice $invoice): \Symfony\Component\HttpFoundation\Response
    {
        $pdf = $this->generate($invoice);
        $filename = 'invoice-'.$invoice->invoice_number.'.pdf';

        return response()->streamDownload(function () use ($pdf) {
            echo $pdf;
        }, $filename, [
            'Content-Type' => 'application/pdf',
        ]);
    }

    /**
     * Get PDF as base64 string
     */
    public function getBase64(Invoice $invoice): string
    {
        $pdf = $this->generate($invoice);

        return base64_encode($pdf);
    }
}
