<?php
/**
 * Register Block Patterns and Categories
 *
 * Handles registering custom pattern categories
 * and loading all block patterns from `/inc/patterns/`.
 *
 * @package    Wira
 * @since      1.0.0
 */

namespace Wira;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'Block_Patterns' ) ) {

	/**
	 * Block_Patterns Class
	 *
	 * Singleton class to register custom block pattern categories
	 * and dynamically load all Wira block patterns.
	 *
	 * @since 1.0.0
	 */
	class Block_Patterns {

		/**
		 * Instance of the class.
		 *
		 * @var null|Block_Patterns
		 */
		private static $instance = null;

		/**
		 * Get class instance (Singleton).
		 *
		 * @since 1.0.0
		 * @return Block_Patterns
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Constructor (private to enforce Singleton).
		 *
		 * Registers init hooks for block pattern categories and patterns.
		 *
		 * @since 1.0.0
		 */
		private function __construct() {
			add_action( 'init', array( $this, 'register_categories' ) );
			add_action( 'init', array( $this, 'load_patterns' ) );
		}

		/**
		 * Register custom block pattern categories.
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function register_categories() {
			register_block_pattern_category(
				'wira-block',
				array( 'label' => __( 'Wira Block', 'wira' ) )
			);

			register_block_pattern_category(
				'wira-page',
				array( 'label' => __( 'Wira Page', 'wira' ) )
			);
		}

		/**
		 * Dynamically load all block patterns from `/inc/patterns/`.
		 *
		 * Looks for files prefixed with `wira-` and registers
		 * them if they return a valid array with `title` and `content`.
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function load_patterns() {
			$pattern_dir = get_template_directory() . '/inc/patterns/';

			// Require each file in `/inc/patterns/` that starts with `wira-`.
			foreach ( glob( $pattern_dir . 'wira-*.php' ) as $pattern_file ) {
				$pattern = require $pattern_file;

				// Ensure the file returns a valid block pattern array.
				if ( is_array( $pattern ) && isset( $pattern['title'], $pattern['content'] ) ) {
					register_block_pattern(
						'wira/' . sanitize_title( $pattern['title'] ),
						$pattern
					);
				}
			}
		}
	}
}
