<?php
namespace Kanews;
use WPSEO_Primary_Term;

class Helper_Wp {

  private static $instance;

  public static function getInstance() {
    if ( null === static::$instance ) {
      static::$instance = new static();
    }
    return static::$instance;
  }

  function __construct() {

    add_action( 'registered_post_type',       array( $this, 'change_post_object' ) );
    $this->comments_order_reverse_parameter();
    add_action( 'admin_init',                 array( $this, 'kanews_new_user_role' ) );
    add_action( 'wp_enqueue_scripts',         array( $this, 'woocommerce_styles' ), 99 );
    add_action( 'pre_get_posts',              array( $this, 'pre_get_posts' ) );
    add_action( 'navigation_markup_template', array( $this, 'sanitize_pagination' ) );
    add_action( 'get_comment_author',         array( $this, 'update_author_nickname' ), 15 );
    add_filter( 'the_tags',                   array( $this, 'the_tags' ) );
    add_filter( 'excerpt_more',               array( $this, 'excerpt_more' ) );
    add_filter( 'widget_tag_cloud_args',      array( $this, 'tag_widget_limit' ) );
    
    // Properly clear get_term_by() cache when a term is updated
    add_action( 'edit_terms', array( $this, 'wp_flush_get_term_by_cache' ), 10, 2 );

    // Properly clear get_term_by() cache when a term is updated
    add_action( 'create_term', array( $this, 'wp_flush_get_term_by_cache' ), 10, 2 );

    // Properly clear term_exists() cache when a term is updated
    add_action( 'delete_term', array( $this, 'wp_flush_term_exists' ), 10, 4 );

    // Flush the cache for published pages so we don't end up with stale data
    add_action( 'transition_post_status', array( $this, 'flush_get_page_by_path_cache'  ), 10, 3 );
    add_action( 'transition_post_status', array( $this, 'flush_get_page_by_title_cache' ), 10, 3 );

    /* Disable Woocommerce Schedule
      * @ https://wordpress.org/support/topic/action_scheduler_run_queue-event/
      */
    add_filter('action_scheduler_run_schedule', function($arg) { return 86400; });


  }


  // Change the number of tags in the cloud tags
  function tag_widget_limit( $args ){

    if( isset($args['taxonomy']) && $args['taxonomy'] == 'post_tag' ){
      $args['number'] = 10;
    }

    return $args;
  }

  // Post Type Filter
  function change_post_object() {
    if(!is_admin())
    return;
    $get_post_type = get_post_type_object('post');
    $labels = $get_post_type->labels;
    $labels->menu_name = __('Haberler', 'kanews');
    $labels->name = __('Haberler', 'kanews');
    $labels->singular_name = __('Haberler', 'kanews');
    $labels->all_items = __('Tüm Haberler', 'kanews');
    $labels->name_admin_bar = __('Haberler', 'kanews');
  }

  // Primary Cat ID
  public static function primary_category_id($pid) {

    $cat_name = $id = $check = '';
		
	if(get_post_meta($pid, 'kanews_primary_category', true) != '0' && get_post_meta($pid, 'kanews_primary_category', true) != '') {
		$idx   = get_post_meta($pid, 'kanews_primary_category', true);
		$categories = get_the_terms($pid, 'category') ;
		foreach($categories as $cat) {
			if($cat->term_id == $idx) {
				$check = 1;
				break;
			}
		}
		if($check == 1) {
			$id = $idx;
		} else {
			$id	= isset($categories[0]->term_id) ? $categories[0]->term_id : '';
		}
	} elseif ( class_exists('WPSEO_Primary_Term') ) {
		$wpseo_primary_term = new WPSEO_Primary_Term( 'category', $pid );
		$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
		$term               = get_term( $wpseo_primary_term );

		if ( is_wp_error($term) ) {
			$categories = get_the_terms($pid, 'category');
			$id			= isset($categories[0]->term_id) ? $categories[0]->term_id : '';
		} else {
			$cat_name = $term->name;
			$id	   	  = $term->term_id;
		}
	} elseif ( class_exists('rank_math') ) {
		$rankmath_primary_term = get_post_meta( $pid, 'rank_math_primary_category', true );
		$term                  = get_term( $rankmath_primary_term );

		if ( is_wp_error($term) ) {
			$categories = get_the_terms($pid, 'category');
			$id			= isset($categories[0]->term_id) ? $categories[0]->term_id : '';
		} else {
			$cat_name = $term->name;
			$id	   	  = $term->term_id;
		}

	} else {
		$categories = get_the_terms($pid, 'category');
		$id			= isset($categories[0]->term_id) ? $categories[0]->term_id : '';
	}



    return $id;
  }

