<?php
namespace Kanews;

class Ads {

  private static $instance;
  private $optionCache = array();
  private $insightsControl = null;
  private $currentUserId = null;

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

  function __construct() {
    add_action( 'wp_head',                     array( $this, 'ad_auto' ) );
    add_action( 'wp_body_open',                array( $this, 'ad_header_below' ) );
    add_action( 'wp_body_open',                array( $this, 'ad_cover' ) );
    add_action( 'kanews_header_ad',            array( $this, 'ad_header_above' ) );
    add_action( 'kanews_footer',               array( $this, 'ad_left_side' ), 1 );
    add_action( 'kanews_footer',               array( $this, 'ad_right_side' ), 1 );
    add_action( 'kanews_footer',               array( $this, 'ad_footer_above' ), 1 );
    add_action( 'kanews_entry_above',          array( $this, 'ad_single_below' ) );
    add_action( 'kanews_entry_below',          array( $this, 'ad_single_above' ) );
    add_action( 'kanews_entry_meta_above',     array( $this, 'ad_single_meta_above' ) );
    add_action( 'kanews_entry_meta_below',     array( $this, 'ad_single_meta_below' ) );
    add_action( 'kanews_entry_comment_above',  array( $this, 'ad_single_comment_above' ) );
    add_filter( 'the_content',                 array( $this, 'ad_single_anywhere' ) );
    add_filter( 'the_content',                 array( $this, 'ad_single_anywhere2' ) );
    add_action( 'amp_post_template_body_open', array( $this, 'ad_amp_auto' ) );
    add_action( 'amp_header',                  array( $this, 'ad_amp_header_below' ) );
    add_action( 'amp_footer',                  array( $this, 'ad_amp_footer_above' ) );
    add_action( 'amp_article_above',           array( $this, 'ad_amp_single_above' ) );
    add_action( 'amp_article_below',           array( $this, 'ad_amp_single_below' ) );
    add_shortcode('kanews-ad',                 array( $this, 'ad_shortcode' ) );
    add_action( 'wp_footer',                   array( $this, 'ad_screen_bottom' ) );
  }

  private function get_option_cached($key, $default = '') {
    if(!array_key_exists($key, $this->optionCache)) {
      $this->optionCache[$key] = kanews_get_option($key, $default);
    }

    return $this->optionCache[$key];
  }

  private function get_current_user_id_cached() {
    if($this->currentUserId === null) {
      $this->currentUserId = get_current_user_id();
    }

    return $this->currentUserId;
  }

  private function user_has_insights_control() {
    if($this->insightsControl === null) {
      $this->insightsControl = (bool) kanews_insights_control($this->get_current_user_id_cached());
    }

    return $this->insightsControl;
  }

  function ad($id, $before = NULL, $after = NULL, $echo = true) {
    $code = $this->get_option_cached($id, '');
    $switch = $this->get_option_cached($id.'-switch', false);

    if( empty($code) || $switch == false || $this->user_has_insights_control() )
    return;

    global $post;
    if(is_singular() && get_post_meta( $post->ID, 'show_post_ads', true ) == 'off')
    return false;

    if( is_array($code) && isset($code['id']) && !empty($code['id']) )
    $code = '<a class="screen-cover" href="'.( $this->get_option_cached('ad-cover-link', '') != '' ? esc_url($this->get_option_cached('ad-cover-link')) : '#').'" style="background-image: url('.wp_get_attachment_image_url( $code['id'], 'full' ).'); background-color: '.( $this->get_option_cached('ad-cover-color', '') != '' ? $this->get_option_cached('ad-cover-color') : '#f5f5f5'  ).'" rel="nofollow noopener" target="_blank"></a></a>';
  
    $close = ($id == 'ad-header-below' || $id == 'ad-screen-bottom') ? '<div class="kanews-close-btn" aria-label="'.esc_html__('Kapat', 'kanews').'"><i class="icon-close"></i></div>' : '';
    
    $close .= $this->get_option_cached('remove-ad', false) ? '<a href="'.kanews_insights_page_url().'" class="kanews-banner-remove">'.esc_html__( 'Reklamı kaldır', 'kanews' ).'</a>' : '';

    if($echo == false)
    return $before.do_shortcode($code).$close.$after;

    echo $before.do_shortcode($code).$close.$after;
  }
  
  function ad_auto() {
    $this->ad('ad-auto');
  }

  function ad_header_below() {
    $this->ad('ad-header-below', '<div id="header-stream"><div class="kanews-banner kanews-banner-header-below">', '</div></div>');
  }
  function ad_cover() {
    $this->ad('ad-cover', '', '');
  }

  function ad_header_above() {
    $this->ad('ad-header', '<div class="container"><div class="kanews-banner kanews-banner-header-above">', '</div></div>');
  }

  function ad_footer_above() {
    $this->ad('ad-footer', '<div class="container"><div class="kanews-banner kanews-banner-footer-below">', '</div></div>');
  }

  function ad_screen_bottom() {
    $this->ad('ad-screen-bottom', '<div class="screen-stream"><div class="kanews-banner">', '</div></div>');
  }

  function ad_left_side() {
    $this->ad('ad-left-side', '<div class="kanews-banner-left-side"><div class="kanews-banner">', '</div></div>');
  }

  function ad_right_side() {
    $this->ad('ad-right-side', '<div class="kanews-banner-right-side"><div class="kanews-banner">', '</div></div>');
  }

