<?php

namespace YOOtheme\Theme\Wordpress\Listener;

use YOOtheme\Config;
use YOOtheme\Http\Uri;

class AddCustomizeParameter
{
    public Config $config;

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

    public function handle($path, $parameters, $secure, callable $next)
    {
        /** @var Uri $uri */
        $uri = $next($path, $parameters, $secure);

        if (
            str_starts_with($uri->getQueryParam('p', ''), 'theme/') &&
            $this->config->get('app.isCustomizer')
        ) {
            $query = $uri->getQueryParams();
            $query['wp_customize'] = 'on';

            $uri = $uri->withQueryParams($query);
        }

        return $uri;
    }
}
