<?php

declare(strict_types=1);

namespace Dealerdirect\Agreements\Pdf\Templates;

use Dealerdirect\Agreements\DataObjects\DataObject;
use Dealerdirect\Agreements\Enums\Locale;
use Dealerdirect\Agreements\Enums\Orientation;
use Dealerdirect\Agreements\Enums\PaperSize;
use Dealerdirect\Agreements\Exceptions\TemplateFileNotFoundException;
use Dealerdirect\Agreements\Exceptions\TemplateRenderingException;
use Dealerdirect\Agreements\Utils\Translator;

abstract class AbstractTemplate
{
    public function __construct(
        protected Locale $locale,
        protected DataObject $data,
        protected Translator $translator,
        protected ?string $resourcesFolder = null
    ) {
        $this->resourcesFolder ??= dirname(__DIR__, 3) . '/resources';
    }

    public function getResourcesFolder(): string
    {
        return $this->resourcesFolder;
    }

    public function render(): string
    {
        $templatePath = sprintf('%s/templates/%s', $this->resourcesFolder, $this->getTemplate());
        if (!file_exists($templatePath)) {
            throw new TemplateFileNotFoundException($this->getTemplate(), $this->resourcesFolder . '/templates');
        }

        try {
            ob_start();
            $data = $this->data;
            include $templatePath;
            $content = ob_get_clean();
        } catch (\Throwable $e) {
            ob_get_clean();

            throw new TemplateRenderingException("Could not render template: '{$e->getMessage()}'", $e);
        }

        return $content;
    }

    public function getPaperSize(): PaperSize
    {
        return PaperSize::A4;
    }

    public function getOrientation(): Orientation
    {
        return Orientation::PORTRAIT;
    }

    /**
     * @param array<string,mixed> $replacements
     */
    public function translate(string $key, array $replacements = []): mixed
    {
        $result = $this->translator->get($key, $replacements);

        // Fix for quotes that are not shown correctly in the PDF with custom (ARegular) fonts
        // Surround quotes with a span to apply a different font
        return preg_replace('/["\']|\x{00b4}/u', '<span class="quote">$0</span>', $result);
    }

    /**
     * @return string The template file name
     */
    abstract protected function getTemplate(): string;
}
