<?php

declare(strict_types=1);

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig;

use Symfony\Component\Intl\Countries;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class IntToDateConvertExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('intToDate', [$this, 'intToDate']),
            new TwigFilter('country_name_alpha3', [$this, 'getCountryNameAlpha3']),
        ];
    }

    public function intToDate(string|int $value): string
    {
        $value = (string) $value;

        if (mb_strlen($value) < 4) {
            $month = '0'.mb_substr($value, 0, 1);
            $day = mb_substr($value, 1, 2);
        } else {
            $month = mb_substr($value, 0, 2);
            $day = mb_substr($value, 2, 2);
        }

        return $day.'-'.$month;
    }

    public function getCountryNameAlpha3(?string $country, ?string $locale = null): ?string
    {
        if (null === $country || '' === $country) {
            return null;
        }

        return Countries::getAlpha3Name($country, $locale);
    }
}
