<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Export\Helper;

use Symfony\Contracts\Translation\TranslatorInterface;

class DateTimeHelper
{
    public function __construct(private readonly TranslatorInterface $translator) {}

    public function getLabel($header): callable
    {
        return function ($value) use ($header) {
            if ('_header' === $value) {
                return $this->translator->trans($header);
            }

            if (null === $value) {
                return '';
            }

            if ($value instanceof \DateTimeInterface) {
                return $value;
            }

            // warning: won't work with DateTimeImmutable as we reset time a few lines later
            $date = \DateTime::createFromFormat('Y-m-d', $value);
            $hasTime = false;

            if (false === $date) {
                $date = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
                $hasTime = true;
            }

            // check that the creation could occurs.
            if (false === $date) {
                throw new \Exception(sprintf('The value %s could not be converted to %s', $value, \DateTime::class));
            }

            if (!$hasTime) {
                $date->setTime(0, 0, 0);
            }

            return $date;
        };
    }
}
