<?php

namespace LoftyIDX\includes\providers;

use LoftyIDX\includes\pages\LoftyIDXListingPage;
use LoftyIDX\includes\pages\LoftyIDXFeatureListingPage;
use LoftyIDX\includes\pages\LoftyIDXMarketReportPage;
use LoftyIDX\includes\pages\LoftyIDXHomeValuationPage;
use LoftyIDX\includes\pages\LoftyIDXPage;
use LoftyIDX\includes\pages\LoftyIDXQuickSearchPage;
use LoftyIDX\includes\common\LoftyIDXListingHelper;

defined('ABSPATH') || exit;

class LoftyIDXShortcodesProvider implements LoftyIDXBaseProvider
{
    const SHORTCODE_LISTING_PAGE = "lofty_idx_listing_page";
    const SHORTCODE_QUICK_SEARCH = "lofty_idx_quick_search";
    const SHORTCODE_FEATURED_LISTING = "lofty_idx_featured_listing";
    const SHORTCODE_SOLD_LISTING = "lofty_idx_sold_listing";
    const SHORTCODE_MARKET_REPORT = "lofty_idx_market_report";
    const SHORTCODE_HOME_VALUATION = "lofty_idx_home_valuation";

    protected $container = null;

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

    public function register()
    {
        add_action('init', [$this, 'registerShortcodes']);
        add_action('wp_enqueue_scripts', function() {
            wp_register_style('lofty-common', LOFTY_IDX_URL.'templates/style/common.css', [], LOFTY_IDX_VERSION, 'all');
            wp_register_style('lofty-iconfont', LOFTY_IDX_URL.'templates/style/iconfont.css', [], LOFTY_IDX_VERSION, 'all');
            wp_register_style('lofty-listing-page', LOFTY_IDX_URL.'templates/style/listing.css', [], LOFTY_IDX_VERSION, 'all');
        });
    }

    public function registerShortcodes()
    {
      add_shortcode(self::SHORTCODE_LISTING_PAGE, [$this, 'getListingPage']);
      add_shortcode(self::SHORTCODE_QUICK_SEARCH, [$this, 'getQuickSearch']);
      add_shortcode(self::SHORTCODE_FEATURED_LISTING, [$this, 'getFeaturedListingPage']);
      add_shortcode(self::SHORTCODE_SOLD_LISTING, [$this, 'getSoldListingPage']);
      add_shortcode(self::SHORTCODE_MARKET_REPORT, [$this, 'getMarketReportPage']);
      add_shortcode(self::SHORTCODE_HOME_VALUATION, [$this, 'getHomeValuationPage']);
    }

