<?php

namespace App\Service;

use App\Entity\Payout;
use Dompdf\Dompdf;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\Writer\PngWriter;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

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

    /**
     * @codeCoverageIgnore Generates PDF with dompdf + QR code
     */
    public function generate(Payout $payout): string
    {
        $logoPath = $this->projectDir.'/public/logo.png';
        $logoBase64 = file_exists($logoPath) ? 'data:image/png;base64,'.base64_encode((string) file_get_contents($logoPath)) : '';

        $checkUrl = $this->urlGenerator->generate('app_attestation_check', [
            'stripePayoutId' => $payout->getStripePayoutId(),
        ], UrlGeneratorInterface::ABSOLUTE_URL);

        $qrCode = (new Builder(
            writer: new PngWriter(),
            data: $checkUrl,
            encoding: new Encoding('UTF-8'),
            size: 150,
            margin: 5,
        ))->build();

        $qrBase64 = 'data:image/png;base64,'.base64_encode($qrCode->getString());

        $html = $this->twig->render('pdf/payout_attestation.html.twig', [
            'payout' => $payout,
            'logoBase64' => $logoBase64,
            'qrBase64' => $qrBase64,
            'checkUrl' => $checkUrl,
        ]);

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

        return $dompdf->output();
    }

    /**
     * @codeCoverageIgnore Generates PDF file on disk
     */
    public function generateToFile(Payout $payout): string
    {
        $dir = $this->projectDir.'/var/payouts';
        if (!is_dir($dir)) {
            mkdir($dir, 0o755, true);
        }

        $filename = $dir.'/attestation_'.$payout->getStripePayoutId().'.pdf';
        file_put_contents($filename, $this->generate($payout));

        return $filename;
    }
}
