<?php
namespace EasyChat\Library\Crm;

final class AmoCrmDomain {
    public static function normalize(string $value): string {
        $value = strtolower(trim($value));
        if (strpos($value, '://') !== false) {
            $parts = parse_url($value);
            if (!is_array($parts)
                || strtolower((string)($parts['scheme'] ?? '')) !== 'https'
                || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
                || (isset($parts['port']) && (int)$parts['port'] !== 443)
                || trim((string)($parts['path'] ?? ''), '/') !== ''
            ) return '';
            $value = strtolower((string)($parts['host'] ?? ''));
        }
        $value = trim($value, '.');
        if ($value === '' || filter_var($value, FILTER_VALIDATE_IP) !== false || !preg_match('/^[a-z0-9][a-z0-9.-]{1,251}[a-z0-9]$/', $value)) return '';
        foreach (array('amocrm.ru', 'amocrm.com', 'kommo.com') as $suffix) {
            if ($value !== $suffix && substr($value, -strlen('.' . $suffix)) === '.' . $suffix) return $value;
        }
        return '';
    }
}
