<?php
namespace Kanews;

class Reactions {

  private static $instance;
  private $optionCache = array();
  private $reactionMetaCache = array();
  private $postMetaCache = array();

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


  function __construct() {
    add_action('kanews_entry_above', array($this,'addContent'), 1);

    add_action( 'wp_ajax_kanews_react', array($this,'react'));
    add_action( 'wp_ajax_nopriv_kanews_react', array($this,'react' ));

    // add_shortcode( 'kanews_reactions', array($this, 'shortCode') );
  }

  function shortCode() {
    return $this->renderPlugin();
  }

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

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

  private function get_post_meta_cached($post_id, $key, $default = null) {
    if(!isset($this->postMetaCache[$post_id])) {
      $this->postMetaCache[$post_id] = array();
    }

    if(!array_key_exists($key, $this->postMetaCache[$post_id])) {
      $meta = get_post_meta($post_id, $key, true);
      $this->postMetaCache[$post_id][$key] = $meta !== '' ? $meta : $default;
    }

    return $this->postMetaCache[$post_id][$key];
  }

  function addContent() {
    $post_id = get_the_ID();

    if( !empty($this->get_post_meta_cached( $post_id, 'kanews_bik_id', '' )) )
	  return;

    $show_on_every_post = (bool) $this->get_option_cached('reaction-system', false);
    
    $enabled = $this->get_post_meta_cached( $post_id, 'kanews_reaction_enable', '' );
    $plugin = '';
    if (!is_page() && $enabled!="off") {
      if ($show_on_every_post==true) {
        $plugin = $this->renderPlugin();
      }
    } else {
      return false;
    }

    echo $plugin;
  }
  
  function react_img($img, $size, $slug = '') {
    $out = '';
    $emoji = (!empty($img))? $img: get_template_directory_uri().'/assets/img/alkis.png';
    if(kanews_get_option('lazy') == true) {
      $out = 'class="kanews-lazy" alt="'.$slug.'" data-src="'.$emoji.'" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" width="'.$size.'" height="'.$size.'"';
    } else {
      $out = 'alt="'.$slug.'" src="'.$emoji.'" width="'.$size.'" height="'.$size.'"';
    }
    return $out;
  }
  
