<?php

namespace Storeplugin\PDFInvoice\App\Settings;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Contracts\ServiceInterface;

class FreeVersionOptionGuard implements ServiceInterface
{
    public function register(): void
    {
        foreach ($this->guardedGroups() as $group) {
            add_filter('pre_update_option_' . $group, [$this, 'enforceLockedValues'], 10, 3);
        }
    }

    /**
     * @return array<int, string>
     */
    private function guardedGroups(): array
    {
        return [
            SettingsSchema::GROUP_INVOICE_EDITOR,
            SettingsSchema::GROUP_PACKING_SLIP_EDITOR,
            SettingsSchema::GROUP_SETTINGS,
        ];
    }

    /**
     * Enforce free-version locked values before WordPress persists the option.
     *
     * @param mixed  $value
     * @param mixed  $oldValue
     * @param string $option
     * @return array<string, mixed>
     */
    public function enforceLockedValues($value, $oldValue, string $option): array
    {
        $value = is_array($value) ? $value : [];
        $option = sanitize_key($option);

        return SettingsSchema::normalizeOptionsForGroup($value, $option);
    }
}
