<?php

namespace LoftyIDX\includes\pages;

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

defined('ABSPATH') || exit;

class LoftyIDXListingDetailPage extends LoftyIDXPage
{
  protected $metaTags = '';
  protected $sold = false;
  protected $data = [];
  protected $seoData = [];
  private static $metaTagsInjected = false;

  public function __construct($template='', $options=[])
  {
        parent::__construct($template, $options);
        $this->loadCss('lofty-listing-detail-page', 'templates/style/listing-detail.css');
        $this->options = $options;
        $this->getListingDetail();
        $this->changePageTitle();
        $this->setupSeoFilters();
        
  }

  public function getListingDetail()
  {
      $this->sold = $this->options['is_sold_page'] ?? false;
      $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_url(wp_unslash($_SERVER['REQUEST_URI'])) : '';
      $lofty_listing_id = get_query_var('lofty_listing_id');
      $forwarder = LoftyIDX::get_instance()->services['proxy'];
      $data = $forwarder->get_data('listing/detail', [
          "listingId" =>  $lofty_listing_id,
          "uri" => $request_uri,
          "isSold" => $this->sold
      ]);
      $this->data = $data['data'] ?? [];
      
      // Extract SEO data for filters from API response
      $page_info = isset($this->data['pluginPage']) ? $this->data['pluginPage'] : [];
      $seo_params = isset($this->data['seoParamMap']) ? $this->data['seoParamMap'] : [];
      
      $defaultTitle = ($this->data['info']['streetAddress'] ?? '').' '.($this->data['info']['cityAddress'] ?? '');
      if(!$this->sold) {
          $defaultTitle = 'Homes for sale - '.$defaultTitle;
      }
      
      // Store comprehensive SEO data for use in filters
      $this->seoData = [
          'title' => $seo_params['og:title'] ?? $seo_params['title'] ?? $defaultTitle,
          'description' => $seo_params['og:description'] ?? $seo_params['description'] ?? '',
          'image' => $seo_params['og:image'] ?? '',
          'favicon' => $seo_params['favicon'] ?? '',
          'canonical' => $seo_params['canonical'] ?? '',
          'keywords' => $seo_params['keywords'] ?? '',
          'page_info' => $page_info, // Store full page info for additional meta extraction
          'seo_params' => $seo_params // Store all seo params
      ];
      
      $this->title = $this->seoData['title'];
  }

