<?php
namespace App\Core;

final class Formatter
{
    public static function lastName(?string $value): string
    {
        return mb_strtoupper(self::cleanSpaces($value), 'UTF-8');
    }

    public static function firstName(?string $value): string
    {
        $value = mb_strtolower(self::cleanSpaces($value), 'UTF-8');

        return preg_replace_callback(
            "/(^|[\s\-'])\p{L}/u",
            static fn(array $match): string =>
                mb_strtoupper($match[0], 'UTF-8'),
            $value
        ) ?? $value;
    }

    public static function city(?string $value): string
    {
        return mb_strtoupper(self::cleanSpaces($value), 'UTF-8');
    }

    public static function email(?string $value): string
    {
        return mb_strtolower(trim((string)$value), 'UTF-8');
    }

    public static function postalCode(?string $value): string
    {
        return substr(
            preg_replace('/\D+/', '', (string)$value) ?? '',
            0,
            5
        );
    }

    public static function phone(?string $value): string
    {
        $digits = self::normalizePhoneDigits($value);

        if ($digits === '') {
            return '';
        }

        if (strlen($digits) !== 9) {
            return trim((string)$value);
        }

        return '+33 ' .
            $digits[0] . ' ' .
            substr($digits, 1, 2) . ' ' .
            substr($digits, 3, 2) . ' ' .
            substr($digits, 5, 2) . ' ' .
            substr($digits, 7, 2);
    }

    /**
     * Nom utilisé par les contrôleurs CDA V3.5 / V4.
     */
    public static function validPhone(?string $value): bool
    {
        if (trim((string)$value) === '') {
            return true;
        }

        return (bool)preg_match(
            '/^[1-9]\d{8}$/',
            self::normalizePhoneDigits($value)
        );
    }

    /**
     * Alias conservé pour les anciens contrôleurs.
     */
    public static function isFrenchPhoneValid(?string $value): bool
    {
        return self::validPhone($value);
    }

    private static function normalizePhoneDigits(?string $value): string
    {
        $digits = preg_replace('/\D+/', '', (string)$value) ?? '';

        if (str_starts_with($digits, '0033')) {
            $digits = substr($digits, 4);
        } elseif (str_starts_with($digits, '33')) {
            $digits = substr($digits, 2);
        } elseif (str_starts_with($digits, '0')) {
            $digits = substr($digits, 1);
        }

        return $digits;
    }

    private static function cleanSpaces(?string $value): string
    {
        return trim(
            preg_replace('/\s+/u', ' ', (string)$value) ?? ''
        );
    }
}
