<?php

namespace ScfPriceUpdater;

class Options
{
    const OPTION_SLUG = 'scf_price_options';
    const OPTION_DEFAULTS = [
        'separator' => ';',
        'delete_empty' => false,
        'skip_trash' => false,
    ];

    /**
     * Updates option value on a specific option key
     * @param string|array $dataOrKey
     * @param $value
     * @return void
     */
    public static function updateOption($dataOrKey, $value = null): void
    {
        if (is_string($dataOrKey)) {
            if (!is_null($value)) {
                $options = array_merge(
                    self::OPTION_DEFAULTS,
                    (!get_option(self::OPTION_SLUG)) ? [] : get_option(self::OPTION_SLUG)
                );
                $options[$dataOrKey] = $value;
                update_option(self::OPTION_SLUG, $options);
            } else {
                new \WP_Error("Options Error", "Value of option was given NULL");
            }
        } else if (is_array($dataOrKey)) {
            $options = array_merge(
                self::OPTION_DEFAULTS,
                (!get_option(self::OPTION_SLUG)) ? [] : get_option(self::OPTION_SLUG)
            );
            update_option(self::OPTION_SLUG, array_merge($options, $dataOrKey));
        } else {
            new \WP_Error("Options Error", "Data or key field is not valid");
        }
    }

    /**
     * Returns the option value by key
     * @param string $key
     * @return mixed|string
     */
    public static function getOption(string $key)
    {
        $options = array_merge(
            self::OPTION_DEFAULTS,
            (!get_option(self::OPTION_SLUG)) ? [] : get_option(self::OPTION_SLUG)
        );
        return $options[$key];
    }

    /**
     * Reset every option value to its default value
     * @return void
     */
    public static function resetDefaults(): void
    {
        update_option(self::OPTION_SLUG, self::OPTION_DEFAULTS);
    }

    /**
     * Deletes the options from options table
     * @return void
     */
    public static function removeOptions(): void
    {
        delete_option(self::OPTION_SLUG);
    }
}
