<?php

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

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


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

		add_action( 'datebook_ajax_friends', array( __CLASS__, 'proccess_ajax_friend_account' ) );
		add_action( 'datebook_friends_settings', array( __CLASS__, 'show_friends_settings_page' ) );

	}


	/**
	 * Count all friends on someone's profile and show amount on the Profile's friends
	 * 
	 * @since 3.8
	 * @access public
	 */
	public static function get_profile_friends($current_user_id) {

		$friends_data_array = get_user_meta($current_user_id, 'friends', true);

		if ($friends_data_array) {
			$get_approved_friends_ids = array_unique(explode(',', $friends_data_array));
		} else {
			$get_approved_friends_ids = array();
		}

		$count_friends = 0;

		if(!empty($get_approved_friends_ids) && count($get_approved_friends_ids) > 0){
			foreach($get_approved_friends_ids as $profile_id){

				$profile_post = get_post($profile_id);
				
				if(isset($profile_post->post_status) && $profile_post->post_status == 'publish'){

					if ( $profile_post === false ) {
						$count_friends += 0;
					} else {
						$count_friends += 1;
					}
				}
			}
		}

		$friends_array = array(
			'all_approved_friends' => $get_approved_friends_ids,
			'count_friends' => $count_friends
		);

		return $friends_array;

	}


	/**
	 * Check email, username and other data via ajax
	 *
	 * @access public
	 * @return void
	 */
	public static function proccess_ajax_friend_account() {
		
		if( isset( $_GET['action'] ) && isset( $_GET['whatisit'] ) ) {
			
			//Catch the whatisit - cities, logincheck, defaultimage, realphotodelete, activateprofile, logodelete, favoriteset, tourdelete, touredit
			$whatisit = isset( $_GET['whatisit'] ) ? esc_attr($_GET['whatisit']) : '';

		
			// Check if the email is free
			if ($whatisit == 'mailcheck') {

				$emailaddress = sanitize_email($_GET['email']);

				if ( is_email($emailaddress) ) {

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

					$currentauth = get_userdata($current_user_id);

					if ( email_exists($emailaddress) ) {

						if ( !is_user_logged_in() || (is_user_logged_in() && isset($currentauth->user_email) && $emailaddress != $currentauth->user_email) ) {

							echo '<span class="badge badge-danger">' . esc_html__( 'This email is already registered. Try another.', 'datebook' ) . '</span>';

						}

					} else {

						echo '<span class="badge badge-success">' . esc_html__( 'You may use this email', 'datebook' ) . '</span>';
					}

				}

			} else if ($whatisit == 'logincheck') {

				// Check if the login is free
				$username = isset($_GET['user']) && strlen($_GET['user']) > 0 ? preg_replace("/([^a-zA-Z0-9])/", '', sanitize_text_field($_GET['user'])) : '';

				if ($username) {
					
					$min_characters_username = of_get_option('min_characters_username') ? of_get_option('min_characters_username') : 4;
					$max_characters_username = of_get_option('max_characters_username') ? of_get_option('max_characters_username') : 30;

					if (strlen($username) < $min_characters_username || strlen($username) > $max_characters_username) {

						echo '<span class="badge badge-danger">' . sprintf(esc_html__( 'Your username must be between %1$s and %2$s characters', 'datebook' ), $min_characters_username, $max_characters_username) . '</span>';

					} else {

						if (username_exists($username)) {

							echo '<span class="badge badge-danger">'.esc_html__( 'This username is already registered. Select another one.', 'datebook' ).'</span>';

						}
					}
				}
			}

			die();

		}
	}


	/**
	 * Set Favorite, Like, Friend
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function ajax_set_buttons_on_profile() {

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

			$whatisit = isset( $_GET['whatisit'] ) ? $_GET['whatisit'] : '';

			$profile_id = isset( $_GET['id'] ) ? $_GET['id'] : 0;

			if (!$profile_id || $profile_id == 0) { die(); }

			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_sender_id = get_user_meta( $current_user_id, 'profile_postid', true );

			$current_profile_data = get_post($profile_sender_id);

			$profile_status = $current_profile_data->post_status;

			if ($profile_status == 'publish') {

				$profile_id = absint($profile_id);

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

				if ($profile_id > 0) {

					// 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();

					// Set featured background image for profile
					if ($whatisit == 'setfeaturedimage') {

						if ($current_profile_data->ID != $profile_sender_id){

							$response = array('success' => 0, 'text' => esc_html__('You cannot select a background image', 'datebook' ));

						} else {

							$featured_background_images = of_get_option('featured_background_images');

							if(isset($featured_background_images) && is_array($featured_background_images) && in_array($_GET['image_url'], $featured_background_images) && isset( $_GET['image_url'] )){

								$datebook_get_data['featured_pattern'] = isset( $_GET['image_url'] ) ? esc_url($_GET['image_url']) : '';

								// 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__('Background image has been selected', 'datebook' ));
								
							} else {

								// display the confirmation of add
								$response = array('success' => 2, 'text' => esc_html__('Background image has NOT been selected', 'datebook' ));

							}
						}

					} else if ($whatisit == 'likeset') {

						// Add to Like
						$profile_current_user_id = absint($profile_sender_id);

						$data_array = get_user_meta( $current_user_id, 'likes', 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 like yourself', 'datebook' ));

							} else {

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

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

								if (!in_array($profile_current_user_id, $whoaddedlikes)) {
									$whoaddedlikes[] = $profile_current_user_id;
									
									$count_data_array = count($whoaddedlikes);
									
									$whoaddedlikes = implode('|', $whoaddedlikes);
									$datebook_get_data['likes']['whoaddedlikes'] = $whoaddedlikes;

									// 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' => 'likes'
									), $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' => 'likes', 'text' => esc_html__('liked your profile', 'datebook' ), 'url' => $profile_get_permalink, 'profile_id' => $profile_current_user_id);
										update_post_meta($profile_id, 'notification', $get_data_notification);

									}
								}

								$datebook_get_data['likes']['count'] = isset($datebook_get_data['likes']['count']) && $datebook_get_data['likes']['count'] > 0 ? $datebook_get_data['likes']['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__('You like it', 'datebook' ), 'mycounter' => $count_data_array, 'youcounter' => $datebook_get_data['likes']['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, 'likes', $data_array);

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

							$whoaddedlikes_key = array_search($profile_current_user_id, $whoaddedlikes);
							if ($whoaddedlikes_key >= 0) {
								unset($whoaddedlikes[$whoaddedlikes_key]);
							}
							$whoaddedlikes = implode('|', $whoaddedlikes);
							$datebook_get_data['likes']['whoaddedlikes'] = $whoaddedlikes;

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

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

							$textmessage = esc_html__( 'You dislike it', 'datebook' );
							$newmessage = '<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'=> $newmessage, 'mycounter' => $count_data_array, 'youcounter' => $datebook_get_data['likes']['count']);

						}

					} else if ($whatisit == 'friendrequest') {

						if (isset($datebook_get_data['friends']['pending'][$profile_sender_id]) && $datebook_get_data['friends']['pending'][$profile_sender_id]['status'] == 'pending') {

							unset($datebook_get_data['friends'][$profile_sender_id]);
							unset($datebook_get_data['friends']['pending'][$profile_sender_id]);

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

							// display the confirmation of remove
							$response = array('success' => 2, 'text' => esc_html__('Friend request canceled', 'datebook' ));

						} else {

							$data_array = get_user_meta( $current_user_id, 'friends', 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_sender_id){

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

								} else {

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

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

									$friendsrequestsent = (isset($datebook_get_data['friends']['requestsent'][$profile_sender_id]) && $datebook_get_data['friends']['requestsent'][$profile_sender_id]['status'] == 'sent') ? 1 : 0;

									if ($friendsrequestsent == 0) {
										
										// Redirect all emails for demo profiles to admin
										$find_this_email = 'website.com';

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

										$admin_email = of_get_option('email_website') ? of_get_option('email_website') : get_bloginfo('admin_email');

										$profile_post = get_post($profile_id);
										$profile_post_author = $profile_post->post_author;
										$profile_name = $profile_post->post_title;

										$currentauth = get_userdata($profile_post_author);

										$to_email = $currentauth->user_email;

										if($redirect_demo_emails_to_admin == 1){
											if(preg_match("~\b{$find_this_email}\b~", $to_email)){
												$to_email = $admin_email;
											}
										}

										$select_email_template = 'friend_request_to_profile';

										include DateBook_Template_Loader::locate( 'misc/email-templates' );
										
										$subject_in_email = esc_html__( 'You receieved friend request', 'datebook' ). ' - ' . of_get_option('email_sitename');
										$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

									}

									// Update the post meta
									$datebook_get_data['friends']['pending'][$profile_sender_id] = array('status' => 'pending');
									$datebook_get_data['friends']['requestsent'][$profile_sender_id] = array('status' => 'sent');
									update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);


									$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_sender_id]) && !empty($get_data_notification[$profile_sender_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_sender_id] = array('time' => $time_submitted, 'status' => 'unread', 'referrer' => 'notification', 'show' => 'friends', 'text' => esc_html__('New friend request is waiting for your approval', 'datebook' ), 'url' => $profile_get_permalink);
										update_post_meta($profile_id, 'notification', $get_data_notification);
								
									}


									// display the confirmation of add
									$response = array('success' => 1, 'text' => esc_html__('Friend request sent', 'datebook' ));

								}

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

								$key = array_search($profile_id, $data_array);
								if ($key >= 0) {
									unset($data_array[$key]);
								}
								$data_array = implode(',', $data_array);
								update_user_meta( $current_user_id, 'friends', esc_attr($data_array));

								// Remove friend. Update data of user who accepts a friend
								$profile_post = get_post($profile_id);
								$profile_post_author = $profile_post->post_author;

								$sender_data_array = get_user_meta($profile_post_author, 'friends', true);
								if ($sender_data_array) {
									$sender_data_array = array_unique(explode(',', $sender_data_array));
								} else {
									$sender_data_array = array();
								}

								$sender_key = array_search($profile_post_author, $sender_data_array);
								if ($sender_key >= 0) {
									unset($sender_data_array[$sender_key]);
								}
								$sender_data_array = implode(',', $sender_data_array);
								update_user_meta($profile_post_author, 'friends', esc_attr($sender_data_array));

								unset($datebook_get_data['friends'][$profile_sender_id]);
								unset($datebook_get_data['friends']['pending'][$profile_sender_id]);

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

								// display the confirmation of remove
								$response = array('success' => 2, 'text' => esc_html__('Friend has been removed', 'datebook' ), 'counter' => $datebook_get_data['friends']);

							}
						}

					} else if ($whatisit == 'acceptfriend') {

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

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

							$data_array = array();

							foreach($old_data_array as $data_profile_id){
								$profile_post = get_post($data_profile_id);

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

									if ( $profile_post !== false ) {
										$data_array[] = $profile_post->ID;
									}
								}
							}

							$friends_count_before = isset($data_array) && count($data_array) > 0 ? count($data_array) : 0;

							/* === Accepting user === */

							// Update data of user who accepts a friend
							$data_array[] = $profile_id;
							$data_array = implode(',', $data_array);
							update_user_meta($current_user_id, 'friends', esc_attr($data_array));

							// Get personal data of accepting user
							$get_current_profile_data = get_post_meta($profile_sender_id, 'profile_personal_data', true);
							$get_current_data = isset($get_current_profile_data) ? $get_current_profile_data : array();

							unset($get_current_data['friends'][$profile_id]);
							unset($get_current_data['friends']['pending'][$profile_id]);
							$get_current_data['friends'][$profile_id] = array('status' => 'approved');
							$get_current_data['friends_count'] = $friends_count_before + 1;

							// Update the post meta of user who accepts a friend
							update_post_meta($profile_sender_id, 'profile_personal_data', $get_current_data);

							/* === Sending Friend request user ==== */

							$profile_post = get_post($profile_id);
							$profile_post_author = $profile_post->post_author;

							// Update data of user who accepts a friend
							$sender_data_array = get_user_meta( $profile_post_author, 'friends', true);
							if ($sender_data_array) {
								$sender_data_array = array_unique(explode(',', $sender_data_array));
							} else {
								$sender_data_array = array();
							}

							$sender_data_array[] = $profile_sender_id;
							$sender_data_array = implode(',', $sender_data_array);
							update_user_meta($profile_post_author, 'friends', esc_attr($sender_data_array));

							unset($datebook_get_data['friends'][$profile_sender_id]);
							unset($datebook_get_data['friends']['pending'][$profile_sender_id]);

							$datebook_get_data['friends'][$profile_sender_id] = array('status' => 'approved');
							$datebook_get_data['friends_count'] = isset($datebook_get_data['friends_count']) && $datebook_get_data['friends_count'] >= 0 ? $datebook_get_data['friends_count'] + 1 : 1;

							// Update the post meta of user who accepts a friend
							update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);

							/* ==================================== */

							$count_pending_friends = isset($get_current_data['friends']['pending']) ? count($get_current_data['friends']['pending']) : 0;

							// display the confirmation of add
							$response = array('success' => 1, 'text' => esc_html__('You added a friend', 'datebook' ), 'counter' => $get_current_data['friends_count'], 'countpending' => $count_pending_friends);

						}

					} else if ($whatisit == 'rejectfriend' || $whatisit == 'removefriend') {

						// Current user
						$data_array = get_user_meta( $current_user_id, 'friends', true);
						if ($data_array) {
							$data_array = array_unique(explode(',', $data_array));
						} else {
							$data_array = array();
						}

						// Get personal data of Sending request user
						$get_current_profile_data = get_post_meta($profile_sender_id, 'profile_personal_data', true);
						$get_current_data = isset($get_current_profile_data) ? $get_current_profile_data : array();

						unset($get_current_data['friends'][$profile_id]);
						unset($get_current_data['friends']['pending'][$profile_id]);

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

							// Sending request user
							$get_current_data['friends_removed'][$profile_id] = array('status' => 'rejected');

							// Update the post meta
							update_post_meta($profile_sender_id, 'profile_personal_data', $get_current_data);
						
							$count_pending_friends = isset($get_current_data['friends']['pending']) ? count($get_current_data['friends']['pending']) : 0;

							// display the confirmation of remove
							$response = array('success' => 1, 'text' => esc_html__('Friend request has been rejected', 'datebook'), 'countpending' => $count_pending_friends);

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

							// Sending request user
							$key = array_search($profile_id, $data_array);
							if ($key >= 0) {
								unset($data_array[$key]);
							}
							$data_re_array = implode(',', $data_array);
							update_user_meta( $current_user_id, 'friends', esc_attr($data_re_array));

							// Sending request user
							$get_current_data['friends_removed'][$profile_id] = array('status' => 'removed');
							$get_current_data['friends_count'] = !empty($data_array) && count($data_array) > 0 ? count($data_array) : 0;

							// Update data of sending request user
							update_post_meta($profile_sender_id, 'profile_personal_data', $get_current_data);

							// Accepting request user
							$profile_accept_data = get_post($profile_id);
							$profile_user_id = $profile_accept_data->post_author;

							$accept_data_array = get_user_meta($profile_user_id, 'friends', true);
							if ($accept_data_array) {
								$accept_data_array = array_unique(explode(',', $accept_data_array));
							} else {
								$accept_data_array = array();
							}

							$accept_key = array_search($profile_sender_id, $accept_data_array);
							if ($accept_key >= 0) {
								unset($accept_data_array[$accept_key]);
							}
							$accept_data_array = implode(',', $accept_data_array);

							// Update data of accepting request user
							update_user_meta($profile_user_id, 'friends', esc_attr($accept_data_array));

							unset($datebook_get_data['friends'][$profile_sender_id]);
							unset($datebook_get_data['friends']['pending'][$profile_sender_id]);
							$datebook_get_data['friends_removed'][$profile_sender_id] = array('status' => 'removed');
							$datebook_get_data['friends_count'] = $datebook_get_data['friends_count'] - 1;

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

							// display the confirmation of remove
							$response = array('success' => 1, 'text' => esc_html__('Friend has been removed', 'datebook' ), 'counter' => $get_current_data['friends_count']);

						}

					}
				
				} else {

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

					$response = array('success' => 3, 'profile_id'=> '', 'text' => $textmessage, 'newmessage'=> $newmessage, '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();

			}
		}
	}


	/**
	 * Return profile friend button
	 *
	 * @access public
	 * @return void
	 */
	public static function process_friend_button($profile_id, $currentauth_ID, $current_user_id, $profile_friends){

		$layout = '';

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

			if (is_user_logged_in() || is_super_admin()) {
			
				if (isset($currentauth_ID) && $currentauth_ID > 0 && $currentauth_ID != $current_user_id){

					// Friends
					$friends = get_user_meta( $current_user_id, 'friends', true);

					if ($friends) {
						$friends = array_unique(explode(',', $friends));
					} else {
						$friends = array();
					}

					if (in_array($profile_id, $friends)) {
						$friend_class = 'btn-outline-success';
						$friend_title = esc_html__( 'Remove friend', 'datebook' );
					} else {
						$friend_class = 'btn-outline-primary';
						$friend_title = esc_html__('Add Friend', 'datebook');
					}

					// Profile ID of current user
					$profile_id_of_current_user = get_user_meta( $current_user_id, 'profile_postid', true );
					
					if(isset($profile_id_of_current_user) && isset($profile_friends['pending'][$profile_id_of_current_user]) && $profile_friends['pending'][$profile_id_of_current_user]['status'] == 'pending'){

						$friend_class = 'btn-outline-warning pr-3 pl-3';
						$friend_title = esc_html__( 'Friend request sent', 'datebook' );

					} else if(isset($profile_id_of_current_user) && isset($profile_friends[$profile_id_of_current_user]['status']) && $profile_friends[$profile_id_of_current_user]['status'] == 'approved'){

						$friend_class = 'btn-outline-success pr-3 pl-3';
						$friend_title = esc_html__( 'Remove friend', 'datebook' );

					}

				} else {

					$friend_class = 'btn-outline-primary';
					$friend_title = esc_html__('Add Friend', 'datebook');

				}

			} else {

				$friend_class = 'btn-outline-primary';
				$friend_title = esc_html__( 'Add Friend', 'datebook' );

			}

			$layout .= '<span class="btn ' . esc_attr($friend_class) . ' ml-0 mr-0 pl-3 pr-3 datebook-add-friend" profile-id="' . absint($profile_id) . '"><i class="fas fa-user-friends fa-lg mr-1"></i> <span class="datebook-title">' . esc_attr($friend_title) . '</span></span>';

		}

		return $layout;

	}


	/**
	 * Validate all input data
	 *
	 * @access private
	 */
	private static function validate_friends_settings() {
	
		if ( ! isset($_POST['action']) && $_POST['action'] != 'change') {
			return;
		}

		// Make global    
		global $datebook_form_error;

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

		$update_data = array();

		// instantiate the class
		$datebook_form_error = new WP_Error;

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

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

		$update_data['enablefriends'] = isset($_POST['enablefriends']) && $_POST['enablefriends'] > 0 ? sanitize_text_field($_POST['enablefriends']) : 0;

		$update_data['who_can_send_friend_request'] = isset($_POST['who_can_send_friend_request']) && strlen($_POST['who_can_send_friend_request']) > 0 ? sanitize_text_field($_POST['who_can_send_friend_request']) : '';

		$update_data['who_can_see_my_friends'] = isset($_POST['who_can_see_my_friends']) && strlen($_POST['who_can_see_my_friends']) > 0 ? sanitize_text_field($_POST['who_can_see_my_friends']) : '';

		return $update_data;

	}
	
	
	/**
	 * Update all data
	 *
	 * @access private
	 * @return void
	 */
	private static function update_friends_settings() {

		global $wpdb, $datebook_get_data, $datebook_form_error, $datebook_alert_error, $datebook_alert_text;
		
		// validate the Profile form input
		$datebook_get_data = self::validate_friends_settings();

		// Ensure WP_Error object ($datebook_form_error) contains no error
		if ( count( $datebook_form_error->get_error_messages() ) < 1 ) {

			// If user logged in then let's update his data
			if ($datebook_get_data['profile_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);
				}

				//Update entire array
				//Get entire array
				$get_profile_data = get_post_meta($datebook_get_data['profile_id'], 'profile_personal_data', true);
				$get_profile_data = !empty($get_profile_data) ? $get_profile_data : array();
				
				// Let's save or update only these data for search
				foreach($datebook_get_data as $key => $value) {

					// sanitize data in array
					if (is_array($value)) {
						$value = array_map( 'sanitize_text_field', $value );
					} else {
						$value = sanitize_text_field( $value );
					}

					//Alter the options array appropriately
					$get_profile_data[sanitize_key($key)] = $value;

				}

				// Update the post meta
				update_post_meta($datebook_get_data['profile_id'], 'profile_personal_data', $get_profile_data);
				
				// If no errors let's show success alert
				$datebook_alert_text['success_friends_settings_updated'] = esc_html__( 'The changes have been saved', 'datebook' );

			}

		} else {

			$datebook_alert_error = array();
			$datebook_alert_text = array();
			
			$datebook_alert_text['error_required_fields'] = esc_html__( 'Please, fill in all required fields colored red', 'datebook' );

			foreach($datebook_form_error->get_error_codes() as $code){

				$datebook_alert_error[$code] = $datebook_form_error->get_error_data($code);
				$datebook_alert_text[$code] = $datebook_form_error->get_error_message($code);

			}

		}

	}


	/**
	 * Show list of friends
	 *
	 * @access public
	 * @return void
	 */
	public static function pre_proccess_friends_list($options){

		if (of_get_option('enable_friendship') == '1') {
			
			return DateBook_Template_Loader::load( 'profile/profile-friends-list', $options );

		}
	}


	/**
	 * Return list of friends
	 *
	 * @access public
	 * @return void
	 */
	public static function proccess_friends_list($options){

		echo self::pre_proccess_friends_list($options);

	}


	/**
	 * Show settings form and process all data
	 *
	 * @access public
	 * @return void
	 */
	public static function return_friends_settings(){

		if (is_user_logged_in() && of_get_option('enable_friendship') == '1') {

	    	if (isset($_POST['action']) && $_POST['action'] == 'change' && isset($_POST['friendssettings']) && $_POST['friendssettings'] == 1) {

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

				$profile_type = get_user_meta( $current_user_id, 'profile_type', true);
				$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
				$profile_post = get_post($profile_id);
				$profile_post_author = $profile_post->post_author;

				// If any field is left empty, add the error message to the error object
				if ($profile_post_author != $current_user_id && is_user_logged_in()) {

					echo '<div class="alert alert-danger">' . esc_html__( 'You are not allowed to edit this profile', 'datebook' ) . '</div>';

				} else {

					// upodate all the input data
					self::update_friends_settings();

				}
	    	}
			
			return DateBook_Template_Loader::load( 'profile/profile-friends-settings' );

		}
	}


	/**
	 * Show Friends settings page
	 *
	 * @access public
	 * @return void
	 */
	public static function show_friends_settings_page() {

		echo self::return_friends_settings();

	}


}

DateBook_Profile_Friends::init();