<?php
declare( strict_types=1 );

namespace FiboFilters\Widgets;

use FiboFilters\Config\Env;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WordPress' widgets class
 */
class Widgets {

	public function __construct() {
		add_filter( 'widget_types_to_hide_from_legacy_widget_block', [ $this, 'hide_widgets' ] );
	}

	public function init(): void {

		$widgets = [
			'filters' => [
				'class'     => '\FiboFilters\Widgets\Filters',
				'file_path' => Env::$path . '/lib/Widgets/Filters.php',
			],
		];

		// Include files.
		foreach ( $widgets as $name => $widget ) {
			$valid = false;
			if ( file_exists( $widget['file_path'] ) ) {
				require_once $widget['file_path'];
				$valid = class_exists( $widget['class'] );
			}

			if ( ! $valid ) {
				unset( $widgets[ $name ] );
			}
		}

		add_action(
			'widgets_init',
			function () use ( $widgets ) {
				if ( ! function_exists( 'register_widget' ) ) {
					return;
				}
				foreach ( $widgets as $widget ) {
					register_widget( $widget['class'] );
				}
			}
		);
	}

	/**
	 * Hide our widgets from the legacy widget block
	 *
	 * @param array $widget_types Widget types.
	 */
	public function hide_widgets( array $widget_types ): array {
		$widget_types[] = 'fibofilters-filters-widget';

		return $widget_types;
	}
}