    public function getListingPage($attrs=[], $content = '')
    {
      $data = $this->getContentData($content);
      $page = new LoftyIDXListingPage('module/md_result_listing/index', [
        'shortcode_config'=> [
            'layout'=> $data['layout'] ?? null,
            'meta'=> $data['meta'] ?? null,
            'featureListingName'=> LoftyIDXListingHelper::getFeaturedListingName([
                'condition' => $data['conditions'] ?? null,
                'timezone' => $data['timezone'] ?? null,
                'sort' => $data['sort'] ?? null
            ]),
        ]
      ]);
      wp_enqueue_style('lofty-common');
      wp_enqueue_style('lofty-iconfont');
      wp_enqueue_style('lofty-listing-page');
      return $page->renderShortCode();
    }
    public function getQuickSearch($attrs=[], $content = '')
    {
        $data = $this->getContentData($content);
        $page = new LoftyIDXQuickSearchPage('module/md_widget_quick_search/index', [
            'shortcode_config'=> [
                'layout'=> $data['layout'] ?? null,
                'meta'=> $data['meta'] ?? null,
                'quick_listing_filters'=>explode(",", $data['quick_listing_filters'] ?? ''),
                'featureListingName'=> LoftyIDXListingHelper::getFeaturedListingName([
                    'condition' => $data['conditions'] ?? null,
                    'timezone' => $data['timezone'] ?? null,
                    'sort' => $data['sort'] ?? null
                ]),
            ]
        ]);
        wp_enqueue_style('lofty-common');
        wp_enqueue_style('lofty-iconfont');
        return $page->renderShortCode();
    }
    public function getSoldListingPage($attrs=[], $content='')
    {
        $data = $this->getContentData($content);
        $page = new LoftyIDXListingPage('module/md_result_listing/index', [
            'shortcode_config'=> [
               'layout'=>$data['layout'] ?? null,
               'meta'=> $data['meta'] ?? null,
               'featureListingName'=> LoftyIDXListingHelper::getFeaturedListingName([
                    'condition' => $data['conditions'] ?? null,
                    'timezone' => $data['timezone'] ?? null,
                    'sort' => $data['sort'] ?? null
               ]),
            ],
            'is_sold_page'=> true
        ]);
        wp_enqueue_style('lofty-common');
        wp_enqueue_style('lofty-iconfont');
        wp_enqueue_style('lofty-listing-page');
        return $page->renderShortCode();
    }
    public function getFeaturedListingPage($attrs=[], $content='')
    {
      $data = $this->getContentData($content);
      $page = new LoftyIDXFeatureListingPage('module/md_feature_listing/index', [
          'shortcode_config'=> [
                'layout'=> $data['layout'] ?? null,
                'layout_config'=>$data['layout_config'] ?? null,
                'meta'=> $data['meta'] ?? null,
                'featureListingName'=> LoftyIDXListingHelper::getFeaturedListingName([
                    'condition' => isset($data['conditions']) ? $data['conditions'] : null,
                    'timezone' => isset($data['timezone']) ? $data['timezone'] : null,
                    'sort' => isset($data['sort']) ? $data['sort'] : null
                ]),
          ]
      ]);
      wp_enqueue_style('lofty-common');
      wp_enqueue_style('lofty-iconfont');
      return $page->renderShortCode();
    }
    public function getMarketReportPage($attrs=[], $content='')
    {
      $data = $this->getContentData($content);
      $page = new LoftyIDXMarketReportPage('module/md_market_report/index', [
        'shortcode_config'=> [
            'title'=> $data['title'] ?? null,
            'location'=>$data['location'] ?? null,
            'show_new'=>$data['show_new'] ?? null,
            'show_pending'=>$data['show_pending'] ?? null,
            'show_sold'=>$data['show_sold'] ?? null,
            'meta'=> $data['meta'] ?? null,
            'featureListingName'=> LoftyIDXListingHelper::getFeaturedListingName([
                'condition' => isset($data['conditions']) ? $data['conditions'] : null,
                'timezone' => isset($data['timezone']) ? $data['timezone'] : null,
                'sort' => 'RELEVANCE'
            ]),
        ]
      ]);
      wp_enqueue_style('lofty-common');
      wp_enqueue_style('lofty-iconfont');
      return $page->renderShortCode();
    }
    public function getHomeValuationPage($attrs=[], $content='')
    {
        $data = $this->getContentData($content);
        $page = new LoftyIDXHomeValuationPage('module/md_home_valuation/index', [
            'shortcode_config' => [
                'imgUrl'=>$data['img_url'] ?? null,
                'config'=>[
                   'step1'=> $data['step1'] ?? null,
                   'step2'=> $data['step2'] ?? null,
                   'step3'=> $data['step3'] ?? null,
                ],
                'meta'=> $data['meta'] ?? null,
                'submitJs'=> isset($data['submitJs']) ? $data['submitJs'] : null,
            ]
        ]);
        wp_enqueue_style('lofty-common');
        wp_enqueue_style('lofty-iconfont');
        return $page->renderShortCode();
    }
    public function getContentData($content = '')
    {
        // Return empty array if content is empty or null
        if (empty($content)) {
            return [];
        }
        
        $json_string = html_entity_decode($content, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $json_string = wp_kses($json_string, [
            'meta'=> ['name'=> [], 'content'=> [], 'itemprop'=>[], 'property'=>[]],
            'title'=> [],
            'link'=> ['rel'=>[], 'type'=>[], 'href'=>[]]
        ]);
        // 替换meta,link属性值里的双引号为单引号
        $json_string = preg_replace_callback('/<[^>]+>/', function ($matches) {
            return preg_replace('/="([^"]*)"/', "='\$1'", $matches[0]);
        }, $json_string);
        $json_string = str_replace(['[[', ']]'], '', $json_string);
        $json_string = trim($json_string);
        $json_string = str_replace(["\xe2\x80\x9c", "\xe2\x80\x9d"], '"', $json_string);
        $json_string = str_replace(["\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x98", "\xe2\x80\x99"], "'", $json_string);
        
        $decoded = json_decode($json_string, true);
        
        // Return empty array if JSON decoding failed
        return is_array($decoded) ? $decoded : [];
    }
}
