<?php
namespace Kanews;
use Kanews\Helper_Wp;

class PostViews {

  private static $instance;

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

  function __construct() {
    add_filter( 'manage_posts_columns',                 array( $this, 'posts_column_views' ) );
    add_filter( 'manage_edit-post_sortable_columns',    array( $this, 'sort_postviews_column' ) );
    add_action( 'manage_posts_custom_column',           array( $this, 'posts_custom_column_views' ), 5, 2 );

    add_action( 'wp_enqueue_scripts',                   array( $this, 'inline_script' ), 9999 );

    add_action( 'wp_footer',                            array( $this, 'set_post_views' ) );
    add_action( 'amp_post_template_head',               array( $this, 'set_post_views' ) );

    add_action( 'wp_ajax_kanews_postviews',             array( $this, 'update_post_views' ) );
    add_action( 'wp_ajax_nopriv_kanews_postviews',      array( $this, 'update_post_views' ) );
  }

  // Set Post Views
  function set_post_views() {

    $source = kanews_get_option('post-views-source') ? kanews_get_option('post-views-source') : 'theme';

    if ($source != 'theme' || kanews_get_option('post-views') == false || ! is_single() || Helper_Wp::is_bot())
    return;

    $page = get_query_var( 'paged', 1 );

    if( $page > 1 ){
      return false;
    }
    
    if( ! self::is_cache_enabled() || ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) ){

      $post_id    = get_the_ID();
      $count_key  = 'post_views_count';

      $count  = (int) get_post_meta($post_id, $count_key, true);
      
      // all time
      if( empty( $count ) || $count == 0  ){
        $count = 0;
      }

      $new_count = $count + 1;
      update_post_meta( $post_id, $count_key, $new_count );

    }

  }

  // Update Post Views
  function update_post_views($postID) {

    $source = kanews_get_option('post-views-source') ? kanews_get_option('post-views-source') : 'theme';

    if( $source != 'theme' || Helper_Wp::is_bot() )
    return;
    
    if( ! empty( $_GET['post_id'] ) && kanews_get_option('post-views') != false && self::is_cache_enabled() ){
      
      $post_id = intval($_GET['post_id']);

      if( $post_id > 0 ){
        $count = 0;

        $count_key  = 'post_views_count';
  
        $count  = (int) get_post_meta($post_id, $count_key, true);

        // all time
        if( empty( $count ) || $count == 0  ){
          $count = 0;
        }

        $new_count = $count + 1;
        update_post_meta( $post_id, $count_key, $new_count );

        $formated = number_format_i18n( $new_count );
        echo '<span class="icon-view" aria-hidden="true"></span> '. $formated .'</span>';
      }
    }

    exit();
  }

  // Get Post Views
  public static function get_post_views($post_id, $time = '', $icon = false, $dropdown = false) {
    $source = kanews_get_option('post-views-source') ? kanews_get_option('post-views-source') : 'theme';

    if (kanews_get_option('post-views') == false)
    return '';

    if($icon == true)
    $icon = '<i class="icon-view"></i>';

    $count = 0;
    
    if($source == 'post-views-counter' && function_exists("pvc_get_post_views"))
    $count = pvc_get_post_views( $post_id ) ? pvc_get_post_views( $post_id ) : 0;
    else
    $count = get_post_meta($post_id, 'post_views_count', true) ? get_post_meta($post_id, 'post_views_count', true) : 0;

    $text = get_post_format() == 'video' ? esc_html__( 'İzlendi', 'kanews' ) : esc_html__( 'Okundu', 'kanews' );
    
    if($dropdown)
    return '<span class="kanews-post-views"><div role="tooltip" data-microtip-position="bottom" aria-label="'.sprintf(esc_attr__( '%s kez okundu', 'kanews' ), number_format_i18n( $count )).'">'.$icon.number_format_i18n( $count ).'</div></span>';
    else
    return '<span class="kanews-post-views">'.$icon.number_format_i18n( $count ).'</span>';

  }

  function is_cache_enabled(){

    if ( defined( 'WP_CACHE' ) && WP_CACHE ){
      return true;
    }
  
    // Wp Fatest Cache
    if( class_exists( 'WpFastestCache' ) ){
      if( ! empty( $GLOBALS['wp_fastest_cache_options']->wpFastestCacheStatus ) && $GLOBALS['wp_fastest_cache_options']->wpFastestCacheStatus == 'on' ){
        return true;
      }
    }
  
    return false;
  }

  function inline_script() {
    $source = kanews_get_option('post-views-source') ? kanews_get_option('post-views-source') : 'theme';
    if( $source != 'theme' || kanews_get_option('post-views') == false || is_page() || ! is_singular() || ! self::is_cache_enabled() ){
      return;
    }

    // Add the js code
    $cache_js = '
      jQuery.ajax({
        type : "GET",
        url  : "'. esc_url( admin_url('admin-ajax.php') ) .'",
        data : "post_id='. get_the_ID() .'&action=kanews_postviews",
        cache: !1,
        success: function( data ){
          jQuery(".kanews-article-meta").find(".kanews-post-views").html( data );
        }
      });
    ';

    wp_add_inline_script( 'kanews-theme', $cache_js );
  }

  function posts_column_views( $defaults ){
    if( kanews_get_option('post-views') == true && kanews_get_option('post-views-source') == 'theme' ){
      $defaults['Kanews\PostViews'] = esc_html__( 'Okunma', 'kanews' );
    }
    return $defaults;
  }

  function posts_custom_column_views( $column_name, $id ){
    if( kanews_get_option('post-views') == false && kanews_get_option('post-views-source') != 'theme' ){
      return;
    }

    if( $column_name === 'Kanews\PostViews' ){
      echo $this->get_post_views( get_the_ID() );
    }
  }

  function sort_postviews_column( $defaults ){
    if( kanews_get_option('post-views') == true && kanews_get_option('post-views-source') == 'theme' ){
      $defaults['Kanews\PostViews'] = 'post_views_count';
    }
    return $defaults;
  }


}