<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Export\Offer\Word;

use Contao\CoreBundle\Filesystem\VirtualFilesystemInterface;
use Ferienpass\CoreBundle\Export\Offer\OffersExportInterface;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\TemplateProcessor;
use Symfony\Component\Filesystem\Filesystem;

abstract class AbstractWordExport implements OffersExportInterface
{
    protected string $templatePath;
    protected Filesystem $filesystem;

    public function __construct(private readonly VirtualFilesystemInterface $exportStorage)
    {
    }

    public function generate(iterable $offers, ?string $destination = null, bool $stream = false): mixed
    {
        if (!is_file($this->templatePath)) {
            throw new \LogicException('No Word template defined');
        }

        $destination ??= \sprintf('%s.docx', uniqid('docx-', true));
        $path = 'docx/'.$destination;

        // See https://stackoverflow.com/questions/6173223/preg-match-has-string-size-limit
        // Too low limit was resulting in only being the last 20 tables being cloned (preg_match inside cloneBlock())
        ini_set('pcre.backtrack_limit', '100000000');

        Settings::setOutputEscapingEnabled(true);

        $tmpFile = $this->generateDocument($offers)->save();
        if ($stream) {
            return fopen($tmpFile, 'r+');
        }

        $this->exportStorage->write($path, file_get_contents($tmpFile));

        return $path;
    }

    abstract protected function generateDocument(iterable $offers): TemplateProcessor;

    protected function formatDatetime(\DateTimeInterface $dateTime, string $pattern): string
    {
        return new \IntlDateFormatter('de-DE', timezone: 'Europe/Berlin', pattern: $pattern)->format($dateTime);
    }
}
