<?php
namespace LoftyIDX\includes\pages;

use LoftyIDX\includes\LoftyIDXFacades;
use LoftyIDX\includes\common\LoftyIDXCustomizationHelper;

defined('ABSPATH') || exit;

abstract class LoftyIDXPage
{
  protected $isLogin = false;
  protected $template = ''; // entry template path
  protected $moduleId = ''; // module id to inject frontend components
  protected $options = [];  // page options
  protected $customizationHelper = null;
  protected $title = null;
  protected static $injectedMetaTags = [];
  protected $allowedTags = [
      'meta'=> ['name'=> [], 'content'=> [], 'itemprop'=>[], 'property'=>[]],
      'title' => [],
      'link'=> ['rel'=>[], 'type'=>[], 'href'=>[]]
  ];

  public function __construct($template='', $options=[])
  {
    $this->isLogin = isset($_COOKIE['lofty_idx_lead_id']);
    $this->template = $template;
    $this->moduleId = 'module'.random_int(1, 99999);
    $this->options = $options;
    $this->customizationHelper = new LoftyIDXCustomizationHelper();
    $this->loadCss('lofty-common', 'templates/style/common.css');
    $this->loadCss('lofty-iconfont', 'templates/style/iconfont.css');
    $this->handleCustomization();
  }

  public function getContextData()
  {
    return [];
  }

  public static function loadCss($name, $path)
  {
      add_action('wp_enqueue_scripts', function() use ($name, $path) {
          wp_enqueue_style(
              $name,
              LOFTY_IDX_URL . $path,
              [],
              LOFTY_IDX_VERSION,
              'all'
          );
      });
  }

  public function render()
  {
      $ctx_data = $this->getContextData();
      get_header();
      LoftyIDXFacades::view($this->template, $ctx_data);
      get_footer();
  }

  public function renderShortCode()
  {
      ob_start();
      $output = LoftyIDXFacades::view($this->template, $this->getContextData(), true);
      ob_end_clean();
      return $output;
  }

  public function changePageTitle()
  {
      if ($this->title !== null) {
          add_filter('pre_get_document_title', function () {
              return $this->title;
          });
          add_filter('wp_title', function () {
              return $this->title;
          }, 10, 2);

      }
  }
  
  /**
   * prevent duplicate meta tag injection across multiple page instances
   */
  protected function preventDuplicateMetaInjection($instanceKey = '')
  {
      $key = get_class($this) . $instanceKey;
      if (isset(self::$injectedMetaTags[$key])) {
          return false; // already injected
      }
      self::$injectedMetaTags[$key] = true;
      return true; // first time injection
  }
  
  /**
   * generic meta tag injection method with duplicate prevention
   */
  public function injectMetaTags()
  {
      if (!$this->preventDuplicateMetaInjection()) {
          return; // skip if already injected
      }
      
      if (property_exists($this, 'metaTags') && !empty($this->metaTags)) {
          echo wp_kses($this->metaTags, $this->allowedTags);
      }
  }
  public function handleCustomization()
  {
    if(is_admin()){
      return;
    }
    // only apply to all frontend pages
    $data = LoftyIDXCustomizationHelper::getCustomData();

    // inject custom css/js
    add_action('wp_head', function () use ($data){
      $this->customizationHelper->injectCustomCss($data);
      $this->customizationHelper->injectCustomHead($data);
    }, 500);

    add_action('wp_footer', function () use ($data){
          $this->customizationHelper->injectCustomJs($data);
    }, 500);

  }

}