<?php

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


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

	private static $datebook_options = null;

    public function __construct($datebook_options_array) {

		self::$datebook_options = $datebook_options_array;

		self::init();

	}

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

		// Load cron function at the beginning before any proccess
		add_action( 'init', array( __CLASS__, 'datebook_start_cron') );

	}

	// Cron functions

	/**
	 * Search for users who did not verify their emails and delete them
	 *
	 * @access private
	 * @return void
	 */
	public static function check_unverified_emails() {
		
		$user_must_validate_email = isset(self::$datebook_options['user_must_validate_email']) ? (self::$datebook_options['user_must_validate_email'] == 1 ? 1 : 0) : (of_get_option('enable_simulation_online') ? 1 : 0);

		if ($user_must_validate_email == 1) {

			$time = get_option('datebook_time_check_unverified');

			if (!isset($time) || $time < time()) {

				$check_notvalidate_email_days = isset(self::$datebook_options['check_notvalidate_email_days']) ? (self::$datebook_options['check_notvalidate_email_days'] > 0 ? self::$datebook_options['check_notvalidate_email_days'] : 1) : (of_get_option('check_notvalidate_email_days') > 0 ? of_get_option('check_notvalidate_email_days') : 1);

				// Check every at least 1 day for users who did not validate their emails
				update_option('datebook_time_check_unverified', strtotime("+" . $check_notvalidate_email_days . " days"));

				$validate_email_days = isset(self::$datebook_options['validate_email_days']) ? (self::$datebook_options['validate_email_days'] > 0 ? self::$datebook_options['validate_email_days'] : 0) : (of_get_option('validate_email_days') > 0 ? of_get_option('validate_email_days') : 0);

				if ($validate_email_days > 0) {

					global $wpdb;

					$users = $wpdb->get_col("SELECT `user_id` FROM `$wpdb->usermeta` WHERE `meta_key` = 'emailhash'");

					if (count($users) > 0) {

						foreach ($users as $user_id) {

							// Check if user with email hash found
							if(isset($user_id) && $user_id > 0) {

								$user_info = get_userdata($user_id);

								// Check if user exists in database
								if(isset($user_info->ID) && $user_info->ID > 0) {

									$user_id = $user_info->ID;
									$to_email = isset($user_info->user_email) ? $user_info->user_email : '';
									$user_registered = isset($user_info->user_registered) ? strtotime($user_info->user_registered) : 0;

									$profile_postid = get_user_meta( $user_id, 'profile_postid', true );
									$profile = get_post($profile_postid);
									$profile_id = isset($profile->ID) && $profile->ID > 0 ? $profile->ID : 0;
									$profile_name = isset($profile->post_title) ? $profile->post_title : '';

									if($profile_id > 0) {

										// Delete profile after xx days
										if ($user_registered < strtotime("-" . $validate_email_days . " day")) {

											DateBook_Utilities::final_delete_profile($profile_id, $user_id);

											// Remove a user from the repeated notification list
											$send_notification_again_users_array = get_option('datebook_send_notification_again_users');

											if (is_array($send_notification_again_users_array) && ($key = array_search($user_id, $send_notification_again_users_array)) !== false) {
												unset($send_notification_again_users_array[$key]);
											}

											update_option('datebook_send_notification_again_users', $send_notification_again_users_array);

										} else {

											// Send notification email 2 days in advance before final deletion
											$enable_notification_verify_email_again = isset(self::$datebook_options['enable_notification_verify_email_again']) ? (self::$datebook_options['enable_notification_verify_email_again'] == 1 ? 1 : 0) : (of_get_option('enable_notification_verify_email_again') ? 1 : 0);

											if ($enable_notification_verify_email_again == 1) {

												$send_notification_again_days = isset(self::$datebook_options['send_notification_again_days']) ? (self::$datebook_options['send_notification_again_days'] >= 0 ? self::$datebook_options['send_notification_again_days'] : 1) : (of_get_option('send_notification_again_days') >= 0 ? of_get_option('send_notification_again_days') : 1);

												$datebook_send_notification_again_users = get_option('datebook_send_notification_again_users') ? get_option('datebook_send_notification_again_users') : array();

												$next_day = strtotime("+" . $send_notification_again_days . " days", $user_registered);

												if ($user_registered > $next_day && !isset($datebook_send_notification_again_users[$user_id])) {

													// Check and notify the user to click the validation link
													$email_emailhash = get_user_meta( $user_id, 'emailhash', true );

													$profile_get_permalink = get_permalink($profile_id);

													$emailhashkey = add_query_arg( array(
														'verifyemail' => $email_emailhash
													), $profile_get_permalink );
													
													$select_email_template = 'activation_link_to_profile';

													include DateBook_Template_Loader::locate( 'misc/email-templates' );

													$subject_in_email = esc_html__( 'Verify your email address (notification)', 'datebook' );

													$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $to_email, $subject_in_email, $body);

													// Add a user to the sent list
													$datebook_send_notification_again_users[$user_id] = 1;
													update_option('datebook_send_notification_again_users', $datebook_send_notification_again_users);

												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}


	/**
	 * Check who deleted their accounts
	 *
	 * @access private
	 * @return void
	 */
	public static function check_deleted_profiles_by_privacy() {

		$allow_delete_account = isset(self::$datebook_options['allow_delete_account']) ? (self::$datebook_options['allow_delete_account'] == 1 ? 1 : 0) : (of_get_option('allow_delete_account') ? 1 : 0);

		if ($allow_delete_account == 1) {

			$time = get_option('datebook_time_deleted_profiles');

			if (!isset($time) || $time < time()) {

				global $wpdb;

				$delete_profile_days = 1;

				if($delete_profile_days > 0){

					// Check every at least 1 day for profiles set to be deleted
					update_option('datebook_time_deleted_profiles', strtotime("+" . $delete_profile_days . " day 5:00:00"));

					$datebook_profiles_set_deleted = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM `" . $wpdb->postmeta . "` WHERE `meta_key` = 'delete_profile_days' AND `meta_value` < %d", time()));

					if (count($datebook_profiles_set_deleted) > 0) {

						foreach ($datebook_profiles_set_deleted as $profile_id) {

							DateBook_Utilities::final_delete_profile($profile_id);

						}
					}
				}
			}
		}
	}


	/**
	 * Imitate the online status of profiles as if users are logged in
	 *
	 * @access private
	 * @return void
	 */
	public static function simulate_online_status_of_profiles() {

		$find_this_email = 'website.com';

		// Simulate Online status
		$enable_simulation_online = isset(self::$datebook_options['enable_simulation_online']) && !empty(self::$datebook_options['enable_simulation_online']) ? (self::$datebook_options['enable_simulation_online'] == 1 ? 1 : 0) : (of_get_option('enable_simulation_online') ? 1 : 0);

		if ($enable_simulation_online == 1) {
			
			$get_simulation_online_update = get_option('simulation_online_update');

			if (!isset($get_simulation_online_update) || $get_simulation_online_update < time()) {

				$simulation_online_update = isset(self::$datebook_options['simulation_online_update']) ? (self::$datebook_options['simulation_online_update'] > 0 ? self::$datebook_options['simulation_online_update'] : 10) : (of_get_option('simulation_online_update') > 0 ? of_get_option('simulation_online_update') : 10);

				// Check every at least 1 day for profiles set to be deleted
				update_option('simulation_online_update', strtotime("+{$simulation_online_update} minutes"));

				$simulation_online_min_time = isset(self::$datebook_options['simulation_online_min_time']) ? (self::$datebook_options['simulation_online_min_time'] >= 0 ? self::$datebook_options['simulation_online_min_time'] : 0) : (of_get_option('simulation_online_min_time') >= 0 ? of_get_option('simulation_online_min_time') : 0);

				$simulation_online_max_time = isset(self::$datebook_options['simulation_online_max_time']) ? (self::$datebook_options['simulation_online_max_time'] >= 0 ? self::$datebook_options['simulation_online_max_time'] : 20) : (of_get_option('simulation_online_max_time') >= 0 ? of_get_option('simulation_online_max_time') : 20);

				$profileusers = get_users( 'role=subscriber' );

				foreach($profileusers as $user) {

					$user_id = $user->ID;
					
					$user_email = $user->user_email;
					
					if(preg_match("~\b{$find_this_email}\b~", $user_email)){
						
						$online_status_minutes = rand($simulation_online_min_time, $simulation_online_max_time);

						$online_status = strtotime("+{$online_status_minutes} minutes");

						update_user_meta($user_id, 'online_status', $online_status);

					}
				}
			}
		}
		
		
		// Simulate Views of profile
		$enable_simulation_views = isset(self::$datebook_options['enable_simulation_views']) ? (self::$datebook_options['enable_simulation_views'] == 1 ? 1 : 0) : (of_get_option('enable_simulation_views') ? 1 : 0);

		if ($enable_simulation_views == 1) {

			$get_simulation_views_update = get_option('simulation_views_update');

			if (!isset($get_simulation_views_update) || $get_simulation_views_update < time()) {

				$simulation_views_update = isset(self::$datebook_options['simulation_views_update']) ? (self::$datebook_options['simulation_views_update'] > 0 ? self::$datebook_options['simulation_views_update'] : 10) : (of_get_option('simulation_views_update') > 0 ? of_get_option('simulation_views_update') : 10);

				// Check every at least 1 day for profiles set to be deleted
				update_option('simulation_views_update', strtotime("+{$simulation_views_update} minutes"));

				$simulation_views_min = isset(self::$datebook_options['simulation_views_min']) ? (self::$datebook_options['simulation_views_min'] >= 0 ? self::$datebook_options['simulation_views_min'] : 0) : (of_get_option('simulation_views_min') >= 0 ? of_get_option('simulation_views_min') : 0);

				$simulation_views_max = isset(self::$datebook_options['simulation_views_max']) ? (self::$datebook_options['simulation_views_max'] >= 0 ? self::$datebook_options['simulation_views_max'] : 5) : (of_get_option('simulation_views_max') >= 0 ? of_get_option('simulation_views_max') : 5);

				$all_profiles_args = array(
					'post_type'  => DATEBOOK_POST_TYPE,
					'post_status' => 'publish',
					'posts_per_page' => -1,
				);

				$all_profiles = new WP_Query($all_profiles_args);

				if ( $all_profiles->have_posts()) :

					while ( $all_profiles->have_posts() ) : $all_profiles->the_post();

						$profile_id = get_the_ID();
						
						$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
						$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

						$simulation_views_quantity = rand($simulation_views_min, $simulation_views_max);

						//Alter the options array appropriately
						$simulation_execute = DateBook_Profile_Views::datebook_get_post_views($profile_id, $datebook_get_data, $simulation_views_quantity, 1);

					endwhile;

				endif;

				wp_reset_postdata();

			}
		}


		// Simulate chat
		$enable_simulation_chat = isset(self::$datebook_options['enable_simulation_chat']) && !empty(self::$datebook_options['enable_simulation_chat']) ? (self::$datebook_options['enable_simulation_chat'] == 1 ? 1 : 0) : (of_get_option('enable_simulation_chat') ? 1 : 0);

		if ($enable_simulation_chat == 1) {

			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);
			}

			$simulation_chat = get_user_meta( $current_user_id, 'simulation_chat', true );

			$stop_chat = isset($simulation_chat['stop_chat']) && $simulation_chat['stop_chat'] == 1 ? 1 : 0;

			if($stop_chat == 0){

				$profile_postid = get_user_meta( $current_user_id, 'profile_postid', true );
				$profile = get_post($profile_postid);

				if(isset($profile->ID) && $profile->ID > 0 && $profile->post_status == 'publish') {

					$current_time = time();

					$simulation_chat_min = isset(self::$datebook_options['simulation_chat_min']) ? (self::$datebook_options['simulation_chat_min'] >= 0 ? self::$datebook_options['simulation_chat_min'] : 2) : (of_get_option('simulation_chat_min') >= 0 ? of_get_option('simulation_chat_min') : 2);

					$simulation_chat_max = isset(self::$datebook_options['simulation_chat_max']) ? (self::$datebook_options['simulation_chat_max'] >= 0 ? self::$datebook_options['simulation_chat_max'] : 8) : (of_get_option('simulation_chat_max') >= 0 ? of_get_option('simulation_chat_max') : 8);

					$online_status_minutes = rand($simulation_chat_min, $simulation_chat_max) * 60;

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

					$online_time = $online_time > 0 ? $online_time + $online_status_minutes : 0;

					$publish_time = strtotime($profile->post_date) > 0 ? strtotime($profile->post_date) + $online_status_minutes : 0;

					if(!empty($online_time) && $online_time >= 0 && $online_time > $current_time && !empty($publish_time) && $publish_time >= 0 && $publish_time < $current_time){

						$next_time = isset($simulation_chat['next_time']) && $simulation_chat['next_time'] > 0 ? $simulation_chat['next_time'] : 0; // time()
						$next_message = isset($simulation_chat['next_message']) && $simulation_chat['next_message'] > 0 ? $simulation_chat['next_message'] : 0; // 0 or 1

						$all_simulation_chat_messages = isset(self::$datebook_options['simulation_chat_messages_' . DATEBOOK_WPLANG]) && !empty(self::$datebook_options['simulation_chat_messages_' . DATEBOOK_WPLANG]) ? self::$datebook_options['simulation_chat_messages_' . DATEBOOK_WPLANG] : (of_get_option('simulation_chat_messages_' . DATEBOOK_WPLANG) && !empty(of_get_option('simulation_chat_messages_' . DATEBOOK_WPLANG)) ? of_get_option('simulation_chat_messages_' . DATEBOOK_WPLANG) : '');

						$chat_messages_lines = explode('<br />', strtr($all_simulation_chat_messages, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')));

						$chat_phrases_array = isset($chat_messages_lines[$next_message]) ? explode('|', $chat_messages_lines[$next_message]) : array();

						$count_chat_phrases = is_array($chat_phrases_array) && count($chat_phrases_array) > 0 ? $chat_phrases_array : 0;

						$simulation_chat_message = $count_chat_phrases > 0 ? $chat_phrases_array[rand(0, (sizeof($chat_phrases_array) -1 ))] : '';

						if($next_time > 0 && $next_message > 0){

							$stop_chat = isset($simulation_chat_message) && !empty($simulation_chat_message) ? 0 : 1;
							
							$user_id = isset($simulation_chat['user_id']) && $simulation_chat['user_id'] > 0 ? $simulation_chat['user_id'] : 0;
							$profile_id = isset($simulation_chat['profile_id']) && $simulation_chat['profile_id'] > 0 ? $simulation_chat['profile_id'] : 0;

							if($next_time + rand(20, 240) < $current_time && isset($simulation_chat_message) && !empty($simulation_chat_message)){

								DateBook_Profile_Messages::process_action_send_pm($simulate = 1, $user_id, $simulation_chat_message);

							}

							$simulation_chat = array(
								'user_id' => $user_id,
								'profile_id' => $user_id,
								'next_time' => time(),
								'next_message' => $next_message + 1,
								'stop_chat' => $stop_chat
							);

							update_user_meta($current_user_id, 'simulation_chat', $simulation_chat);

						} else if($next_time == 0 && $next_message == 0){

							$users = $wpdb->get_results($wpdb->prepare("SELECT `user_id`, `meta_value` FROM `$wpdb->usermeta` WHERE `meta_key` = 'online_status' AND `meta_value` > %d", time()));

							if (count($users) > 0) {

								foreach ($users as $user) {

									// Check if user with email hash found
									if(isset($user->user_id) && $user->user_id > 0) {

										if($user->user_id == $current_user_id) continue;
									
										$user_info = get_userdata($user->user_id);

										// Check if user exists in database
										if(isset($user_info->ID) && $user_info->ID > 0) {

											$user_id = $user_info->ID;
											$user_email = isset($user_info->user_email) ? $user_info->user_email : '';

											if(preg_match("~\b{$find_this_email}\b~", $user_email)){

												$profile_user_id = get_user_meta( $user_id, 'profile_postid', true );
												$profile_user = get_post($profile_user_id);

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

													DateBook_Profile_Messages::process_action_send_pm($simulate = 1, $user_id, $simulation_chat_message);

													$simulation_chat = array(
														'user_id' => $user_id,
														'profile_id' => $profile_user->ID,
														'next_time' => time(),
														'next_message' => 1,
														'stop_chat' => 0
													);

													update_user_meta($current_user_id, 'simulation_chat', $simulation_chat);

													break;
													
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}


	/**
	 * Session schedule
	 *
	 */
	public static function datebook_sessions_activation(){
		$args = array( false );
		if (!wp_next_scheduled( 'datebook_sessions_gc', $args)){
			wp_schedule_event( time(), 'hourly', 'datebook_sessions_gc', $args );
		}
	}


	/**
	 * Deactivate Session schedule
	 *
	 */
	public static function datebook_sessions_deactivation() {
		wp_clear_scheduled_hook('datebook_sessions_gc');
	}


	/**
	 * Cron-powered garbage collection.
	 */
	public static function cron_gc($current_user_id) {

		// Make global    
		global $wpdb, $time_in_seconds_array;

		$current_user_id = defined('DATEBOOK_CURRENT_USER_ID') ? DATEBOOK_CURRENT_USER_ID : $current_user_id;

		$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($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 = isset(self::$datebook_options['period_for_chatters']) ? (self::$datebook_options['period_for_chatters'] > 0 ? self::$datebook_options['period_for_chatters'] : 0) : (of_get_option('period_for_chatters') > 0 ? of_get_option('period_for_chatters') : 0);
			
			$period_for_chatters = time() + 60 * 60 * $period_for_chatters;

		}

		$last_login_date = get_user_meta($current_user_id, 'last_login', true);
		$last_login_date = strtotime($last_login_date);
		$login_date = $last_login_date + $period_for_chatters;

		if($login_date > time()){

			$current_user_md5_id = md5($current_user_id.'datebook_security_chat');

			$table_sessions = strtolower($wpdb->prefix) . 'datebook_sessions';

			// the table to be used by the class
			$wpdb->query($wpdb->prepare("DELETE FROM " . $table_sessions . " WHERE id = %s AND timestamp < %d;", $current_user_md5_id, $period_for_chatters));

		}

	}


	/**
	 * Set our custom time to send notifications
	 *
	 */
	public static function datebook_notification_custom_time( $schedules ) {

		$notification_time = isset(self::$datebook_options['notification_about_new_message']) ? (self::$datebook_options['notification_about_new_message'] > 0 ? self::$datebook_options['notification_about_new_message'] : 5) : (of_get_option('notification_about_new_message') > 0 ? of_get_option('notification_about_new_message') : 5);

		// Hook into that action that'll fire every six hours
		$schedules['notification_cron_time_' . $notification_time] = array(
			'interval' => $notification_time * MINUTE_IN_SECONDS,
			'display'  => 'Every ' . $notification_time . ' minutes'
		);
	    return $schedules;
	}


	/**
	 * Notification schedule
	 *
	 */
	public static function datebook_notification_activation() {
		if(!wp_next_scheduled('datebook_notification_cron_hook')){

			$notification_time = isset(self::$datebook_options['notification_about_new_message']) ? (self::$datebook_options['notification_about_new_message'] > 0 ? self::$datebook_options['notification_about_new_message'] : 5) : (of_get_option('notification_about_new_message') > 0 ? of_get_option('notification_about_new_message') : 5);

			$get_cron = get_option('datebook_cron');

			if (isset($get_cron['notification_about_new_message']) && $get_cron['notification_about_new_message'] == $notification_time){
			
				wp_schedule_event(time(), 'notification_cron_time_' . $notification_time, 'datebook_notification_cron_hook');

			} else {

				self::datebook_notification_deactivation();
				
				$notification_cron = array('notification_about_new_message' => $notification_time);
				
				update_option( 'datebook_cron', $notification_cron );

			}
		}
	}


	/**
	 * Deactivate Notification schedule
	 *
	 */
	public static function datebook_notification_deactivation() {
		wp_clear_scheduled_hook('datebook_notification_cron_hook');
	}


	/**
	 * Cron: Notification email about new message
	 * 
	 * @since 3.7
	 * @access public
	 */
	public static function notification_about_new_message() {

		global $wpdb;

		$table_private_messages = strtolower($wpdb->prefix) . 'datebook_private_messages';
		$check_private_messages = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_private_messages));

		if($table_private_messages == $check_private_messages) {

			$group_messages = $wpdb->get_results("SELECT id, senderid, rcpid, message, chat_mode FROM " . $table_private_messages . " WHERE tosee = 0 AND todelete = 0 AND status = 0 AND notified = 0");

			if ($group_messages) {

				$all_messages_array = array();

				foreach ($group_messages as $message) {

					// Check if sender is not in black list of receiver
					$blacklists = get_user_meta( $message->rcpid, 'blacklist', true);
					if (!empty($blacklists)) {
						$blacklists = array_unique(explode(',', $blacklists));
					} else {
						$blacklists = array();
					}

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

					if (in_array($sender_profile_id, $blacklists)) continue;
				
					$dublicate_id = $message->rcpid . '.' . $message->senderid;

					$all_messages_array[] = array('id' => $message->id, 'dublicate_id' => $dublicate_id, 'receiver_id' => $message->rcpid, 'sender_id' => $message->senderid, 'send_profile_id' => $sender_profile_id, 'message' => $message->message, 'chat_mode' => $message->chat_mode);

				}

				// Sort in descending order
				array_multisort($all_messages_array,SORT_DESC);

				foreach($all_messages_array as $k=>$v){
					$unique=array_unique($v);
					$all_messages_array[$k]=$unique;
				}

				// Remove all messages but last
				$ids = array_column($all_messages_array, 'receiver_id');
				$ids = array_unique($ids);
				$all_messages_array = array_filter($all_messages_array, function ($key, $value) use ($ids) {
					return in_array($value, array_keys($ids));
				}, ARRAY_FILTER_USE_BOTH);

				$countnew = is_array($all_messages_array) && !empty($all_messages_array) ? count($all_messages_array) : 0;

				if($countnew > 0){
					
					$find_this_email = 'website.com';

					$check_online_status_option = isset(self::$datebook_options['check_online_status']) ? (self::$datebook_options['check_online_status'] > 0 ? self::$datebook_options['check_online_status'] : 120) : (of_get_option('check_online_status') > 0 ? of_get_option('check_online_status') : 120); // 120 seconds = 2 minutes

					$additional_time = isset(self::$datebook_options['add_time_before_notification']) ? (self::$datebook_options['add_time_before_notification'] > 0 ? self::$datebook_options['add_time_before_notification'] : 0) : (of_get_option('add_time_before_notification') > 0 ? of_get_option('add_time_before_notification') : 0);

					$redirect_demo_emails_to_admin = isset(self::$datebook_options['redirect_demo_emails_to_admin']) ? (self::$datebook_options['redirect_demo_emails_to_admin'] > 0 ? self::$datebook_options['redirect_demo_emails_to_admin'] : 0) : (of_get_option('redirect_demo_emails_to_admin') > 0 ? of_get_option('redirect_demo_emails_to_admin') : 0);

					$admin_email = isset(self::$datebook_options['email_website']) ? self::$datebook_options['email_website'] : (of_get_option('email_website') ? of_get_option('email_website') : get_bloginfo('admin_email'));

					$get_repeated_users = get_option('datebook_repeated_notifications');

					$get_repeated_days = isset(self::$datebook_options['repeat_notification_about_new_message']) ? (self::$datebook_options['repeat_notification_about_new_message'] > 0 ? self::$datebook_options['repeat_notification_about_new_message'] : 0) : (of_get_option('repeat_notification_about_new_message') > 0 ? of_get_option('repeat_notification_about_new_message') : 0);
					
					$repeated_days = $get_repeated_days == 1 ? 'day' : 'days';
					$next_time = strtotime("+" . $get_repeated_days . " " . $repeated_days);

					foreach ($all_messages_array as $single_message) {

						// Check if notification was sent already
						if(isset($get_repeated_users[$single_message['receiver_id']])){
							if($get_repeated_days == 0 && isset($get_repeated_users[$single_message['receiver_id']]['status']) && $get_repeated_users[$single_message['receiver_id']]['status'] == '1'){
								continue;
							} else if($get_repeated_days > 0 && isset($get_repeated_users[$single_message['receiver_id']]['status']) && $get_repeated_users[$single_message['receiver_id']]['status'] == '1' && isset($get_repeated_users[$single_message['receiver_id']]['time']) && $get_repeated_users[$single_message['receiver_id']]['time'] >= time()){
								continue;
							}
						}

						$receiver_info = get_userdata($single_message['receiver_id']);

						if(isset($receiver_info->user_email)){
							
							$online_time = get_user_meta( $single_message['receiver_id'], 'online_status', true );

							if ( !empty($online_time) && $online_time >= 0 ) {

								$last_logout = get_user_meta( $single_message['receiver_id'], 'last_logout', true );

								if($last_logout == 1){
									$check_online_status = 1; // 0 seconds
								} else {
									$check_online_status = $check_online_status_option; // 120 seconds
								}

								if (time() - $online_time > $check_online_status + $additional_time ) {

									$profile_id = get_user_meta($single_message['receiver_id'], 'profile_postid', true);

									$profile = get_post($profile_id);
									$profile_exists = isset($profile->ID) ? 1 : 0;

									if($profile_exists == 1 && isset($single_message['sender_id']) && $single_message['sender_id'] > 0 && isset($single_message['send_profile_id']) && $single_message['send_profile_id'] > 0){

										$sender_info = get_userdata($single_message['sender_id']);

										if(isset($sender_info->user_email)){

											$sender_profile = get_post($single_message['send_profile_id']);
											$sender_profile_exists = isset($sender_profile->ID) ? 1 : 0;

											if($sender_profile_exists == 1){

												$profile_name = isset($profile->post_title) ? $profile->post_title : '';

												$from_sender_name = isset($sender_profile->post_title) ? $sender_profile->post_title : '';
												$from_sender_email = $sender_info->user_email;
												$to_receiver_email = $receiver_info->user_email;

												// Set as notified
												$wpdb->query($wpdb->prepare("UPDATE " . $table_private_messages . " SET notified = 1 WHERE senderid = '%d' AND rcpid = '%d'", $single_message['sender_id'], $single_message['receiver_id']));

												// If profie is demo then send message to admin
												if($redirect_demo_emails_to_admin == 1){
													if(preg_match("~\b{$find_this_email}\b~", $to_receiver_email)){
														$to_receiver_email = $admin_email;
														$from_sender_email = '';
													}
												}

												$profile_get_permalink = get_permalink($profile_id);

												$from_sender_newmessage = $single_message['message'];

												if (isset($single_message['chat_mode']) && $single_message['chat_mode'] == 3) {
													$image_result_array = unserialize($single_message['message']);
													$from_sender_newmessage = '<img src="' . esc_url($image_result_array['imgurl']) . '" height="' . $image_result_array['height'] . 'px" alt="" />';
												}

												// Let's send email to User or Admin
												$datebook_email_var = array(
													'select_email_template' => 'new_message_to_profile',
													'subject' => esc_html__( 'You received a message', 'datebook' ),
													'profile_id' => $profile_id,
													'profile_name' => $profile_name,
													'profile_get_permalink' => $profile_get_permalink,

													'from_contacting_name' => $from_sender_name,
													'from_contacting_email' => $from_sender_email,
													'from_contacting_text' => $from_sender_newmessage,
												);

												set_query_var( 'datebook_email_var', $datebook_email_var );

												include DateBook_Template_Loader::locate( 'misc/email-templates' );

												$subject_in_email = esc_html__( 'You received a message', 'datebook' );

												$datebook_mail = DateBook_Utilities::datebook_email_send($from_sender_name, $from_sender_email, $to_receiver_email, $subject_in_email, $body);

												$get_repeated_users[$single_message['receiver_id']] = array('status' => '1', 'time' => $next_time);
											}
										}
									}
								}
							}
						}
					}

					update_option( 'datebook_repeated_notifications', $get_repeated_users );
					
				}
			}
		}
	}


	/**
	 * Start cron to check profiles for different functions
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_start_cron() {

		// Check users who did not verify their emails and delete them
		self::check_unverified_emails();

		// Check profiles set to be deleted
		self::check_deleted_profiles_by_privacy();

		// Update online status for demo profiles
		self::simulate_online_status_of_profiles();
		
		self::notification_about_new_message();

		// Check the maximum number of users in the chat and periodically delete
		//self::datebook_sessions_activation(); //register_activation_hook(__FILE__, array( __CLASS__, 'datebook_sessions_activation'));
		//add_action( 'datebook_sessions_gc', array( __CLASS__, 'cron_gc' ) );
		//register_deactivation_hook(__FILE__, array( __CLASS__, 'datebook_sessions_deactivation'));

		// Send notification about a new message
		//register_activation_hook(__FILE__, array( __CLASS__, 'datebook_notification_activation'));
		add_filter( 'cron_schedules', array( __CLASS__, 'datebook_notification_custom_time' ));
		self::datebook_notification_activation();
		add_action( 'datebook_notification_cron_hook', array( __CLASS__, 'notification_about_new_message') );
		register_deactivation_hook(__FILE__, array( __CLASS__, 'datebook_notification_deactivation'));

	}


}

//DateBook_Cron::init();
$dateBook_cron = new DateBook_Cron($datebook_options_array);