<?php
namespace Wpupgrader\Libraries\WordPress\Plugins\Core;

abstract class BaseConfig
{
    /** @var \Wpupgrader\Libraries\WordPress\Plugins\Core\PluginBaseInterface $plugin */
    protected $plugin;

    /** @var array $config */
    protected $config;

    /**
     * Initialize the BaseConfig for a PluginBaseInterface
     *
     * @param \Wpupgrader\Libraries\WordPress\Plugins\Core\PluginBaseInterface $plugin
     */
    final public function __construct(PluginBaseInterface &$plugin)
    {
        $this->plugin = $plugin;
        $this->initDefaultConfig();
    }

    /**
     * Initializes the default Configuration
     */
    final private function initDefaultConfig()
    {
        $reflectorSource = new \ReflectionClass(\get_class($this));
        $sourcepath = $reflectorSource->getFileName();

        $reflector = new \ReflectionClass(\get_class($this->plugin));
        $pluginpath = $reflector->getFileName();

        $config['plugin_path'] = \plugin_dir_path($pluginpath);
        $config['plugin_url'] = \plugin_dir_url($pluginpath);
        $config['basename'] = \str_replace('-lite', '', \basename(\dirname($pluginpath)));
        $config['txt_domain'] = 'wpupgrader';
        $config['namespace'] = $reflectorSource->getNamespaceName();
        $config['source_path'] = \plugin_dir_path($sourcepath);
        $config['prefix'] = Utilities::tableizer($config['basename']);
        $config['name'] = \str_replace('Gdpr', 'GDPR', Utilities::labelizer($config['basename']));
        $config['options'] = Utilities::tableizer(\get_option($config['prefix'].'_settings'));

        $this->config = (array)$this->initConfig($config);
    }

    /**
     * Allow custom configuration
     *
     * @param array $config
     * @return array
     */
    protected function initConfig(array $config)
    {
        return $config;
    }

    /**
     * Set a setting on the Config object
     *
     * @param string $setting
     * @param mixed $value
     * @return mixed
     */
    final public function set($setting, $value)
    {
        $this->config[$setting] = $value;
    }

    /**
     * Get a setting from the Config object
     *
     * @param string $setting
     * @return mixed
     */
    final public function get($setting)
    {
        if (empty($this->config)) {
            $this->initDefaultConfig();
        }

        if (isset($this->config[$setting])) {
            return $this->config[$setting];
        }
        return null;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return $this->config;
    }
}