<?php

namespace Limb_Chatbot\Includes\Widgets\Data;

use Limb_Chatbot\Includes\Data_Objects\Widget;

class Messages_Widget_Config extends Abstract_Widget_Config {
	const TYPE = 'messages';

	/**
	 * Normalize REST payload into an array.
	 *
	 * WP REST can decode JSON bodies into either arrays or stdClass depending on context.
	 * We want to reliably preserve scalar keys like `delay` (including `0`).
	 */
	private function normalize_input_to_array( $data ): array {
		if ( is_array( $data ) ) {
			return $data;
		}

		if ( is_object( $data ) ) {
			$decoded = json_decode( json_encode( $data ), true );
			return is_array( $decoded ) ? $decoded : [];
		}

		return [];
	}

	public function sanitize( $data ): array {
		$data  = $this->normalize_input_to_array( $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'] ?? [] ),
				];
			}
		}

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

		if ( isset( $data['appearance'] ) && is_array( $data['appearance'] ) ) {
			$sanitized['appearance'] = [
				'theme' => $this->sanitize_string( $data['appearance']['theme'] ?? 'inherit', 'inherit' ),
			];
		}
		if ( array_key_exists( 'delay', $data ) ) {
			$raw_delay = $data['delay'];
			// Be permissive with non-numeric falsy values; delay==0 must be preserved.
			if ( is_bool( $raw_delay ) ) {
				$raw_delay = $raw_delay ? 1 : 0;
			}

			$sanitized['delay'] = max( 0, $this->sanitize_int( $raw_delay, 0 ) );
		}

		return $sanitized;
	}

	public function get_validation_errors( $data ): array {
		$data = $this->normalize_input_to_array( $data );

		if ( isset( $data['items'] ) && is_array( $data['items'] ) ) {
			return [];
		}

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

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

	public function extract_content( Widget $widget ) {
		$content = [];
		if ( $widget->get_type() != self::TYPE ) {
			return $content;
		}
		$config = is_array( $widget->config ?? null ) ? $widget->config : [];
		$items  = is_array( $config['items'] ?? null ) ? $config['items'] : [];
		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$item_content = is_array( $item['content'] ?? null ) ? $item['content'] : [];
			$content      = array_merge( $content, $item_content );
		}

		return $content;
	}
}
