<?php

declare(strict_types=1);

namespace App\Framework\View\Table\Formatters;

use App\Framework\View\Table\CellFormatter;

final readonly class DateFormatter implements CellFormatter
{
    public function __construct(
        private string $format = 'Y-m-d H:i:s'
    ) {
    }

    public function format(mixed $value): string
    {
        if ($value === null || $value === '') {
            return '';
        }

        if ($value instanceof \DateTimeInterface) {
            return $value->format($this->format);
        }

        if (is_string($value) || is_numeric($value)) {
            try {
                $date = new \DateTime($value);

                return $date->format($this->format);
            } catch (\Exception) {
                return htmlspecialchars((string) $value, ENT_QUOTES);
            }
        }

        return htmlspecialchars((string) $value, ENT_QUOTES);
    }

    public static function short(): self
    {
        return new self('Y-m-d');
    }

    public static function long(): self
    {
        return new self('d.m.Y H:i:s');
    }

    public static function german(): self
    {
        return new self('d.m.Y');
    }
}
