<?php
/**
 * Scan post block content for DSM library icon picker values.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Extensions\IconLibraries;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

/**
 * Collects icon settings from saved block JSON for conditional asset loading.
 */
final class PostContentIconScanner {

	/**
	 * Scan post block content for DSM icon settings used on the page.
	 *
	 * @param int $post_id Post ID.
	 * @return array<string, array<string, mixed>>
	 */
	public static function collect_from_post_content( int $post_id ): array {
		if ( $post_id <= 0 ) {
			return array();
		}

		$content = (string) get_post_field( 'post_content', $post_id );

		if ( '' === trim( $content ) ) {
			return array();
		}

		$collected = array();

		if ( function_exists( 'parse_blocks' ) ) {
			$blocks = parse_blocks( $content );

			foreach ( $blocks as $block ) {
				if ( ! is_array( $block ) ) {
					continue;
				}

				self::walk( $block, $collected );

				if ( isset( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
					foreach ( $block['innerBlocks'] as $inner ) {
						self::walk( $inner, $collected );
					}
				}
			}
		}

		/**
		 * Allow themes/plugins to supply additional icon settings for the current request.
		 *
		 * @param array<string, array<string, mixed>> $collected Unique icon settings.
		 * @param int                                 $post_id   Post ID.
		 */
		return apply_filters( 'dsm_icon_libraries_collected_icons', $collected, $post_id );
	}

	/**
	 * @param mixed                               $value     Node to walk.
	 * @param array<string, array<string, mixed>> $collected Unique icons keyed by cache key.
	 * @return void
	 */
	private static function walk( $value, array &$collected ): void {
		if ( ! is_array( $value ) ) {
			return;
		}

		if (
			isset( $value['type'], $value['unicode'] )
			&& is_string( $value['type'] )
			&& is_string( $value['unicode'] )
			&& IconLibraryRegistry::is_dsm_library_icon( $value )
		) {
			$library_id = sanitize_key( $value['type'] );
			$icon_id    = sanitize_key( $value['unicode'] );
			$variant    = IconLibraryRegistry::resolve_variant_from_icon( $value );
			$key        = $library_id . ':' . $icon_id . ':' . $variant;

			if ( ! isset( $collected[ $key ] ) ) {
				$collected[ $key ] = $value;
			}
		}

		foreach ( $value as $child ) {
			self::walk( $child, $collected );
		}
	}
}
