<?php
namespace PortalPeople\ShippingFields\Model;

class ShippingDateFormatter
{
    /**
     * Normalize accepted date inputs to canonical storage format.
     */
    public function normalizeForStorage($value): ?string
    {
        if ($value === null) {
            return null;
        }

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

        foreach (['Y-m-d', 'd/m/Y'] as $format) {
            $date = \DateTime::createFromFormat('!' . $format, $value);
            if ($date && $date->format($format) === $value) {
                return $date->format('Y-m-d');
            }
        }

        try {
            return (new \DateTime($value))->format('Y-m-d');
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Format a stored date for human-friendly display.
     */
    public function formatForDisplay($value): string
    {
        $normalized = $this->normalizeForStorage($value);
        if ($normalized === null) {
            return '';
        }

        return \DateTime::createFromFormat('!Y-m-d', $normalized)->format('d/m/Y');
    }
}