<?php

namespace Limb_Chatbot\Includes\Widgets\Data;

use Limb_Chatbot\Includes\Data_Objects\Widget;

/**
 * Base class for widget-type data sanitization.
 *
 * @since 2.0.0
 */
abstract class Abstract_Widget_Config implements Widget_Config_Interface {

	/**
	 * Normalized config payload.
	 *
	 * @var array
	 */
	protected array $config = [];

	public function get_config(): array {
		return $this->config;
	}

	public function set_config( array $config ): void {
		$this->config = $config;
	}

	protected function set_config_value( string $key, $value ): void {
		$this->config[ $key ] = $value;
	}

	public function get_config_value( string $key, $default = null ) {
		return $this->config[ $key ] ?? $default;
	}

	protected function sanitize_string( $value, string $default = '' ): string {
		if ( ! is_scalar( $value ) ) {
			return $default;
		}

		return sanitize_text_field( (string) $value );
	}

	protected function sanitize_textarea( $value, string $default = '' ): string {
		if ( ! is_scalar( $value ) ) {
			return $default;
		}

		return sanitize_textarea_field( (string) $value );
	}

	protected function sanitize_bool( $value, bool $default = false ): bool {
		if ( is_bool( $value ) ) {
			return $value;
		}
		if ( is_numeric( $value ) ) {
			return (int) $value == 1;
		}
		if ( is_string( $value ) ) {
			return in_array( strtolower( $value ), [ '1', 'true', 'yes' ], true );
		}

		return $default;
	}

	protected function sanitize_int( $value, int $default = 0 ): int {
		if ( ! is_numeric( $value ) ) {
			return $default;
		}

		return (int) $value;
	}

	protected function sanitize_url_or_empty( $value ): string {
		if ( ! is_scalar( $value ) ) {
			return '';
		}
		$url = esc_url_raw( (string) $value );

		return is_string( $url ) ? $url : '';
	}

	protected function sanitize_rich_blocks( $value ): array {
		if ( ! is_array( $value ) ) {
			return [];
		}

		return wp_kses_post_deep( $value );
	}

	public function get_dependencies() {
		return [];
	}

	public function get_translatable_fields(): array {
		return [];
	}

	/**
	 * @param  mixed  $data  Sanitized payload.
	 *
	 * @return array<string, string>
	 */
	public function get_validation_errors( $data ): array {
		if ( $this->validate( $data ) ) {
			return [];
		}

		return [
			'general' => __( 'Please review this widget\'s settings.', 'limb-chatbot' ),
		];
	}
}
