<?php

namespace LoftyIDX\includes\pages;

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

defined('ABSPATH') || exit;

class LoftyIDXMarketReportPage extends LoftyIDXPage
{
    protected $proxy = null;
    protected $siteConfig = []; // raw site config from api
    protected $metaTags = '';
    protected $isShortCode = false;
    protected $submitJs = '';

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

    public function getSiteConfig()
    {
        $proxy = LoftyIDX::get_instance()->services['proxy'];
        $site_config = $proxy->get_data('/wp-plugin/admin/report/init-info');
        if($site_config === false){
            return [];
        }
        $this->submitJs = $site_config['data']['pageConfigMap']['submitJs'] ?? '';
        return $site_config;
    }

    public function getMetaTags() {
        $this->siteConfig = $this->getSiteConfig();
        $site_info = $this->siteConfig['data']['pluginPage'];
        $this->metaTags = $site_info['metaTag'] ?? '';
        $valueMap = $this->siteConfig['data']['seoParamMap'] ?? [];
        if ($this->isShortCode) {
            $this->metaTags = $this->options['shortcode_config']['meta'];
            $config = $this->options['shortcode_config'];
            $valueMap = [
                "Market Report Title"=> $config['title'] ?? '',
                "Market Report Location"=> $config['location'] ?? ''
            ];
        }
        $result = preg_replace_callback('/\{([^}]+)}/', function($matches) use ($valueMap) {
            return $valueMap[$matches[1]] ?? $matches[0];
        }, $this->metaTags);
        $this->metaTags = implode(PHP_EOL, LoftyIDXListingHelper::filterMetaTags($result));
        $this->title = LoftyIDXListingHelper::filterTitle($result);
    }
    public function getContextData()
    {
        $shortcode_config = $this->options['shortcode_config'] ?? [];
        $data = [
            'isShortCode' => $this->isShortCode,
            'shortcode_config' => $shortcode_config,
            'submitJs'=> $this->submitJs
        ];
        return [
            'moduleId' => $this->moduleId,
            'data' => wp_json_encode($data),
        ];
    }

    public function injectMetaTags()
    {
        echo wp_kses($this->metaTags, $this->allowedTags);
    }
}
