<?php 
namespace Kanews\Members;
use Kanews\Helper_Wp;

class Notifications {
	
  private static $instance;
  public $author;
  static $a = '_kan_notifications_submited';
  static $b = 'kan_user_notifications';
  private $mailPreferenceCache = array();
  private $userStatusCache = array();
  private $userOptionCache = array();

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

  public function __construct() {
    if(!kanews_get_option('notifications'))
    return false;

    // Notifications
    // add_action( 'init',    array( $this, 'set_cookie' ) );
    add_action( 'transition_post_status',    array( $this, 'publish_post' ), 10, 3 );
    add_action( 'transition_comment_status', array( $this, 'approved_comment' ), 10, 3 );
    add_filter( 'comment_post', array( $this, 'post_commented' ), 10, 2 );
    add_filter( 'wp_ajax_nopriv_clear_user_notifications', array( $this, 'clear_user_notifications' ) );
    add_filter( 'wp_ajax_clear_user_notifications', array( $this, 'clear_user_notifications' ) );
    add_filter( 'wp_ajax_nopriv_update_user_notifications', array( $this, 'update_user_notifications' ) );
    add_filter( 'wp_ajax_update_user_notifications', array( $this, 'update_user_notifications' ) );
  }

  private function user_allows_mail($user_id) {
    if(!$user_id)
    return false;

    if(!isset($this->mailPreferenceCache[$user_id])) {
      $preference = get_user_option( 'kanews_mail_notification', $user_id );
      $this->mailPreferenceCache[$user_id] = ( empty($preference) || in_array( $preference, array( 'yes', 'true', '1', 1, true ), true ) );
    }

    return $this->mailPreferenceCache[$user_id];
  }

  private function user_is_active($user_id) {
    if(!$user_id)
    return false;

    if(!isset($this->userStatusCache[$user_id])) {
      $this->userStatusCache[$user_id] = (bool) kanews_user_status($user_id);
    }

    return $this->userStatusCache[$user_id];
  }

  private function user_should_receive_email($user_id) {
    return $this->user_is_active($user_id) && $this->user_allows_mail($user_id);
  }

  private function get_cached_user_option_array($user_id, $option_name) {
    if(!$user_id || !$option_name)
    return array();

    if(!isset($this->userOptionCache[$option_name])) {
      $this->userOptionCache[$option_name] = array();
    }

    if(!array_key_exists($user_id, $this->userOptionCache[$option_name])) {
      $option = get_user_option( $option_name, $user_id );
      $this->userOptionCache[$option_name][$user_id] = is_array($option) ? $option : array();
    }

    return $this->userOptionCache[$option_name][$user_id];
  }

  // Set Cookie
  function set_cookie() {
    if(!is_user_logged_in() || is_admin())
    return;
    $user_id = get_current_user_id();
    if( !get_user_meta($user_id, 'kanews_user_date', true) ) {
      update_user_meta($user_id, 'kanews_user_date', time());
    } else {
      if(!preg_match('/[0-9]{10}/', get_user_meta($user_id, 'kanews_user_date', true))) {
        update_user_meta($user_id, 'kanews_user_date', time());
      } elseif(date('Y.m.d H:i:s', get_user_meta($user_id, 'kanews_user_date', true) < date('Y.m.d H:i:s', strtotime('-1 year')))) {
        update_user_meta($user_id, 'kanews_user_date', time());
      }
    }
  }

  // Send Notification
  public static function message($author_id, $msg, $type) {
    if( (! $msg && ! $author_id)  ) 
    return;

    $key = $type ? 'kan_user_notifications2' : 'kan_user_notifications';
    
    $notifications   = get_user_meta($author_id, $key, true) != '' ? get_user_meta($author_id, $key, true) : array();
    $notifications[] = $msg;
    
    if($notifications) {
      $count = count($notifications);
      if($count > 21) {
        array_shift($notifications);
      }
      update_user_meta( $author_id, $key, $notifications );
    } else 
      add_user_meta( $author_id, $key, $notifications );
  }

