<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Class DateBook_Session_Handler
 *
 * @class DateBook_Session_Handler
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Session_Handler {

    /**
     * the name of the DB table which handles the sessions
     * @var string
     */
	private $table_name;
	private $table_private_messages;
	private $current_user_id;
	private $chatter_id;
	private $chatter_active;

    public function __construct($current_user_id, $chatter_id, $security_code, $chatter_activated = 0, $lock_to_ip = true, $lock_to_user_agent = true) {

		global $wpdb;

		$this->wpdb = $wpdb;

		// the table to be used by the class
		$this->table_name = strtolower($wpdb->prefix) . 'datebook_sessions';
		
		$this->table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

		$this->current_user_id = $current_user_id;

		$this->current_user_md5_id = md5($current_user_id.$security_code);

		$this->chatter_id = $chatter_id;
		
		$this->chatter_active = $chatter_activated;

		$ip = Class_DateBook_IP::get_ip_address();
		$browser = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
		$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
		if (isset($referred) && $referred == '') {
			$referrer = 'This page was accessed directly';
		}

		$this->data = maybe_serialize(array('ip' => $ip, 'browser' => $browser, 'referrer' => $referrer));

		$this->hasher = md5(($lock_to_user_agent && isset($browser) ? $browser : '') . ($lock_to_ip && isset($ip) ? $ip : '') . $security_code);

		$this->write();

    }


	/**
	 * Read chatters data.
	 *
	 * @param sting $id Session id.
	 * @return mixed Session data or null.
	 */
	public function read_chatters() {
		if ( ! $this->wpdb )
			return null;

		$get_chatters = $this->wpdb->get_var( $this->wpdb->prepare( "SELECT `chatters` FROM `{$this->table_name}` WHERE `id` = %s AND `hash` = %s;", $this->current_user_md5_id, $this->hasher ) );

		return $get_chatters;
	}


	/**
	 * Count active chatters
	 *
	 * @param sting $id Session id.
	 * @return mixed Session data or null.
	 */
	public function simultaneous_chatters() {

		$quantity_simultaneous_chatters = 0;
		
		$simultaneous_chatters_array = array();

		// Get Subscription plans
		$get_subscription_plans = get_option('datebook_subscription_plans');

		if (is_array($get_subscription_plans)){

			// Get user subscription data
			$member = datebook_get_member($this->current_user_id);

			$datebook_get_subscriptionplan = isset($member->subscriptions) && is_array($member->subscriptions) && !empty($member->subscriptions) && isset($member->subscriptions[0]['subscription_plan_id']) && strlen($member->subscriptions[0]['subscription_plan_id']) > 1 ? $member->subscriptions[0]['subscription_plan_id'] : '';

			$simultaneous_chatters_array['enable_simultaneous_chatters'] = isset($get_subscription_plans[$datebook_get_subscriptionplan]['simultaneous_chatters']) && $get_subscription_plans[$datebook_get_subscriptionplan]['simultaneous_chatters'] == 1 ? 1 : 0;
			
			$quantity_simultaneous_chatters = isset($get_subscription_plans[$datebook_get_subscriptionplan]['quantity_simultaneous_chatters']) && $get_subscription_plans[$datebook_get_subscriptionplan]['quantity_simultaneous_chatters'] > 0 ? $get_subscription_plans[$datebook_get_subscriptionplan]['quantity_simultaneous_chatters'] : 10000;
			
			$simultaneous_chatters_array['period_number_simultaneous_chatters'] = isset($get_subscription_plans[$datebook_get_subscriptionplan]['period_number_simultaneous_chatters']) ? $get_subscription_plans[$datebook_get_subscriptionplan]['period_number_simultaneous_chatters'] : 0;
			$simultaneous_chatters_array['period_simultaneous_chatters'] = isset($get_subscription_plans[$datebook_get_subscriptionplan]['period_simultaneous_chatters']) ? $get_subscription_plans[$datebook_get_subscriptionplan]['period_simultaneous_chatters'] : 0;
			
			$simultaneous_chatters_array['suggest_simultaneous_chatters'] = isset($get_subscription_plans[$datebook_get_subscriptionplan]['suggest_simultaneous_chatters']) ? $get_subscription_plans[$datebook_get_subscriptionplan]['suggest_simultaneous_chatters'] : 0;

		}

		if(isset($quantity_simultaneous_chatters) && $quantity_simultaneous_chatters > 0){

			$simultaneous_chatters_array['simultaneous_chatters'] = $quantity_simultaneous_chatters;

		} else {

			$simultaneous_chatters_array['simultaneous_chatters'] = of_get_option('simultaneous_chatters') > 0 ? of_get_option('simultaneous_chatters') : 10000;

		}

		return $simultaneous_chatters_array;

	}


	/**
	 * Write a session.
	 *
	 * @param string $id Session id.
	 * @param string $data Session data (serialized for session storage).
	 */
	public function write() {
		if ( ! $this->wpdb ){
			return null;
		}

		global $time_in_seconds_array;

		$period_for_chatters = 0;

		// Get Subscription plans
		$get_subscription_plans = get_option('datebook_subscription_plans');

		if (is_array($get_subscription_plans)){

			// Get profile data and check if it has subscription plan
			$profile_id = get_user_meta($this->current_user_id, 'profile_postid', true);

			// Get profile data and check if it has subscription plan
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			$datebook_get_subscriptionplan = isset($datebook_get_data['profile_subscription']['plan']) && strlen($datebook_get_data['profile_subscription']['plan']) > 1 ? $datebook_get_data['profile_subscription']['plan'] : '';

			$period_number_simultaneous_chatters = isset($get_subscription_plans[$datebook_get_subscriptionplan]['period_number_simultaneous_chatters']) ? $get_subscription_plans[$datebook_get_subscriptionplan]['period_number_simultaneous_chatters'] : 0;
			$period_simultaneous_chatters = isset($get_subscription_plans[$datebook_get_subscriptionplan]['period_simultaneous_chatters']) ? $get_subscription_plans[$datebook_get_subscriptionplan]['period_simultaneous_chatters'] : 0;

			$period_for_chatters = time() + ($period_number_simultaneous_chatters * $time_in_seconds_array[$period_simultaneous_chatters]);

		}

		if($period_for_chatters > 0){

			$period_for_chatters = $period_for_chatters;

		} else {

			$period_for_chatters = of_get_option('period_for_chatters') > 0 ? of_get_option('period_for_chatters') : 0;
			$period_for_chatters = time() + 60 * 60 * $period_for_chatters;

		}

		$chatters_array = array();
		$count_chatters = $count_new_chatters = $chatter_new = 0;
		$enable_simultaneous_chatters = 1;
		$get_chatters = self::read_chatters($this->current_user_md5_id);

		if($get_chatters != ''){

			$chatters_array_unserial = maybe_unserialize($get_chatters);

			foreach($chatters_array_unserial as $key => $value){

				$count_chatters++;

				$chatters_array[$key] = $value;

				if(isset($value['active']) && $value['active'] == 1 && isset($value['chatter_new']) && $value['chatter_new'] == 1 && isset($value['start_time']) && $value['start_time'] > time()){
					$count_new_chatters++;
				}
			}
		}

		// Get limit of chatter from Subscription
		if (DateBook_Utilities::check_if_gateway_activated()) {
			$simultaneous_chatters = self::simultaneous_chatters();
			$enable_simultaneous_chatters = isset($simultaneous_chatters['enable_simultaneous_chatters']) && $simultaneous_chatters['enable_simultaneous_chatters'] == 1 ? 1 : 0;
			$simultaneous_chatters_count = isset($simultaneous_chatters['simultaneous_chatters']) && $simultaneous_chatters['simultaneous_chatters'] > 0 ? $simultaneous_chatters['simultaneous_chatters'] : 0;
		} else {
			$simultaneous_chatters_count = of_get_option('simultaneous_chatters') > 0 ? of_get_option('simultaneous_chatters') : 1000000;
		}

		if (!array_key_exists($this->chatter_id, $chatters_array) || $this->chatter_active == 1) {

			// Chatter was not added yet then add him to session
			if ($count_new_chatters >= $simultaneous_chatters_count) {

				$chatter_active = 0;
				$chatter_new = 0;
				$chatter_time = $period_for_chatters;

			} else {

				$get_already_active_chatter_array = $this->wpdb->get_results( $this->wpdb->prepare("SELECT * FROM `{$this->table_private_messages}` WHERE senderid = '%d' AND rcpid = '%d'", $this->current_user_id, $this->chatter_id));

				if($this->wpdb->num_rows > 0){

					$chatter_active = 1;

					if(isset($chatters_array_unserial[$this->chatter_id]['active']) && $chatters_array_unserial[$this->chatter_id]['active'] == 0 && isset($chatters_array_unserial[$this->chatter_id]['chatter_new']) && $chatters_array_unserial[$this->chatter_id]['chatter_new'] == 1){
						$chatter_new = $count_new_chatters >= $simultaneous_chatters_count ? 0 : 1;
					} else {
						$chatter_new = 0;
					}

					$chatter_time = isset($chatters_array_unserial[$this->chatter_id]['start_time']) ? $chatters_array_unserial[$this->chatter_id]['start_time'] : $period_for_chatters;

				} else {

					if($this->chatter_active == 0){
						$chatter_active = 0;
						$chatter_time = $period_for_chatters;
					} else if($this->chatter_active == 1){
						$chatter_active = 1;
						$chatter_time = isset($chatters_array_unserial[$this->chatter_id]['start_time']) ? $chatters_array_unserial[$this->chatter_id]['start_time'] : $period_for_chatters;
					}

					$chatter_new = $count_new_chatters >= $simultaneous_chatters_count ? 0 : 1;

				}

			}

			$chatters_array[$this->chatter_id] = array('active' => $chatter_active, 'chatter_new' => $chatter_new, 'start_time' => $chatter_time);

		} else if(isset($chatters_array_unserial[$this->chatter_id]['active']) && $chatters_array_unserial[$this->chatter_id]['active'] == 1 && isset($chatters_array_unserial[$this->chatter_id]['chatter_new']) && $chatters_array_unserial[$this->chatter_id]['chatter_new'] == 1 && isset($chatters_array_unserial[$this->chatter_id]['start_time']) && $chatters_array_unserial[$this->chatter_id]['start_time'] < time()){

			// Chatter was added yet but make he as not new

			$chatter_active = 1;
			$chatter_new = 0;
			$chatter_time = isset($chatters_array_unserial[$this->chatter_id]['start_time']) ? $chatters_array_unserial[$this->chatter_id]['start_time'] : $period_for_chatters;

			$chatters_array[$this->chatter_id] = array('active' => $chatter_active, 'chatter_new' => $chatter_new, 'start_time' => $chatter_time);

		} else if($count_new_chatters >= $simultaneous_chatters_count && isset($chatters_array_unserial[$this->chatter_id]['active']) && $chatters_array_unserial[$this->chatter_id]['active'] == 0){

			// Chatter was added but cannot write

			$chatter_active = 0;
			$chatter_new = 0;
			$chatter_time = $period_for_chatters;

			$chatters_array[$this->chatter_id] = array('active' => $chatter_active, 'chatter_new' => $chatter_new, 'start_time' => $chatter_time);

		}

		// active - 1; chatter_new - 0 = full active
		// active - 1; chatter_new - 1 = full active but counted as new for some period
		// active - 0; chatter_new - 1 = can write but did not write yet
		// active - 0; chatter_new - 0 = cannot write at all

		if($enable_simultaneous_chatters == 1 && isset($chatters_array) && is_array($chatters_array) && !empty($chatters_array)){

			$chatters_array_serial = maybe_serialize($chatters_array);

			return $this->wpdb->query( $this->wpdb->prepare( "REPLACE INTO `{$this->table_name}` VALUES ( %s, %s, %s, %s, %d );", $this->current_user_md5_id, $this->data, $chatters_array_serial, $this->hasher, time() ) );

		} else {

			return false;

		}
	}

}


