<?php

namespace Limb_Chatbot\Includes\Services\Actions\Parameter_Types;

use Limb_Chatbot\Includes\Data_Objects\Parameter;

/**
 * Class Phone_Parameter_Type
 *
 * Handles phone parameter validation and sanitization.
 *
 * @package Limb_Chatbot\Includes\Services\Actions\Parameter_Types
 * @since 1.0.0
 */
class Phone_Parameter_Type extends Abstract_Parameter_Type {

	/**
	 * @inheritDoc
	 */
	public function get_type(): string {
		return Parameter::TYPE_PHONE;
	}

	/**
	 * @inheritDoc
	 */
	public function sanitize( string $value, Parameter $parameter ): string {
		return sanitize_text_field( trim( $value ) );
	}

	/**
	 * @inheritDoc
	 */
	public function validate( string $value, Parameter $parameter ): bool {
		$this->clear_errors();

		$trimmed_value = trim( $value );
		if ( empty( $trimmed_value ) ) {
			if ( $this->is_required( $parameter ) ) {
				$this->add_error(
					sprintf(
						__( '%s is required.', 'limb-chatbot' ),
						$this->get_label( $parameter )
					)
				);

				return false;
			}

			return true;
		}

		$digits = preg_replace( '/\D/', '', $trimmed_value );
		if ( strlen( $digits ) < 6 ) {
			$this->add_error(
				sprintf(
					__( 'Please provide a valid phone number for %s.', 'limb-chatbot' ),
					$this->get_label( $parameter )
				)
			);

			return false;
		}

		return true;
	}

	/**
	 * For phone parameters, config items are valid when value is not empty.
	 *
	 * @param  string  $config_key
	 * @param  mixed  $config_value
	 *
	 * @return bool
	 */
	public function is_valid_config( string $config_key, $config_value ): bool {
		return ! empty( $config_value );
	}

	public function get_hint( Parameter $parameter ): ?string {
		$placeholder = $parameter->get_placeholder();

		return sprintf(
			__( 'For example: %s', 'limb-chatbot' ),
			$placeholder ?: '+1 (555) 123-4567'
		);
	}
}

