<?php


namespace Eventman\Admin;


class Options
{

    use RequestMetaTrait;
    use LogTrait;

    const _OPTION_ID = 'ms_eventman_options';


    public function __construct()
    {
        global $ms_eventman_options;
    }

    public function displayOptions(): string
    {
        $error = '';

        global $ms_eventman_options;
        if ($this->isPost()) {
            $this->log('Saving options with post: ' . $this->pretty($this->getPost()));

            if (wp_verify_nonce($this->getPost('_wpnonce') ?? '', 'save-ms-eventman-options')) {
                $this->log('Nonce is valid, updating options.');

                $this->updateOptions($this->getPost('ms_eventman_options'));
            } else {
                $error .= $this->noticeError('Nonce is invalid!');
            }
        }

        $ms_eventman_options = self::getOptions();

        ob_start();
        echo $error;
        require 'partials/options.php';
        $out = ob_get_flush();

        return $out;
    }

    public function displayLogs(): string
    {
        return '';
    }

    public function updateOptions($array = [])
    {
        // fix null input
        $array = is_null($array) ? [] : $array;

        $mergedOptions = array_merge(self::getOptions(), $this->defaultOptions(), $array ?? []);
        $options = $mergedOptions ?? [];

        if (isset($options['debug_hooks'])) {
            $hooks = explode(',', $options['debug_hooks']);
            $hooks = array_map(function ($hook) {
                return trim($hook);
            }, $hooks);
            $options['debug_hooks'] = $hooks;
        }

        $this->log('Updating options "ms_eventman_options": ' . $this->pretty([
                'final' => $options,
                'merged' => $mergedOptions,
                'original' => self::getOptions(),
                'default' => $this->defaultOptions(),
                'function_arg' => $array
            ]));
        update_option(self::_OPTION_ID, serialize($options));
    }

    public function noticeError($content)
    {
        ob_start();
        $class = 'error';
        require 'partials/notice.php';
        return ob_get_flush();
    }

    /**
     * @return bool[]
     */
    protected function defaultOptions(): array
    {
        return [
            'enable_debug' => false,
            'debug_hooks' => ''
        ];
    }

    public static function getOptions()
    {
        $options = get_blog_option(get_main_site_id(), self::_OPTION_ID);
        return $options ? unserialize($options) : [];
    }

}