<?php

namespace Storeplugin\PDFInvoice\Framework\Rest;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Config;
use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractSetting;

/**
 * Register framework settings panels with the WordPress settings REST endpoint.
 */
final class SettingOptionRegistrar
{
    /**
     * Register a settings panel option for REST exposure.
     *
     * @param AbstractSetting $setting
     * @return void
     */
    public static function register(AbstractSetting $setting): void
    {
        $optionName = $setting->restOptionName();
        if ($optionName === '') {
            return;
        }

        $properties = [];
        foreach ($setting->restFields() as $field) {
            if (!is_array($field)) {
                continue;
            }

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

            $properties[$fieldId] = FieldSchemaFactory::buildForField($field);
        }

        \register_setting(Config::option('settings_rest'), $optionName, [
            'type' => 'object',
            'label' => $setting->restLabel(),
            'description' => $setting->restDescription(),
            'default' => [],
            'sanitize_callback' => [$setting, 'restSanitizeOptionValue'],
            'show_in_rest' => [
                'schema' => [
                    'type' => 'object',
                    'properties' => $properties,
                    'additionalProperties' => false,
                ],
            ],
        ]);
    }
}
