<?php
/**
 * @package Hafenstudios\Leadlotse
 */

namespace Hafenstudios\Leadlotse\Fields\Types;

use Hafenstudios\Leadlotse\Fields\AbstractFieldType;

defined( 'ABSPATH' ) || exit;

/**
 * E-Mail-Feld.
 */
final class EmailField extends AbstractFieldType {

	public function key(): string {
		return 'email';
	}

	/**
	 * @param mixed                $value Rohwert.
	 * @param array<string, mixed> $field Felddefinition.
	 * @return string
	 */
	public function sanitize( $value, array $field ) {
		return sanitize_email( (string) ( is_array( $value ) ? '' : $value ) );
	}

	/**
	 * @param mixed                $value Wert.
	 * @param array<string, mixed> $field Felddefinition.
	 * @return string|null
	 */
	public function validate( $value, array $field ): ?string {
		$error = $this->validate_required( $value, $field );
		if ( null !== $error ) {
			return $error;
		}
		if ( ! $this->is_empty( $value ) && ! is_email( (string) $value ) ) {
			return sprintf(
				/* translators: %s: Feldname */
				__( 'Die E-Mail-Adresse im Feld "%s" ist ungueltig. Bitte pruefen Sie die Schreibweise, z.B. name@firma.de.', 'leadlotse' ),
				(string) ( $field['label'] ?? '' )
			);
		}
		return null;
	}
}
