<?php
/**
 * WeCodeArt Framework
 *
 * WARNING: This file is part of the core WeCodeArt Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package		WeCodeArt Framework
 * @subpackage  Gutenberg Pattern
 * @copyright   Copyright (c) 2025, WeCodeArt Framework
 * @since		5.0.0
 * @version		6.3.7
 */

namespace WeCodeArt\Gutenberg\Patterns;

defined( 'ABSPATH' ) || exit;

/**
 * Class representing a block template.
 */
class Categories {
    /**
	 * Container of data in categories.json format.
	 *
	 * @var array
	 */
	private $theme_json = null;

	/**
	 * Container of valid json properties.
	 *
	 * @var array
	 */
	const VALID_PROPERTIES = [
		'slug',
		'label',
	];

	/**
	 * Constructor.
	 *
	 * @param array $theme_json A structure that follows the theme.json schema.
	 */
	public function __construct( $theme_json = [] ) {
		$this->theme_json = self::sanitize( $theme_json );
	}

	/**
	 * Sanitizes the input according to the schemas.
	 *
	 * @param array $input 				Structure to sanitize.
	 *
	 * @return array The sanitized output.
	 */
	private static function sanitize( $input ) {
		$output = [];

		if ( ! is_array( $input ) ) {
			return $output;
		};

		// Remove anything that's not present in the schema.
		foreach( $input as $key => $category ) {
			$result = array_intersect_key( (array) $category, array_flip( self::VALID_PROPERTIES ) );
			
			if ( empty( $result ) ) {
				unset( $output[ $key ] );
			} else {
				$output[ $key ] = array_map( 'sanitize_text_field', $result );
			}
		}

		return $output;
	}

	/**
	 * Register the categories.
	 *
	 * @return void.
	 */
	public function register() {
		foreach( $this->theme_json as $category ) {
			// Skip registered
			if( \WP_Block_Pattern_Categories_Registry::get_instance()->is_registered( $category['slug'] ) ) {
				continue;
			}

			// Register pattern
			register_block_pattern_category( $category['slug'], wp_array_slice_assoc( $category, [ 'label' ] ) );
		}
	}
}
