<?php

namespace YOOtheme\Theme\Wordpress\Listener;

use YOOtheme\Config;
use YOOtheme\Event;
use YOOtheme\Metadata;

class LoadThemeConfig
{
    public Config $config;
    public Metadata $metadata;

    public function __construct(Config $config, Metadata $metadata)
    {
        $this->config = $config;
        $this->metadata = $metadata;
    }

    /**
     * @param \WP_Customize_Manager $customizer
     */
    public function handle($customizer)
    {
        // add settings
        $customizer->add_setting('config');
        $customizer->add_setting('page');
        $customizer->add_setting('template');
        $customizer->remove_setting('site_icon');

        // encode config
        add_filter(
            'customize_sanitize_js_config',
            fn() => base64_encode(json_encode($this->config->get('~theme')))
        );

        // decode config
        add_filter('customize_sanitize_config', fn($value) => base64_decode($value));

        // decode page
        add_filter(
            'customize_sanitize_page',
            fn($value) => json_decode(base64_decode($value), true)
        );

        // decode template
        add_filter(
            'customize_sanitize_template',
            fn($value) => json_decode(base64_decode($value), true)
        );

        add_action('customize_save', function (\WP_Customize_Manager $customizer) {
            $setting = $customizer->get_setting('config');

            if ($setting) {
                $value = json_decode($setting->post_value(), true);
                $value = Event::emit('config.save|filter', $value);
                $customizer->set_post_value('config', base64_encode(json_encode($value)));
            }

            // remove page, template
            $customizer->remove_setting('page');
            $customizer->remove_setting('template');
        });

        // add data
        $this->metadata->set(
            'script:customizer-data',
            fn($script) => $script->withValue(
                sprintf(
                    'window.yootheme = window.yootheme || {}; var $customizer = yootheme.customizer = JSON.parse(atob("%s"));',
                    base64_encode(json_encode($this->config->get('customizer', [])))
                )
            )
        );
    }
}
