<?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\Xml;

use Contao\CoreBundle\Filesystem\VirtualFilesystemInterface;
use Contao\File;
use Contao\FilesModel;
use Ferienpass\CoreBundle\Entity\Host;
use Ferienpass\CoreBundle\Entity\Offer\Base;
use Ferienpass\CoreBundle\Export\Offer\OffersExportInterface;
use Symfony\Component\DependencyInjection\Attribute\Exclude;
use Twig\Environment;

#[Exclude]
class XmlExport implements OffersExportInterface
{
    public function __construct(private readonly string $template, private readonly Environment $twig, private readonly VirtualFilesystemInterface $exportStorage)
    {
    }

    public static function getName(): string
    {
        // Service locator name is set via DI extension
        return '';
    }

    public function generate(iterable $offers, ?string $destination = null, bool $stream = false): mixed
    {
        $xml = $this->render($offers);
        $hash = md5($xml);
        $destination ??= \sprintf('xml-%s.xml', $hash);
        $path = 'xml/'.$destination;

        if ($stream) {
            $stream = fopen('php://temp', 'r+');
            fwrite($stream, $xml);
            rewind($stream);

            return $stream;
        }

        $this->exportStorage->write($path, $xml);

        return $path;
    }

    private function render(iterable $items): string
    {
        $images = [];
        /** @var Base $item */
        foreach ($items as $item) {
            foreach (array_filter($item->getHosts()->map(static fn (Host $h) => FilesModel::findByPk($h->getLogoOld()))->toArray()) as $logo) {
                $images[$logo->uuid] = array_merge($logo->row(), [
                    'path' => $logo->path,
                    'dimensions' => new File($logo->path)->imageViewSize,
                ]);
            }
        }

        return $this->twig->render($this->template, ['offers' => $items, 'images' => $images]);
    }
}
