<?php

namespace Easymailing\App\Utils;

class MemberPayload
{
	private static $fieldAliases = [
		'email' => ['email'],
		'phone' => ['phone'],
		'first_name' => ['first_name', 'firstname', 'firstName'],
		'last_name' => ['last_name', 'lastname', 'lastName'],
	];

	public static function identityFields(array $input): array
	{
		$body = [];
		foreach (self::$fieldAliases as $field => $aliases) {
			$value = self::firstPopulated($input, $aliases);
			if ($value !== null) {
				$body[$field] = $value;
			}
		}

		return $body;
	}

	public static function hasIdentity(array $input): bool
	{
		$body = self::identityFields($input);
		return !empty($body['email']) || !empty($body['phone']);
	}

	private static function firstPopulated(array $input, array $aliases)
	{
		foreach ($aliases as $alias) {
			if (!array_key_exists($alias, $input)) {
				continue;
			}
			$value = $input[$alias];
			if ($alias === 'phone') {
				return E164Phone::normalize($value);
			}
			if (is_string($value)) {
				$value = trim($value);
			}
			if ($value !== null && $value !== '') {
				return $value;
			}
		}

		return null;
	}
}
