<?php

namespace Velis\Pdf;

use Velis\App;
use Velis\Mvc\View;
use Velis\Pdf\Renderer\DompdfRenderer;
use Velis\Pdf\Renderer\WkhtmltopdfRenderer;

/**
 * @author Łukasz Gąsiorek <lukasz.gasiorek@velistech.com>
 */
abstract class PdfView
{
    /**
     * @var Document
     */
    protected Document $pdf;

    public function __construct()
    {
        $this->pdf = new Document();
    }

    abstract public function render(): string;

    /**
     * Render PDF from template file
     *
     * @param string $template
     * @param array $templateVars
     * @return string
     */
    protected function renderPdf(string $template, array $templateVars = []): string
    {
        /** @var View\Engine\EngineFactory $factory */
        $factory = App::getService('templatingEngineFactory');
        $view = new View();
        $renderer = $factory->createEngine($view);

        $moduleViewPath = explode('\\', get_class($this));
        $namespaceTemplatesDir = MODULE_PATH . reset($moduleViewPath) . '/view/pdf';
        $renderer->setTemplateDir($namespaceTemplatesDir);
        $renderer->assign($templateVars);

        $documentContent = $renderer->fetch($template);
        $pdfRenderer = null;

        if (App::$config->settings->pdfRenderer == 'dompdf' && class_exists('\Dompdf\Dompdf')) {
            $pdfRenderer = new DompdfRenderer($this->pdf);
        } else {
            $pdfRenderer = new WkhtmltopdfRenderer($this->pdf);
        }

        $pdfRenderer->setContent($documentContent);

        return $pdfRenderer->render();
    }
}
