<?php

namespace Formatrica\Frontend;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
final class Block_Registrar
{
    public function register_block(): void
    {
        if (!function_exists('register_block_type')) {
            return;
        }

        $metadata_path = FORMATRICA_PATH . 'blocks/form/block.json';

        if (!file_exists($metadata_path)) {
            return;
        }

        $args = [
            'render_callback' => [$this, 'render_block'],
            'editor_script'   => 'formatrica-block',
        ];

        // Editor styles: the block bundle's own CSS plus the frontend form CSS,
        // so the server-side-rendered preview is styled in the Gutenberg canvas.
        $editor_styles = [];
        if (wp_style_is('formatrica-block-style', 'registered')) {
            $editor_styles[] = 'formatrica-block-style';
        }
        if (wp_style_is('formatrica-block-editor', 'registered')) {
            $editor_styles[] = 'formatrica-block-editor';
        }
        if (count($editor_styles) === 1) {
            $args['editor_style'] = $editor_styles[0];
        } elseif (count($editor_styles) > 1) {
            $args['editor_style_handles'] = $editor_styles;
        }

        register_block_type_from_metadata($metadata_path, $args);
    }

    public function render_block(array $attributes, string $content, \WP_Block $block): string
    {
        $form_id = isset($attributes['formId']) ? (int) $attributes['formId'] : 0;

        if ($form_id <= 0) {
            return '';
        }

        // Reuse shortcode which enforces active flag
        return do_shortcode('[formatrica id="' . $form_id . '"]');
    }
}
