<?php

namespace Storeplugin\PDFInvoice\Framework\Rest;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Forms\Term;

/**
 * Register term meta REST schemas for framework term forms.
 */
final class TermMetaRegistrar
{
    /**
     * Register the term meta fields exposed by the provided form.
     *
     * @param Term $form
     * @return void
     */
    public static function register(Term $form): void
    {
        $taxonomies = $form->restTaxonomies();
        if ($taxonomies === []) {
            return;
        }

        foreach ($form->restSections() as $section) {
            $fields = isset($section['fields']) && is_array($section['fields']) ? $section['fields'] : [];

            foreach ($fields as $field) {
                if (!is_array($field)) {
                    continue;
                }

                $id = \sanitize_key((string) ($field['id'] ?? ''));
                if ($id === '') {
                    continue;
                }

                $schema = FieldSchemaFactory::buildForField($field);
                $type = isset($schema['type']) && is_string($schema['type']) ? $schema['type'] : 'string';

                foreach ($taxonomies as $taxonomy) {
                    \register_meta('term', $id, [
                        'object_subtype'    => $taxonomy,
                        'type'              => $type,
                        'description'       => $field['label'] ?? '',
                        'single'            => true,
                        'sanitize_callback' => [$form, 'sanitizeRegisteredMeta'],
                        'auth_callback'     => [$form, 'authorizeRegisteredMetaWrite'],
                        'show_in_rest'      => [
                            'schema' => $schema,
                        ],
                    ]);
                }
            }
        }
    }
}
