<?php

namespace Limb_Chatbot\Includes\Services\Actions\Parameter_Types;

use Limb_Chatbot\Includes\Data_Objects\Parameter;

/**
 * Class URL_Parameter_Type
 *
 * Handles URL parameter validation and sanitization.
 * Supports validation rules: allowed_schemes.
 *
 * @package Limb_Chatbot\Includes\Services\Actions\Parameter_Types
 * @since 1.0.0
 */
class URL_Parameter_Type extends Abstract_Parameter_Type {

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

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

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

		$trimmed_value = trim( $value );

		// Check if field is empty
		if ( empty( $trimmed_value ) ) {
			// If empty and required, show required error
			if ( $this->is_required( $parameter ) ) {
				$this->add_error( sprintf(
					__( '%s is required.', 'limb-chatbot' ),
					$this->get_label( $parameter )
				) );
				return false;
			}
			// If empty and not required, it's valid
			return true;
		}

		// Field has value, validate URL format
		if ( ! filter_var( $trimmed_value, FILTER_VALIDATE_URL ) ) {
			$this->add_error( sprintf(
				__( 'Please provide a valid URL for %s.', 'limb-chatbot' ),
				$this->get_label( $parameter )
			) );
			return false;
		}

		// Check allowed schemes if specified
		$rules = $parameter->get_validation_rules();
		if ( ! empty( $rules ) ) {
			if ( isset( $rules['allowed_schemes'] ) && is_array( $rules['allowed_schemes'] ) ) {
				if ( ! $this->validate_scheme( $trimmed_value, $rules['allowed_schemes'], $parameter ) ) {
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Validate URL scheme
	 *
	 * @param  string  $value  URL value
	 * @param  array  $allowed_schemes  Allowed schemes
	 * @param  Parameter  $parameter  Parameter configuration
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	private function validate_scheme( string $value, array $allowed_schemes, Parameter $parameter ): bool {
		$url_scheme = parse_url( $value, PHP_URL_SCHEME );

		if ( ! in_array( $url_scheme, $allowed_schemes, true ) ) {
			$this->add_error( sprintf(
				__( '%s must use one of these protocols: %s', 'limb-chatbot' ),
				$this->get_label( $parameter ),
				implode( ', ', $allowed_schemes )
			) );

			return false;
		}

		return true;
	}

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

		return sprintf(
			__( 'For example: %s', 'limb-chatbot' ),
			$placeholder ?: 'https://example.com'
		);
	}

	public function get_config_schema(): array {
		return array(
			'lead_capture_map_field' => array(
				'type'        => 'integer',
				'description' => 'Lead capture map field',
				'required'    => false,
			),
		);
	}
}