  /**
   * Setup SEO filters - simplified version
   */
  public function setupSeoFilters()
  {
    // WordPress core title filters
      add_filter('document_title_parts', [$this, 'filterDocumentTitle'], 10, 1);
      add_filter('wp_title', [$this, 'filterWpTitle'], 10, 2);
      
      // Common SEO plugin filters (Yoast SEO)
      add_filter('wpseo_title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('wpseo_metadesc', [$this, 'filterSeoDescription'], 10, 1);
      add_filter('wpseo_opengraph_title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('wpseo_opengraph_desc', [$this, 'filterSeoDescription'], 10, 1);
      add_filter('wpseo_opengraph_image', [$this, 'filterSeoImage'], 10, 1);
      
      // RankMath SEO plugin filters
      add_filter('rank_math/frontend/title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('rank_math/frontend/description', [$this, 'filterSeoDescription'], 10, 1);
      add_filter('rank_math/opengraph/facebook/og_title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('rank_math/opengraph/facebook/og_description', [$this, 'filterSeoDescription'], 10, 1);
      add_filter('rank_math/opengraph/facebook/og_image', [$this, 'filterSeoImage'], 10, 1);
      
      // All in One SEO plugin filters
      add_filter('aioseo_title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('aioseo_description', [$this, 'filterSeoDescription'], 10, 1);
      add_filter('aioseo_facebook_title', [$this, 'filterSeoTitle'], 10, 1);
      add_filter('aioseo_facebook_description', [$this, 'filterSeoDescription'], 10, 1);
      
      // Always add our custom meta tags
      add_action('wp_head', [$this, 'addCustomMetaTags'], 1);
  }

  public function filterDocumentTitle($title_parts)
  {
      if (!empty($this->seoData['title'])) {
          $title_parts['title'] = $this->seoData['title'];
      }
      return $title_parts;
  }

  public function filterWpTitle($title, $sep = '')
  {
      if (!empty($this->seoData['title'])) {
          return $this->seoData['title'];
      }
      return $title;
  }

  public function filterSeoTitle($title)
  {
      if (!empty($this->seoData['title'])) {
          return $this->seoData['title'];
      }
      return $title;
  }

  public function filterSeoDescription($description)
  {
      if (!empty($this->seoData['description'])) {
          return $this->seoData['description'];
      }
      return $description;
  }

  public function filterSeoImage($image)
  {
      if (!empty($this->seoData['image'])) {
          return $this->seoData['image'];
      }
      return $image;
  }

  /**
   * Add meta tags intelligently - avoid conflicts with SEO plugins
   */
  public function addCustomMetaTags()
  {
      // prevent duplicate execution across multiple instances
      if (self::$metaTagsInjected) {
          return;
      }
      self::$metaTagsInjected = true;
      
      // Debug comment to confirm this method is called
      echo "<!-- LoftyIDX Custom Meta Tags Start -->\n";
      
      // Check if major SEO plugins are active
      $has_seo_plugin = defined('WPSEO_VERSION') || // Yoast SEO
                       defined('RANK_MATH_VERSION') || // RankMath
                       defined('AIOSEO_VERSION') || // All in One SEO
                       class_exists('SEOPressor');
      
      if (!empty($this->seoData)) {
          
          // Always add favicon (SEO plugins usually don't handle this)
          if (!empty($this->seoData['favicon'])) {
              echo '<link rel="icon" href="' . esc_url($this->seoData['favicon']) . '" type="image/x-icon">' . "\n";
              echo '<link rel="shortcut icon" href="' . esc_url($this->seoData['favicon']) . '" type="image/x-icon">' . "\n";
          }
          
          // Always process API-specific meta tags (these are unique to our plugin)
          $this->processApiMetaTags();
          
          // Only add basic meta tags if no SEO plugin is present AND no API meta tags were processed
          if (!$has_seo_plugin) {
              // Check if API meta tags already contain title/description to avoid duplication
              $page_info = $this->seoData['page_info'] ?? [];
              $api_meta_tag = $page_info['metaTag'] ?? $page_info['metaTagHtml'] ?? '';
              $has_api_meta = strpos($api_meta_tag, '<meta') !== false;
              
              if (!$has_api_meta) {
                  echo "<!-- No SEO plugin detected and no api meta tags, adding fallback meta tags -->\n";
                  
                  // Basic meta tags
                  if (!empty($this->seoData['description'])) {
                      echo '<meta name="description" content="' . esc_attr($this->seoData['description']) . '">' . "\n";
                  }
                  
                  if (!empty($this->seoData['keywords'])) {
                      echo '<meta name="keywords" content="' . esc_attr($this->seoData['keywords']) . '">' . "\n";
                  }
                  
                  // Open Graph meta tags
                  if (!empty($this->seoData['title'])) {
                      echo '<meta property="og:title" content="' . esc_attr($this->seoData['title']) . '">' . "\n";
                  }
                  if (!empty($this->seoData['description'])) {
                      echo '<meta property="og:description" content="' . esc_attr($this->seoData['description']) . '">' . "\n";
                  }
                  if (!empty($this->seoData['image'])) {
                      echo '<meta property="og:image" content="' . esc_url($this->seoData['image']) . '">' . "\n";
                  }
                  
                  echo '<meta property="og:type" content="website">' . "\n";
                  echo '<meta property="og:url" content="' . esc_url(get_permalink()) . '">' . "\n";
                  
                  // Twitter Card meta tags
                  echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
                  if (!empty($this->seoData['title'])) {
                      echo '<meta name="twitter:title" content="' . esc_attr($this->seoData['title']) . '">' . "\n";
                  }
                  if (!empty($this->seoData['description'])) {
                      echo '<meta name="twitter:description" content="' . esc_attr($this->seoData['description']) . '">' . "\n";
                  }
                  if (!empty($this->seoData['image'])) {
                      echo '<meta name="twitter:image" content="' . esc_url($this->seoData['image']) . '">' . "\n";
                  }
                  
                  // Canonical URL
                  if (!empty($this->seoData['canonical'])) {
                      echo '<link rel="canonical" href="' . esc_url($this->seoData['canonical']) . '">' . "\n";
                  }
              } else {
                  echo "<!-- no seo plugin detected but API meta tags present, skipping fallback meta tags -->\n";
              }
          } else {
              echo "<!-- SEO plugin detected, using filters only -->\n";
          }
      }
      
      // Debug comment to confirm method completed
      echo "<!-- LoftyIDX Custom Meta Tags End -->\n";
  }
  
  /**
   * Process additional meta tags from API response
   */
  private function processApiMetaTags()
  {
      $page_info = $this->seoData['page_info'] ?? [];
      $meta_tag = $page_info['metaTag'] ?? $page_info['metaTagHtml'] ?? '';
      
      if (!empty($meta_tag)) {
          $seo_params = $this->seoData['seo_params'] ?? [];
          
          // Replace parameters in meta tags
          $processed_tags = preg_replace_callback('/\{([^}]+)}/', function ($matches) use ($seo_params) {
              return $seo_params[$matches[1]] ?? $matches[0];
          }, $meta_tag);
          
          // Filter and output meta tags safely
          if (!empty($processed_tags)) {
              $filtered_tags = LoftyIDXListingHelper::filterMetaTags($processed_tags);
              foreach ($filtered_tags as $tag) {
                  if (!empty(trim($tag))) {
                      echo $tag . "\n";
                  }
              }
          }
      }
  }

  public function getContextData()
  {
    $mls_list = LoftyIDXListingHelper::get_mls_info();
    $first_groups = LoftyIDXListingDetailHelper::first_group($this->data);
    $other_groups = array_slice(isset($this->data["listingGroups"]) ? $this->data["listingGroups"] : [], 1);
    $original_info = isset($this->data['info']) ? $this->data['info'] : [];
    $info = LoftyIDXHouseHelper::format_house(isset($this->data['info']) ? $this->data['info'] : [], $mls_list);
            $mapCenter = [
            'lat' => isset($info['latitude']) ? $info['latitude'] : null,
            'lng' => isset($info['longitude']) ? $info['longitude'] : null
        ];
            $info['marketInfo'] = is_array($original_info) ? LoftyIDXListingDetailHelper::createTime($original_info, $mls_list) : null;
        $info['mlsInfo'] = LoftyIDXHouseHelper::get_provider_html(isset($original_info['mlsOrg']['template']) ? $original_info['mlsOrg']['template'] : null, $original_info);
        $info['bedInfo'] = LoftyIDXHouseHelper::get_bed_bath_sqft_text($original_info);
        $info['firstGroup'] = $first_groups;
        $info['otherGroup'] = $other_groups;
        $info['detailsDescribe'] = $original_info['detailsDescribe'] ?? '';
        $info['tourLink'] = $original_info['link'] ?? '';
        $info['updateTimeLong'] = $original_info['updateTimeLong'] ?? 0;
        $info['mlsOrg'] = isset($original_info['mlsOrg']) ? $original_info['mlsOrg'] : [];
    $data['data']['info'] = $info;
    $isActiveMls = LoftyIDXHouseHelper::is_active_mls($original_info, $mls_list);

    // ssr data
    $json = wp_json_encode([
                  'listingId' => isset($info['id']) ? $info['id'] : null,
            'previewPictures' => isset($info['previewPictures']) ? $info['previewPictures'] : [],
      'sold'=> $this->sold,
      'mapCenter' => $mapCenter
    ]);

      return [
      'data' => $data['data'],
      'isActiveMls'=>$isActiveMls,
      'json_data'=> $json,
      'moduleId'=> $this->moduleId,
      'sold'=> $this->sold
    ];
  }
}
