<?php

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

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


	/**
	 * Initialize filtering
	 *
	 * @access public
	 * @return void
	 */
	public static function init() {

		self::datebook_stop_password_notification();

		add_filter( 'pre_get_document_title', array( __CLASS__, 'datebook_custom_title' ) );
		add_action( 'wp_head', array( __CLASS__, 'datebook_meta_description'));
		add_action( 'wp_head', array( __CLASS__, 'hook_custom_code_in_header' ) );
		add_filter( 'wp_footer', array( __CLASS__, 'hook_custom_code_in_footer' ) );
		add_filter( 'show_admin_bar', array( __CLASS__, 'datebook_show_admin_bar_for_admins_only' ) );
		add_action( 'admin_init', array( __CLASS__, 'datebook_restricted_pages' ) );
		add_filter( 'private_title_format', array( __CLASS__, 'datebook_title_format' ) );
		add_filter( 'protected_title_format', array( __CLASS__, 'datebook_title_format' ) );
		add_action( 'template_redirect', array( __CLASS__, 'datebook_check_online' ) );
		add_filter( 'get_avatar', array( __CLASS__, 'datebook_show_avatar' ), 5, 5);
		add_action( 'datebook_currentuser_check_login', array( __CLASS__, 'datebook_currentuser_check_login' ), 10, 1 );
		add_action( 'datebook_auth_and_redirect_messages', array( __CLASS__, 'datebook_proccess_redirect_my_messages_page' ) );
		
		$enable_shortcodes_in_meta_tags = of_get_option('enable_shortcodes_in_meta_tags');

		// Rank Math
		// Allow shortcodes in the Meta Data
		add_filter( 'rank_math/paper/auto_generated_description/apply_shortcode', '__return_true' );

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_title']) && $enable_shortcodes_in_meta_tags['rank_math_seo_title'] == '1') {
			add_filter('rank_math/frontend/title', array( __CLASS__, 'doShortcodes' ), 10);
		}
		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_title']) && $enable_shortcodes_in_meta_tags['rank_math_seo_title'] == '1') {
			add_filter('rank_math/frontend/description', array( __CLASS__, 'doShortcodes' ), 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_schema']) && $enable_shortcodes_in_meta_tags['rank_math_seo_schema'] == '1') {

			/*$types = \RankMath\Helpers\Choices::choices_rich_snippet_types();
			foreach(array_keys($types) as $type) {
				add_filter('rank_math/snippet/rich_snippet_'.$type.'_entity', array( __CLASS__, 'doShortcodesSchema' ), 10);
			}*/

			add_filter('rank_math/json_ld', array( __CLASS__, 'doShortcodesSchema' ), PHP_INT_MAX, 2);
		}

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_facebook_title']) && $enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_facebook_title'] == '1') {
			add_filter('rank_math/opengraph/facebook/og_title', array( __CLASS__, 'doShortcodes' ), 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_facebook_description']) && $enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_facebook_description'] == '1') {
			add_filter('rank_math/opengraph/facebook/og_description', array( __CLASS__, 'doShortcodes' ), 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_twitter_title']) && $enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_twitter_title'] == '1') {
			add_filter('rank_math/opengraph/twitter/title', array( __CLASS__, 'doShortcodes' ), 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_twitter_description']) && $enable_shortcodes_in_meta_tags['rank_math_seo_opengraph_twitter_description'] == '1') {
			add_filter('rank_math/opengraph/twitter/description', array( __CLASS__, 'doShortcodes' ), 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['wp_title']) && $enable_shortcodes_in_meta_tags['wp_title'] == '1') {
			add_filter('wp_title', 'do_shortcode', 10);
			add_filter('the_title', 'do_shortcode', 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['the_content']) && $enable_shortcodes_in_meta_tags['the_content'] == '1') {
			add_filter('the_content', 'do_shortcode', 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['nav_menu']) && $enable_shortcodes_in_meta_tags['nav_menu'] == '1') {
			add_filter('walker_nav_menu_start_el', 'do_shortcode', 10);
		}

		if (isset($enable_shortcodes_in_meta_tags['widget']) && $enable_shortcodes_in_meta_tags['widget'] == '1') {
			add_filter('widget_title', array( __CLASS__, 'doShortcodes' ), 10, 3);
			add_filter('widget_text', 'do_shortcode', 10, 3);
			add_filter('widget_custom_html_content', 'do_shortcode', 10, 3);
		}

	}


	/**
	 * Execute shortcodes in title and description
	 *
	 * @access public
	 */
	public static function doShortcodes($content) {
        $is_url = filter_var( $content, FILTER_VALIDATE_URL );
        if ( ! $is_url ) {
            $content = html_entity_decode($content);
        }
        $content = do_shortcode($content);
        if ( ! $is_url ) {
            $content = htmlentities($content);
        }
        return $content;
        
    }

    public static function doShortcodesSchema($entity) {
        if (is_array($entity)) {
            foreach($entity as $key => $value) {
                if (is_array($value)) {
                    $entity[$key] = self::doShortcodesSchema($value);
                }
                else {
                    $entity[$key] = self::doShortcodes($value);
                }
            }
        }
        return $entity;
    }
    

	/**
	 * Put custom code in the Header of each page
	 *
	 * @access public
	 * @param string $content
	 * @return string
	 */
	public static function hook_custom_code_in_header() {

		$output = '';

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

			$output = of_get_option('custom_code_html_header');

		}

		echo wp_specialchars_decode(esc_html($output), ENT_QUOTES );

	}


	/**
	 * Put custom code in the Footer of each page
	 *
	 * @access public
	 * @param string $content
	 * @return string
	 */
	public static function hook_custom_code_in_footer() {

		$output = '';

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

			$output = of_get_option('custom_code_html_footer');

		}

		echo wp_specialchars_decode(esc_html($output), ENT_QUOTES );

	}


	/**
	 * Disable default WordPress change password notifications
	 *
	 * @access public
	 * @param string $content
	 * @return string
	 */
	public static function datebook_stop_password_notification() {
		
		if (of_get_option('stop_password_change_notification') == '1') {
			
			add_filter( 'send_password_change_email', '__return_false' );
			
			add_filter( 'send_email_change_email', '__return_false' );
			
			remove_action( 'after_password_reset', 'wp_password_change_notification' );
			
			if (!function_exists('wp_password_change_notification')) {
				function wp_password_change_notification() {
					return;
				}
			}
		}
	}


	/**
	 * Disable admin bar for subscribers
	 *
	 * @access public
	 * @param string $content
	 * @return string
	 */
	public static function datebook_show_admin_bar_for_admins_only( $content ) {

		if (of_get_option('hide_administrator_bar') == '1' && current_user_can('subscriber')) {

			$show_admin_bar_out = false;
			
		} else {
			
			$show_admin_bar_out = $content;
			
		}
		
		return $show_admin_bar_out;

	}


	/**
	 * Restrict access to the admin dashboard for users other than admin
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_restricted_pages() {

		if (of_get_option('enable_restricted_pages') == '1' && !is_super_admin()) {

			header('HTTP/1.0 404 Not Found');
			wp_redirect(home_url());
			exit;

		}

	}


	/**
	 * Rewrite Title
	 *
	 * @access public
	 */
	public static function datebook_custom_title($title) {

		$page_id = absint(get_the_ID());

		$comma = 0;
		
		$enable_meta_title = of_get_option('enable_meta_title');

		if (isset($enable_meta_title['search_page']) && $enable_meta_title['search_page'] == '1' && $page_id == of_get_option('search_results_page')) {
			
			if(isset($_REQUEST['country']) && $_REQUEST['country'] > 0){

				$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $_REQUEST['country'], 3 );
				$profile_place = isset($term_data->country) ? $term_data->country : '';

				if (isset($profile_place) && $profile_place != '') {
					
					$title = esc_html__( 'Profiles from', 'datebook' ).' '.$profile_place.' | ';
					
				}
				
			}

			$title .= get_bloginfo('name').' - '.get_bloginfo('description');

			return esc_html($title);

		} else if (isset($enable_meta_title['single_profile']) && $enable_meta_title['single_profile'] == '1' && get_post_type() == DATEBOOK_POST_TYPE && is_single()) {

			$profile_data = get_post($page_id);
			
			if(isset($profile_data->post_title)){
				$name = $profile_data->post_title;
				$comma = 1;
			} else {
				$name = '';
			}
			
			if(DateBook_Utilities::datebook_show_field('birthdate', 1)){
				$age_array = get_post_meta($page_id, 'birthday', true);

				if(!empty($age_array)){
					$age = $comma > 0 ? ', ' : '';
					$age .= floor((time() - strtotime($age_array))/31556926) . ' ' . esc_html__( 'years old', 'datebook' );
					$comma = 1;
				} else {
					$age = '';
				}
			} else {
				$age = '';
			}

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

			if(DateBook_Utilities::datebook_show_field('countrycity', 1) && isset($city_id)){

				$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );

				if(isset($term_data->city)){
					$city = $comma > 0 ? ', ' : '';
					$city .= $term_data->city;
					$comma = 1;
				} else {
					$city = '';
				}

				if(isset($term_data->region)){
					$region = $comma > 0 ? ', ' : '';
					$region .= $term_data->region;
					$comma = 1;
				} else {
					$region = '';
				}

				if(isset($term_data->country)){
					$country = $comma > 0 ? ', ' : '';
					$country .= $term_data->country;
					$comma = 1;
				} else {
					$country = '';
				}

			} else {

				$city = '';
				$region = '';
				$country = '';

			}

			$aboutme = isset($profile_data->post_content) ? $profile_data->post_content : '';
			$aboutme = wp_trim_words(wp_strip_all_tags($aboutme), 150, '');

			$meta_title_profile = of_get_option('meta_title_profile');
			if($meta_title_profile){
				$title = str_replace('[datebook_profile_name]', $name, $meta_title_profile);
				$title = str_replace('[datebook_profile_age]', $age, $title);
				$title = str_replace('[datebook_profile_city]', $city, $title);
				$title = str_replace('[datebook_profile_region]', $region, $title);
				$title = str_replace('[datebook_profile_country]', $country, $title);
				$title = str_replace('[datebook_profile_description]', $aboutme, $title);
			} else {
				$title = $name . $age . $city . $country . ' | ';
				$title .= get_bloginfo('name') . ' - ' . get_bloginfo('description');
			}

			return esc_html($title);

		}

	}


	/**
	 * Rewrite Meta Description
	 *
	 * @access public
	 */
	public static function datebook_meta_description() {

		global $post;

		$page_id = get_the_ID();

		$des_post = '';
		
		$enable_meta_description = of_get_option('enable_meta_description');

		if (isset($enable_meta_description['search_page']) && $enable_meta_description['search_page'] == '1' && $page_id == of_get_option('search_results_page')) {

			if(isset($_REQUEST['country']) && $_REQUEST['country'] > 0){

				$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $_REQUEST['country'], 3 );
				$profile_place = isset($term_data->country) ? $term_data->country : '';

				if (isset($profile_place) && $profile_place != '') {

					$des_post = esc_html__( 'Profiles from', 'datebook' ) . ' ' . $profile_place . ' | ';

				}
			} else {

				$des_post = strip_tags( $post->post_content );
				$des_post = strip_shortcodes( $post->post_content );
				$des_post = str_replace( array("\n", "\r", "\t"), ' ', $des_post );
				$des_post = mb_substr( $des_post, 0, 300, 'utf8' );

			}

		} else if (isset($enable_meta_description['single_profile']) && $enable_meta_description['single_profile'] == '1' && get_post_type() == DATEBOOK_POST_TYPE && is_single()) {

			$profile_data = get_post($page_id);

			if(isset($profile_data->post_title)){
				$name = $profile_data->post_title;
				$comma = 1;
			} else {
				$name = '';
				$comma = 0;
			}

			if(DateBook_Utilities::datebook_show_field('birthdate', 1)){
				$age_array = get_post_meta($page_id, 'birthday', true);

				if(!empty($age_array)){
					$age = $comma > 0 ? ', ' : '';
					$age .= floor((time() - strtotime($age_array))/31556926) . ' ' . esc_html__( 'years old', 'datebook' );
					$comma = 1;
				} else {
					$age = '';
					$comma = 0;
				}
			} else {
				$age = '';
				$comma = 0;
			}

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

			if(DateBook_Utilities::datebook_show_field('countrycity', 1) && isset($city_id)){

				$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $city_id );

				if(isset($term_data->city)){
					$city = $comma > 0 ? ', ' : '';
					$city .= $term_data->city;
					$comma = 1;
				} else {
					$city = '';
					$comma = 0;
				}

				if(isset($term_data->region)){
					$region = $comma > 0 ? ', ' : '';
					$region .= $term_data->region;
					$comma = 1;
				} else {
					$region = '';
					$comma = 0;
				}

				if(isset($term_data->country)){
					$country = $comma > 0 ? ', ' : '';
					$country .= $term_data->country;
					$comma = 1;
				} else {
					$country = '';
					$comma = 0;
				}

			} else {

				$city = '';
				$region = '';
				$country = '';

			}

			$des_post = isset($profile_data->post_content) ? wp_trim_words($profile_data->post_content, 150, '') : '';

			$meta_description_profile = of_get_option('meta_description_profile');
			if($meta_description_profile){
				$des_post_pre = str_replace('[datebook_profile_name]', $name, $meta_description_profile);
				$des_post_pre = str_replace('[datebook_profile_age]', $age, $des_post_pre);
				$des_post_pre = str_replace('[datebook_profile_city]', $city, $des_post_pre);
				$des_post_pre = str_replace('[datebook_profile_country]', $country, $des_post_pre);
				$des_post = str_replace('[datebook_profile_description]', $des_post, $des_post_pre);
			}

			echo '<meta name="description" content="' . esc_html(wp_strip_all_tags($des_post)) . '" />' . "\n";

		} else if (is_singular()) {

			$des_post = strip_tags( $post->post_content );
			$des_post = strip_shortcodes( $post->post_content );
			$des_post = str_replace( array("\n", "\r", "\t"), ' ', $des_post );
			$des_post = mb_substr( $des_post, 0, 300, 'utf8' );

			//echo '<meta name="description" content="' . esc_html(wp_strip_all_tags($des_post)) . '" />' . "\n";

		} else if (is_home()) {

			//$des_post = get_bloginfo('description');

			//echo '<meta name="description" content="' . esc_html(wp_strip_all_tags($des_post)) . '" />' . "\n";

		} else if (is_category()) {

			//$des_post = strip_tags(category_description());

			//echo '<meta name="description" content="' . esc_html(wp_strip_all_tags($des_post)) . '" />' . "\n";

		} else {

			//$des_post = get_bloginfo('name') . ' - ' . get_bloginfo('description');

			//echo '<meta name="description" content="' . esc_html(wp_strip_all_tags($des_post)) . '" />' . "\n";

		}

	}
	

	/**
	 * Remove the "Private" word in Profile Title when not activated
	 *
	 * @access public
	 */
	public static function datebook_title_format($content) {
	
		return '%s';
	}


	/**
	 * Who is Online. Update profile online status
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_check_online() {
	
		if ( !is_user_logged_in() )
			return null;

		global $user_ID;

		$activity_time = strtotime(gmdate( 'Y-m-d H:i:s' ) . ' GMT');

		update_user_meta( absint($user_ID), 'online_status', $activity_time );
	}


	/**
	 * Display Profile avatar
	 *
	 * @access public
	 */
	public static function datebook_show_avatar($avatar, $id_or_email, $size = 50, $default = '', $alt = false) {

		$id = 0;
		
		$avatar = isset($avatar) && !empty($avatar) ? $avatar : '';

		if (is_numeric($id_or_email)) {

			$id = $id_or_email;

		} else if (is_object($id_or_email)) {

			$id = $id_or_email->user_id;

		} else if (is_string($id_or_email)) {
			
			if (is_email($id_or_email)) {

				$u = get_user_by('email', $id_or_email);
				$id = $u->ID;

			} else {
				
				$u = get_user_by('login', $id_or_email);
				$id = $u->ID;
				
			}

		}

		if ($id == 0) return $avatar;

		//if we have an avatar uploaded and is not Gravatar return it
		if(strpos($avatar, home_url()) !== FALSE && strpos($avatar, 'gravatar') === FALSE) return $avatar;

		if ($id > 0) {

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

			if ($profile_id > 0) {

				$gender = get_post_meta($profile_id, 'gender', true);
				$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($profile_id, 'image_small', $gender, true);

				if ( $thumbnail_url['image_exists'] == 'no' ) return $avatar;

				if ( !empty($thumbnail_url['img_full_url']) ) {

					$avatar = preg_replace('/src=("|\').*?("|\')/i', 'src=\'' . $thumbnail_url['img_full_url'] . '\'', $avatar);

				}
			}
		}

		return $avatar;

	}


	/**
	 * Check if user logged in
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_currentuser_check_login($page_id = 0) {

		$option_name = preg_replace( "/\W/", '_', strtolower( get_option( 'stylesheet' ) ) );
		$themename = get_option( $option_name );
		if (!of_get_option('default_language') || $themename == '') {

			wp_redirect(home_url());
			exit();

		} else if (!is_user_logged_in()) {

			$get_option_login_page = get_permalink(of_get_option('login_page'));

			$display_alert_must_login = $get_option_login_page;

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

				DateBook_Utilities::set_redirect_to($page_id);

				$display_alert_must_login = add_query_arg( array(
					'message' => 'mustlogin'
				), $get_option_login_page );

			}

			wp_redirect($display_alert_must_login);
			exit();

		}
	}


	/**
	 * Redirect to My Message page after user logged in
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_proccess_redirect_my_messages_page() {

		if (is_user_logged_in() && !is_super_admin()) {

			$redirect_to_after_login = of_get_option('redirect_to_after_login') > 0 ? of_get_option('redirect_to_after_login') :  (of_get_option('my_messages_page') > 0 ? of_get_option('my_messages_page') : home_url());

			wp_redirect(get_permalink($redirect_to_after_login));
			exit();

		}

	}


}

DateBook_Filter::init();