  // Published Article
  function publish_post( $new_status, $old_status, $post ) {

    $this->author = get_userdata($post->post_author);
    
    if(!$this->author->ID)
    return;


    if ( ( $new_status == 'publish' ) && ( $old_status != 'publish' ) && ! get_post_meta($post->ID, '_kan_notifications_submited', true) && ( $post->post_type == 'post' || $post->post_type == 'columist' ) ) {
      date_default_timezone_set('Europe/Istanbul');
      $this->message( $this->author->ID , array(
        'pid'  => $post->ID,
        'date' => current_time( 'timestamp', 1 )
      ), false );

      // Email to post author
      if( $this->user_should_receive_email($this->author->ID) ) {
        $email = array();
        $email[] = get_the_author_meta('email', $this->author->ID );
        $site_name = get_bloginfo( 'name' );
        $my_content = apply_filters('the_content', $post->post_content);
        $cat_color = get_term_meta( Helper_Wp::primary_category_id($post->ID), '_category_color', true );
        $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
        $email_args = [
          'title' => esc_html__( 'Yazınız Yayınlandı!', 'kanews' ),
          'subtitle' => esc_html__( 'Paylaştığınız yazı editörlerimiz tarafından inceleyip yayına alınmıştır.', 'kanews' ),
          'body_title' => $post->post_title,
          'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
          'button_link' => get_the_permalink($post->ID),
          'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
          'color' => !empty($cat_color) ? '#'.$cat_color.'' : $primary_color
        ];
        kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
      }

      if( kanews_get_option('follow-categories') || kanews_get_option('follow-authors') )
      $users = get_users( array(
        'fields' => array( 'ID', 'user_email' )
      ) );

      // Email to subscribers
      if( kanews_get_option('follow-categories') && $categories = get_the_category() ) {
        $emails = array();
        foreach($users as $user) {
          if( $this->user_allows_mail($user->ID) ) {
            $user_cats = $this->get_cached_user_option_array( $user->ID, 'kanews_subscribe_category' );
            
            if( ! empty($user_cats) ) {
              foreach($categories as $category) {
                if(in_array($category->term_id, $user_cats) && $user->ID != $post->post_author) {
                  $this->message( $user->ID, array(
                    'pid'  => $post->ID,
                    'follow'  => true,
                    'date' => current_time( 'timestamp', 1 )
                  ), true );
                  $emails[] = $user->user_email;
                  break;
                }
              }
            }
          }
        }

        if( ! empty($emails) ) {
          $site_name = get_bloginfo( 'name' );
          $my_content = apply_filters('the_content', $post->post_content);
          $cat_color = get_term_meta( Helper_Wp::primary_category_id($post->ID), '_category_color', true );
          $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
          $email_args = [
            'title' => esc_html__( 'Yeni Bir Bildiriminiz Var!', 'kanews' ),
            'subtitle' => esc_html__( 'Takip ettiğiniz kategoride yeni bir yazı yayınlandı.', 'kanews' ),
            'body_title' => $post->post_title,
            'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
            'button_link' => get_the_permalink($post->ID),
            'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
            'color' => !empty($cat_color) ? '#'.$cat_color.'' : $primary_color
          ];
          kanews_send_mail($emails, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
        }
        
      }

      // Email to followers
      if( kanews_get_option('follow-authors') ) {
        $emails = array();
        foreach($users as $user) {
          if( $this->user_allows_mail($user->ID) ) {
            $user_cats = $this->get_cached_user_option_array( $user->ID, 'kanews_subscribe_authors' );
            
            if( ! empty($user_cats) ) {
              foreach($categories as $category) {
                if(in_array($post->post_author, $user_cats) && $user->ID != $post->post_author) {
                  $this->message( $user->ID, array(
                    'pid'  => $post->ID,
                    'follow2' => true,
                    'date' => current_time( 'timestamp', 1 )
                  ), true );
                  $emails[] = $user->user_email;
                  break;
                }
              }
            }
          }
        }

        if( ! empty($emails) ) {
          $site_name = get_bloginfo( 'name' );
          $my_content = apply_filters('the_content', $post->post_content);
          $cat_color = get_term_meta( Helper_Wp::primary_category_id($post->ID), '_category_color', true );
          $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
          $email_args = [
            'title' => esc_html__( 'Yeni Bir Bildiriminiz Var!', 'kanews' ),
            'subtitle' => esc_html__( 'Takip ettiğiniz yazarın yeni bir yazısı yayınlandı.', 'kanews' ),
            'body_title' => $post->post_title,
            'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
            'button_link' => get_the_permalink($post->ID),
            'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
            'color' => !empty($cat_color) ? '#'.$cat_color.'' : $primary_color
          ];
          kanews_send_mail($emails, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
        }
        
      }

      update_post_meta($post->ID, '_kan_notifications_submited', 1);
    }
    
  }

  // Approved Comment
  function approved_comment($new_status, $old_status, $comment) {


    if ( ( $new_status == 'approved' ) && ( $old_status != 'approved' ) && ! get_comment_meta($comment->comment_ID, '_kan_notifications_submited', true) ) {
      $user_id = $comment->user_id;
      $post_id = $comment->comment_post_ID;
      $post_author_id = get_post_field( 'post_author', $post_id );
      
      if( $post_author_id != $user_id  ) {
        date_default_timezone_set('Europe/Istanbul');
        if($comment->comment_parent == 0) {
          $this->message( $post_author_id, array(
            'pid'     => $post_id,
            'cid'     => $comment->comment_ID,
            'date'    => current_time( 'timestamp', 1 )
          ), false );
          // Submit email
          if( $this->user_should_receive_email($post_author_id) ) {
            $email = array();
            $email[] = get_the_author_meta('email', $post_author_id );
            $site_name = get_bloginfo( 'name' );
            $my_content = apply_filters('the_content', $comment->comment_content);
            $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
            $email_args = [
              'title' => esc_html__( 'Yazınıza Yeni Bir Yorum Yapıldı!', 'kanews' ),
              'subtitle' => esc_html__( 'Sitemizde yayında olan yazınıza yeni bir yorum yapıldı.', 'kanews' ),
              'body_title' => get_the_title($post_id),
              'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
              'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
              'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
              'color' => $primary_color
            ];
            kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
          }
        } else {
          // post author
          $this->message( $post_author_id, array(
            'pid'     => $post_id,
            'cid'     => $comment->comment_ID,
            'date'    => current_time( 'timestamp', 1 )
          ), false );
          // Submit email
          if( $this->user_should_receive_email($post_author_id) ) {
            $email = array();
            $email[] = get_the_author_meta('email', $post_author_id );
            $site_name = get_bloginfo( 'name' );
            $my_content = apply_filters('the_content', $comment->comment_content);
            $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
            $email_args = [
              'title' => esc_html__( 'Yazınıza Yeni Bir Yorum Yapıldı!', 'kanews' ),
              'subtitle' => esc_html__( 'Sitemizde yayında olan yazınıza yeni bir yorum yapıldı.', 'kanews' ),
              'body_title' => get_the_title($post_id),
              'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
              'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
              'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
              'color' => $primary_color
            ];
            kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
          }
          // parent comment author
          $comment_parent = get_comment($comment->comment_parent);
          $comment_parent_user_id = $comment_parent->user_id;
          $this->message( $comment_parent_user_id, array(
            'pid2'     => $post_id,
            'cid2'     => $comment->comment_ID,
            'date'    => current_time( 'timestamp', 1 )
          ), false );
          // Submit email
          if( $this->user_should_receive_email($comment_parent_user_id) ) {
            $email = array();
            $email[] = get_the_author_meta('email', $comment_parent_user_id );
            $site_name = get_bloginfo( 'name' );
            $my_content = apply_filters('the_content', $comment->comment_content);
            $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
            $email_args = [
              'title' => esc_html__( 'Yorumunuz Cevaplandı!', 'kanews' ),
              'subtitle' => esc_html__( 'Yaptığınız yorum cevaplandı.', 'kanews' ),
              'body_title' => get_the_title($post_id),
              'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
              'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
              'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
              'color' => $primary_color
            ];
            kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
          }
        }
        update_comment_meta($comment->comment_ID, '_kan_notifications_submited', 1);
      }
    }
  }

  // Approved Comment
  function post_commented($comment_id, $comment_approved ) {

    $comment = get_comment($comment_id);
    $user_id = $comment->user_id;
    $post_id = $comment->comment_post_ID;
    $post_author_id = get_post_field( 'post_author', $post_id );
    
    if(1 === $comment_approved ) {
      date_default_timezone_set('Europe/Istanbul');
      if($comment->comment_parent == 0) {
        if($post_author_id != $user_id) {
          $this->message( $post_author_id, array(
            'pid'     => $post_id,
            'cid'     => $comment_id,
            'date'    => current_time( 'timestamp', 1 )
          ), false );
          // Submit email
          if( $this->user_should_receive_email($post_author_id) ) {
            $email = array();
            $email[] = get_the_author_meta('email', $post_author_id );
            $site_name = get_bloginfo( 'name' );
            $my_content = apply_filters('the_content', $comment->comment_content);
            $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
            $email_args = [
              'title' => esc_html__( 'Yazınıza Yeni Bir Yorum Yapıldı!', 'kanews' ),
              'subtitle' => esc_html__( 'Sitemizde yayında olan yazınıza yeni bir yorum yapıldı.', 'kanews' ),
              'body_title' => get_the_title($post_id),
              'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
              'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
              'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
              'color' => $primary_color
            ];
            kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
          }
        }
      } else {
        if($post_author_id != $user_id) {
          // post author
          $this->message( $post_author_id, array(
            'pid'     => $post_id,
            'cid'     => $comment_id,
            'date'    => current_time( 'timestamp', 1 )
          ), false );
          // Submit email
          if( $this->user_should_receive_email($post_author_id) ) {
            $email = array();
            $email[] = get_the_author_meta('email', $post_author_id );
            $site_name = get_bloginfo( 'name' );
            $my_content = apply_filters('the_content', $comment->comment_content);
            $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
            $email_args = [
              'title' => esc_html__( 'Yazınıza Yeni Bir Yorum Yapıldı!', 'kanews' ),
              'subtitle' => esc_html__( 'Sitemizde yayında olan yazınıza yeni bir yorum yapıldı.', 'kanews' ),
              'body_title' => get_the_title($post_id),
              'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
              'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
              'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
              'color' => $primary_color
            ];
            kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
          }
        }
        // parent comment author
        $comment_parent = get_comment($comment->comment_parent);
        $comment_parent_user_id = $comment_parent->user_id;
        $this->message( $comment_parent_user_id, array(
          'pid2'     => $post_id,
          'cid2'     => $comment_id,
          'date'    => current_time( 'timestamp', 1 )
        ), false );
        // Submit email
        if( $this->user_should_receive_email($comment_parent_user_id) ) {
          $email = array();
          $email[] = get_the_author_meta('email', $comment_parent_user_id );
          $site_name = get_bloginfo( 'name' );
          $my_content = apply_filters('the_content', $comment->comment_content);
          $primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';
          $email_args = [
            'title' => esc_html__( 'Yorumunuz Cevaplandı!', 'kanews' ),
            'subtitle' => esc_html__( 'Yaptığınız yorum cevaplandı.', 'kanews' ),
            'body_title' => get_the_title($post_id),
            'body_excerpt' =>  wp_trim_words( wp_strip_all_tags($my_content), 55, NULL ),
            'button_link' => get_the_permalink($post_id).'#comment-'.$comment->comment_ID,
            'copyright' => sprintf(esc_html__( 'Copyright © %s %s Tüm Hakları Saklıdır', 'kanews' ), $site_name, date('Y')),
            'color' => $primary_color
          ];
          kanews_send_mail($email, sprintf(esc_html__( '%s için okunmamış bildirimleriniz var!', 'kanews' ), $site_name), $email_args);
        }
      }
    }
  }

  // User Notifications
  public static function get_user_notifications($device) {

    if( !kanews_get_option('notifications') )
    return;

    if($device != 'account' && $device != 'tab') {
      if( kan_is_mobile() )
      return;
    }
      
    $user_id  = get_current_user_id();
    
    $msgs = get_user_meta($user_id, 'kan_user_notifications', true) ? get_user_meta($user_id, 'kan_user_notifications', true) : array();
    $msgs2 = get_user_meta($user_id, 'kan_user_notifications2', true) ? get_user_meta($user_id, 'kan_user_notifications2', true) : array();
    date_default_timezone_set('Europe/Istanbul');
    
    if($fake_msgs = kanews_get_option('fake_notifications')  ) {
      foreach($fake_msgs as $fake_msg) {
        
        if( $fake_msg['title'] && $fake_msg['date'] && $fake_msg['link'] ) {
          if($fake_msg['show'] == 'members' && is_user_logged_in()) {
            $msgs[] = array(
              'fake'       => true,
              'fake_title' => $fake_msg['title'],
              'fake_link'  => $fake_msg['link'],
              'fake_img'   => $fake_msg['image'],
              'date'       => strtotime($fake_msg['date'])
            );
          }elseif($fake_msg['show'] == 'visitors' && !is_user_logged_in()) {
            $msgs[] = array(
              'fake'       => true,
              'fake_title' => $fake_msg['title'],
              'fake_link'  => $fake_msg['link'],
              'fake_img'   => $fake_msg['image'],
              'date'       => strtotime($fake_msg['date'])
            );
          }elseif($fake_msg['show'] == 'all') {
            $msgs[] = array(
              'fake'       => true,
              'fake_title' => $fake_msg['title'],
              'fake_link'  => $fake_msg['link'],
              'fake_img'   => $fake_msg['image'],
              'date'       => strtotime($fake_msg['date'])
            );
          }
        }
      }
    }
    
    $counter = 0;
    $counter2 = 0;
    $allc = 0;
    $allc2 = 0;
    $not = '';
    $not2 = '';

    if( kanews_get_option('kanews-insights') && ! kanews_insights_control($user_id) && !current_user_can('administrator') ) {
      $allc++;
      $class = 'new-item';
      $page = kanews_insights_page_url();
      $not .= '<li class="'.$class.'"><a href="'.$page.'"></a>';
        $not .= '<div class="notification-left"></div>';
        if( is_user_logged_in() )
        $not .= '<div class="notification-right">'.sprintf(esc_html__('Aktif bir aboneliğiniz bulunmuyor. Abonelik başlatmak için tıklayın.', 'kanews')).'</div>';
        else
        $not .= '<div class="notification-right">'.sprintf(esc_html__('Reklam görmemek için, özel sayfa ve yazılara erişim için hemen bir abonelik başlat.', 'kanews')).'</div>';
      $not .= '</li>';
    }
    
    // Notifications
    if(!empty($msgs) && isset($msgs) && is_array($msgs)) {
      
      if(!isset($msg['date']))
      $msg['date'] = 51412412;
    
      if( ! $user_date = get_user_meta($user_id, 'kanews_user_date', true))
      $user_date = 970219617;
    
      if( !kanews_user_status($user_id) ) {
        $allc++;
        $class = 'new-item';
        $counter++;
        $settings_url = kanews_get_option('account-page');
        if ($settings_url != '') {
          $page = get_page_link($settings_url);
        } else {
          $page = get_edit_user_link();
        }
        $not .= '<li class="'.$class.'"><a href="'.$page.'"></a>';
          $not .= '<div class="notification-left"></div>';
          $not .= '<div class="notification-right">'.esc_html__('Üyeliğinizin aktifleştirilmesi için e-posta adresinizi doğrulayın!', 'kanews').'</div>';
        $not .= '</li>';
      } else {

        foreach(array_reverse($msgs) as $msg) {
          if( ( isset($msg['pid']) && !empty($msg['pid']) ) && isset($msg['cid']) && !empty($msg['cid']) ) {
            $comment = get_comment($msg['cid']);
            if($comment->comment_approved == 1) {
              $allc++;
              $class = get_user_meta($user_id, 'kanews_user_date', true) && ($msg['date'] > $user_date) ? 'new-item' : null; 
              if($class == 'new-item')
              $counter++;
              $a       = $comment->comment_author_url ? '<a href="'.$comment->comment_author_url.'">'.$comment->comment_author.'</a>' : '<strong>'.$comment->comment_author.'</strong>';
              $not .= '<li class="'.$class.'"><a href="'.get_the_permalink($comment->comment_post_ID).'#comment-'.$msg['cid'].'"></a>';
                $not .= '<div class="notification-left">'.kanews_user_avatar($comment->user_id, 50).'</div>';
                $not .= '<div class="notification-right">'.sprintf(__('%1$s adlı kullanıcı %2$s adlı yazınıza yorum yaptı. %3$s', 'kanews'), $a, '<a href="'.get_the_permalink($comment->comment_post_ID).'">'.get_the_title($msg['pid']).'</a>', '<span>'.date('d.m.Y H:i:s', $msg['date']).'</span>' ).'</div>';
              $not .= '</li>';
            }
          }elseif( ( isset($msg['pid2']) && !empty($msg['pid2']) ) && isset($msg['cid2']) && !empty($msg['cid2']) ) {
            $comment = get_comment($msg['cid2']);
            if($comment->comment_approved == 1) {
              $allc++;
              $class = $user_date && ($msg['date'] > $user_date) ? 'new-item' : null; 
              if($class == 'new-item')
              $counter++;
              $a       = $comment->comment_author_url ? '<a href="'.$comment->comment_author_url.'">'.$comment->comment_author.'</a>' : '<strong>'.$comment->comment_author.'</strong>';
              $not .= '<li class="'.$class.'"><a href="'.get_the_permalink($comment->comment_post_ID).'#comment-'.$msg['cid2'].'"></a>';
                $not .= '<div class="notification-left">'.kanews_user_avatar($comment->user_id, 50).'</div>';
                $not .= '<div class="notification-right">'.sprintf(__('%1$s adlı kullanıcı %2$s adlı yazıdaki yorumunuzu cevapladı. %3$s', 'kanews'), $a, '<a href="'.get_the_permalink($comment->comment_post_ID).'">'.get_the_title($comment->comment_post_ID).'</a>', '<span>'.date('d.m.Y H:i:s', $msg['date']).'</span>' ).'</div>';
              $not .= '</li>';
            }
          } elseif( isset($msg['pid']) && !empty($msg['pid']) ) {
            $allc++;
            $class = $user_date && ($msg['date'] > $user_date) ? 'new-item' : null; 
            if($class == 'new-item')
            $counter++;
            $not .= '<li class="'.$class.'"><a href="'.get_the_permalink($msg['pid']).'"></a>';
              $not .= '<div class="notification-left">'.get_the_post_thumbnail( $msg['pid'], 'thumbnail', array( 'class' => 'alignleft' ) ).'</div>';
              $not .= '<div class="notification-right">'.sprintf(__('%1$s adlı yazınız yayınlanmıştır. %2$s', 'kanews'), '<a href="'.get_the_permalink($msg['pid']).'">'.get_the_title($msg['pid']).'</a>', '<span>'.date('d.m.Y H:i:s', $msg['date']).'</span>' ).'</div>';
            $not .= '</li>';
          } elseif( isset($msg['fake']) ) {
            $allc++;
            $class = $user_date && ($msg['date'] > $user_date) ? 'new-item' : null; 
            if($class == 'new-item')
            $counter++;
            $not .= '<li class="'.$class.'"><a aria-label="'.esc_attr($msg['fake_title']).'" href="'.esc_url($msg['fake_link']).'"></a>';
              if($msg['fake_img'] != '') {
                if(kanews_lazyload_active())
                $not .= '<div class="notification-left"><img width="34" height="34" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" data-src="'.esc_url($msg['fake_img']).'" class="kanews-lazy" /></div>';
                else
                $not .= '<div class="notification-left"><img width="34" height="34" src="'.esc_url($msg['fake_img']).'"  /></div>';
              } else {
                $not .= '<div class="notification-left"></div>';
              }
              $not .= '<div class="notification-right">'.$msg['fake_title'].'<span>'.date('d.m.Y H:i:s', $msg['date']).'</span></div>';
            $not .= '</li>';
          }elseif( isset($msg['points']) ) {
            $allc++;
            $class = $user_date && ($msg['date'] > $user_date) ? 'new-item' : null; 
            if($class == 'new-item')
            $counter++;
            switch($msg['points']) {
              case 'cover':
              $notf_t11sa = sprintf(esc_html__('Profil arkaplanı eklediğiniz için +%s puan kazandınız.', 'kanews'), kanews_get_option('cover_score', 15));
              break;
              case 'avatar':
              $notf_t11sa = sprintf(esc_html__('Avatar eklediğiniz için +%s puan kazandınız.', 'kanews'), kanews_get_option('avatar_score', 15));
              break;
              case 'post':
              $notf_t11sa = sprintf(esc_html__('Yazı paylaştığınız için +%s puan kazandınız.', 'kanews'), kanews_get_option('entry_score', 50));
              break;
              case 'comment':
              $notf_t11sa = sprintf(esc_html__('Yorum yaptığınız için +%s puan kazandınız.', 'kanews'), kanews_get_option('comment_score', 25));
              case 'social':
              $notf_t11sa = sprintf(esc_html__('Sosyal medya hesabınızı eklediğiniz için +%s puan kazandınız.', 'kanews'), kanews_get_option('social_score', 5));
              break;
              default:
              $notf_t11sa = sprintf(esc_html__( '+%s puan kazandınız.', 'kanews'), esc_html__('Bilinmiyor', 'kanews'));
            }
            $not .= '<li class="'.$class.'"><a aria-label="'.$notf_t11sa.'" href="#"></a>';
              $not .= '<div class="notification-left">'.kanews_user_avatar(get_the_author_meta('ID', $user_id),'90').'</div>';
              $not .= '<div class="notification-right">'.$notf_t11sa.'<span>'.date('d.m.Y H:i:s', $msg['date']).'</span></div>';
            $not .= '</li>';
          }
        }
      }
      
      if($allc < 1) {
        $not = '<li>'.esc_html__('Bildiriminiz bulunmamaktadır.', 'kanews').'</li>';
      }
    
    } else {
      if( !kanews_user_status($user_id) ) {
        $allc++;
        $class = 'new-item';
        $counter++;
        $settings_url = kanews_get_option('account-page');
        if ($settings_url != '') {
          $page = get_page_link($settings_url);
        } else {
          $page = get_edit_user_link();
        }
        $not .= '<li class="'.$class.'"><a href="'.$page.'"></a>';
          $not .= '<div class="notification-left"></div>';
          $not .= '<div class="notification-right">'.esc_html__('Üyeliğinizin aktifleştirilmesi için e-posta adresinizi doğrulayın!', 'kanews').'</div>';
        $not .= '</li>';
      } else {
        if($allc < 1) {
          $not = '<li>'.esc_html__('Bildiriminiz bulunmamaktadır.', 'kanews').'</li>';
        }
      }
    }

    if(!empty($msgs2) && isset($msgs2) && is_array($msgs2)) {
      
      if(!isset($msg['date']))
      $msg['date'] = 51412412;
    
      if( ! $user_date = get_user_meta($user_id, 'kanews_user_date', true))
      $user_date = 970219617;
    
      foreach(array_reverse($msgs2) as $msg) {
        if( isset($msg['follow']) && isset($msg['pid']) && !empty($msg['pid']) ) {
          $allc2++;
          $class = ($user_date && ($msg['date'] > $user_date)) ? 'new-item' : null; 
          if($class == 'new-item') 
          $counter2++;
          $not2 .= '<li class="'.$class.'"><a href="'.get_the_permalink($msg['pid']).'"></a>';
            $not2 .= '<div class="notification-left">'.get_the_post_thumbnail( $msg['pid'], 'thumbnail', array( 'class' => 'alignleft' ) ).'</div>';
            $not2 .= '<div class="notification-right"><div class="d-flex flex-wrap">'.sprintf(__('Takip ettiğiniz bir kategoride&nbsp; %1$s &nbsp;adlı yazı yayınlanmıştır.', 'kanews'), '<a class="truncate truncate-2" href="'.get_the_permalink($msg['pid']).'">'.get_the_title($msg['pid']).'</a>' ).'</div><span>'.date('d.m.Y H:i:s', $msg['date']).'</span></div>';
          $not2 .= '</li>';
        }elseif( isset($msg['follow2']) && isset($msg['pid']) && !empty($msg['pid']) ) {
          $allc2++;
          $class = ($user_date && ($msg['date'] > $user_date)) ? 'new-item' : null; 
          if($class == 'new-item')
          $counter2++;
          $not2 .= '<li data-1="'.$user_date.'" data-2="'.$msg['date'].'" class="'.$class.'"><a href="'.get_the_permalink($msg['pid']).'"></a>';
            $not2 .= '<div class="notification-left">'.get_the_post_thumbnail( $msg['pid'], 'thumbnail', array( 'class' => 'alignleft' ) ).'</div>';
            $not2 .= '<div class="notification-right"><div class="d-flex flex-wrap">'.sprintf(__('Takip ettiğiniz bir yazarın&nbsp; %1$s &nbsp;adlı yazısı yayınlanmıştır.', 'kanews'), '<a class="truncate truncate-2" href="'.get_the_permalink($msg['pid']).'">'.get_the_title($msg['pid']).'</a>' ).'</div><span>'.date('d.m.Y H:i:s', $msg['date']).'</span></div>';
          $not2 .= '</li>';
        } 
      }

      if($allc2 < 1) {
        $not2 = '<li>'.esc_html__('Bildiriminiz bulunmamaktadır.', 'kanews').'</li>';
      }

    } else {
      if($allc2 < 1) {
        $not2 = '<li>'.esc_html__('Bildiriminiz bulunmamaktadır.', 'kanews').'</li>';
      }
    }

    
    
    // Content
    if( is_user_logged_in() )
    $clear_notification = '<a id="clearNotifications" href="doSomething()">'.esc_html__('Bildirimleri Temizle', 'kanews').'</a>';
    else
    $clear_notification = '';
    if($device == 'account') {
      $out = '<div class="row"><div class="kanews-notifications-item"><h3 class="kanews-custom-page-title mb-1">'.esc_html__('Genel Bildirimler', 'kanews').'</h3><ul class="kanews-notifications-content">'.$not.'</ul><h3 class="kanews-custom-page-title mb-1">'.esc_html__('Takip Ettiklerimden', 'kanews').'</h3><ul class="kanews-notifications-content">'.$not2.'</ul></div></div>';
    } elseif($device == 'tab') {
      $out = $counter;
    } else {
      $counterall = $counter + $counter2;
      $tooltip = $counterall > 0 ? 'role="tooltip" data-microtip-visible data-microtip-position="bottom" aria-label="'.esc_html__('Okunmamış bildirimleriniz var', 'kanews').'"' : 'aria-label="'.sprintf( esc_html__( 'Bildirimler (%s).', 'kanews' ), $counter).'"';
      $out = '<div class="kanews-notifications-item" data-user-id="'.get_current_user_id().'" data-new-count="" data-toggle="kanews-notifications"><button  '.$tooltip.'  class="kanews-notification-button header-btn-icon"><i class="icon-notifications"></i><span class="kanews-notifications-count">'.$counter.'</span></button>';
      $out .= '<div id="kanews-notifications" class="kanews-notifications-content">';
      $out .= '<div class="kanews-notifications-header d-flex justify-content-between">'.__('Bildirimler', 'kanews').'<span class="pull-right">'.$clear_notification.'</span></div>';
      $out .= '<div class="kanews_widget_tab_menu">
      <div class="kanews-tab">
        <ul class="nav nav-tabs d-flex flex-wrap p-0 mb-0" role="tablist" id="kanewsTab-Not">
          <li role="presentation" class="nav-item"><div class="nav-link active" id="kanewsTab-Not1x" data-toggle="tab" href="#kanewsTab-Not1" role="tab" data-controls="kanewsTab-Not1" data-selected="true">'.esc_html__('Sosyal', 'kanews').' ('.$counter.')</div></li>
          <li role="presentation" class="nav-item"><div class="nav-link" id="kanewsTab-Not2x" data-toggle="tab" href="#kanewsTab-Not2" role="tab" data-controls="kanewsTab-Not2" data-selected="false">'.esc_html__('Takip', 'kanews').' ('.$counter2.')</div></li>
          </ul>';
      $out .= '<div class="tab-content" id="kanewsTab-NotContent-1">';
      $out .= '<div class="tab-pane fade show active" id="kanewsTab-Not1" role="tabpanel" data-labelledby="kanewsTab-Not1x">';
      $out .= '<ul>'.$not.'</ul>';
      $out .= '</div>';
      $out .= '<div class="tab-pane fade" id="kanewsTab-Not2" role="tabpanel" data-labelledby="kanewsTab-Not2x">';
      $out .= '<ul>'.$not2.'</ul>';
      $out .= '</div>';
      $out .= '</div>';
      $out .= '</div>';
      $out .= '</div>';
      $out .= '</div>';
      $out .= '</div>';
    }
    
    return $out;
    
  }

  // Update Notifications
  function update_user_notifications() {
    
    $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : 0;
    if ( !wp_verify_nonce( $nonce, 'kanews-ajax-nonce' ) ) {
      exit( __( 'İzin verilmedi!', 'kanews' ) );
    }
    
    if( ! is_user_logged_in() ){
      wp_send_json_error();
      exit();
    }
    
    $user_id = get_current_user_id();
    update_user_meta( $user_id, 'kanews_user_date', time() );
    wp_send_json( esc_html__('Bildirimleriniz temizlenmiştir.', 'kanews') );
    exit();
  }

  // Clear Notifications
  function clear_user_notifications() {
    

    $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : 0;
    if ( !wp_verify_nonce( $nonce, 'kanews-ajax-nonce' ) ) {
      exit( __( 'İzin verilmedi!', 'kanews' ) );
    }
    
    if( ! is_user_logged_in() ){
      wp_send_json_error();
      exit();
    }
    
    $user_id = get_current_user_id();
    $meta    = get_user_meta( $user_id, 'kan_user_notifications', true );
    $meta2   = get_user_meta( $user_id, 'kan_user_notifications2', true );
    
    if( empty($meta) && empty($meta2) ) {
      wp_send_json(esc_html__('Zaten bildiriminiz bulunmamaktadır.', 'kanews'));
      exit();
    }
    
    update_user_meta( $user_id, 'kan_user_notifications', array() );
    update_user_meta( $user_id, 'kan_user_notifications2', array() );
    wp_send_json( esc_html__('Bildirimleriniz temizlenmiştir.', 'kanews') );
    exit();
  }

}

// wp_die(get_user_meta(1, 'last_post_publish_date', true));