<?php

namespace App\Support;

class PhoneNumber
{
    public static function normalize(?string $value, string $defaultCountryDialCode = '57'): string
    {
        $normalized = trim((string) $value);
        if ($normalized === '') {
            return '';
        }

        $normalized = preg_replace('/[^\d\+]/', '', $normalized) ?? '';
        $normalized = preg_replace('/(?!^)\+/', '', $normalized) ?? $normalized;

        if (str_starts_with($normalized, '00')) {
            $normalized = '+' . substr($normalized, 2);
        }

        $digits = preg_replace('/\D+/', '', $normalized) ?? '';
        if ($digits === '') {
            return '';
        }

        if (str_starts_with($normalized, '+')) {
            return '+' . $digits;
        }

        $defaultCountryDialCode = preg_replace('/\D+/', '', $defaultCountryDialCode) ?? '57';
        if ($defaultCountryDialCode !== '' && strlen($digits) <= 10) {
            return '+' . $defaultCountryDialCode . $digits;
        }

        return $digits;
    }

    public static function whatsappDigits(?string $value, string $defaultCountryDialCode = '57'): string
    {
        return preg_replace('/\D+/', '', self::normalize($value, $defaultCountryDialCode)) ?? '';
    }

    public static function digits(?string $value, string $defaultCountryDialCode = '57'): string
    {
        $normalized = self::normalize($value, $defaultCountryDialCode);
        return preg_replace('/\D+/', '', $normalized) ?? '';
    }

    public static function display(?string $value, string $defaultCountryDialCode = '57'): string
    {
        $normalized = self::normalize($value, $defaultCountryDialCode);
        if ($normalized === '') {
            return '';
        }

        if (preg_match('/^\+57(\d{10})$/', $normalized, $matches)) {
            return '+57 ' . substr($matches[1], 0, 3) . ' ' . substr($matches[1], 3, 3) . ' ' . substr($matches[1], 6, 4);
        }

        if (preg_match('/^\+1(\d{10})$/', $normalized, $matches)) {
            return '+1 ' . substr($matches[1], 0, 3) . ' ' . substr($matches[1], 3, 3) . ' ' . substr($matches[1], 6, 4);
        }

        if (preg_match('/^\+34(\d{9})$/', $normalized, $matches)) {
            return '+34 ' . substr($matches[1], 0, 3) . ' ' . substr($matches[1], 3, 3) . ' ' . substr($matches[1], 6, 3);
        }

        if (str_starts_with($normalized, '+')) {
            $digits = substr($normalized, 1);
            if (strlen($digits) > 4) {
                return '+' . substr($digits, 0, 2) . ' ' . trim(chunk_split(substr($digits, 2), 3, ' '));
            }
        }

        return $normalized;
    }
}
