<?php

namespace App\Service;

use App\Entity\BilletBuyer;
use Dompdf\Dompdf;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Twig\Environment;

/**
 * @codeCoverageIgnore PDF generation with dompdf
 */
class InvoiceService
{
    public function __construct(
        private Environment $twig,
        #[Autowire('%kernel.project_dir%')] private string $projectDir,
    ) {
    }

    public function generatePdf(BilletBuyer $order): string
    {
        $organizer = $order->getEvent()->getAccount();

        $logoBase64 = '';
        $logoPath = $this->projectDir.'/public/logo.png';
        if (file_exists($logoPath)) {
            $logoBase64 = 'data:image/png;base64,'.base64_encode((string) file_get_contents($logoPath));
        }

        $html = $this->twig->render('pdf/invoice.html.twig', [
            'order' => $order,
            'organizer' => $organizer,
            'logoBase64' => $logoBase64,
        ]);

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4');
        $dompdf->render();

        return $dompdf->output();
    }

    public function generateToFile(BilletBuyer $order): string
    {
        $dir = $this->projectDir.'/var/invoices';
        if (!is_dir($dir)) {
            mkdir($dir, 0o755, true);
        }

        $filename = $dir.'/facture_'.$order->getOrderNumber().'.pdf';
        file_put_contents($filename, $this->generatePdf($order));

        return $filename;
    }
}
