<?php

namespace GriffinForms\Editors\Gutenberg;

/**
 * Registers the Gutenberg block and hooks REST routes.
 */
class Registrar
{
    /**
     * Hook into init to register block + REST.
     */
    public static function register(): void
    {
        Rest::registerRoutes();
        static::registerBlockType();
    }

    /**
     * Register Gutenberg block definition from block.json.
     */
    private static function registerBlockType(): void
    {
        if (!function_exists('register_block_type')) {
            return;
        }

        // `editors/gutenberg` -> plugin root
        $plugin_root = dirname(__DIR__, 2);
        $block_json = $plugin_root . '/blocks/gutenberg/block.json';

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

        register_block_type(
            $block_json,
            array(
                'render_callback' => array(static::class, 'renderBlock'),
            )
        );
    }

    /**
     * Front-end render callback: delegate to existing shortcode/renderer.
     *
     * @param array $attributes Block attributes.
     * @return string
     */
    public static function renderBlock(array $attributes = array()): string
    {
        $form_id = isset($attributes['formId']) ? absint($attributes['formId']) : 0;

        if ($form_id < 1 && isset($_GET['gf_preview_form']) && current_user_can('edit_posts')) {
            $form_id = absint(wp_unslash($_GET['gf_preview_form']));
        }

        if ($form_id < 1) {
            return '';
        }

        // Optional: custom submit label wiring can be added later via filter/param.
        return do_shortcode('[griffinforms_form id="' . $form_id . '"]');
    }
}
