<?php

namespace YOOtheme\Builder\Wordpress\Source\Listener;

use YOOtheme\Builder;
use YOOtheme\Builder\Templates\TemplateHelper;
use YOOtheme\Config;
use YOOtheme\Event;
use YOOtheme\View;

class LoadTemplate
{
    public View $view;
    public Config $config;
    public Builder $builder;
    public TemplateHelper $template;

    public function __construct(
        View $view,
        Config $config,
        Builder $builder,
        TemplateHelper $template
    ) {
        $this->view = $view;
        $this->config = $config;
        $this->builder = $builder;
        $this->template = $template;
    }

    public function handle($tpl)
    {
        $template = Event::emit('builder.template', $tpl);

        if (empty($template['type'])) {
            return $tpl;
        }

        if ($this->config->get('app.isCustomizer')) {
            $this->config->set('customizer.view', $template['type']);
        }

        if ($this->view['sections']->exists('builder')) {
            return $tpl;
        }

        if ($matched = $this->template->match($template)) {
            $template += $matched + ['layout' => [], 'params' => []];

            // set template identifier
            if ($this->config->get('app.isCustomizer')) {
                $this->config->set('customizer.template', $template['id']);
            }

            // get template from request?
            if (($templ = get_theme_mod('template')) && $templ['id'] == $template['id']) {
                $template['layout'] = $templ['layout'];
            }

            if (!empty($template['layout'])) {
                $this->view['sections']->set(
                    'builder',
                    fn() => $this->builder->render(
                        json_encode($template['layout']),
                        $template['params'] + [
                            'prefix' => "template-{$template['id']}",
                        ]
                    )
                );
            }
        }

        return $tpl;
    }
}
