<?php

namespace LoftyIDX\includes\pages;

use LoftyIDX\includes\common\LoftyIDXListingHelper;
use LoftyIDX\includes\LoftyIDX;

defined('ABSPATH') || exit;

class LoftyIDXQuickSearchPage extends LoftyIDXPage
{
    protected $proxy = null;
    protected $metaTags = '';

    public function __construct($template = '', $options = []) {
        parent::__construct($template, $options);
        $this->options = $options;
        $this->proxy = LoftyIDX::get_instance()->services['proxy'];
        $this->getMetaTags();
        $this->changePageTitle();
        add_action('wp_head', [$this, 'injectMetaTags']);
        
    }

    public function getContextData()
    {
        $shortcode_config = $this->options['shortcode_config'] ?? [];
        return [
            'moduleId' => $this->moduleId,
            'config' => $shortcode_config,
            'data' => wp_json_encode($shortcode_config)
        ];
    }
    public function getMetaTags()
    {
        $resp = $this->proxy->get_data('/wp-plugin/seo/original-param');
        $common_values = [];
        if($resp !== false){
            $seo_params = $resp['data'];
            $common_values = $seo_params['commonNonPageParamMap'] ?? [];
        }
        $config = $this->options['shortcode_config'];
        $meta = $config['meta'] ?? '';
        $result = preg_replace_callback('/\{([^}]+)}/', function($matches) use ($common_values) {
            return $common_values[$matches[1]] ?? $matches[0];
        }, $meta);
        $this->metaTags = implode(PHP_EOL, LoftyIDXListingHelper::filterMetaTags($result));
        $this->title = LoftyIDXListingHelper::filterTitle($result);
    }
    public function injectMetaTags() {
        echo wp_kses($this->metaTags, $this->allowedTags);
    }
}
