<?php

declare(strict_types=1);

namespace Dealerdirect\Agreements\Pdf;

use Dealerdirect\Agreements\Exceptions\PdfGenerationException;
use Dealerdirect\Agreements\Pdf\Templates\AbstractTemplate;
use Dompdf\Dompdf;

final class Generator
{
    public function __construct(
        private Dompdf $domPdf,
        private AbstractTemplate $template
    ) {
        // throw exception if dompdf does not have the required options
        $this->validateDomPdfOptions($template->getResourcesFolder());
    }

    public function getTemplate(): AbstractTemplate
    {
        return $this->template;
    }

    public function generate(): string
    {

        $this->domPdf->loadHtml($this->template->render());
        $this->domPdf->setPaper(
            $this->template->getPaperSize()->value,
            $this->template->getOrientation()->value
        );

        $this->domPdf->render();
        if (empty($pdf = $this->domPdf->output())) {
            throw new PdfGenerationException($this->template);
        }

        // Workaround for dompdf issue with multiple render calls
        $this->domPdf = self::applyOptionsToPdf(clone $this->domPdf, $this->template->getResourcesFolder());

        return $pdf;
    }

    public static function applyOptionsToPdf(Dompdf $domPdf, string $resourcesFolder): Dompdf
    {
        $options = $domPdf->getOptions();
        $options->setChroot([$options->getRootDir(), $resourcesFolder]);
        $options->setFontDir("$resourcesFolder/fonts");
        $options->setFontCache("$resourcesFolder/fonts/cache");

        return new Dompdf($options);
    }

    public static function fromTemplate(AbstractTemplate $template): self
    {
        $domPdf = self::applyOptionsToPdf(new Dompdf(), $template->getResourcesFolder());

        return new self($domPdf, $template);
    }

    private function validateDomPdfOptions(string $resourcesFolder): void
    {
        $options = $this->domPdf->getOptions();

        if (
            !in_array($resourcesFolder, $options->getChroot(), true)
            || $options->getFontDir() !== "$resourcesFolder/fonts"
            || $options->getFontCache() !== "$resourcesFolder/fonts/cache"
        ) {
            // var_dump($resourcesFolder, $options->getChroot(), $options->getFontDir(), $options->getFontCache());die;
            throw new \InvalidArgumentException('Dompdf options do not match the resources folder');
        }
    }
}
