<?php

namespace Limb_Chatbot\Includes\Widgets\Data;

class Prompts_Widget_Config extends Abstract_Widget_Config {
	public function sanitize( $data ): array {
		$data = is_array( $data ) ? $data : [];
		$items = [];

		if ( isset( $data['items'] ) && is_array( $data['items'] ) ) {
			foreach ( $data['items'] as $item ) {
				if ( ! is_array( $item ) ) {
					continue;
				}
				$items[] = [
					'content' => $this->sanitize_rich_blocks( $item['content'] ?? [] ),
					'value'   => $this->sanitize_rich_blocks( $item['value'] ?? [] ),
				];
			}
		}

		$sanitized = [
			'section_title' => $this->sanitize_string( $data['section_title'] ?? '' ),
			'items'         => $items,
		];

		if ( isset( $data['appearance'] ) && is_array( $data['appearance'] ) ) {
			$sanitized['appearance'] = [
				'theme'  => $this->sanitize_string( $data['appearance']['theme'] ?? 'inherit', 'inherit' ),
				'layout' => $this->sanitize_string( $data['appearance']['layout'] ?? 'row', 'row' ),
				'size'   => $this->sanitize_string( $data['appearance']['size'] ?? 'md', 'md' ),
			];
		}
		if ( array_key_exists( 'delay', $data ) ) {
			$sanitized['delay'] = max( 0, $this->sanitize_int( $data['delay'], 0 ) );
		}

		return $sanitized;
	}

	public function get_validation_errors( $data ): array {
		if ( is_array( $data ) && isset( $data['items'] ) && is_array( $data['items'] ) && count( $data['items'] ) > 0 ) {
			return [];
		}

		return [
			'items' => __( 'Add at least one prompt suggestion.', 'limb-chatbot' ),
		];
	}

	public function validate( $data ): bool {
		return empty( $this->get_validation_errors( $data ) );
	}
}