  function renderPlugin() {

    if(get_post_type() !=  'post')
    return false;

    $post_id = get_the_ID();
    $reactions = $this->get_option_cached('reaction-buttons', array());

    if( ! empty( $reactions ) ) {
      $reaction_buttons = array();
      $i = 0;
      foreach( $reactions as $reaction ) {
        $i++;
        $react_slug = (!empty($reaction['title']) ? strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $reaction['title']))): 'emoji-'.$i);
        $value = $this->getAmount($react_slug,$post_id);
        $reaction_buttons[] = [
          'slug'  => $react_slug,
          'label' => !empty($reaction['title']) ? $reaction['title']: 'Emoji',
          'value' => is_numeric($value) ? $value : 0,
          'class' => $this->getClass($react_slug,$post_id),
          'emoji' => $this->react_img($reaction['emoji'], 40, $react_slug),
        ];
      }
    } else {
      return;
    }

    $total = array_sum(array_column($reaction_buttons,'value'));
    $total = $total > 0 ? $total : 1;
    
    ob_start(); ?>

      <div class="reaction-wrapper reaction-wrapper-style-<?php echo esc_attr( $this->get_option_cached('reaction-system-style', '1') ); ?>">
      
        <div class="reaction-wrapper-inner">
          <?php if( $this->get_option_cached('reaction-system-style', '1') == '2' ) : ?>
            <div class="reaction-wrapper-action"><div class="reaction-wrapper-action-icon">☺ <i class="icon-add"></i></div> <?php esc_html_e( 'Tepki Ver', 'kanews' ); ?>
              <?php 
              $reaction_buttons2 = $reaction_buttons;
              usort($reaction_buttons2, function($a, $b) {
                return strnatcmp($b['value'], $a['value']);
              });      

              if( $reaction_buttons2[0]['value'] > 0 )
              echo '<span><span>|</span> <img '.$reaction_buttons2[0]['emoji'].' />'.$reaction_buttons2[0]['value'].'</span>';
              else
              echo '<span><span>|</span> '.esc_html__('Tepki verilmemiş', 'kanews').'</span>'; 
              ?>
            </div>
        
          <?php endif; ?>
            <div class="reaction-wrapper-icons" data-post-id="<?php echo esc_attr($post_id) ?>" <?php echo $this->getReactStatus($post_id); ?>>
              <?php 
                if( $reaction ) {
                  foreach ( $reaction_buttons as $reaction_button ) {
                    $count = $reaction_button['value'];
                    echo '
                      <div data-reaction="'.$reaction_button['slug'].'" aria-label="'.esc_attr__( $reaction_button['label'], 'kanews' ).'" '.$reaction_button['class'].' class="reaction-item">
                        <div class="reaction-count">'.$reaction_button['value'].'</div>
                        <div class="reaction-bar" style="height: '.round($count/$total*100, 2).'px"></div>
                        <div class="reaction-img">
                          <img '.$reaction_button['emoji'].' >
                        </div>
                        <div class="reaction-text">'.esc_html__( $reaction_button['label'], 'kanews' ).'</div>
                      </div>
                    ';
                  }
                }
              ?>
            </div>
        </div>
      </div>

    <?php
    $plugin = ob_get_contents();
    ob_clean();
    return $plugin;
  }

  function getClass($reaction, $post_id) {
    $out = '';
    if (isset($_COOKIE["kanews_reacted_".$reaction."_".$post_id])) {
      $out = 'data-reacted="yes"';
    } else {
      $out = 'data-reacted="no"';
    }
    return $out;
  }
  
  function getReactStatus($post_id) {
    $out = '';
    $_COOKIE["kanews_reacted_".$post_id] = !empty($_COOKIE["kanews_reacted_".$post_id]) ? $_COOKIE["kanews_reacted_".$post_id] : '';
    if ($_COOKIE["kanews_reacted_".$post_id] == 1){
      $out = 'data-reacted="yes"';
    }
    return $out;
  }
  

  function getAmount($reaction, $post_id) {
    $meta_key = "kanews_reaction_".$reaction;
    if(!isset($this->reactionMetaCache[$post_id])) {
      $this->reactionMetaCache[$post_id] = array();
    }

    if(!array_key_exists($meta_key, $this->reactionMetaCache[$post_id])) {
      $amount = get_post_meta($post_id, $meta_key, true);
      $this->reactionMetaCache[$post_id][$meta_key] = is_numeric($amount) ? (int) $amount : 0;
    }

    return $this->reactionMetaCache[$post_id][$meta_key];
  }

  function react() {
    $post_id  = isset($_POST["postid"]) ? (int) $_POST["postid"] : 0;
    $reaction = isset($_POST["reaction"]) ? sanitize_key($_POST["reaction"]) : '';
    $unreact  = isset($_POST["unreact"]) ? sanitize_text_field($_POST["unreact"]) : '';

    if(!$post_id || !$reaction) {
      wp_send_json_error();
    }

    $amount = $this->getAmount($reaction, $post_id);
    if (isset($unreact) && $unreact === "true") {
      // unset($_COOKIE['kanews_reacted_'.$post_id]);
      // unset($_COOKIE['kanews_reacted_'.$reaction.'_'.$post_id]);
        // setcookie('kanews_reacted_'.$reaction.'_'.$post_id, '', time() - 3600, "/");
      // $amount = (int) $amount - 1;
      // if ($amount >=0) {
        // echo "Amount: ".$amount." ";
        // update_post_meta($post_id, "kanews_reaction_".$reaction, $amount);
      // }
    }
    else {
      setcookie('kanews_reacted_'.$post_id, true, time() + (86400 * 30), "/");
      setcookie('kanews_reacted_'.$reaction.'_'.$post_id, $reaction, time() + (86400 * 30), "/");
      $amount = max(0, (int) $amount + 1);
      $this->reactionMetaCache[$post_id]["kanews_reaction_".$reaction] = $amount;
      update_post_meta($post_id, "kanews_reaction_".$reaction, $amount);
      wp_send_json_success(array('amount' => $amount));
    }
    wp_send_json_success(array('amount' => $amount));
  }
  
}


function geo_reaction_badge($post_id) {
	if (ot_get_option('geo_post_emoji_show') != 'off') 
	$r1 = get_post_meta($post_id, 'geo_reaction_aci', true);
	$r2 = get_post_meta($post_id, 'geo_reaction_begendim', true);
	$r3 = get_post_meta($post_id, 'geo_reaction_begenmedim', true);
	$r4 = get_post_meta($post_id, 'geo_reaction_cokiyi', true);
	$r5 = get_post_meta($post_id, 'geo_reaction_sevdim', true);
	$r6 = get_post_meta($post_id, 'geo_reaction_kizgin', true);
	$r7 = get_post_meta($post_id, 'geo_reaction_dusunceli', true);
	$geo_react = array($r1, $r2, $r3, $r4, $r5, $r6, $r7);
	$minsayi = '5';
	$geo_max  = max($geo_react);
	if ($geo_max >= $minsayi) {
	echo '<div class="geo_reaction_badge" data-balloon="'.__('En Çok Kullanılan Emoji', 'geo').'" data-balloon-pos="top">';
		if ($geo_max == ''){
		}
		elseif ($geo_max == $r1){
			echo '<img alt="reaksiyon-aci" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/aci.png" />';
		}
		elseif ($geo_max == $r2) {
			echo '<img alt="reaksiyion-alkis" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/alkis.png" />';
		}
		elseif ($geo_max == $r3) {
			echo '<img alt="reaksiyion-begenme" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/begenme.png" />';
		}
		elseif ($geo_max == $r4) {
			echo '<img alt="reaksiyion-cok-iyi" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/cok-iyi.png" />';
		}
		elseif ($geo_max == $r5) {
			echo '<img alt="reaksiyion-sevdim" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/sevdim.png" />';
		}
		elseif ($geo_max == $r6) {
			echo '<img alt="reaksiyion-kizgin" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/kizgin.png" />';
		}
		elseif ($geo_max == $r7) {
			echo '<img alt="reaksiyion-dusunce" width="20" height="20" src="'.get_template_directory_uri().'/assets/img/dusunce.png" />';
		}
		echo '</div>';
		}
	
}