  public static function ad_archives($style,$counter) {
    $instance = self::getInstance();
    if($instance->user_has_insights_control() == true )
    return false;

    $ads = $instance->get_option_cached('ad-archieve-per-post', false);

    if($ads && is_array($ads)) {
      switch($style) {
        case '1':
          $col = 'col-12 toinfinite';
          $item = 'kanews-post-item kanews-post-list-item';
        break;
        case '2':
          $col = 'col-12 col-md-6 toinfinite';
          $item = 'kanews-post-item kanews-post-grid-item';
        break;
        case '3':
          $col = 'col-6 col-md-4 toinfinite';
          $item = 'kanews-post-item kanews-post-grid-item';
        break;
        case '4':
          $col = 'col-12 toinfinite';
          $item = 'kanews-post-item kanews-post-big-item';
        break;
        case '5':
          $col = 'col-12 toinfinite';
          $item = 'kanews-post-item kanews-post-special-item';
        break;
        case '6':
          $col = 'col-12 col-md-6 toinfinite';
          $item = 'kanews-post-item kanews-post-special-item';
        break;
      }
      foreach($ads as $ad) {
        // echo
        if($counter == $ad['count']) {
          echo '<div class="'.$col.'"><div class="kanews-banner kanews-banner-archieve-item">'.do_shortcode($ad['code']).'</div></div>';
        }
      }
    }
  }

  function ad_single_above() {
    $this->ad('ad-single-above', '<div class="kanews-banner kanews-banner-single">', '</div>');
  }

  function ad_single_below() {
    $this->ad('ad-single-below', '<div class="kanews-banner kanews-banner-single">', '</div>');
  }

  function ad_single_meta_above() {
    $this->ad('ad-single-meta-above', '<div class="kanews-banner kanews-banner-single kanews-banner-single-meta mt-0">', '</div>');
  }

  function ad_single_meta_below() {
    $this->ad('ad-single-meta-below', '<div class="kanews-banner kanews-banner-single kanews-banner-single-meta mb-0">', '</div>');
  }

  function ad_single_comment_above() {
    $this->ad('ad-single-comment-above', '<div class="kanews-banner kanews-banner-footer-below">', '</div>');
  }

  function ad_single_anywhere( $content ) {
    
    if(function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
      $code = $this->get_option_cached('amp-ad-single-amid', '');
      $switch = $this->get_option_cached('amp-ad-single-amid-switch', false);
      $ad_position = $this->get_option_cached('amp-ad-single-amid-limit');
    } else {
      $code = $this->get_option_cached('ad-single-amid', '');
      $switch = $this->get_option_cached('ad-single-amid-switch', false);
      $ad_position = $this->get_option_cached('ad-single-amid-limit');
    }

    if($code && $switch == true && $this->user_has_insights_control() == false )
      return $this->ad_single_insert( '<div class="kanews-banner kanews-banner-single">'.$code.'</div>', $ad_position, $content );
    else 
      return $content;
  }

  function ad_single_anywhere2( $content ) {
    
    if(function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
      $code = $this->get_option_cached('amp-ad-single-amid2', '');
      $switch = $this->get_option_cached('amp-ad-single-amid-switch2', false);
      $ad_position = $this->get_option_cached('amp-ad-single-amid-limit2');
    } else {
      $code = $this->get_option_cached('ad-single-amid2', '');
      $switch = $this->get_option_cached('ad-single-amid-switch2', false);
      $ad_position = $this->get_option_cached('ad-single-amid-limit2');
    }

    if($code && $switch == true && $this->user_has_insights_control() == false )
      return $this->ad_single_insert( '<div class="kanews-banner kanews-banner-single">'.$code.'</div>', $ad_position, $content );
    else 
      return $content;
  }

  function ad_single_insert( $insertion, $paragraph_id, $content ) {
    global $post;
    if(get_post_meta( $post->ID, 'show_post_ads', true ) == 'off')
    return $content;
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
      if ( trim( $paragraph ) ) {
        $paragraphs[$index] .= $closing_p;
      }
      if ( $paragraph_id == $index + 1 ) {
        $paragraphs[$index] .= $insertion;
      }
    } 
    return implode( '', $paragraphs );
  }

  function ad_shortcode( $atts, $content = null ) {
    global $post;
    if(get_post_meta( $post->ID, 'show_post_ads', true ) == 'off')
    return false;
    if( is_array( $atts ) ) extract($atts);
    if(function_exists( 'is_amp_endpoint' ) && is_amp_endpoint())
    $option = 'amp-ad-single-shortcode';
    else
    $option = 'ad-single-shortcode';
    $out = $this->ad('ad-single-shortcode', '<div class="kanews-banner kanews-banner-single">', '</div>', false);
    return $out;
  }

  function ad_amp_header_below() {
    $this->ad('amp-ad-header', '<div class="kanews-banner" style="margin-left:-15px;">', '</div>');
  }
  function ad_amp_footer_above() {
    $this->ad('amp-ad-footer', '<div class="kanews-banner">', '</div>');
  }
  function ad_amp_single_above() {
    $this->ad('amp-ad-single-above', '<div class="kanews-banner">', '</div>');
  }
  function ad_amp_single_below() {
    $this->ad('amp-ad-single-below', '<div class="kanews-banner">', '</div>');
  }
  function ad_amp_auto() {
    $this->ad('amp-ads-auto');
  }
  
}
