<?php
/**
 * Gutenberg block registration.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_Blocks {

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'init', array( $this, 'register_blocks' ) );
	}

	/**
	 * Register the QR Code block.
	 */
	public function register_blocks(): void {
		register_block_type( GOVALID_QR_PLUGIN_DIR . 'blocks/qr-code', array(
			'render_callback' => array( $this, 'render_qr_block' ),
		) );

		register_block_type( GOVALID_QR_PLUGIN_DIR . 'blocks/form', array(
			'render_callback' => array( $this, 'render_form_block' ),
		) );
	}

	/**
	 * Server-side render callback for the QR Code block.
	 *
	 * @param array $attributes Block attributes.
	 * @return string HTML output.
	 */
	public function render_qr_block( array $attributes ): string {
		$uuid       = isset( $attributes['qrId'] ) ? sanitize_text_field( $attributes['qrId'] ) : '';
		$width      = isset( $attributes['width'] ) ? absint( $attributes['width'] ) : 200;
		$alignment  = isset( $attributes['alignment'] ) ? sanitize_text_field( $attributes['alignment'] ) : 'center';
		$show_label = isset( $attributes['showLabel'] ) ? (bool) $attributes['showLabel'] : false;

		if ( empty( $uuid ) ) {
			if ( current_user_can( 'edit_posts' ) ) {
				return '<p class="govalid-qr-placeholder">'
					. esc_html__( 'Select a QR code in the block settings.', 'govalid-qr-validator' )
					. '</p>';
			}
			return '';
		}

		// Reuse shortcode rendering.
		$shortcodes = new GoValid_Shortcodes();
		return $shortcodes->render_qr_shortcode( array(
			'id'         => $uuid,
			'width'      => (string) $width,
			'align'      => $alignment,
			'show_label' => $show_label ? 'true' : 'false',
		) );
	}

	/**
	 * Server-side render callback for the Form block.
	 *
	 * @param array $attributes Block attributes.
	 * @return string HTML output.
	 */
	public function render_form_block( array $attributes ): string {
		$form_id = isset( $attributes['formId'] ) ? absint( $attributes['formId'] ) : 0;

		$form_shortcode = new GoValid_Form_Shortcode();
		return $form_shortcode->render( array( 'id' => $form_id ) );
	}
}