  // Remove Woocommerce Styles
  function woocommerce_styles() {
    if ( ! class_exists( 'WooCommerce' ) ) {
      return;
    }
    remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
    if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
      wp_dequeue_style( 'wc-block-style' );
      wp_dequeue_style( 'wc-block-vendors-styl' );
      wp_dequeue_style( 'woocommerce_frontend_styles' );
      wp_dequeue_style( 'woocommerce-general');
      wp_dequeue_style( 'woocommerce-layout' );
      wp_dequeue_style( 'woocommerce-smallscreen' );
      wp_dequeue_style( 'woocommerce_fancybox_styles' );
      wp_dequeue_style( 'woocommerce_chosen_styles' );
      wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
      wp_dequeue_script( 'selectWoo' );
      wp_deregister_script( 'selectWoo' );
      wp_dequeue_script( 'wc-add-payment-method' );
      wp_dequeue_script( 'wc-lost-password' );
      wp_dequeue_script( 'wc_price_slider' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-add-to-cart' );
      wp_dequeue_script( 'wc-cart-fragments' );
      wp_dequeue_script( 'wc-credit-card-form' );
      wp_dequeue_script( 'wc-checkout' );
      wp_dequeue_script( 'wc-add-to-cart-variation' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-cart' );
      wp_dequeue_script( 'wc-chosen' );
      wp_dequeue_script( 'woocommerce' );
      wp_dequeue_script( 'prettyPhoto' );
      wp_dequeue_script( 'prettyPhoto-init' );
      wp_dequeue_script( 'jquery-blockui' );
      wp_dequeue_script( 'jquery-placeholder' );
      wp_dequeue_script( 'jquery-payment' );
      wp_dequeue_script( 'fancybox' );
      wp_dequeue_script( 'jqueryui' );
    } else {
      wp_enqueue_style('kanews-wc-style', get_template_directory_uri() . '/assets/css/wc.css', array(), KAN_THEME_VER);
    }
  }

  // Comments Order Reverse
  function comments_order_reverse_parameter() {
    if (!isset($_GET['comments_order']))
    return;

    if ($_GET['comments_order'] == 'asc') {
      add_filter( 'comments_array', function( $comments ) { return array_reverse( $comments ); } );
    }
  }

  // Excerpt
  public static function excerpt_more( $more ) {
    return '&#46;&#46;&#46;';
  }

  // Remove h2 tag from pagination
  function sanitize_pagination($content) {
    $content = preg_replace('#<h2.*?>(.*?)<\/h2>#si', '', $content);
    return $content;
  }

  // Tags Filter
  function the_tags($html) {
      $html = str_replace('<a','<a class="kanews-entry-tag"',$html);
      $html = str_replace('rel="tag">','rel="tag"># ',$html);
      return $html;
  }
  
  // Link Pages
  public static function wp_link_pages($args) {
    global $page, $numpages, $more, $pagenow;

    if (!$args['next_or_number'] == 'next_and_number') 
        return $args; # exit early

    $args['next_or_number'] = 'number'; # keep numbering for the main part
    if (!$more)
        return $args; # exit early
    
        $args['link_before'] = '<span class="classlinks %s">';

    return $args;
  }

  // Update Author Nickname
  function update_author_nickname($author) {
    global $comment;
    if (!empty($comment->user_id)){
        $user=get_userdata($comment->user_id);
        $author=$user->display_name;    
    }

    return $author;
  }


  function pre_get_posts($query) {
	if ( is_admin() || ! $query->is_main_query() ) {
		return;
	}
		
	if (  is_author() || is_tag() ) {
		$query->set( 'post_type', array('post', 'columist') );
	}else if ( is_category() ) {

		$cid = is_object(get_queried_object()) ? get_queried_object()->term_id : '';

		$posts = get_term_meta( $cid, 'category-posts-per-page', true );
		if($posts != '')
		$query->set( 'posts_per_page', $posts );

	} 
    
  }

  // Custom User Role
  function kanews_new_user_role() {
    if ( get_option( 'kanews_roles_version2' ) < 1 ) {
      add_role( 'columist', 'Köşe Yazarı', get_role( 'author' )->capabilities );
      update_option( 'kanews_roles_version2', 1 );
    }
  }


  // Is Bot
  public static function is_bot( $ua = null ){

    if ( empty( $ua ) && ! empty( $_SERVER['HTTP_USER_AGENT'] ) ){
      $ua = $_SERVER['HTTP_USER_AGENT'];
    }

    if( ! empty( $ua ) ){

      $bot_agents = array(
        'alexa', 'altavista', 'ask jeeves', 'attentio', 'baiduspider', 'bingbot', 'chtml generic', 'crawler', 'fastmobilecrawl',
        'feedfetcher-google', 'firefly', 'froogle', 'gigabot', 'googlebot', 'googlebot-mobile', 'heritrix', 'httrack', 'ia_archiver', 'irlbot',
        'iescholar', 'infoseek', 'jumpbot', 'linkcheck', 'lycos', 'mediapartners', 'mediobot', 'motionbot', 'msnbot', 'mshots', 'openbot',
        'pss-webkit-request', 'pythumbnail', 'scooter', 'slurp', 'Speed Insights', 'snapbot', 'spider', 'taptubot', 'technoratisnoop',
        'teoma', 'twiceler', 'yahooseeker', 'yahooysmcm', 'yammybot', 'ahrefsbot', 'Pingdom', 'GTmetrix', 'PageSpeed', 'Google Page Speed',
        'kraken', 'yandexbot', 'twitterbot', 'tweetmemebot', 'openhosebot', 'queryseekerspider', 'linkdexbot', 'grokkit-crawler',
        'livelapbot', 'germcrawler', 'domaintunocrawler', 'grapeshotcrawler', 'cloudflare-alwaysonline',
      );

      foreach ( $bot_agents as $bot_agent ) {
        if ( false !== stripos( $ua, $bot_agent ) ) {
          return true;
        }
      }
    }

    return false;
  }

  /**
   * Cached version of get_term_by.
   *
   * Many calls to get_term_by (with name or slug lookup) across on a single pageload can easily add up the query count.
   * This function helps prevent that by adding a layer of caching.
   *
   * @param string $field Either 'slug', 'name', or 'id'
   * @param string|int $value Search for this term value
   * @param string $taxonomy Taxonomy Name
   * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N
   * @param string $filter Optional. Default is 'raw' or no WordPress defined filter will applied.
   * @return mixed|null|bool Term Row from database in the type specified by $filter. Will return false if $taxonomy does not exist or $term was not found.
   * @link http://vip.wordpress.com/documentation/uncached-functions/ Uncached Functions
   */
  public static function get_term_by( $field, $value, $taxonomy, $output = OBJECT, $filter = 'raw' ){

    // ID lookups are cached
    if ( 'id' == $field )
      return get_term_by( $field, $value, $taxonomy, $output, $filter );

    $cache_key = $field . '|' . $taxonomy . '|' . md5( $value );
    $term_id = wp_cache_get( $cache_key, 'get_term_by' );

    if ( false === $term_id ){
      $term = get_term_by( $field, $value, $taxonomy );
      if ( $term && ! is_wp_error( $term ) )
        wp_cache_set( $cache_key, $term->term_id, 'get_term_by' );
      else
        wp_cache_set( $cache_key, 0, 'get_term_by' ); // if we get an invalid value, let's cache it anyway
    } else {
      $term = get_term( $term_id, $taxonomy, $output, $filter );
    }

    if ( is_wp_error( $term ) )
      $term = false;

    return $term;
  }

  /**
   * Optimized version of get_term_link that adds caching for slug-based lookups.
   *
   * Returns permalink for a taxonomy term archive, or a WP_Error object if the term does not exist.
   *
   * @param int|string|object $term The term object / term ID / term slug whose link will be retrieved.
   * @param string $taxonomy The taxonomy slug. NOT required if you pass the term object in the first parameter
   *
   * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
   */
  public static function get_term_link( $term, $taxonomy = null ){
    // ID- or object-based lookups already result in cached lookups, so we can ignore those.
    if ( is_numeric( $term ) || is_object( $term ) ){
      return get_term_link( $term, $taxonomy );
    }

    $term_object = self::get_term_by( 'slug', $term, $taxonomy );
    return get_term_link( $term_object );
  }

  /**
   * Properly clear get_term_by() cache when a term is updated
   */
  function wp_flush_get_term_by_cache( $term_id, $taxonomy ){
    $term = get_term_by( 'id', $term_id, $taxonomy );
    if ( ! $term ){
      return;
    }
    foreach( array( 'name', 'slug' ) as $field ){
      $cache_key = $field . '|' . $taxonomy . '|' . md5( $term->$field );
      $cache_group = 'get_term_by';
      wp_cache_delete( $cache_key, $cache_group );
    }
  }

  /**
   * Flush the cache for published pages so we don't end up with stale data
   *
   * @param string $new_status The post's new status
   * @param string $old_status The post's previous status
   * @param WP_Post $post The post
   * @link http://vip.wordpress.com/documentation/uncached-functions/ Uncached Functions
   */
  function flush_get_page_by_title_cache( $new_status, $old_status, $post ){
    if ( 'publish' == $new_status || 'publish' == $old_status )
      wp_cache_delete( $post->post_type . '_' . sanitize_key( $post->post_title ), 'get_page_by_title' );
  }

  /**
   * Flush the cache for published pages so we don't end up with stale data
   *
   * @param string  $new_status The post's new status
   * @param string  $old_status The post's previous status
   * @param WP_Post $post       The post
   *
   * @link http://vip.wordpress.com/documentation/uncached-functions/ Uncached Functions
   */
  function flush_get_page_by_path_cache( $new_status, $old_status, $post ){
    if ( 'publish' === $new_status || 'publish' === $old_status ){
      $page_path = get_page_uri( $post->ID );
      wp_cache_delete( $post->post_type . '_' . sanitize_key( $page_path ), 'get_page_by_path' );
    }
  }

  /**
   * Cached version of term_exists()
   *
   * Term exists calls can pile up on a single pageload.
   * This function adds a layer of caching to prevent lots of queries.
   *
   * @param int|string $term The term to check can be id, slug or name.
   * @param string $taxonomy The taxonomy name to use
   * @param int $parent Optional. ID of parent term under which to confine the exists search.
   * @return mixed Returns null if the term does not exist. Returns the term ID
   *               if no taxonomy is specified and the term ID exists. Returns
   *               an array of the term ID and the term taxonomy ID the taxonomy
   *               is specified and the pairing exists.
   */

  public static function term_exists( $term, $taxonomy = '', $parent = null ){
    //If $parent is not null, let's skip the cache.
    if ( null !== $parent ){
      return term_exists( $term, $taxonomy, $parent );
    }

    if ( ! empty( $taxonomy ) ){
      $cache_key = $term . '|' . $taxonomy;
    }else{
      $cache_key = $term;
    }

    $cache_value = wp_cache_get( $cache_key, 'term_exists' );

    //term_exists frequently returns null, but (happily) never false
    if ( false  === $cache_value ){
      $term_exists = term_exists( $term, $taxonomy );
      wp_cache_set( $cache_key, $term_exists, 'term_exists' );
    }else{
      $term_exists = $cache_value;
    }

    if ( is_wp_error( $term_exists ) )
      $term_exists = null;

    return $term_exists;
  }

  /**
   * Properly clear term_exists() cache when a term is updated
   */
  function wp_flush_term_exists( $term, $tt_id, $taxonomy, $deleted_term ){
    foreach( array( 'term_id', 'name', 'slug' ) as $field ){
      $cache_key = $deleted_term->$field . '|' . $taxonomy ;
      $cache_group = 'term_exists';
      wp_cache_delete( $cache_key, $cache_group );
    }
  }
    

}
