<?php
/**
 * Class model page
 *
 * @package wp-viral-click
 * @author InstaProduct
 * @link http://insta-product.com/
 */

if ( ! class_exists( 'IPJck_Model_Page' )) {

  /**
   * Class model page
   */
  class IPJck_Model_Page
  {
    /**
     * Take setting name
     *
     * @var string
     */
    protected $_settingName = '__ipjck-page-setting';

    /**
     * Save setting
     *
     * @param  int $postId
     * @return void
     */
    public function saveSetting( $postId )
    {
      $postId   = absint( $postId );
      $setting  = new IPJck_Setting( $postId, $this->_settingName );

      //
      //Get remote content
      $this->_getRemoteContent( $setting, $postId );

      //
      //Save settings
      $data   = $this->_getSettingData( $postId );
      $result = $setting->setSettings( $data );

      //
      //Fix remote content
      $this->_fixRemoteContent( $setting, $postId );

      return $result;
    }

    /**
     * Get setting data
     *
     * @param  int $postId
     * @return array
     */
    protected function _getSettingData( $postId )
    {
      $settings = array();
      $data     = array_merge( $_POST, $_GET );

      //
      //General
      $general  = $this->_saveSettingGeneral( $data );
      $settings = array_merge( $settings, $general );

      //
      //Content
      $content  = $this->_saveSettingContent( $data );
      $settings = array_merge( $settings, $content );

      //
      //SEO
      $seo = $this->_saveSettingSeo( $data );
      $settings = array_merge( $settings, $seo );

      return $settings;
    }

    /**
     * Save general settings
     *
     * @param  array $data
     * @return array
     */
    protected function _saveSettingGeneral( $data )
    {
      if ( isset( $data['status'] )) {
        $settings['status'] = apply_filters( 'pre_term_name', $data['status'] );
      }
      if ( isset( $data['pull_url'] )) {
        $settings['pull_url'] = apply_filters( 'pre_link_url', $data['pull_url'] );
      }
      if ( isset( $data['restricted'] )) {
        $settings['restricted'] = apply_filters( 'pre_term_name', $data['restricted'] );
      }
      return $settings;
    }

    /**
     * Save content settings
     *
     * @param  array $data
     * @return array
     */
    protected function _saveSettingContent( $data )
    {
      $settings = array();

      if ( isset( $data['prepend_html'] )) {
          $settings['prepend_html'] = $data['prepend_html'];
      }
      if ( isset( $data['append_html'] )) {
          $settings['append_html'] = $data['append_html'];
      }
      if ( isset( $data['link_replace_active'] )) {
        $settings['link_replace_active'] = apply_filters( 'single_post_title', $data['link_replace_active'] );
      }
      if ( isset( $data['link_replace_url'] )) {
        $settings['link_replace_url'] = apply_filters( 'pre_link_url', $data['link_replace_url'] );
      }
      if ( isset( $data['page_bar'] )) {
        $settings['page_bar'] = absint( $data['page_bar'] );
      }
      if ( isset( $data['page_slidein'] )) {
        $settings['page_slidein'] = absint( $data['page_slidein'] );
      }
      if ( isset( $data['page_modal'] )) {
        $settings['page_modal'] = absint( $data['page_modal'] );
      }

      return $settings;
    }

    /**
     * Save SEO settings
     *
     * @param  array $data
     * @return array
     */
    protected function _saveSettingSeo( $data )
    {
      $settings = array();

      if ( isset( $data['seo_meta_title'] )) {
          $settings['seo_meta_title'] = apply_filters( 'single_post_title', $data['seo_meta_title'] );
      }
      if ( isset( $data['seo_meta_description'] )) {
          $settings['seo_meta_description'] = apply_filters( 'single_post_title', $data['seo_meta_description'] );
      }
      if ( isset( $data['seo_meta_keywords'] )) {
          $settings['seo_meta_keywords'] = apply_filters( 'single_post_title', $data['seo_meta_keywords'] );
      }
      if ( isset( $data['seo_graph_image'] )) {
          $settings['seo_graph_image'] = apply_filters( 'pre_link_url', $data['seo_graph_image'] );
      }
      if ( isset( $data['seo_favicon'] )) {
          $settings['seo_favicon'] = apply_filters( 'pre_link_url', $data['seo_favicon'] );
      }
      if ( isset( $data['seo_tracking_code'] )) {
          $settings['seo_tracking_code'] = $data['seo_tracking_code'];
      }

      return $settings;
    }

    /**
     * Get remote content
     *
     * @param  object $setting
     * @param  int $postId
     * @return array
     */
    protected function _getRemoteContent( $setting, $postId )
    {
      $data       = array_merge( $_POST, $_GET );
      $currentUrl = $setting->getSetting( 'pull_url' );

      if ( isset( $data['pull_url'] ) && $data['pull_url'] != $currentUrl )
      {
        $pullUrl = apply_filters( 'pre_link_url', $data['pull_url'] );
        $rootUrl = $this->_getRootUrl( $pullUrl );
        $raw     = @file_get_contents( $pullUrl );
        $body    = '';
        $head    = '';
        $class   = '';
        $assets  = '';
        if ( ! empty( $raw ))
        {
          //
          //Get body
          //
          $bodyraw = $raw;
          $bodyraw = str_replace( '"<body', '"<ipjck_temp_body', $bodyraw );
          $bodyraw = str_replace( "'<body", "'<ipjck_temp_body", $bodyraw );
          preg_match("/<body[^>]*>(.*?)<\/body>/is", $bodyraw, $matches);
          if ( ! empty( $matches ))
          {
            $body = $matches[1];
            $body = $this->_fixContentBody( $body, $rootUrl );
          }

          //
          //Get head
          //
          preg_match("/<head>(.*?)<\/head>/is", $raw, $matches);
          if ( ! empty( $matches ))
          {
            $head = $matches[1];

            $html  = @str_get_html( $head );
            if ( $html )
            {
              //Get link stylesheets
              foreach( $html->find('link[rel=stylesheet]') as $element )
              {
                //Check dynamic link
                $href = $this->_fixDynamicLink( $element->href, $rootUrl );
                $element->href = $href;
                $assets .= $element->outertext;
              }
              //Get styles
              foreach( $html->find('style') as $element )
              {
                $assets .= $element->outertext;
              }
              //Get scripts
              foreach( $html->find('script') as $element )
              {
                if ( $element->src )
                {
                  $src = $this->_fixDynamicLink( $element->src, $rootUrl );
                  $element->src = $src;
                }
                $assets .= $element->outertext;
              }
            }
          }

          //
          //Get body class
          //
          preg_match_all(
          '/<body
          (?:\s+
            (?:
               class=["\'](?P<class>[^"\'<>]+)["\']
              |
               \w+=["\'][^"\'<>]+["\']
            )
          )+/ix',
          $raw, $results, PREG_PATTERN_ORDER);
          if ( ! empty( $results ) && ! empty( $results['class'] ))
          {
            $class = $results['class'][0];
          }
        }

        //Save data
        update_post_meta( $postId, '__ipjck-page-raw', $raw );
        update_post_meta( $postId, '__ipjck-page-class', $class );
        update_post_meta( $postId, '__ipjck-page-head', $head );
        update_post_meta( $postId, '__ipjck-page-body', $body );
        update_post_meta( $postId, '__ipjck-page-body-raw', $body );
        update_post_meta( $postId, '__ipjck-page-assets', $assets );
      }
    }

    /**
     * Get root url
     *
     * @param string $url
     * @return string
     */
    protected function _getRootUrl( $url )
    {
      $parts = parse_url( $url );
      $root  = $parts['scheme'] . '://' . $parts['host'];
      return $root;
    }

    /**
     * Fix dynamic link
     *
     * @param string $url
     * @param string $root Url root
     * @return string
     */
    protected function _fixDynamicLink( $url, $root )
    {
      if ( strpos( $url, 'http' ) !== 0 && strpos( $url, '//' ) !== 0 )
      {
        $url = ltrim( $url, '/' );
        $url = $root . '/' . $url;
      }
      return $url;
    }

    /**
     * Fix content body
     *
     * @param string $content
     * @return string
     */
    protected function _fixContentBody( $content, $root )
    {
      global $hostUrl;
      $hostUrl = $root;

      // Fix img src
      $content = preg_replace_callback(
        "/(<img[^>]*src *= *[\"']?)([^\"']*)/i",
        function ($matches)
        {
          global $hostUrl;
          return $matches[1] . $this->_fixDynamicLink( $matches[2], $hostUrl );
        },
        $content
      );

      // Fix link
      $content = preg_replace_callback(
        "/(<a[^>]*href *= *[\"']?)([^\"']*)/i",
        function ($matches)
        {
          global $hostUrl;
          $result = $matches[1] . $this->_fixDynamicLink( $matches[2], $hostUrl );
          return $result;
        },
        $content
      );

      return $content;
    }

    /**
     * Fix remote content
     *
     * @param  object $setting
     * @param  int $postId
     * @return string
     */
    protected function _fixRemoteContent( $setting, $postId )
    {
      global $replaceUrl;

      $content    = get_post_meta( $postId, '__ipjck-page-body-raw', true );
      $replaceOn  = $setting->getSetting( 'link_replace_active' );
      $replaceUrl = $setting->getSetting( 'link_replace_url' );

      // Fix link
      if ( ! empty( $content ) )
      {
        if ( $replaceOn == 'true' )
        {
          $content = preg_replace_callback(
            "/(<a[^>]*href *= *[\"']?)([^\"']*)/i",
            function ($matches)
            {
              global $replaceUrl;
              $result = $matches[1] . $replaceUrl;
              return $result;
            },
            $content
          );
        }
        //Save
        update_post_meta( $postId, '__ipjck-page-body', $content );
      }

      return $content;
    }
  }
}