/**
 * Class DateBook_Profile_Messages
 *
 * @class DateBook_Profile_Messages
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Profile_Messages {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		add_action( 'datebook_ajax_messages', array( __CLASS__, 'datebook_action_read' ) );
		add_action( 'datebook_profile_messages', array( __CLASS__, 'datebook_process_profile_messages' ) );
		add_action( 'datebook_new_msg_alert', array( __CLASS__, 'datebook_show_new_msg_alert' ), 10, 1 );

	}
	
	
	/**
	 * Show messages menu
	 * 
	 * @access private
	 */
	private static function datebook_message_action_menu($what_message_text, $allowed_contacts, $favorite_contacts, $blacklist_contacts) {
		
		include DateBook_Template_Loader::locate( 'profile/profile-messages-action-menu' );
	
	}


	/**
	 * Count Favorite Profiles
	 * 
	 * @access private
	 */
	private static function datebook_count_favorites($user_id) {

		$found_contacts = get_user_meta($user_id, 'favorites', true);

		if ($found_contacts != '') {
			$found_contacts = array_unique(explode(',', $found_contacts));
			$found_contacts = count($found_contacts);
		} else {
			$found_contacts = '0';
		}
	
		return $found_contacts;

	}


	/**
	 * Count Blacklisted Profiles
	 * 
	 * @access private
	 */
	private static function datebook_count_blacklist($user_id) {

		$found_contacts = get_user_meta($user_id, "blacklist", true);

		if ($found_contacts != '') {
			$found_contacts = array_unique(explode(',', $found_contacts));
			$found_contacts = count($found_contacts);
		} else {
			$found_contacts = '0';
		}
	
		return $found_contacts;
	
	}


	/**
	 * Cycle Contacts
	 * 
	 * @access private
	 */
	private static function datebook_cycle_contacts() {

		global $wpdb;

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

		$messages = $wpdb->get_results($wpdb->prepare("SELECT senderid, rcpid, fromsee, tosee, fromdelete, todelete FROM {$table_private_messages} WHERE senderid = '%d' OR rcpid = '%d' ORDER BY date DESC, status ASC", $current_user_id, $current_user_id));

		$data = array();

		if($messages) {

			foreach ($messages as $message) {

				if($message->senderid == $current_user_id && $message->fromdelete == 1) continue;
				if($message->rcpid == $current_user_id && $message->todelete == 1) continue;

				$data[] = $message->senderid;
				$data[] = $message->rcpid;

			}
		}

		$group_messages = array_count_values($data);

		return $group_messages;

	}


	/**
	 * Count Normal Contacts
	 * 
	 * @access private
	 */
	private static function datebook_count_normal_contacts() {

		global $wpdb;

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$i = 0;

		$messages = self::datebook_cycle_contacts();
		
		if($messages) {

			$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
			if ($blacklists) {
				$blacklists = array_unique(explode(',', $blacklists));
			} else {
				$blacklists = array();
			}

			foreach ($messages as $key => $message) {

				if ($key == $current_user_id) continue;

				$profile_postid = get_user_meta( $key, 'profile_postid', true );

				if (!empty($profile_postid) && $profile_postid > 0) {

					$post = get_post($profile_postid);

					if (isset($post->ID) && $post->ID > 0) {
				
					if (in_array($profile_postid, $blacklists)) continue;

					$i++;

					}
				}
			}
		}

		return $i;

	}


	/**
	 * Show Received Messages
	 * 
	 * @access private
	 */
	private static function datebook_action_received($options) {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$what_message_text = $options['what_message_text'];

		self::datebook_delete_message();

		$count_messages = 0;

		$count_normal_contacts = self::datebook_count_normal_contacts();
		$count_favorites = self::datebook_count_favorites($current_user_id);
		$count_blacklist = self::datebook_count_blacklist($current_user_id);

		self::datebook_message_action_menu($what_message_text, $count_normal_contacts, $count_favorites, $count_blacklist);

		$favorites_or_blacklist = self::datebook_cycle_contacts();

		if ($favorites_or_blacklist) {

			$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
			if ($blacklists) {
				$blacklists = array_unique(explode(',', $blacklists));
			} else {
				$blacklists = array();
			}

			foreach ($favorites_or_blacklist as $key => $message) {

				if ($key == $current_user_id) continue;

				$profile_postid = get_user_meta( $key, 'profile_postid', true );

				if (!empty($profile_postid) && $profile_postid > 0) {

					$post = get_post($profile_postid);

					if (isset($post->ID) && $post->ID > 0) {

						if (in_array($profile_postid, $blacklists)) continue;
				
						$count_messages += $message;

						self::datebook_design_messages($key, $message, $favorites_or_blacklist, $current_user_id, $options);
						
					}
				}
			}

			echo '<hr />';
			echo '<p>' . esc_html__( 'Total messages', 'datebook' ) . ': ' . absint($count_messages) . '</p>';

		}

		if ($count_messages <= 0) {

			echo '<hr />';
			echo esc_html__( 'No contacts yet', 'datebook' );

		}
		
	}


	/**
	 * Show Favorite Contacts
	 * 
	 * @access private
	 */
	private static function datebook_action_favorites($options) {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$what_message_text = $options['what_message_text'];

		self::datebook_delete_message();

		$count_messages = 0;

		$count_normal_contacts = self::datebook_count_normal_contacts();
		$count_favorites = self::datebook_count_favorites($current_user_id);
		$count_blacklist = self::datebook_count_blacklist($current_user_id);

		self::datebook_message_action_menu($what_message_text, $count_normal_contacts, $count_favorites, $count_blacklist);
		
		$favorites_or_blacklist = get_user_meta($current_user_id, 'favorites', true);

		if ($favorites_or_blacklist) {

			$favorites_or_blacklist = array_unique(explode(',', $favorites_or_blacklist));

			$group_messages = self::datebook_cycle_contacts();

			foreach ($favorites_or_blacklist as $favor) {

				$post = get_post($favor);

				if(isset($post->ID) && $post->ID > 0){

					$key = $post->post_author;

					if ($key == $current_user_id) continue;

					if (is_array($group_messages) && !empty($group_messages) && isset($group_messages[$key])) {
						$message = $group_messages[$key];
					} else {
						$message = 0;
					}

					$count_messages += $message;

					self::datebook_design_messages($key, $message, $favorites_or_blacklist, $current_user_id, $options);
				
				}
		
			}
			
			echo '<hr />';
			echo '<p>' . esc_html__( 'Total messages', 'datebook' ) . ': ' . esc_attr($count_messages) . '</p>';

		} else {

			echo '<hr />';
			echo esc_html__( 'No profiles here yet', 'datebook' );

		}
		
	}


	/**
	 * Show Blacklisted Contacts
	 * 
	 * @access private
	 */
	private static function datebook_action_blacklist($options) {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$i = 0;
		$count_messages = 0;

		$what_message_text = $options['what_message_text'];

		self::datebook_delete_message();

		$count_normal_contacts = self::datebook_count_normal_contacts();
		$count_favorites = self::datebook_count_favorites($current_user_id);
		$count_blacklist = self::datebook_count_blacklist($current_user_id);

		self::datebook_message_action_menu($what_message_text, $count_normal_contacts, $count_favorites, $count_blacklist);

		$favorites_or_blacklist = get_user_meta($current_user_id, 'blacklist', true);

		if ($favorites_or_blacklist) {

			$favorites_or_blacklist = array_unique(explode(',', $favorites_or_blacklist));

			$group_messages = self::datebook_cycle_contacts();

			foreach ($favorites_or_blacklist as $favor) {

				$post = get_post($favor);

				if (isset($post->ID) && $post->ID > 0) {

					$key = isset($post->post_author) ? $post->post_author : 0;

					if ($key == $current_user_id) continue;

					if (is_array($group_messages) && !empty($group_messages) && isset($group_messages[$key])) {
						$message = $group_messages[$key];
					} else {
						$message = 0;
					}

					$count_messages += $message;

					self::datebook_design_messages($key, $message, $favorites_or_blacklist, $current_user_id, $options);
					
				}
			}
			
			echo '<hr />';
			echo '<p>' . esc_html__( 'Total messages', 'datebook' ) . ': ' . esc_attr($count_messages) . '</p>';

		} else {

			echo '<hr />';
			echo esc_html__( 'No profiles here yet', 'datebook' );

		}

	}


	/**
	 * Design Messages
	 * 
	 * @access private
	 */
	private static function datebook_design_messages($key, $message, $favorites_or_blacklist, $current_user_id, $options) {

		global $wpdb;

		$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

		$open_profile_new_tab = $options['open_profile_new_tab'];
		$open_message_new_window = $options['open_message_new_window'];
		$my_favorites_page = $options['my_favorites_page'];
		$my_blacklist_page = $options['my_blacklist_page'];
		$show_name = $options['show_name'];
		$show_age = $options['show_age'];
		$show_gender = $options['show_gender'];
		$show_sexual_orientation = $options['show_sexual_orientation'];
		$show_city = $options['show_city'];
		$show_country = $options['show_country'];

		$countnew = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table_private_messages} WHERE senderid = '%d' AND rcpid = '%d' AND tosee = 0 AND todelete = 0 AND status = 0", $key, $current_user_id));

		if ($countnew > 0) {

			$status_new_message = 'display:block';
			$status_open_message = 'display:none';
			$status_message_class = 'success';

		} else {

			$status_new_message = 'display:none';
			$status_open_message = 'display:block';
			$status_message_class = 'light';

		}

		$profile_postid = get_user_meta( $key, 'profile_postid', true );

		if (!empty($profile_postid) && $profile_postid > 0) {

			$post = get_post($profile_postid);
			
			$post_id = isset($post->ID) && $post->ID > 0 ? $post->ID : 0;
			
			if ($post_id > 0) {

				$birthday = get_post_meta($post_id, 'birthday', true);
				$age = !empty($birthday) ? floor((time() - strtotime($birthday))/31556926) : '';

				$city_id = get_post_meta($post_id, 'city', true);

				if(isset($city_id)){

					$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );
					$city = isset($term_data->city) ? $term_data->city : '';
					$country = isset($term_data->country) ? $term_data->country : '';

				}

				$gender = get_post_meta($post_id, 'gender', true);

				if ($gender == 1) {
					$icogender = 'fa fa-venus';
				} else if ($gender == 2) {
					$icogender = 'fa fa-mars';
				} else {
					$icogender = 'fa fa-user';
				}

				include DateBook_Template_Loader::locate( 'profile/profile-messages' );

			}
		}
	}


	/**
	 * Delete Message
	 * 
	 * @access private
	 */
	private static function datebook_delete_message() {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		if( isset($_GET['action']) && $_GET['action'] == 'datebook_message_actions' && (is_user_logged_in() || is_super_admin())) {

			$sender_id = isset($_GET['id']) ? absint($_GET['id']) : '';

			if (isset($_GET['whatisit']) && $_GET['whatisit'] == 'deletemessages' && $sender_id > 0) {

				self::datebook_action_delete_pm($sender_id);

			} else if (isset($_GET['whatisit']) && $_GET['whatisit'] == 'favoriteset' && $sender_id > 0) {

				self::datebook_add_remove_favorite($sender_id);

			} else if (isset($_GET['whatisit']) && ($_GET['whatisit'] == 'blacklistset' || $_GET['whatisit'] == 'addblacklist') && $sender_id > 0) {

				self::datebook_add_remove_blacklist($sender_id);

			}
		}
	}


	/**
	 * Delete Private Message
	 * 
	 * @access private
	 */
	private static function datebook_action_delete_pm($sender_id) {

		global $wpdb;

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$sender_id = absint($sender_id);
		
		if (!$sender_id) { esc_html_e( 'Oops! Something went wrong.', 'datebook' ); return; }

		$sender_user = get_userdata($sender_id);

		$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

		$messages = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table_private_messages} WHERE (senderid = %d AND rcpid = %d) OR (senderid = %d AND rcpid = %d) ORDER BY date ASC", $sender_user->ID, $current_user_id, $current_user_id, $sender_user->ID));
	
		if ($messages) {
			$wpdb->update( $table_private_messages, array('fromdelete' => 1), array('senderid' => $current_user_id, 'rcpid' => $sender_user->ID));
			$wpdb->update( $table_private_messages, array('todelete' => 1), array('senderid' => $sender_user->ID, 'rcpid' => $current_user_id));
		}
		
		// Get profile ID of current user
		$profile_id = get_user_meta( $sender_user->ID, 'profile_postid', true );

		$textmessage = esc_html__( 'All the messages have been successfully deleted.', 'datebook' );
		$message_text = '<div id="datebook-messages-profile-box-' . $profile_id . '" class="alert alert-success mt-3 mb-0 w-100">' . $textmessage . '</div>';

		$count_normal_contacts = self::datebook_count_normal_contacts();

		$response = array('success' => 2, 'profile_id'=> $profile_id, 'text' => $textmessage, 'newmessage'=> $message_text, 'counter' => $count_normal_contacts);

		echo wp_send_json($response);

		if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

			die();

		}
	}


	/**
	 * Add  or remove User to from Favorite
	 * 
	 * @access private
	 */
	private static function datebook_add_remove_favorite($profile_sender_id) {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		// Get profile ID of current user
		$profile_current_user_id = get_user_meta( $current_user_id, 'profile_postid', true );

		$current_profile_data = get_post($profile_current_user_id);

		$profile_status = $current_profile_data->post_status;

		if ($profile_status == 'publish') {

			$profile_id = absint($profile_sender_id);
			
			// Get personal data of sender user
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
			
			// display the confirmation of nothing changed
			$response = array('success' => 0, 'text' => esc_html__('Nothing changed', 'datebook' ));

			if ($profile_id > 0) {

				$data_array = get_user_meta( $current_user_id, 'favorites', true);
				if ($data_array) {
					$data_array = array_unique(explode(',', $data_array));
				} else {
					$data_array = array();
				}

				if (!in_array($profile_id, $data_array)) {

					if ($profile_id == $profile_current_user_id){

						$response = array('success' => 0, 'text' => esc_html__('You cannot add yourself to Favorites', 'datebook' ));

					} else {

						$data_array[] = $profile_id;

						$count_data_array = count($data_array);

						$data_array = implode(',', $data_array);
						update_user_meta( $current_user_id, 'favorites', esc_attr($data_array));

						// Who added to favorites
						if (isset($datebook_get_data['favorites']['whoaddedfavorites']) && !empty($datebook_get_data['favorites']['whoaddedfavorites'])) {
							$whoaddedfavorites = array_unique(explode('|', $datebook_get_data['favorites']['whoaddedfavorites']));
						} else {
							$whoaddedfavorites = array();
						}

						if (!in_array($profile_current_user_id, $whoaddedfavorites)) {
							$whoaddedfavorites[] = $profile_current_user_id;
							$whoaddedfavorites = implode('|', $whoaddedfavorites);
							$datebook_get_data['favorites']['whoaddedfavorites'] = $whoaddedfavorites;

							// Send email notification about Friend request to profile user
							$profile_link = get_permalink($profile_current_user_id);

							$profile_get_permalink = add_query_arg( array(
								'show' => 'favorites'
							), $profile_link );

							$get_data_notification = get_post_meta($profile_id, 'notification', true);

							if(is_array($get_data_notification) && !empty($get_data_notification)){

								$user_sent_notification = isset($get_data_notification[$profile_id]) && !empty($get_data_notification[$profile_id]) ? 1 : 0;

								$get_data_notification = $get_data_notification;

							} else {

								$user_sent_notification = 0;

								$get_data_notification = array();

							}

							if($user_sent_notification == 0){

								$time_submitted = time();

								$get_data_notification[$profile_id] = array('time' => $time_submitted, 'status' => 'unread', 'referrer' => 'notification', 'show' => 'favorites', 'text' => esc_html__('added your profile to favorites', 'datebook' ), 'url' => $profile_get_permalink, 'profile_id' => $profile_current_user_id);
								update_post_meta($profile_id, 'notification', $get_data_notification);

							}
						}

						$datebook_get_data['favorites']['count'] = isset($datebook_get_data['favorites']['count']) && $datebook_get_data['favorites']['count'] > 0 ? $datebook_get_data['favorites']['count'] + 1 : 1;

						// Update the post meta
						update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

						// display the confirmation of add
						$response = array('success' => 1, 'text' => esc_html__('Added to Favorites', 'datebook' ), 'mycounter' => $count_data_array, 'youcounter' => $datebook_get_data['favorites']['count']);

					}

				} else if (in_array($profile_id, $data_array)) {

					$key = array_search($profile_id, $data_array);
					if ($key >= 0) {
						unset($data_array[$key]);
					}
					
					$count_data_array = count($data_array);

					$data_array = implode(',', $data_array);
					update_user_meta( $current_user_id, 'favorites', esc_attr($data_array));

					// Who added to Favorites
					if (isset($datebook_get_data['favorites']['whoaddedfavorites']) && !empty($datebook_get_data['favorites']['whoaddedfavorites'])) {
						$whoaddedfavorites = array_unique(explode('|', $datebook_get_data['favorites']['whoaddedfavorites']));
					} else {
						$whoaddedfavorites = array();
					}

					$whoaddedfavorites_key = array_search($profile_current_user_id, $whoaddedfavorites);
					if ($whoaddedfavorites_key >= 0) {
						unset($whoaddedfavorites[$whoaddedfavorites_key]);
					}
					$whoaddedfavorites = implode('|', $whoaddedfavorites);
					$datebook_get_data['favorites']['whoaddedfavorites'] = $whoaddedfavorites;

					$datebook_get_data['favorites']['count'] = isset($datebook_get_data['favorites']['count']) && $datebook_get_data['favorites']['count'] > 0 ? $datebook_get_data['favorites']['count'] - 1 : 0;

					// Update the post meta
					update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

					$textmessage = esc_html__( 'Removed from Favorites', 'datebook' );
					$message_text = '<div id="datebook-messages-profile-box-' . $profile_id . '" class="alert alert-success mt-3 mb-0">' . $textmessage . '</div>';

					// display the confirmation of remove
					$response = array('success' => 2, 'text' => $textmessage, 'newmessage'=> $message_text, 'mycounter' => $count_data_array, 'youcounter' => $datebook_get_data['favorites']['count']);

				}

			} else {

				$textmessage = esc_html__( 'Oops! Something went wrong', 'datebook' );
				$message_text = '<div class="alert alert-danger">' . $textmessage . '</div>';

				$response = array('success' => 3, 'profile_id'=> '', 'text' => $textmessage, 'newmessage'=> $message_text, 'counter' => '');

			}

		} else {

			// display the confirmation of nothing changed
			$response = array('success' => 0, 'text' => esc_html__('This action cannot be done due to your profile is not active yet', 'datebook' ));
				
		}

		echo wp_send_json($response);

		if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

			die();

		}
	}


	/**
	 * Add or remove User to Blacklist
	 * 
	 * @access private
	 */
	private static function datebook_add_remove_blacklist($profile_sender_id) {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		// Get profile ID of current user
		$profile_current_user_id = get_user_meta( $current_user_id, 'profile_postid', true );
		
		$current_profile_data = get_post($profile_current_user_id);

		$profile_status = $current_profile_data->post_status;

		if ($profile_status == 'publish') {

			// display the confirmation of nothing changed
			$response = array('success' => 0, 'text' => esc_html__('Nothing changed', 'datebook' ));

			// Get personal data of receiver user
			$get_profile_data = get_post_meta($profile_current_user_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			$profile_id = absint($profile_sender_id);

			if ($profile_id > 0) {

				$data_array = get_user_meta( $current_user_id, 'blacklist', true);
				if ($data_array) {
					$data_array = array_unique(explode(',', $data_array));
				} else {
					$data_array = array();
				}

				if (!in_array($profile_id, $data_array)) {

					if ($profile_id == $profile_current_user_id){

						$response = array('success' => 0, 'text' => esc_html__('You cannot add yourself to Blacklist', 'datebook' ));

					} else {

						$data_array[] = $profile_id;
						$data_array = implode(',', $data_array);
						update_user_meta( $current_user_id, 'blacklist', esc_attr($data_array));

						// Remove from Favorites
						if ($profile_id > 0) {

							$data_array = get_user_meta( $current_user_id, 'favorites', true);
							if ($data_array) {
								$data_array = array_unique(explode(',', $data_array));
							} else {
								$data_array = array();
							}

							if (in_array($profile_id, $data_array)) {

								$key = array_search($profile_id, $data_array);
								if ($key >= 0) {
									unset($data_array[$key]);
								}

								$data_array_count = $data_array;

								$data_array = implode(',', $data_array);
								update_user_meta( $current_user_id, 'favorites', esc_attr($data_array));

								$datebook_get_data['favorites'] = count($data_array_count);

							}
						}

						$datebook_get_data['blacklist'] = isset($datebook_get_data['blacklist']) && $datebook_get_data['blacklist'] > 0 ? $datebook_get_data['blacklist'] + 1 : 1;

						// Update the post meta
						update_post_meta($profile_current_user_id, 'profile_personal_data', $datebook_get_data);

						$message_text = '<div class="jumbotron shadow-none text-center">
							<div class="jumbotron-contents mt-5">
								<h2 class="card-title">' . esc_html__( 'You have blocked this user!', 'datebook' ) . '</h2>
								<p class="jumbotron-photo"><img src="' . esc_url(DATEBOOK_URL . 'assets/images/lock-folder.png') . '" alt="" /></p>
								<p>' . esc_html__( 'User has been moved to your black list', 'datebook' ) . '</p>
							</div>
						</div>';

						// display the confirmation of add
						$response = array('success' => 1, 'text' => esc_html__('Added to Blacklist', 'datebook' ), 'newmessage'=> $message_text, 'counter' => $datebook_get_data['blacklist'] );

					}

				} else if (in_array($profile_id, $data_array)) {
					
					// What is it
					$whatisit = isset( $_REQUEST['whatisit'] ) ? esc_attr($_REQUEST['whatisit']) : '';

					// Upload file in chat windows
					if ($whatisit == 'addblacklist') {
						
						$textmessage = esc_html__( 'User is already blocked!', 'datebook' );
						$message_text = '<div class="jumbotron shadow-none text-center">
							<div class="jumbotron-contents mt-5">
								<h2 class="card-title">' . esc_html__( 'User is already blocked!', 'datebook' ) . '</h2>
								<p class="jumbotron-photo"><img src="' . esc_url(DATEBOOK_URL . 'assets/images/lock-folder.png') . '" alt="" /></p>
								<p>' . esc_html__( 'User has already been moved to your black list', 'datebook' ) . '</p>
							</div>
						</div>';
						
					} else {

						$key = array_search($profile_id, $data_array);
						if ($key >= 0) {
							unset($data_array[$key]);
						}

						$data_array_count = $data_array;

						$data_array = implode(',', $data_array);
						update_user_meta( $current_user_id, 'blacklist', esc_attr($data_array));

						$datebook_get_data['blacklist'] = count($data_array_count);
						// Update the post meta
						update_post_meta($profile_current_user_id, 'profile_personal_data', $datebook_get_data);

						$textmessage = esc_html__( 'Removed from Blacklist', 'datebook' );
						$message_text = '<div id="datebook-messages-profile-box-' . $profile_id . '" class="alert alert-success mt-3 mb-0">' . $textmessage . '</div>';
						
					}

					// display the confirmation of remove
					$response = array('success' => 2, 'text' => $textmessage, 'newmessage'=> $message_text, 'counter' => $datebook_get_data['blacklist']);

				}

			} else {

				$textmessage = esc_html__( 'Oops! Something went wrong', 'datebook' );
				$message_text = '<div class="alert alert-danger">' . $textmessage . '</div>';

				$response = array('success' => 3, 'profile_id'=> '', 'text' => $textmessage, 'newmessage'=> $message_text, 'counter' => '');

			}

		} else {

			// display the confirmation of nothing changed
			$response = array('success' => 0, 'text' => esc_html__('This action cannot be done due to your profile is not active yet', 'datebook' ));
				
		}

		echo wp_send_json($response);

		if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

			die();

		}
	}


	/**
	 * New Messages badge in Profile menu
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_show_new_msg_alert($nosup = 'sup') {

		global $wpdb;

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		if (of_get_option('contact_method') != '3') {

			$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

			$group_messages = $wpdb->get_results($wpdb->prepare("SELECT senderid, rcpid  FROM {$table_private_messages} WHERE rcpid = %d AND tosee = 0 AND todelete = 0 AND status = 0", $current_user_id));

			$countnew = 0;

			if ($group_messages) {

				$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
				if (!empty($blacklists)) {
					$blacklists = array_unique(explode(',', $blacklists));
				} else {
					$blacklists = array();
				}

				foreach ($group_messages as $message) {

					$profile_postid = get_user_meta($message->senderid, 'profile_postid', true);

					if (!empty($profile_postid) && $profile_postid > 0) {

						$post = get_post($profile_postid);

						if (isset($post->ID) && $post->ID > 0) {

							if (in_array($profile_postid, $blacklists)) continue;

							$countnew ++;
						
						}
					}
				}
			}


			$indicator_out = '';

			$count_messages = $countnew > 0 ? $countnew : '';

			if ($nosup == 'nosup') {

				$indicator_out = '<span class="badge badge-pill badge-warning datebook-count-messages">' . esc_attr($count_messages) . '</span>';

			} else if ($nosup == 'withsup') {

				$indicator_out = '<sup><span class="badge badge-pill badge-warning datebook-count-messages">' . esc_attr($count_messages) . '</span></sup>';

			}

			$indicator_hide = $countnew > 0 ? '' : 'style="display: none"';

			echo '<span class="datebook-new-messages-indicator" ' . $indicator_hide . '>' . $indicator_out . '</span> ';
		
		}

	}


	/**
	 * Send Private Message in Chat
	 * 
	 * @access public
	 */
	public static function process_action_send_pm($simulate = 0, $user_id = 0, $pmessage = '') {

		global $wpdb, $current_user;
		wp_get_current_user();

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$to_senderid = $simulate == 1 && $user_id > 0 ? $current_user_id : (isset($_POST['sid']) && $_POST['sid'] > 0 ? $_POST['sid'] : 0);
		$to = $wpdb->get_var($wpdb->prepare("SELECT user_nicename FROM $wpdb->users WHERE ID = %d", $to_senderid));

		$from = $simulate == 1 ? $to : $current_user->user_login;

		$msg = $simulate == 1 && strlen($pmessage) > 0 ? $pmessage : (isset($_POST['pmessage']) ? wp_trim_words(htmlentities(stripslashes($_POST['pmessage'])), 1000, '') : '');

		if ($to != '' && $from != '' && $msg != '' && $to_senderid != '') {

			$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

			$chat_mode = 1; // 1 - chat, 2 - message, 3 - image

			$subject = 'New message!';
			$date = date("Y-m-d H:i:s");

			$fromid = $simulate == 1 && $user_id > 0 ? $user_id : $current_user_id;

			$ip = Class_DateBook_IP::get_ip_address();

			$result = $wpdb->query( $wpdb->prepare("INSERT INTO {$table_private_messages} (senderid, rcpid, sender, recipient, subject, message, fromsee, tosee, fromdelete, todelete, chat_mode, date, status, notified, ip) VALUES ( %d, %d, %s, %s, %s, %s, %d, %d, %d, %d, %d, %s, %d, %d, %s )", $fromid, $to_senderid, $from, $to, $subject, $msg, 0, 0, 0, 0, $chat_mode, $date, 0, 0, $ip ) );

			$profile_qid = get_user_meta( $to_senderid, 'profile_postid', true);

			$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
			if ($blacklists) {
				$blacklists = array_unique(explode(',', $blacklists));
			} else {
				$blacklists = array();
			}

			if (in_array($profile_qid, $blacklists)) {

				$key = array_search($profile_qid, $blacklists);

				if ($key >= 0) {
					unset($blacklists[$key]);
				}

				$blacklists = implode(',', $blacklists);
				update_user_meta( $current_user_id, 'blacklist', esc_attr($blacklists));
			}

			return $result;
		
		}

	}


	/**
	 * Get All Messages
	 * 
	 * @access private
	 */
	private static function datebook_getallmessages($sender_id, $current_user_id){

		global $wpdb, $allowedposttags;

		$message_not_read = 0;

		$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';

		$sender_id = absint($sender_id);

		$messages = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table_private_messages} WHERE (senderid = %d AND rcpid = %d) OR (senderid = %d AND rcpid = %d) ORDER BY date ASC", $sender_id, $current_user_id, $current_user_id, $sender_id));

		if ($messages) {

			$is_super_admin = is_super_admin() ? 1 : 0;

			foreach ($messages as $message) {
				
				$tosee = (int)$message->tosee;
				$status = (int)$message->status;
				$senderid = (int)$message->senderid;
				$fromdelete = (int)$message->fromdelete;
				$rcpid = (int)$message->rcpid;
				$todelete = (int)$message->todelete;

				if($senderid == $current_user_id && $fromdelete == 1) continue;
				if($rcpid == $current_user_id && $todelete == 1) continue;

				// Get local time and covert date of message to local time.
				$message_post_time = DateBook_Utilities::datebook_date_i18n(2, $message->date);

				if ($tosee == 0 && $is_super_admin == 0) {

					$wpdb->update( $table_private_messages, array('tosee' => 1, 'notified' => 1), array('senderid' => $sender_id, 'rcpid' => $current_user_id));
					
				}

				if ($status == 0 && $is_super_admin == 0) {

					$wpdb->update( $table_private_messages, array('status' => 1, 'notified' => 1), array('senderid' => $sender_id, 'rcpid' => $current_user_id));

					$message_not_read = 1;

				}

				if ($current_user_id == $senderid) {
					$class_message_bg = ' datebook-chat-r';
					$class_message = ' text-dark';
					$class_float = ' float-right';
					$class_margin = ' ml-auto';
					$class_color = ' blue lighten-5 datebook-bg-recipient';
					$class_text_align = ' text-right';
				} else {
					$class_message_bg = ' datebook-chat-l';
					$class_message = ' text-dark';
					$class_float = ' float-left';
					$class_margin = ' mr-auto';
					$class_color = ' grey lighten-3 datebook-bg-sender';
					$class_text_align = ' text-left';
				}

				echo '<div class="mb-2 datebook-chat-text-width ' . esc_attr( $class_message_bg ) . '">';
				echo '<div class="mb-1 ' . esc_attr( $class_margin ) . ' ">';

				if ($message->chat_mode == 1) {

					echo '<p class="mb-0 pr-2 pl-2 datebook-message-body ' . esc_attr($class_message . $class_color) . '">' . nl2br(wp_kses( $message->message, $allowedposttags ) ) . '</p>';

				} else if ($message->chat_mode == 3) {

					$image_result_array = unserialize($message->message);

					echo '<div id="blueimp-gallery-links" class="datebook-gallery">';

					echo '<p class="mb-0 p-2 text-dark datebook-message-body ' . esc_attr($class_color) . '"><a class="mb-1 d-block datebook-image-in-chat" href="' . esc_url($image_result_array['imgbig']) . '"><img class="img-fluid" src="' . esc_url($image_result_array['imgurl']) . '" alt="" /></a></p>';

					echo '</div>';

				}

				echo '<div class="w-100 datebook-clear"></div>';

				echo '<p class="mb-0 p-0 datebook-message-body datebook-chat-text-width ' . esc_attr($class_margin . $class_text_align) . '"><span class="m-0 small datebook-message-user"><span class="chat-time text-grey ' . esc_attr($class_margin) . '">' . esc_attr($message_post_time) . '</span>';

				if ($current_user_id == $senderid) {
					if ($tosee == 0) {
						echo '<i class="ml-2 fas fa-check text-grey"></i>';
					} else if ($tosee == 1) {
						echo '<i class="ml-2 fas fa-check text-success"></i>';
					}
				}

				echo '</span></p>';

				echo '</div>';
				echo '</div>';

			}

			if ($message_not_read > 0 && $current_user_id == $senderid) {

				//echo '<div id="datebook-lastmessagenotread" class="list-group-item float-right ml-auto text-center datebook-bg-warning datebook-lastmessagenotread">'.esc_html__( 'Your last message has not been read yet!', 'datebook' ).'</div>';

			}
			
		}
	
	}


	/**
	 * Update Chat via Ajax
	 * 
	 * @access public
	 */
	public static function datebook_ajax_update_chat($current_user_id) {

		if (isset($_REQUEST['action'])) {
			
			$is_super_admin = is_super_admin() ? 1 : 0;

			if (is_user_logged_in() || $is_super_admin == 1) {

				// Make global
				global $wpdb, $datebook_image_sizes;

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				// Delete Tour
				$whatisit = isset( $_REQUEST['whatisit'] ) ? esc_attr($_REQUEST['whatisit']) : '';

				$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';
				
				// Upload file in chat windows
				if ($whatisit == 'chatfileupload') {

					$postvals = array();

					if(isset($_FILES['imagefile']) ){ 

						$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

						if ($profile_id) {

							$current_user = get_userdata($current_user_id);

							$date = date("Y-m-d H:i:s");
							$to_senderid = $_POST['senderid'];
							$subject = 'New image!';
							$from = $current_user->user_login;
							$ip = Class_DateBook_IP::get_ip_address();

							$datebook_post_image_upload = 'upload';
							$datebook_files_images = $_FILES['imagefile'];

							// Mark this action as Profile Photos
							$datebook_photo_type = DATEBOOK_IMAGE_CHAT;

							// Define which image formats to be created
							$datebook_photo_formats = array('image_big' => array('crop' => false, 'watermark' => false));

							// Set up Default image to show after upload
							$default_thumbnail_show = array('format' => 'image_front_feature', 'crop' => false, 'watermark' => false);

							$image_result_array = DateBook_Utilities::process_upload_photo($datebook_post_image_upload, $datebook_files_images, $datebook_photo_type, $datebook_photo_formats, $profile_id, $default_thumbnail_show, $current_user_id);

							// Insert into database
							$post_message = serialize(array('imgbig' => $image_result_array['imgbig'], 'imgurl' => $image_result_array['imgurl'], 'height' => $image_result_array['height']));

							$to = $wpdb->get_var($wpdb->prepare("SELECT user_nicename FROM $wpdb->users WHERE ID = %d", $to_senderid));

							$chat_mode = 3; // 1 - chat, 2 - message, 3 - image

							$result = $wpdb->query( $wpdb->prepare("INSERT INTO {$table_private_messages} (senderid, rcpid, sender, recipient, subject, message, fromsee, tosee, fromdelete, todelete, chat_mode, date, status, notified, ip) VALUES ( %d, %d, %s, %s, %s, %s, %d, %d, %d, %d, %d, %s, %d, %d, %s )", $current_user_id, $to_senderid, $from, $to, $subject, $post_message, 0, 0, 0, 0, $chat_mode, $date, 0, 0, $ip ) );

							$message_text = '';
							$lastmessagenotread = 0;
							$name = '';

							if ($result) {

								// Start session and insert user ID to database
								$session_instance = new DateBook_Session_Handler($current_user_id, $to_senderid, 'datebook_security_chat', 1);

								// Remove user from black list
								$profile_qid = get_user_meta( $to_senderid, 'profile_postid', true);

								$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
								if ($blacklists) {
									$blacklists = array_unique(explode(',', $blacklists));
								} else {
									$blacklists = array();
								}

								if (in_array($profile_qid, $blacklists)) {

									$key = array_search($profile_qid, $blacklists);

									if ($key >= 0) {
										unset($blacklists[$key]);
									}

									$blacklists = implode(',', $blacklists);
									update_user_meta( $current_user_id, 'blacklist', esc_attr($blacklists));
								}
								
								// Deduct point by myCred
								if (of_get_option('points_system') == 1 && class_exists('myCRED_Core')) {

									$all_splans = get_option('datebook_subscription_plans');
									
									// Get profile data and check if it has subscription plan
									$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
									$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
									
									$subscriptionplan_id = isset($datebook_get_data['profile_subscription']['plan']) && strlen($datebook_get_data['profile_subscription']['plan']) > 1 ? $datebook_get_data['profile_subscription']['plan'] : '';
									
									$points_for_one_message = isset($all_splans[$subscriptionplan_id]['points_for_one_message']) ? $all_splans[$subscriptionplan_id]['points_for_one_message'] : 0;

									if($points_for_one_message > 0){
										mycred_add( 'subscription', $current_user_id, -$points_for_one_message, 'Points deducted for sending a message' );
									}
								}

								$message_post_time = DateBook_Utilities::datebook_date_i18n( 3, $date);

								$message_text .= '<div class="mb-2 datebook-chat-text-width datebook-chat-r">';
								$message_text .= '<div class="mb-1 ml-auto">';
								$message_text .= '<div id="blueimp-gallery-links" class="datebook-gallery">';
								$message_text .= '<p class="mb-0 p-2 datebook-message-body text-dark blue lighten-5 datebook-bg-recipient"><a class="mb-1 d-block datebook-image-in-chat" style="height: ' . esc_attr($image_result_array['height']) . 'px" href="' . esc_url($image_result_array['imgbig']) . '"><img class="img-fluid" src="' . esc_url($image_result_array['imgurl']) . '" alt="" /></a></p>';
								$message_text .= '<div class="w-100 datebook-clear"></div>';
								$message_text .= '<p class="mb-0 p-0 ml-auto text-right datebook-message-body datebook-chat-text-width"><span class="m-0 small datebook-message-user"><span class="chat-time text-grey  ml-auto">' . esc_attr($message_post_time) . '</span><i class="ml-2 fas fa-check text-grey"></i></span></p>';
								$message_text .= '</div>';

								$response = array(
									'status'=> 200,
									'newmessage'=> $message_text,
									'lastmessagenotread'=> $lastmessagenotread
								);

							} else {

								$response = array(
									'status' => 201,
									'newmessage'=> '',
									'lastmessagenotread'=> $lastmessagenotread
								);

							}

							echo wp_send_json($response);

						}
					}
				}

				// Submit a message in chat window
				if ($whatisit == 'chatsubmit') {

					$current_user = get_userdata($current_user_id);
					$from = $current_user->user_login;

					$post_message = $_POST['message'];

					if (strlen($post_message) > 1000) {
						// truncate string
						$post_message = substr($post_message, 0, 1000);
					}

					$post_message = DateBook_Utilities::datebook_word_filter(stripslashes_deep(sanitize_textarea_field($post_message)));

					$date = date("Y-m-d H:i:s");
					$to_senderid = $_POST['senderid'];
					$subject = 'New message!';
					$tryagain = ' ' . esc_html__( 'Please, try again.', 'datebook' );

					$ip = Class_DateBook_IP::get_ip_address();

					if ($from == '' || $post_message == '' || $to_senderid == '') {
						return;
					}

					$to = $wpdb->get_var($wpdb->prepare("SELECT user_nicename FROM $wpdb->users WHERE ID = %d", $to_senderid));
					
					$chat_mode = 1; // 1 - chat, 2 - message, 3 - image

					$todelete_blocked = 0;

					$profile_id = get_user_meta( $current_user_id, 'profile_postid', true);

					$blacklist_of_sender = get_user_meta( $to_senderid, 'blacklist', true);
					if ($blacklist_of_sender) {
						$blacklist_of_sender = array_unique(explode(',', $blacklist_of_sender));
					} else {
						$blacklist_of_sender = array();
					}

					if (in_array($profile_id, $blacklist_of_sender)) {
						
						$todelete_blocked = 1;

					}


					$result = $wpdb->query( $wpdb->prepare("INSERT INTO {$table_private_messages} (senderid, rcpid, sender, recipient, subject, message, fromsee, tosee, fromdelete, todelete, chat_mode, date, status, notified, ip) VALUES ( %d, %d, %s, %s, %s, %s, %d, %d, %d, %d, %d, %s, %d, %d, %s )", $current_user_id, $to_senderid, $from, $to, $subject, $post_message, 0, 0, 0, $todelete_blocked, $chat_mode, $date, 0, 0, $ip ) );

					$profile_qid = get_user_meta( $to_senderid, 'profile_postid', true);

					$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
					if ($blacklists) {
						$blacklists = array_unique(explode(',', $blacklists));
					} else {
						$blacklists = array();
					}

					if (in_array($profile_qid, $blacklists)) {

						$key = array_search($profile_qid, $blacklists);

						if ($key >= 0) {
							unset($blacklists[$key]);
						}

						$blacklists = implode(',', $blacklists);
						update_user_meta( $current_user_id, 'blacklist', esc_attr($blacklists));
					}
					
					$message_text = '';
					$lastmessagenotread = 0;
					$name = '';

					if ($result) {

						global $allowedposttags;

						// Start session and insert user ID to database
						$session_instance = new DateBook_Session_Handler($current_user_id, $to_senderid, 'datebook_security_chat', 1);
						
						$chatpointsdeducted = $sendmessagenotallowed = 0;

						// Deduct point by myCred
						if (of_get_option('points_system') == 1 && class_exists('myCRED_Core')) {

							$all_splans = get_option('datebook_subscription_plans');

							// Get profile data and check if it has subscription plan
							$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
							$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

							$subscriptionplan_id = isset($datebook_get_data['profile_subscription']['plan']) && strlen($datebook_get_data['profile_subscription']['plan']) > 1 ? $datebook_get_data['profile_subscription']['plan'] : '';

							$points_for_one_message = isset($all_splans[$subscriptionplan_id]['points_for_one_message']) ? $all_splans[$subscriptionplan_id]['points_for_one_message'] : 0;

							if($points_for_one_message > 0){
								mycred_add( 'subscription', $current_user_id, -$points_for_one_message, 'Points deducted for sending a message' );
								$chatpointsdeducted = mycred_get_users_balance($current_user_id);
								
								$sendmessagenotallowed = $chatpointsdeducted < $points_for_one_message ? 1 : 0;
							}
						}

						$message_post_time = DateBook_Utilities::datebook_date_i18n( 3, $date);

						$message_text .= '<div class="mb-2 datebook-chat-text-width datebook-chat-r">';
						$message_text .= '<div class="mb-1 ml-auto">';
						$message_text .= '<p class="mb-0 pr-2 pl-2 datebook-message-body text-dark blue lighten-5 datebook-bg-recipient">' . nl2br(wp_kses( $post_message, $allowedposttags ) ) . '</p>';
						$message_text .= '<div class="w-100 datebook-clear"></div>';
						$message_text .= '<p class="mb-0 p-0 ml-auto text-right datebook-message-body datebook-chat-text-width"><span class="m-0 small datebook-message-user"><span class="chat-time text-grey  ml-auto">' . esc_attr($message_post_time) . '</span><i class="ml-2 fas fa-check text-grey"></i></span></p>';
						$message_text .= '</div>';

						$chatnotallowedmessage = '<div class="alert alert-warning m-0">';
						$chatnotallowedmessage .= '<h6>' . esc_html__( 'You do not have enough points to send messages!', 'datebook' ) . '</h6>';
						$chatnotallowedmessage .= '<p class="small m-0 p-0">' . esc_html__( 'You can buy more points and keep chatting.', 'datebook' ) . ' <a class="btn btn-sm btn-primary" href="' . esc_url(get_permalink(of_get_option('my_upgrade_page'))) . '" target="_blank">' . esc_html__( 'Buy more points', 'datebook' ) . '</a></p>';
						$chatnotallowedmessage .= '</div>';

						$response = array(
							'status'=> 200,
							'newmessage'=> $message_text,
							'lastmessagenotread'=> $lastmessagenotread,
							'chatpointsdeducted' => $chatpointsdeducted,
							'sendmessagenotallowed' => $sendmessagenotallowed,
							'chatnotallowedmessage' => $chatnotallowedmessage
						);

					} else {

						$response = array(
							'status' => 201,
							'newmessage'=> '',
							'lastmessagenotread'=> $lastmessagenotread,
							'chatpointsdeducted' => 0,
							'chatnotallowedmessage' => ''
						);

					}

					echo wp_send_json($response);

				}


				// Get New Messages in Chat
				if ($whatisit == 'chatupdate' && $is_super_admin == 0) {

					$sender_id = (int)$_REQUEST['senderid'];
					if ($sender_id == 0) { die(); }

					$message_text = '';
					$lastmessagenotread = 0;
					$message_not_read = 0;

					$all_profile_array = $all_message_array = $profile_data = array();

					$messages = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table_private_messages} WHERE rcpid = %d OR senderid = %d AND todelete = 0 ORDER BY date ASC", $current_user_id, $current_user_id));


					// Get profile ID, gender, online status
					$profile_id_of_current_user = get_user_meta( $sender_id, 'profile_postid', true );
					$gender = get_post_meta($profile_id_of_current_user, 'gender', true);
					$online_status_sender = DateBook_Utilities::return_online_status( $sender_id, $gender, 1, 'full' );

					if ($messages) {

						global $allowedposttags;

						foreach ($messages as $message) {

							$tosee = (int)$message->tosee;
							$status = (int)$message->status;
							$notified = (int)$message->notified;
							$senderid = (int)$message->senderid;
							$fromsee = (int)$message->fromsee;
							$chat_mode = (int)$message->chat_mode;
							$rcpid = (int)$message->rcpid;


							if ($notified == 0) {
								$wpdb->update( $table_private_messages, array('notified' => 1), array('rcpid' => $current_user_id));
								
								$notify = 1;
							} else {
								$notify = 0;
							}

							if (($senderid == $sender_id && $rcpid == $current_user_id) || ($senderid == $current_user_id && $rcpid == $sender_id)) {

								$message_post_time = DateBook_Utilities::datebook_date_i18n(3, $message->date);

								if ($status == 1) {
									$message_not_read += 1;
								}

								if ($current_user_id == $senderid) {

									if (count($messages) == $message_not_read) {
										$lastmessagenotread += 1;
									}

									if ($fromsee == 0) {
										// Set status - message read by Sender
										$wpdb->update( $table_private_messages, array('fromsee' => 1), array('senderid' => $current_user_id, 'rcpid' => $sender_id));
										continue;
									}
									if ($fromsee == 1) continue;

								} else {

									if ($tosee == 0) {
										// Set status - message read by Reciever
										$wpdb->update( $table_private_messages, array('tosee' => 1), array('senderid' => $sender_id, 'rcpid' => $current_user_id));
									}
									if ($tosee == 1) continue;

									if ($status == 0) {
										// Set status unread to read
										$wpdb->update( $table_private_messages, array('status' => 1), array('senderid' => $sender_id, 'rcpid' => $current_user_id));
										$lastmessagenotread += 1;
									}

								}

								if ($current_user_id == $message->senderid) {
									$class_message_bg = ' datebook-chat-r';
									$class_message = ' text-dark';
									$class_float = ' float-right';
									$class_margin = ' ml-auto';
									$class_color = ' blue lighten-5 datebook-bg-recipient';
									$class_text_align = ' text-right';
								} else {
									$class_message_bg = ' datebook-chat-l';
									$class_message = ' text-dark';
									$class_float = ' float-left';
									$class_margin = ' mr-auto';
									$class_color = ' grey lighten-3 datebook-bg-sender';
									$class_text_align = ' text-left';
								}

								$message_text .= '<div class="mb-2 datebook-chat-text-width ' . esc_attr( $class_message_bg ) . '">';
								$message_text .= '<div class="mb-1 ' . esc_attr( $class_margin ) . ' ">';
								if ($chat_mode == 1) {
									$message_text .= '<p class="mb-0 pr-2 pl-2 datebook-message-body ' . esc_attr($class_message . $class_color) . '">' . nl2br(wp_kses( $message->message, $allowedposttags ) ) . '</p>';
								} else if ($chat_mode == 3) {
									$image_result_array = unserialize($message->message);
									$message_text .= '<div id="blueimp-gallery-links" class="datebook-gallery">';
									$message_text .= '<p class="mb-0 p-2 datebook-message-body text-dark ' . esc_attr($class_color) . '"><a class="mb-1 d-block datebook-image-in-chat" style="height: ' . esc_attr($image_result_array['height']) . 'px" href="' . esc_url($image_result_array['imgbig']) . '"><img class="img-fluid" src="' . esc_url($image_result_array['imgurl']) . '" alt="" /></a></p>';
									$message_text .= '</div>';
								}

								$message_text .= '<div class="w-100 datebook-clear"></div>';

								$message_text .= '<p class="mb-0 p-0 datebook-message-body datebook-chat-text-width ' . esc_attr($class_margin . $class_text_align) . '"><span class="m-0 small datebook-message-user"><span class="chat-time text-grey ' . esc_attr($class_margin) . '">' . esc_attr($message_post_time) . '</span>';

								if ($current_user_id == $message->senderid) {
									if ($tosee == 0) {
										$message_text .= '<i class="ml-2 fas fa-check text-grey"></i>';
									} else if ($tosee == 1) {
										$message_text .= '<i class="ml-2 fas fa-check text-success"></i>';
									}
								}

								$message_text .= '</span></p>';

								$message_text .= '</div>';
								$message_text .= '</div>';

							}

							// Get profiles array
							$all_profile_array[] = $senderid;

							$all_message_array[] = array('senderid' => $senderid, 'countnewmsgsender' => $tosee, 'notify' => $notify);

						}
					}

					$profile_result_array = array_unique($all_profile_array, SORT_REGULAR);

					// Recount all messages
					foreach ($profile_result_array as $senderid) {

						if($senderid != $sender_id && $senderid != $current_user_id){

							$message_countnewmsgsender = $message_notified = 0;

							foreach ($all_message_array as $key => $message_single) {

								if($message_single['senderid'] == $senderid){
									if($message_single['countnewmsgsender'] == 0){
										$message_countnewmsgsender++;
									}
									if($message_single['notify'] == 1){
										$message_notified++;
									}
								}
							}

							// Get profile ID, gender, online status
							$profile_id = get_user_meta( $senderid, 'profile_postid', true );
							$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
							$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
							$gender = isset($datebook_get_data['gender']) ? $datebook_get_data['gender'] : 0;
							$online_status_sender = DateBook_Utilities::return_online_status( $senderid, $gender, 1, 'full' );

							if($message_countnewmsgsender > 0 && $message_notified > 0){

								$profile_data[] = array('profile_id' => $profile_id, 'online_status_sender' => $online_status_sender, 'countnewmsgsender' => $message_countnewmsgsender, 'notify' => $message_notified);
								
							}
						}
					}

					$response = array(
						'status'=> 200,
						'newmessage'=> $message_text,
						'lastmessagenotread'=> $lastmessagenotread,
						'online_status_sender' => $online_status_sender,
						'profile_data' => $profile_data
					);

					echo wp_send_json($response);

				}

				// Check for New Messages in database and display count in user panel
				if ($whatisit == 'checknewmessages') {

					if ($is_super_admin == 0) {

						$columns_image_format = 'image_mini';

						$countnewmessages = $countnotified = $notify = $newmessages = 0;

						$all_profile_array = $all_message_array = $profile_data = array();

						$current_profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

						$search_default_thumbnail = of_get_option('search_default_thumbnail') ? 1 : 0;

						//$open_message_new_window = of_get_option('open_message_new_window') ? 1 : 0;
						
						$check_online_status_option = of_get_option('check_online_status') ? of_get_option('check_online_status') : 120; // 120 seconds = 2 minutes

						$last_login_date = get_user_meta($current_user_id, 'last_login', true);
						
						$last_login_date = isset($last_login_date) && $last_login_date > 0 ? $last_login_date : time() - $check_online_status_option;

						$online_time = get_user_meta($current_user_id, 'online_status', true);

						$messages = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table_private_messages} WHERE (senderid = %d OR rcpid = %d) AND todelete = 0", $current_user_id, $current_user_id));

						// Loop all messages
						foreach ($messages as $message) {

							$message_submitted_date = strtotime($message->date);

							$tosee = (int)$message->tosee;
							$status = (int)$message->status;
							$notify = (int)$message->notified;
							$senderid = (int)$message->senderid;
							$rcpid = (int)$message->rcpid;

							$tosee = $tosee == 1 ? 1 : 0;
							$status = $status == 1 ? 1 : 0;
							$notify = $notify == 0 ? 1 : 0;
							$senderid = $senderid > 0 ? $senderid : 0;
							$rcpid = $rcpid > 0 ? $rcpid : 0;

							$tosee = $rcpid == $current_user_id ? $tosee : 1;
							$senderid = $rcpid == $current_user_id ? $senderid : $rcpid;
							$notify = $rcpid == $current_user_id ? $notify : 0;

							if($rcpid == $current_user_id){

								/*if ($tosee == 1 && $status == 0) {
									$countnewmessages++;
								}*/

								if ($notify == 1 && $last_login_date < $message_submitted_date) {
									if (!empty($online_time) && $online_time >= 0 && $online_time + $check_online_status_option > $message_submitted_date) {
										$countnotified++;
										$wpdb->update( $table_private_messages, array('notified' => 1), array('rcpid' => $current_user_id));
									}
								}
								
								$profile_id = get_user_meta( $senderid, 'profile_postid', true );
								
							} else {
								
								$profile_id = get_user_meta( $rcpid, 'profile_postid', true );

							}

							$all_profile_array[] = $profile_id . '_' . $senderid;							

							$all_message_array[] = array('profile_id' => $profile_id, 'senderid' => $senderid, 'countnewmsgsender' => $tosee, 'notify' => $notify);
						}

						$profile_result_array = array_unique($all_profile_array, SORT_REGULAR);

						// Recount all messages
						foreach ($profile_result_array as $profile_arr) {

							$profile_arr = explode('_', $profile_arr);
							$profile_id = isset($profile_arr[0]) && $profile_arr[0] > 0 ? $profile_arr[0] : 0;
							$senderid = isset($profile_arr[1]) && $profile_arr[1] > 0 ? $profile_arr[1] : 0;

							$message_countnewmsgsender = $message_notified = 0;

							if($senderid != $current_user_id){

								foreach ($all_message_array as $key => $message_single) {

									if($message_single['profile_id'] == $profile_id){
										if($message_single['countnewmsgsender'] == 0){
											$message_countnewmsgsender++;
										}
										if($message_single['notify'] == 1){
											$message_notified++;
										}
									}
								}

								$countnewmessages += $message_countnewmsgsender;
								
							}

							// Get profile ID, gender, online status
							$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
							$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
							$gender = isset($datebook_get_data['gender']) ? $datebook_get_data['gender'] : 0;
							$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($profile_id, $columns_image_format, $gender, true, $datebook_get_data, $search_default_thumbnail);
							$profile_get_permalink = add_query_arg( array(
								'action' => 'read',
								'sid' => $senderid,
								'rid' => $current_user_id,
							), get_permalink(of_get_option('my_messages_page')) );
							$online_status_sender = DateBook_Utilities::return_online_status( $senderid, $gender, 1, 'full' );

							$profile_data[] = array('profile_id' => $profile_id, 'profile_get_permalink' => $profile_get_permalink, 'thumbnail_url' => $thumbnail_url['img_full_url'], 'online_status_sender' => $online_status_sender, 'countnewmsgsender' => $message_countnewmsgsender, 'notify' => $message_notified);
							
						}

						$response = array(
							'status'=> 200,
							'countmessages'=> $countnewmessages,
							'countnotified' => $countnotified,
							'profile_data' => $profile_data
						);

						echo wp_send_json($response);

					}
				}


				// Move or remove user to black list
				if (($whatisit == 'blacklistset' || $whatisit == 'addblacklist') && isset($_REQUEST['id']) && absint($_REQUEST['id']) > 0) {

					self::datebook_add_remove_blacklist($_REQUEST['id']);

				}
				
			}
		}

		if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

			die();

		}

	}


	/**
	 * Loads ajax scripts
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_messages_ajax_scripts() {

		wp_enqueue_script('datebook-messages-ajax', DATEBOOK_URL . 'assets/js/datebook-messages-ajax.js', array('jquery'), false, false );

		$datebook_chat_css = "
			html { margin-top: 0 !important }
			#wpadminbar { display:none }
		";
		
		wp_register_style( 'datebook-chat-footer', false );
		wp_enqueue_style( 'datebook-chat-footer' );
		wp_add_inline_style( 'datebook-chat-footer', $datebook_chat_css );

	}
	


	/**
	 * Read Private Message in Chat
	 * 
	 * @access public
	 */
	public static function datebook_show_messages_popup($current_user_id, $options) {

		if (isset($_GET['action']) && $_GET['action'] == 'read' && (is_user_logged_in() || is_super_admin())) {

			$sid = isset($_REQUEST['sid']) ? absint($_REQUEST['sid']) : 0;

			if (!$sid) { esc_html_e( 'Oops! Something went wrong.', 'datebook' ); return; }
			
			$open_profile_new_tab = $options['open_profile_new_tab'];
			$open_message_new_window = $options['open_message_new_window'];
			$my_favorites_page = $options['my_favorites_page'];
			$my_blacklist_page = $options['my_blacklist_page'];
			$show_name = $options['show_name'];
			$show_age = $options['show_age'];
			$show_gender = $options['show_gender'];
			$show_sexual_orientation = $options['show_sexual_orientation'];
			$show_city = $options['show_city'];
			$show_country = $options['show_country'];

			$profile_id = get_user_meta($current_user_id, 'profile_postid', true);
			$profile_data = get_post($profile_id);
			$profile_status = isset($profile_data->post_status) ? $profile_data->post_status : '';
			
			// Get Profile personal data
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			// 1. Check and notify the user to click the validation link
			$user_verified_email_array = DateBook_Utilities::check_if_email_verified($current_user_id);
			
			$emailhash = isset($user_verified_email_array['emailhash']) && $user_verified_email_array['emailhash'] != '' ? 1 : 0;

			// 2. Check a profile has a photo
			$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
			$profile_photo_id_parse = explode('/', $profile_photo_id);
			$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];

			$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;


			// Start session and insert user ID to database
			$session_instance = new DateBook_Session_Handler($current_user_id, $sid, 'datebook_security_chat', 0);

			$fetch_chatters = $session_instance->read_chatters();

			$allow_notsubscribed_users = of_get_option('allow_notsubscribed_users');
			$allow_notsubscribed_users = isset($allow_notsubscribed_users['3']) && $allow_notsubscribed_users['3'] == 1 ? 0 : 1;

			if (DateBook_Utilities::check_if_gateway_activated()) {

				$fetch_simultaneous_chatters = $session_instance->simultaneous_chatters();

				$enable_simultaneous_chatters = isset($fetch_simultaneous_chatters['enable_simultaneous_chatters']) && $fetch_simultaneous_chatters['enable_simultaneous_chatters'] == 1 ? 1 : 0;
				$simultaneous_chatters_quantity = $fetch_simultaneous_chatters['simultaneous_chatters'];

				$period_number_simultaneous_chatters = isset($fetch_simultaneous_chatters['period_number_simultaneous_chatters']) ? $fetch_simultaneous_chatters['period_number_simultaneous_chatters'] : 0;
				$period_simultaneous_chatters = isset($fetch_simultaneous_chatters['period_simultaneous_chatters']) ? $fetch_simultaneous_chatters['period_simultaneous_chatters'] : 0;

				$per_period = isset($period_number_simultaneous_chatters) && $period_number_simultaneous_chatters > 0 ? DateBook_Utilities::datebook_plural_text($period_number_simultaneous_chatters, $period_simultaneous_chatters) : esc_html__( 'unlimited', 'datebook' );

				$chatters_limit_message = sprintf(esc_html__( 'You may contact', 'datebook' ) . ' %d ' . esc_html__( 'users per', 'datebook' ) . ' %s', $fetch_simultaneous_chatters['simultaneous_chatters'], $per_period);

				$suggest_simultaneous_chatters = $fetch_simultaneous_chatters['suggest_simultaneous_chatters'];


				$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );
				$check_if_splan_selected = isset($member_subscriptions[0]->status) && ($member_subscriptions[0]->status == 'active' || $member_subscriptions[0]->status == 'completed') ? 1 : 0;

				$subscriptionplan_id = isset($member_subscriptions[0]->subscription_plan_id) ? $member_subscriptions[0]->subscription_plan_id : 0;

				$all_splans = get_option('datebook_subscription_plans');

				$points_for_one_message = isset($all_splans[$subscriptionplan_id]['points_for_one_message']) ? $all_splans[$subscriptionplan_id]['points_for_one_message'] : 0;

			} else {

				global $datebook_hourly_period;

				$simultaneous_chatters_quantity = of_get_option('simultaneous_chatters') > 0 ? of_get_option('simultaneous_chatters') : 1000000;

				$period_for_chatters = of_get_option('period_for_chatters') > 0 ? of_get_option('period_for_chatters') : '';

				$per_period = $datebook_hourly_period[$period_for_chatters];

				$check_if_splan_selected = 1;
				$allow_notsubscribed_users = 1;
				$enable_simultaneous_chatters = 1;

				$subscriptionplan_id = 0;
				$points_for_one_message = 0;

			}


			if($check_if_splan_selected == 1 && $allow_notsubscribed_users == 0){
				$allow_notsubscribed_users = 1;				
			}


			$chatters_limit_message = sprintf(esc_html__( 'You may contact', 'datebook' ) . ' %d ' . esc_html__( 'users per', 'datebook' ) . ' %s', $simultaneous_chatters_quantity, $per_period);


			if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'sendmessage' && absint($_REQUEST['sid']) > 0 && $enable_simultaneous_chatters == 1) {

				self::process_action_send_pm();

			}

			?><!DOCTYPE html>
			<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]-->
			<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" <?php language_attributes(); ?>> <![endif]-->
			<!--[if IE 8]> <html class="no-js lt-ie9" <?php language_attributes(); ?>> <![endif]-->
			<!--[if gt IE 8]><!--><html class="no-js" <?php language_attributes(); ?>><!--<![endif]-->
			<head>
			<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
			<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no" />
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			<meta name="HandheldFriendly" content="True" />

			<?php if ( get_theme_mod( 'datebook_favicon' ) != '' ) { ?>
				<link rel="shortcut icon" href="<?php echo esc_url( get_theme_mod( 'datebook_favicon' ) ); ?>" />
			<?php } else { ?>
				<link rel="shortcut icon" href="<?php echo esc_url(get_template_directory_uri() . '/assets/images/favicon.ico'); ?>" />
			<?php } ?>

			<?php wp_head(); ?>
			
			<style>
				html { margin-top: 0 !important }
				#wpadminbar { display:none }
			</style>
			
			</head>

			<body onload="datebook_all_chat_fuctions()" <?php echo body_class('datebook-chat-window bg-white'); ?>>

			<div class="datebook-wrapper">
			<div class="datebook-panel-messages">
			<div class="card border-0">
			<div id="datebook-chatpanel-sidebar no-gutters">
			<div id="datebook-messages-layout">
			
			<?php

			$chat_sidebar_bg_color = of_get_option('chat_sidebar_bg_color') ? of_get_option('chat_sidebar_bg_color') : 'rgb(33, 150, 243)';

			$chat_sidebar_layout_mobile = of_get_option('chat_sidebar_layout_mobile') ? of_get_option('chat_sidebar_layout_mobile') : 'top';

			$datebook_chatters_sidebar_top = $chat_sidebar_layout_mobile == 'top' ? 'datebook-chatters-sidebar-top' : 'datebook-chatters-sidebar-side';

			if($chat_sidebar_layout_mobile == 'sidebar'){

			?>

				<!-- Menu toggle -->
				<nav class="navbar navbar-dark shadow-none">

					<button id="datebook-menuLink" class="navbar-toggler black datebook-menu-link" type="button" data-toggle="collapse" data-target="#navbarTopContent" aria-controls="navbarTopContent" aria-expanded="false" aria-label="<?php esc_html_e( 'Menu', 'datebook' ); ?>"><span class="navbar-toggler-icon"></span></button>
				
					<ul class="navbar-nav ml-3 mr-auto">
						<li class="nav-item"><a href="<?php echo esc_url(get_permalink(of_get_option('my_messages_page'))); ?>" class="nav-link text-dark"><?php esc_html_e( 'Messages', 'datebook' ); ?></a></li>
					</ul>

				</nav>

			<?php } ?>

			<?php

			$fetch_chatters = $fetch_chatters ? maybe_unserialize($fetch_chatters) : array();

			//$fetch_chatters[$sid] = "value";

			$fetch_chatters_count = count($fetch_chatters) > 1 ? '' : 'datebook-hide ';

			$blacklists = get_user_meta( $current_user_id, 'blacklist', true);
			if (!empty($blacklists)) {
				$blacklists = array_unique(explode(',', $blacklists));
			} else {
				$blacklists = array();
			}

			$count_active_chatter = 0;

			?>
			
			<div id="datebook-messages-menu" class="datebook-messages-menu <?php echo esc_attr($fetch_chatters_count . $datebook_chatters_sidebar_top); ?>" style="background-color:<?php echo esc_attr($chat_sidebar_bg_color); ?>">

				<div id="datebook-chatters-sidebar" class="datebook-chatters-sidebar swiper-container">

					<ul class="list-inline bg-white m-0 p-2 small w-100 datebook-display-on-mobile">
						<li class="list-inline-item"><a href="<?php echo esc_url(get_permalink(of_get_option('my_messages_page')));?>"><?php echo esc_html__( 'Messages', 'datebook' );?></a></li>
					</ul>

					<div class="swiper-wrapper" style="background-color:<?php echo esc_attr($chat_sidebar_bg_color); ?>">

					<?php

					$my_messages_page = get_permalink(of_get_option('my_messages_page'));

					$chat_sidebar_details_show = $show_name == 1 ? '' : 'datebook-chat-profile-name-hide';

					foreach($fetch_chatters as $key => $value){

						$sender_user = get_userdata($key);
						$profile_qid = get_user_meta( $sender_user->ID, 'profile_postid', true);
						$post = get_post($profile_qid);

						if (!empty($post->ID) && $post->ID > 1) {
							
							//if (in_array($profile_qid, $blacklists)) continue;
					
							if(isset($value['active']) && $value['active'] == 1){
								$count_active_chatter++;
							}

							$name = isset($post->post_title) ? $post->post_title : '';
							$birthday = get_post_meta($post->ID, 'birthday', true);
							$age = !empty($birthday) ? floor((time() - strtotime($birthday))/31556926) : '';

							$gender = get_post_meta($post->ID, 'gender', true);
							
							$city_id = get_post_meta($post->ID, 'city', true);

							if(isset($city_id)){

								$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );
								$city = isset($term_data->city) ? $term_data->city : '';
								$country = isset($term_data->country) ? $term_data->country : '';

							}

							if ($gender == 1) {
								$icogender = 'fa fa-venus';
							} else if ($gender == 2) {
								$icogender = 'fa fa-mars';
							} else {
								$icogender = 'fa fa-user';
							}

							$online_time = get_user_meta( $sender_user->ID, 'online_status', true );

							$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($post->ID, 'image_mini', $gender, true);

							if($sid == $key){
								$chatter_selected = array('li' => ' white', 'a' => '', 'text' => 'text-grey');
							} else {
								$chatter_selected = array('li' => '', 'a' => ' datebook-chat-sidebar-color', 'text' => 'text-light');
							}

							$profile_chat_url = add_query_arg( array(
								'action' => 'read',
								'sid' => $sender_user->ID,
								'rid' => $current_user_id,
							), $my_messages_page );

							echo '<div id="datebook-messages-profile-box-' . absint($profile_qid) . '" class="p-0 ' . $chatter_selected['li'] . ' swiper-slide datebook-chat-profile datebook-ellipsis" style="background-color:' . esc_attr($chat_sidebar_bg_color) . '">';

							echo '<a ';

							if ($open_message_new_window == 1) {

								echo 'id="datebook-chatpopup '.$sender_user->ID.'" ';

							}

							echo 'class="d-block p-1 w-100 datebook-ellipsis datebook-chat-profile ' . $chatter_selected['a'] . '" href="' . esc_url($profile_chat_url) . '" style="display:contents"><img class="float-left rounded-circle" src="' . esc_url( $thumbnail_url['img_full_url'] ) . '" alt="" />';

							echo '<span class="badge badge-pill float-right orange d-none datebook-new-messages-count-sidebar">0</span>';

							if ($show_name == 1 || $show_age == 1 || $show_gender == 1) {

								$show_comma = 0;

								echo '<span class="ml-2 datebook-chat-profile-name ' . $chat_sidebar_details_show . '">';

								if ($show_name == 1) {
									echo esc_attr($name);
									$show_comma = 1;
								}

								if ($show_age == 1) {
									if ($show_comma > 0) {
										echo ' ';
									}
									echo '<span class="' . $chatter_selected['text'] . '">';
									echo esc_attr($age);
									echo '</span>';
									
									$show_comma = 1;
								}
								
								if ($show_gender == 1) {
									if ($show_comma > 0) {
										echo ' ';
									}
									echo '<i class="' . esc_attr($icogender) . '"></i>';
								}
								
								echo '</span>';
								
								echo '<br>';
							}
							
							

							echo '<span class="ml-2 small ' . $chatter_selected['text'] . ' ' . $chat_sidebar_details_show . '">';
							if ($show_city == 1 && isset($city)) {
								echo esc_attr($city);
							}
							if ($show_city == 1 && !empty($city) && $show_country == 1 && !empty($country)) {
								echo ', ';
							}
							if ($show_country == 1 && isset($country)) {
								echo esc_attr($country);
							}
							echo '</span>';

							echo '</a>';
							echo '</div>';

						}
					}

					?>

				</div>
				</div>
				</div>

				<div id="datebook-panelbody" class="card-body pt-0 p-0">

					<div class="datebook-chat">

						<?php if ($emailhash == 1) {
					
					$redirect_my_edit_profile_page = add_query_arg( array(
						'message' => 'mustverifyemail',
						'stop' => 1,
					), get_permalink(of_get_option('my_edit_profile_page')) );

					?>

					<div class="jumbotron shadow-none">
						<div class="jumbotron-contents text-center">

							<h1><?php esc_html_e( 'You must verify your email address', 'datebook' ); ?></h1>

							<hr>

							<p><?php esc_html_e( 'In order to send messages to other users you must verify your email address', 'datebook' ); ?></p>

							<p><a class="btn btn-primary" href="<?php echo esc_url($redirect_my_edit_profile_page); ?>" target="_blank"><?php esc_html_e( 'Go to the email page', 'datebook' ); ?></a></p>

						</div>
					</div>

					<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

					<?php } else if (of_get_option('user_must_upload_photo') == '1' && $profile_photo_id == '') { ?>

					<div class="jumbotron shadow-none">
						<div class="jumbotron-contents text-center">

							<h1><?php esc_html_e( 'You must upload a photo', 'datebook' ); ?></h1>

							<hr>

							<p><?php esc_html_e( 'In order to send messages to other users you must upload a photo', 'datebook' ); ?></p>

							<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_photos_page'))); ?>" target="_blank"><?php esc_html_e( 'Go to the photo page', 'datebook' ); ?></a></p>


						</div>
					</div>

					<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

					<?php
					
				} else if (of_get_option('user_must_complete_profile') == '1' && $profile_must_complete == 0) {

					?>

					<div class="jumbotron shadow-none">
						<div class="jumbotron-contents text-center">

							<h1><?php esc_html_e( 'You must complete your profile', 'datebook' ); ?></h1>

							<hr>

							<p><?php esc_html_e( 'In order to send messages to other users you must fill in the fields in your profile', 'datebook' ); ?></p>

							<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_edit_profile_page'))); ?>" target="_blank"><?php esc_html_e( 'Go to the profile page', 'datebook' ); ?></a></p>


						</div>
					</div>

					<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

					<?php

				} else if ($profile_status != 'publish') { ?>

					<div class="jumbotron shadow-none">
						<div class="jumbotron-contents text-center">

							<h1><?php esc_html_e( 'Your account is not active yet', 'datebook' ); ?></h1>

							<hr>

							<p><?php esc_html_e( 'Sorry! You can not communicate with other users, because your profile is not active.', 'datebook' ); ?></p>

						</div>
					</div>

					<div class="text-center"><?php do_action('datebook_copyright'); ?></div>
					
				<?php } else if ($check_if_splan_selected == 1 && $allow_notsubscribed_users == 1) {

					if ($enable_simultaneous_chatters == 1 && $sid != $current_user_id){

						if (((isset($fetch_chatters[$sid]['active']) && $fetch_chatters[$sid]['active'] == 1) || (isset($fetch_chatters[$sid]['active']) && $fetch_chatters[$sid]['active'] == 0 && isset($fetch_chatters[$sid]['chatter_new']) && $fetch_chatters[$sid]['chatter_new'] == 1))) {

							$sender_user = get_userdata($sid);
							$post = get_post(get_user_meta( $sender_user->ID, 'profile_postid', true ));

							if (of_get_option('contact_method') == '3' && of_get_option('chat_placement') == '1') {

								if (!empty($post->ID) && $post->ID > 1) {

									$chat_shortcode = str_replace('profile_id', $profile_id + $post->ID . '_' . $current_user_id + $sid . '_' . $profile_id + $current_user_id + $post->ID + $sid, of_get_option('chat_shortcode'));

									echo do_shortcode(wp_specialchars_decode(esc_html($chat_shortcode), ENT_QUOTES ));

								}

							} else {

								$allow_read_messages_if_points_over = of_get_option('points_system') == 1 && class_exists('myCRED_Core') ? (of_get_option('allow_read_messages_if_points_over') == 1 && mycred_get_users_balance($current_user_id) <= $points_for_one_message ? 1 : (mycred_get_users_balance($current_user_id) >= $points_for_one_message ? 1 : 0)) : 1;

								if ($allow_read_messages_if_points_over == 1) {
								
									echo '<div id="datebook-chat-header" class="bg-white shadow-sm datebook-chat-header atebook-modal-header">';
									echo '<div class="pt-2 pb-0 pl-2 pr-2 datebook-chat-profile atebook-chat-main-profile">';

									if (!empty($post->ID) && $post->ID > 1) {

										$name = isset($post->post_title) ? $post->post_title : '';
										$birthday = get_post_meta($post->ID, 'birthday', true);
										$age = floor((time() - strtotime($birthday))/31556926);

										$city_id = get_post_meta($post->ID, 'city', true);

										if(isset($city_id)){

											$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );
											$city = isset($term_data->city) ? $term_data->city : '';
											$country = isset($term_data->country) ? $term_data->country : '';

										}

										$gender = get_post_meta($post->ID, 'gender', true);

										if ($gender == 1) {
											$icogender = 'fa fa-venus';
										} else if ($gender == 2) {
											$icogender = 'fa fa-mars';
										} else {
											$icogender = 'fa fa-user';
										}

										$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($post->ID, 'image_mini', $gender, true);

										echo '<div class="datebook-chat-header-left">';
		
										echo '<a class="float-left mr-2 mb-1 datebook-hide-on-mobile" href="' . esc_url(get_permalink($post->ID)) . '" target="' . $open_profile_new_tab . '"><img class="rounded" src="' . esc_url( $thumbnail_url['img_full_url'] ) . '" alt="" /></a>';

										echo '<a class="float-left mr-2 datebook-display-on-mobile" href="' . esc_url(get_permalink($post->ID)) . '" target="_self"><img class="rounded" src="' . esc_url( $thumbnail_url['img_full_url'] ) . '" alt="" /></a>';

										echo '<h6 class="d-inline datebook-ellipsis m-0">

										<a class="datebook-hide-on-mobile" href="' . esc_url(get_permalink($post->ID)) . '" target="' . $open_profile_new_tab . '">'.esc_attr($name).'</a><a class="datebook-display-on-mobile" href="' . esc_url(get_permalink($post->ID)) . '" target="_self">'.esc_attr($name). '</a>';

										if ($show_age == 1) { echo ', <span class="small text-muted">' . esc_attr($age) . '</span>'; }
										if ($show_gender == 1) { echo ', <i class="' . esc_attr($icogender) . '"></i>'; }

										echo '</h6>';

										echo '<p>';

										do_action('datebook_online_status', $sender_user->ID, $gender, 1, 'full');

										echo '<span class="ml-1 small">';
										if ($show_city == 1 && isset($city)) {
											echo esc_attr($city);
										}
										if ($show_city == 1 && !empty($city) && $show_country == 1 && !empty($country)) {
											echo ', ';
										}
										if ($show_country == 1 && isset($country)) {
											echo esc_attr($country);
										}
										echo '</span>';

										echo '</p>';

										echo '</div>';

										echo '<div class="datebook-chat-header-right">';

										if (of_get_option('enable_blacklisted_profiles') == '1') {

											echo '<a class="btn btn-sm btn-light shadow-none p-0 pr-2 pl-2 float-right datebook-user-blocked" profile-id="' . absint($post->ID) . '" onClick="return false;" href="javascript:void(0)">' . esc_html__( 'Ignore', 'datebook' ) . '</a>';

										}

										if (of_get_option('points_system') == 1 && class_exists('myCRED_Core')) {

											echo '<span class="small p-1 mr-2 ml-2 float-right datebook-chat-points">';
											echo esc_html__('My points', 'datebook') .': <span class="datebook-chat-points-number">' . mycred_get_users_balance($current_user_id) . '</span>';
											echo '</span>';
										}

										echo '</div>';

										echo '<a href="javascript:void(0)" class="btn btn-sm blue-grey lighten-5 shadow-none p-1 pr-2 pl-2 datebook-show-button float-right">' . esc_html__( 'show more', 'datebook' ) . '</a>';

									}

									echo '</div>';
									echo '</div>';

									?>

									<div id="datebook-list-messages" class="p-2 datebook-chat-box datebook-chat-container atebook-modal-footer">

										<?php echo self::datebook_getallmessages($sid, $current_user_id); ?>

										<div class="mb-2 datebook-chat-text-width datebook-chat-r" style="background: none; display: none;"><span class="float-right ml-auto p-1 pr-2 pl-2 white"><?php esc_html_e( 'Image uploading', 'datebook' ); ?> <span class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></span></span></div>

										<div id="datebook-loader" class="float-right ml-auto text-right" style="background: none; display: none;"><span class="float-right ml-auto p-1 pr-2 pl-2 white"><?php esc_html_e( 'Image uploading', 'datebook' ); ?> <span class="spinner-border spinner-border-sm ml-3" role="status" aria-hidden="true"></span></span></div>

										<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" style="display:none">
											<div class="slides"></div>
											<h3 class="title"></h3>
											<a class="prev">‹</a>
											<a class="next">›</a>
											<a class="close">×</a>
											<a class="play-pause"></a>
											<ol class="indicator"></ol>
										</div>

									</div>

									<div id="datebook-chat-footer" class="datebook-chat-footer">
										<?php if (of_get_option('points_system') == 1 && class_exists('myCRED_Core') && mycred_get_users_balance($current_user_id) < $points_for_one_message) { ?>

										<div class="alert alert-warning m-0">

											<h6><?php esc_html_e( 'You do not have enough points to send messages!', 'datebook' ); ?></h6>
											<p class="small m-0 p-0"><?php esc_html_e( 'You can buy more points and keep chatting.', 'datebook' ); ?> <a class="btn btn-sm btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_upgrade_page'))); ?>" target="_blank"><?php esc_html_e( 'Buy more points', 'datebook' ); ?></a></p>
											
										</div>

									<?php } else if (!is_super_admin() || (is_super_admin() && of_get_option('allow_admin_write_inchat') == 1)) {

										$enable_emoji_in_private_chat = of_get_option('enable_emoji_in_private_chat');

										$emoji_icons = $enable_emoji_in_private_chat == 1 && of_get_option('emoji_icons') ? json_decode(base64_decode(of_get_option('emoji_icons'))) : '';

										$enable_image_upload_in_private_chat = of_get_option('enable_image_upload_in_private_chat');

										$chat_form_url = add_query_arg( array(
											'action' => 'read',
											'sid' => $sid,
											'rid' => $current_user_id,
										), get_permalink(of_get_option('my_messages_page')) );

										?>

										<form name="datebook-message-forms" class="w-100 p-2 datebook-message-form" method="post" action="<?php echo esc_url($chat_form_url);?>">
											<input id="datebook-chat-sid" type="hidden" name="sid" value="<?php echo absint($sid); ?>" />
											<input type="hidden" name="action" value="sendmessage" />
											<input type="hidden" name="datebook_image_upload" value="upload" />

											<?php

											if ($emoji_icons) {

												$datebook_emoji_list = DateBook_Utilities::detect_emoji_symbols($emoji_icons);

												?>

												<div class="white card-body p-0 shadow-none datebook-chat-emoji-icons collapse" id="datebookemojicollapse">
													<?php echo wp_specialchars_decode(esc_html($datebook_emoji_list), ENT_QUOTES ); ?>
												</div>
	
											<?php } ?>
	
											<div class="input-group datebook-chat-message-box">
	
												<textarea name="pmessage" id="datebook-messagebox" class="form-control" aria-label="Enter" aria-describedby="button-addon1"></textarea>

												<div class="input-group-append" id="button-addon1">

												<?php if ($emoji_icons) { ?>

													<button class="btn btn-md m-0 px-2 py-2 z-depth-0 datebook-chat-button-emoji-icon" type="button" data-toggle="collapse" data-target="#datebookemojicollapse" aria-expanded="true" aria-controls="datebookemojicollapse"><i class="far fa-smile fa-2x"></i></button>

												<?php } ?>

												<?php if ($enable_image_upload_in_private_chat == 1) { ?>

													<label for="datebook-select-file" class="btn btn-md m-0 px-2 py-2 z-depth-0 datebook-chat-button-clip-icon"><i class="far fa-image fa-2x"></i> <input id="datebook-select-file" type="file" name="file" hidden></label>

												<?php } ?>

													<button onClick="return false;" type="submit" name="submit" class="btn btn-primary m-0 ml-1 px-3 py-2 z-depth-0 waves-effect datebook-chat-submit"><i class="fas fa-paper-plane fa-lg"></i></button>

												</div>
											</div>
										</form>

									<?php } else if (is_super_admin()) { ?>

										<div class="alert alert-warning m-0">

											<?php esc_html_e( 'You are logged in as Administrator. The chat form has been disabled so that you cannot accidentally send a message on behalf of the user.', 'datebook' ); ?>
											<hr>
											<?php esc_html_e( 'You can activate this option here', 'datebook' ); ?>: <em>WordPress -> DateBook -> Dashboard -> Chat and Messages -> Allow Administrator write messages in chat window</em>

										</div>

									<?php } ?>

									</div>

								<?php } else { ?>

									<div class="jumbotron shadow-none">
										<div class="jumbotron-contents text-center">

											<h1><?php esc_html_e( 'All points are finished or not enough to send messages!', 'datebook' ); ?></h1>
											<p class="small"><?php esc_html_e( 'You have spent all your points. You can buy more points and keep chatting.', 'datebook' ); ?></p>
											<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_upgrade_page'))); ?>" target="_blank"><?php esc_html_e( 'Buy more points', 'datebook' ); ?></a></p>

										</div>
									</div>

								<?php

								}
							}

						} else { ?>

							<div class="jumbotron shadow-none">
								<div class="jumbotron-contents text-center">

									<h1><?php esc_html_e( 'You have reached the limit', 'datebook' ); ?></h1>

									<p><?php echo esc_attr($chatters_limit_message); ?></p>

									<?php if (isset($suggest_simultaneous_chatters) && $suggest_simultaneous_chatters == 1) { ?>

										<hr>

										<p><?php esc_html_e( 'You may get another subscription plan that has no limit', 'datebook' ); ?></p>

										<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_upgrade_page'))); ?>" target="_blank"><?php esc_html_e( 'Upgrade', 'datebook' ); ?></a></p>

									<?php } ?>

								</div>
							</div>
	
							<div class="text-center"><?php do_action('datebook_copyright'); ?></div>
						
						<?php } ?>

					<?php } else if ($enable_simultaneous_chatters == 0 && $sid != $current_user_id && $count_active_chatter <= $simultaneous_chatters_quantity) { ?>

						<div class="jumbotron shadow-none">
							<div class="jumbotron-contents text-center">

								<h1><?php esc_html_e( 'You may not send messages', 'datebook' ); ?></h1>

									<p><?php esc_html_e( 'The subscription plan does not include the posibility to send message to other users', 'datebook' ); ?></p>
									
									<hr>

									<p><?php esc_html_e( 'You may get another subscription plan that has no limit', 'datebook' ); ?></p>

									<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_upgrade_page'))); ?>" target="_blank"><?php esc_html_e( 'Select another subscription plan', 'datebook' ); ?></a></p>

							</div>
						</div>

						<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

					<?php } else { ?>

						<div class="jumbotron shadow-none">
							<div class="jumbotron-contents text-center">
								<h1><?php esc_html_e( 'You are trying to write messages to yourself!', 'datebook' ); ?></h1>
								<h2><?php esc_html_e( 'Sorry! This action is not allowed.', 'datebook' ); ?></h2>

								<?php if (is_super_admin()) { ?>

									<h4><?php esc_html_e( 'You are logged in as Administrator', 'datebook' ); ?></h4>

								<?php } ?>

							</div>
						</div>

						<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

					<?php } ?>
				
				<?php } else { ?>

					<div class="jumbotron shadow-none">
						<div class="jumbotron-contents text-center">

							<h1><?php esc_html_e( 'You must select a subscription plan', 'datebook' ); ?></h1>

							<hr>

							<p><?php esc_html_e( 'In order to send messages to other users you must select a subscription plan', 'datebook' ); ?></p>

							<p><a class="btn btn-primary" href="<?php echo esc_url(get_permalink(of_get_option('my_upgrade_page'))); ?>" target="_blank"><?php esc_html_e( 'Select a subscription plan', 'datebook' ); ?></a></p>


						</div>
					</div>

					<div class="text-center"><?php do_action('datebook_copyright'); ?></div>

				<?php } ?>
			
				</div>

			</div>
			</div>
			</div>
			</div>
			</div>
			</div>

			<?php wp_footer(); ?>

			</body>
			</html>
			
			<?php 

			die();

		}

	}


	/**
	 * Get all options
	 *
	 * @access public
	 * @return void
	 */
	public static function get_all_options($page_or_popup, $page_id, $what_message_text = '') {

		$page_id = isset($page_id) && $page_id > 0 ? $page_id : get_the_ID();

		$mobile_detect = DateBook_Utilities::mobile_detect() == 'mobile' ? 1 : 0;

		$open_profile_new_tab = of_get_option('open_profile_new_tab') ? ($mobile_detect == 1 ? '_self' : '_blank') : '_self';
		$open_message_new_window = of_get_option('open_message_new_window') ? ($mobile_detect == 1 ? 0 : 1) : 0;

		$my_favorites_page = $page_id == of_get_option('my_favorites_page') ? 1 : 0;
		$my_blacklist_page = $page_id == of_get_option('my_blacklist_page') ? 1 : 0;

		$show_profile_details = $page_or_popup == 'page' ? of_get_option( 'show_profile_details_on_messages' ) : of_get_option('show_profile_details_on_chat_sidebar');

		$show_name = isset($show_profile_details['name']) && $show_profile_details['name'] == 1 ? 1 : 0;
		$show_age = isset($show_profile_details['age']) && $show_profile_details['age'] == 1 && DateBook_Utilities::datebook_show_field('birthdate', 1) ? 1 : 0;
		$show_gender = isset($show_profile_details['gender']) && $show_profile_details['gender'] == 1 && DateBook_Utilities::datebook_show_field('gender', 1) && (of_get_option('gender_allowed') != '' || of_get_option('gender_allowed_other_' . DATEBOOK_WPLANG) != '') ? 1 : 0;
		$show_sexual_orientation = isset($show_profile_details['sexorientation']) && $show_profile_details['sexorientation'] == 1 && DateBook_Utilities::datebook_show_field('sexualorientation', 1) && (of_get_option('sexual_orientation_allowed') != '' || of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG) != '') ? 1 : 0;
		$show_city = isset($show_profile_details['city']) && $show_profile_details['city'] == 1 && DateBook_Utilities::datebook_show_field('countrycity', 1) ? 1 : 0;
		$show_country = isset($show_profile_details['country']) && $show_profile_details['country'] == 1 && DateBook_Utilities::datebook_show_field('countrycity', 1) ? 1 : 0;

		$options = array(
			'open_profile_new_tab' => $open_profile_new_tab,
			'open_message_new_window' => $open_message_new_window,
			'what_message_text' => $what_message_text,
			'my_favorites_page' => $my_favorites_page,
			'my_blacklist_page' => $my_blacklist_page,
			'show_name' => $show_name,
			'show_age' => $show_age,
			'show_gender' => $show_gender,
			'show_sexual_orientation' => $show_sexual_orientation,
			'show_city' => $show_city,
			'show_country' => $show_country,
		);

		return $options;

	}


	/**
	 * Show messages popup Chat window (ajax)
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_action_read(){

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'datebook_message_actions') {

			if (isset($_REQUEST['whatisit'])){
				if ($_REQUEST['whatisit'] == 'chatsubmit' || $_REQUEST['whatisit'] == 'chatupdate' || $_REQUEST['whatisit'] == 'chatfileupload' || $_REQUEST['whatisit'] == 'checknewmessages' || $_REQUEST['whatisit'] == 'addblacklist'){

					// update all the input data
					add_action( 'wp_loaded', self::datebook_ajax_update_chat($current_user_id) );

				} else if ($_REQUEST['whatisit'] == 'deletemessages' || $_REQUEST['whatisit'] == 'favoriteset' || $_REQUEST['whatisit'] == 'blacklistset' || $_REQUEST['whatisit'] == 'addblacklist'){

					// update add fevorite
					add_action( 'wp_loaded', self::datebook_delete_message($current_user_id) );

				}
			}

		} else {
			
			if (isset($_GET['action']) && $_GET['action'] == 'read' && (is_user_logged_in() || is_super_admin())) {

				//add_action( 'wp_footer', self::datebook_messages_ajax_scripts() );
				
				$page_id = get_the_ID();
				
				$options = self::get_all_options('popup', $page_id);

				self::datebook_show_messages_popup($current_user_id, $options);

			}
		}
	}


	/**
	 * Initialise functions
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_profile_messages() {

		$page_id = get_the_ID();

		echo '<div class="datebook-custom-card card">';
		echo '<div class="card-body">';

		if (isset($_GET['action']) && $_GET['action'] == 'read') {
			$action = 'read';
			$what_message_text = '';
		} else if ($page_id == of_get_option('my_favorites_page')) {
			$action = 'favorites';
			$what_message_text = esc_html__( 'List of profiles you have favorited', 'datebook' );
			echo '<h2>'.esc_html__( 'My favorites', 'datebook' ).'</h2>';
		} else if ($page_id == of_get_option('my_blacklist_page')) {
			$action = "blacklist";
			$what_message_text = esc_html__( 'List of profiles you have blocked', 'datebook' );
			echo '<h2>'.esc_html__( 'My blacklist', 'datebook' ).'</h2>';
		} else if ($page_id == of_get_option('my_messages_page')) {
			$action = '';
			$what_message_text = esc_html__( 'List of your contacts', 'datebook' );
			echo '<h2>'.esc_html__( 'My messages', 'datebook' ).'</h2>';
		} else {
			$action = '';
			$what_message_text = esc_html__( 'List of your contacts', 'datebook' );
			echo '<h2>'.esc_html__( 'My messages', 'datebook' ).'</h2>';
		}

		echo '<hr />';

		$options = self::get_all_options('page', $page_id, $what_message_text);

		switch($action) {
			case 'read': self::datebook_action_read(); break;
			case 'favorites': self::datebook_action_favorites($options); break;
			case 'blacklist': self::datebook_action_blacklist($options); break;
			default: self::datebook_action_received($options); break;
		}

		echo '</div>';
		echo '</div>';

	}


}

DateBook_Profile_Messages::init();