<?php

namespace AutoAdmin\Bundle\Content\Twig\Extension;

use AutoAdmin\Bundle\Content\Context\SiteContext;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use function twig_date_format_filter;

class SiteContextExtension extends AbstractExtension
{
    public function __construct(
        protected SiteContextHelper $siteContextHelper,
        protected Environment $twig,
    ) {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_site_context', $this->getCurrentContext(...)),
        ];
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('date', $this->formatDate(...), ['is_safe' => ['html']]),
        ];
    }

    public function getCurrentContext(): ?SiteContext
    {
        return $this->siteContextHelper->getCurrentContext();
    }

    public function formatDate($date, $format = null, $timezone = null): string
    {
        if ($timezone === null) {
            $timezone = $this->siteContextHelper->getLocale()?->getTimezone();
        }

        return twig_date_format_filter($this->twig, $date, $format, $timezone);
    }
}
