<?php

declare( strict_types=1 );

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

/**
 * Registers all Playard Gutenberg blocks and the "Playard" block category.
 */
class Playard_Blocks {

	/** Block slugs — used by both registration and the frontend-asset check. */
	const BLOCKS = [
		'booking-widget',
		'field-list',
		'book-now-button',
		'facility-info',
		'facility-map',
		'my-bookings',
	];

	public function register(): void {
		add_filter( 'block_categories_all', [ $this, 'add_block_category' ], 10, 2 );
		add_action( 'init',                 [ $this, 'register_block_types' ] );
	}

	/**
	 * Inject a "Playard" category at the top of the block inserter.
	 *
	 * @param array<int,array<string,mixed>> $categories
	 * @return array<int,array<string,mixed>>
	 */
	public function add_block_category( array $categories ): array {
		return array_merge(
			[
				[
					'slug'  => 'playard',
					'title' => __( 'Playard', 'playard' ),
					'icon'  => 'calendar-alt',
				],
			],
			$categories
		);
	}

	public function register_block_types(): void {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		foreach ( self::BLOCKS as $slug ) {
			register_block_type(
				PLAYARD_PATH . 'blocks/' . $slug,
				[
					'render_callback' => [ $this, 'render_' . str_replace( '-', '_', $slug ) ],
				]
			);
		}
	}

	// ── Render callbacks ──────────────────────────────────────────────────────────

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_booking_widget( array $attributes ): string {
		return ( new Playard_Shortcodes() )->render_booking_widget( [
			'field' => sanitize_text_field( (string) ( $attributes['fieldIds'] ?? '' ) ),
			'theme' => sanitize_text_field( (string) ( $attributes['theme']    ?? 'light' ) ),
		] );
	}

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_field_list( array $attributes ): string {
		ob_start();
		include PLAYARD_PATH . 'blocks/field-list/render.php';
		return (string) ob_get_clean();
	}

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_book_now_button( array $attributes ): string {
		ob_start();
		include PLAYARD_PATH . 'blocks/book-now-button/render.php';
		return (string) ob_get_clean();
	}

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_facility_info( array $attributes ): string {
		ob_start();
		include PLAYARD_PATH . 'blocks/facility-info/render.php';
		return (string) ob_get_clean();
	}

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_facility_map( array $attributes ): string {
		ob_start();
		include PLAYARD_PATH . 'blocks/facility-map/render.php';
		return (string) ob_get_clean();
	}

	/**
	 * @param array<string,mixed> $attributes
	 */
	public function render_my_bookings( array $attributes ): string {
		return ( new Playard_Shortcodes() )->render_my_bookings();
	}
}
