<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Wordpress;

use YOOtheme\Http\Request;
use ZOOlanders\YOOessentials\Config\AbstractConfigRepository;
use ZOOlanders\YOOessentials\Config\ConfigInterface;
use ZOOlanders\YOOessentials\Config\ConfigRepositoryInterface;
use function YOOtheme\app;

class ConfigRepository extends AbstractConfigRepository implements ConfigRepositoryInterface
{
    protected const NAME = 'yooessentials';

    public function load(ConfigInterface $config): void
    {
        $data = json_decode(get_option(self::NAME), true);
        if (!$data) {
            return;
        }

        $config->replace($data);
    }

    public function authorize(): bool
    {
        return current_user_can('edit_theme_options');
    }

    public function persist(array $values): void
    {
        $data = json_encode($values);
        if (!$data) {
            return;
        }

        update_option(self::NAME, $data);
    }

    public function fromRequest(Request $request): ?array
    {
        // TODO: drop 4.1 support at some point

        // if < 4.2, use the old way.
        // 4.2+ has the same customizer of joomla
        $ytpVersion = app()->config->get('theme.version', '');
        if (version_compare($ytpVersion, '4.2', 'lt')) {
            $params = get_theme_mod('config', '{}');
            $params = json_decode($params, true) ?: [];

            return $params['yooessentials'] ?? null;
        }

        // if in preview request
        if ($custom = $request('customizer')) {
            $params = json_decode(base64_decode($custom), true);

            return $params['yooessentials'] ?? null;
        }

        return null;
    }
}
