<?php

declare(strict_types=1);

namespace MyCustomizer\WooCommerce\Connector\Libs;

use Exception;

class MczrSettings
{
    private const SETTING_OPTION_FIELDS = [
        'authorizationKey',
        'iframeWidth',
        'iframeHeight',
        'iframeHook',
        'iframeHookPriority',
        'productCss',
        'brand',
        'shopId',
        'apiToken',
    ];
    public const SETTING_OPTION_PREFIX = 'mczrSetting';

    public function getAll(): array
    {
        $settings = [];
        foreach (self::SETTING_OPTION_FIELDS as $fieldName) {
            $settings[$fieldName] = $this->get($fieldName);
        }

        return $settings;
    }

    /**
     * @return mixed
     * 
     * @throws Exception
     */
    public function get(string $name, bool $default = false)
    {
        if (!is_string($name)) {
            throw new Exception('Invalid name parameter');
        }

        return \get_option($this->getFullName($name), $default);
    }

    public function update(array $options): self
    {
        foreach ($options as $key => $option) {
            $this->updateOne($key, $option);
        }

        return $this;
    }

    /**
     * @param mixed $value
     */
    public function updateOne(string $name, $value): bool
    {
        $fullName = $this->getFullName($name);

        return \update_option($fullName, \sanitize_text_field($value));
    }

    private function getFullName(string $name): string
    {
        return self::SETTING_OPTION_PREFIX . ucfirst($name);
    }
}
