<?php
namespace LoftyIDX\includes\pages;

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

;

defined('ABSPATH') || exit;

class LoftyIDXListingPage extends LoftyIDXPage
{
  protected $siteConfig = []; // raw site config from api
  protected $metaTags = '';
  protected $siteInfo = [];
  protected $sold = false;
  protected $isShortCode = false;

  public function __construct($template='', $options=[])
  {
    parent::__construct($template, $options);
    $this->loadCss('lofty-listing-page', 'templates/style/listing.css');
    $this->options = $options;
    $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'];
      if ($this->sold){
          $site_config=$proxy->get_data('/wp-plugin/admin/sold-listing/init-info');
      } else {
          $site_config=$proxy->get_data('/wp-plugin/admin/listing-search/searchCondition/init-info');
      }
      if($site_config === false){
          return [];
      }
      return $site_config;
  }
  public function getMetaTags()
  {
    if (isset($this->options['is_sold_page']) && $this->options['is_sold_page'] === true) {
        $this->sold = true;
    }
    $this->siteConfig = $this->getSiteConfig();
    if (isset($this->siteConfig['data']['pluginPage']) && !empty($this->siteConfig)) {
        $site_info = $this->siteConfig['data']['pluginPage'];
        $this->siteInfo = $site_info;
        $tags = $site_info['metaTag'] ?? '';
        if($this->isShortCode) {
            $tags = $this->options['shortcode_config']['meta'];
        }
        // handle seo params
        $seo_params = $this->siteConfig['data']['seoParamMap'] ?? [];
        $result = preg_replace_callback('/\{([^}]+)}/', function ($matches) use ($seo_params) {
            return $seo_params[$matches[1]] ?? $matches[0];
        }, $tags);
        $this->metaTags = implode(PHP_EOL, LoftyIDXListingHelper::filterMetaTags($result));
        $this->title = LoftyIDXListingHelper::filterTitle($result);
    }
  }

  public function getContextData()
  {
    $shortcode_class = '';
    $mls_list = LoftyIDXListingHelper::get_mls_info();
    $extra = [];
    if ($this->isShortCode) {
        $shortcode_class = 'lofty-is-shortcode';
        $extra['featureListingName'] = $this->options['shortcode_config']['featureListingName'] ?? '';
    } elseif (isset($_GET['featureListingName'])) {
        $extra['featureListingName'] = sanitize_text_field(wp_unslash($_GET['featureListingName']));
    }
    if ($this->sold) {
      $listingResult = LoftyIDXListingHelper::getSoldListing(null, $extra);
    } else {
      $listingResult = LoftyIDXListingHelper::getActiveListing(null, $extra);
    }
    if (!empty($listingResult['listings'])) {
        foreach ($listingResult['listings'] as &$item) {
            LoftyIDXHouseHelper::format_house_card($item, $mls_list);
        }
        unset($item);
        $firstHouse = $listingResult['listings'][0];
    }
    $mapCenter = null;
    if(!empty($extra['featureListingName']) && !empty($firstHouse)) {
        $mapCenter = [
            'lng' => $firstHouse['longitude'],
            'lat' => $firstHouse['latitude'],
        ];
    }

    $layout = $this->options['shortcode_config']['layout'] ?? $this->siteInfo['layout'];
    $data = wp_json_encode([
      'counts' => $listingResult['counts'],
      'totalPage' => $listingResult['totalPage'],
      'searchType' => $listingResult['searchType'],
      'mls_list' => array_column($mls_list, 'id'),
      'sold' => $this->sold,
      'hasMap'=> $layout === 'map-grid' || $layout === '',
      'shortcode_config'=> $this->options['shortcode_config'] ?? [],
      'featureListingName'=> $extra['featureListingName'] ?? "",
      'mapCenter' => $mapCenter,
    ]);

    return [
      'moduleId'=> $this->moduleId,
      'list'=> $listingResult['listings'],
      'mls_list'=> $mls_list,
      'data'=> $data,
      'site_config'=> $this->siteInfo,
      'hasMap'=> $layout === 'map-grid' || $layout === '',
      'shortcode_class' => $shortcode_class
    ];
  }

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

}