<?php
declare( strict_types=1 );

namespace FiboFilters\Sorting;

use FiboFilters\Util\ArrayUtil;

/**
 * Class CustomSortOptionsProvider
 */
class CustomSortOptionsProvider {
	/**
	 * @var array Custom sort options cache
	 */
	private array $options;

	public function get(): array {
		if ( isset( $this->options ) ) {
			return $this->options;
		}

		$custom_catalog_orderby_raw = apply_filters( 'fibofilters/custom_catalog_orderby', [] );

		$custom_catalog_orderby_list = ArrayUtil::to_indexed_array( $custom_catalog_orderby_raw );

		try {
			// Sanitize each item individually.
			foreach ( $custom_catalog_orderby_list as $index => $item ) {
				$source      = $item['source'] ?? '';
				$item_schema = Schema\CustomSortItemSchema::get( $source );
				$item_result = rest_sanitize_value_from_schema( $item, $item_schema );
				if ( ! $item_result instanceof \WP_Error ) {
					$custom_catalog_orderby_list[ $index ] = $item_result;
				}
			}

			// Validate the entire list.
			$valid = rest_validate_value_from_schema( $custom_catalog_orderby_list, Schema\CustomSortListSchema::get() );
			if ( $valid instanceof \WP_Error ) {
				throw new \InvalidArgumentException( $valid->get_error_message() );
			}
			$this->options = $custom_catalog_orderby_list;
		} catch ( \Exception $e ) {
			_doing_it_wrong( __METHOD__, 'Invalid data returned by filter "fibofilters/custom_catalog_orderby": ' . esc_html( $e->getMessage() ), '1.11.0 of FiboFilters' );

			$this->options = [];
		}

		return $this->options;
	}
}
