<?php

namespace Easymailing\App\Utils;

class CustomerPayload
{
	public static function body(array $input, ?string $resourceId = null, ?string $country = null): array
	{
		$body = [];
		foreach (['email', 'phone', 'firstname', 'lastname', 'company'] as $field) {
			$value = $input[$field] ?? null;
			if ($field === 'phone') {
				$value = self::normalizePhone($value, $country ?: ($input['country'] ?? null));
			}
			if (is_string($value)) {
				$value = trim($value);
			}
			if ($value !== null && $value !== '') {
				$body[$field] = $value;
			}
		}

		if (!empty($resourceId)) {
			$body['resource_id'] = $resourceId;
		}

		return $body;
	}

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

	public static function optInQuery(): array
	{
		return [
			'disableDoubleOptIn' => true,
			'disableWelcomeEmail' => true,
			'disableSmsDoubleOptIn' => true,
		];
	}

	public static function normalizePhone($phone, ?string $country = null): ?string
	{
		return E164Phone::normalize($phone, $country);
	}
}
