<?php
/**
 * Core Function for theme
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @author ThemeRox
 * @category HelperFunctions
 * @package Ayyash\Core
 */

if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	die();
}

/**
 * @global string $ayyash_get_current_screen Ayyash Current Screen Name
 * @global array $ayyash_loaded_sidebar_position Ayyash Loaded Sidebar position for screens
 * @global array $ayyash_loaded_layout_options Ayyash Loaded loaded layout options for posts/pages/cpt etc.
 */
global
	$ayyash_screen,
	$ayyash_loaded_sidebar_position,
	$ayyash_loaded_layout_options;

if ( ! function_exists( 'ayyash_class_attribute_helper' ) ) {
	/**
	 * Combine base classes with extra.
	 *
	 * @param string[] $base base class names.
	 * @param string|string[] $extra Space-separated string or array of extra class names to add to the class list.
	 *
	 * @return array
	 */
	function ayyash_class_attribute_helper( $base, $extra ) {
		if ( ! empty( $extra ) ) {
			if ( ! is_array( $extra ) ) {
				$extra = preg_split( '#\s+#', $extra );
			}
			$base = array_merge( $base, $extra ); // @phpstan-ignore-line
		} else {
			$extra = array();
		}

		return array( array_map( 'esc_attr', $base ), $extra );
	}
}

if ( ! function_exists( 'ayyash_is_not_default_val' ) ) {
	/**
	 * Check input value is not eqeqeq to 'default' && not empty.
	 *
	 * @param mixed $input input value to check.
	 *
	 * @return bool
	 */
	function ayyash_is_not_default_val( $input ) {
		return ( ! empty( $input ) && 'default' !== $input );
	}
}

if ( ! function_exists( 'ayyash_get_post_layout_options' ) ) {
	/**
	 * Get Post Settings.
	 *
	 * @param string $option Option to get.
	 * @param int|WP_Post|null $post Post id. Default null. If not set will use the current post id.
	 *
	 * @return array|string|int|false
	 */
	function ayyash_get_post_layout_options( $option = '', $post = null ) {
		global $ayyash_loaded_layout_options;

		$post = get_post( $post );

		if ( null === $ayyash_loaded_layout_options ) {
			$ayyash_loaded_layout_options = array();
		}

		$option   = strtolower( $option );
		$defaults = apply_filters(
			'ayyash_page_post_layout_defaults',
			array(
				'ayyash_display_header'           => 'default',
				'ayyash_secondary_header'         => 'default',
				'ayyash_section_height'           => 0,
				'ayyash_site_layout'              => 'default',
				'ayyash_titlebar'                 => 'default',
				'ayyash_page_title'               => 'default',
				'ayyash_content_layout'           => 'default',
				'ayyash_sidebar'                  => 'default',
				'ayyash_display_main_footer'      => 'default',
				'ayyash_display_secondary_footer' => 'default',
				'ayyash_display_credit'           => 'default',
			)
		);

		// fx option name.
		if ( ! $option ) {
			$option = 'all';
		} else {
			$option = str_replace( 'ayyash_', '', $option );
		}

		if ( $post ) {

			if ( 'all' !== $option && has_filter( "ayyash_pre_get_post_{$option}_option" ) ) {
				// Eg. ayyash_pre_get_post_content_layout_option
				// Eg. ayyash_pre_get_post_display_header_option
				return apply_filters( "ayyash_pre_get_post_{$option}_option", $post );
			}

			if ( ! isset( $ayyash_loaded_layout_options[ $post->ID ] ) ) {
				$settings = (array) get_post_meta( $post->ID, 'ayyash', true );
				$settings = array_filter( $settings );
				$settings = wp_parse_args( $settings, $defaults );
				$settings = apply_filters( 'ayyash_post_layout_options', $settings, $post );
				// Store into cache.
				$ayyash_loaded_layout_options[ $post->ID ] = $settings;
			} else {
				// Read from cache.
				$settings = $ayyash_loaded_layout_options[ $post->ID ];
			}
		} else {
			// This function can be called from any archive pages...
			$settings = apply_filters( 'ayyash_post_layout_options', $defaults, null );
		}

		if ( 'all' === $option ) {
			return $settings;
		}

		if ( isset( $settings[ $option ] ) ) {
			return $settings[ $option ];
		}

		if ( isset( $settings[ 'ayyash_' . $option ] ) ) {
			return $settings[ 'ayyash_' . $option ];
		}

		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
			/* translators: %s: Option name. */
				esc_html__( 'Option %s is not registered within current theme', 'ayyash' ),
				'<code>' . esc_html( $option ) . '</code>'
			),
			'1.0.0'
		);

		return false;
	}
}

if ( ! function_exists( 'ayyash_get_current_screen' ) ) {
	/**
	 * Determine the current view.
	 *
	 * @return string The string representing the current view.
	 */
	function ayyash_get_current_screen() {
		global $ayyash_screen;

		if ( isset($ayyash_screen) ) {
			return $ayyash_screen;
		}

		// Post types.
		$post_types   = get_post_types(
			array(
				'public'   => true,
				'_builtin' => false,
			)
		);
		$post_types[] = 'post';

		// Post parent.
		$parent_post_type = '';
		if ( is_attachment() ) {
			$attachment       = get_post();
			$parent_post_type = $attachment ? get_post_type($attachment->post_parent) : '';
		}

		$ayyash_screen = 'post';

		if ( is_home() ) {
			$ayyash_screen = 'blog'; // Blog.
		} elseif ( is_archive() && ! is_post_type_archive('product') ) {
			$ayyash_screen = 'archive'; // Archives.
		} elseif ( is_search() ) {
			$ayyash_screen = 'search'; // Search results.
			// @phpstan-ignore-next-line
		} elseif ( is_singular($post_types) || ( is_attachment() && in_array($parent_post_type, $post_types, true) ) ) {
			$ayyash_screen = 'post'; // Posts and public custom post types.
		} elseif ( is_page() || ( is_attachment() && 'page' === $parent_post_type ) ) {
			$ayyash_screen = 'page'; // Pages.
		}

		return apply_filters('ayyash_current_screen', $ayyash_screen);
	}
}

if ( ! function_exists( 'ayyash_get_sidebar_position' ) ) {
	/**
	 * Get Sidebar Position.
	 *
	 * @param string $screen current view.
	 *
	 * @return string
	 */
	function ayyash_get_sidebar_position( $screen = '' ) {
		global $ayyash_loaded_sidebar_position;

		if ( ! $screen ) {
			$screen = ayyash_get_current_screen();
		}

		if ( null === $ayyash_loaded_sidebar_position ) {
			$ayyash_loaded_sidebar_position = array();
		}

		if ( isset( $ayyash_loaded_sidebar_position[ $screen ] ) ) {
			return $ayyash_loaded_sidebar_position[ $screen ];
		}

		if ( class_exists( 'WooCommerce' ) && is_post_type_archive( 'product' ) ) {
			$position = ayyash_get_mod( 'woocommerce_shop_archive_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_product() ) {
			$position = ayyash_get_mod( 'woocommerce_single_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_cart() ) {
			$position = ayyash_get_mod( 'woocommerce_cart_sidebar_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_checkout() ) {
			$position = ayyash_get_mod( 'woocommerce_checkout_sidebar_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_account_page() ) {
			$position = ayyash_get_mod( 'woocommerce_myaccount_sidebar_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_product_category() ) {
			$position = ayyash_get_mod( 'woocommerce_taxonomy_archive_cat_layout' );
		} elseif ( class_exists( 'WooCommerce' ) && is_product_tag() ) {
			$position = ayyash_get_mod( 'woocommerce_taxonomy_archive_tag_layout' );
		} elseif ( class_exists( 'WeDevs_Dokan' ) && dokan_is_store_page() ) {
			$position = 'none';
		} else {
			/**
			 * @var string $single_sidebar_position
			 */
			$single_sidebar_position = ayyash_get_post_layout_options( 'content_layout' );
			if ( 'default' !== $single_sidebar_position && $single_sidebar_position ) {
				$position = $single_sidebar_position;
			} else {
				$position = ayyash_get_mod( 'layout_' . $screen . '_sidebar' );
				// In case current screen is modified and not found in default values.
				if ( ! $position ) {
					$position = 'none';
				}
			}
		}

		$ayyash_loaded_sidebar_position[ $screen ] = apply_filters( 'ayyash_sidebar_position', $position, $screen );

		return $ayyash_loaded_sidebar_position[ $screen ];
	}
}

if ( ! function_exists( 'ayyash_layzload_enabled' ) ) {
	/**
	 * Checks if lazy-loading images is enabled.
	 *
	 * @return bool
	 */
	function ayyash_layzload_enabled() {
		return (bool) ayyash_get_mod( 's_config_lazyload_enable' );
	}
}

if ( ! function_exists( 'ayyash_doing_rest' ) ) {
	/**
	 * Ayyash rest api request
	 *
	 * @return false|mixed|void
	 */
	function ayyash_doing_rest() {
		if ( empty( $_SERVER['REQUEST_URI'] ) ) {
			return false;
		}

		$rest_prefix         = trailingslashit( rest_get_url_prefix() );
		$is_rest_api_request = ( false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix ) ); // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		return apply_filters( 'ayyash_is_rest_api_request', $is_rest_api_request );
	}
}

if ( ! function_exists( 'ayyash_maybe_lazyload_post_thumbnail' ) ) {
	/**
	 * Ayyash lazyload post thumbnail
	 *
	 * @return mixed|void
	 */
	function ayyash_maybe_lazyload_post_thumbnail() {
		return apply_filters(
			'ayyash_lazyload_post_thumbnail',
			(
				ayyash_layzload_enabled() &&
				! is_admin() &&
				! wp_doing_ajax() &&
				! ayyash_doing_rest()
			)
		);
	}
}

if ( ! function_exists( 'ayyash_search_menu_icon' ) ) {
	/**
	 * Mobile search icon
	 *
	 * @param string $items nav items.
	 * @param object $args  nav args.
	 *
	 * @return string
	 */
	function ayyash_search_menu_icon() {
		if ( ayyash_get_mod( 'layout_header_search' ) ) {
			?>

			<div class="ayyash-header-search d-none d-md-block dropdown" id="ayyash-header-search">
				<a href="#" class="search-icon dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" ><i class="ai ai-search"></i></a>
				<div class="ayyash-header-search-box dropdown-menu"><?php get_search_form( array( 'echo' => true ) ); ?></div>
			</div>

			<?php
		}
	}
}

if ( ! function_exists( 'ayyash_mobile_icon' ) ) {
	/**
	 * Mobile Menu Icon.
	 *
	 * @return void
	 */
	function ayyash_mobile_icon() {
		$mobile_icon_grid = ayyash_get_mod( 'layout_header_menu_mobileshow' );

		switch ( $mobile_icon_grid ) {
			case 'sm':
				$mobile_icon_grid = ' d-block d-md-none';
				break;
			case 'md':
				$mobile_icon_grid = ' d-block d-lg-none';
				break;
			case 'lg':
				$mobile_icon_grid = ' d-block d-xl-none';
				break;
			case 'xl':
				$mobile_icon_grid = ' d-block';
				break;
			default:
				$mobile_icon_grid = ' d-block d-xl-none';
		}
		?>
		<a href="#" id="ayyash-mobile-toggle" class="<?php echo esc_attr( $mobile_icon_grid ); ?>" role="button" aria-controls="navigation-mobile">
			<i class="ai ai-hamburger" aria-hidden="true"></i>
		</a>
		<?php
	}
}

if ( ! function_exists( 'ayyash_get_mobile_menu' ) ) {
	/**
	 * Get Mobile Menu
	 *
	 * @return void
	 */
	function ayyash_get_mobile_menu() {
		if ( has_nav_menu( 'mobile' ) ) {
			wp_nav_menu( array( 'theme_location' => 'mobile' ) );
		} else {
			wp_nav_menu(
				array(
					'theme_location' => 'primary',
					'mobile'         => true,
				)
			);
		}
	}
}

if ( ! function_exists( 'ayyash_header_user_account_info' ) ) {
	/**
	 * Right Nav Panel.
	 *
	 * @return void
	 */
	function ayyash_header_user_account_info() {
		$stat  = is_user_logged_in();
		$label = $stat ? __( 'My Account', 'ayyash' ) : __( 'Sign Up / Log In', 'ayyash' );
		$title = $stat ? __( 'My Account', 'ayyash' ) : __( 'Login', 'ayyash' );
		/** @noinspection HtmlUnknownTarget */
		printf(
			'<a class="ayyash-signup hidden-xs" href="%s" title="%s"> <i class="ti-user" aria-hidden="true"></i> %s</a>',
			esc_url( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) ), // @phpstan-ignore-line
			esc_attr( $title ),
			esc_html( $label )
		);
	}
}

if ( ! function_exists( 'ayyash_wp_page_menu' ) ) {

	/**
	 * Display or retrieve list of pages with optional home link.
	 *
	 * This function is copied from WP wp_page_menu function to add an extra class as
	 * the default WP function has no inbuilt way to achieve this without using hacks
	 *
	 * @param array $args args.
	 *
	 * @return string html menu
	 */
	function ayyash_wp_page_menu( $args = array() ) {
		$defaults = array(
			'sort_column' => 'menu_order, post_title',
			'menu_class'  => 'menu',
			'echo'        => true,
			'link_before' => '',
			'link_after'  => '',
		);
		$args     = wp_parse_args( $args, $defaults );

		/**
		 * Filter the arguments used to generate a page-based menu.
		 *
		 * @see wp_page_menu()
		 *
		 * @param array $args An array of page menu arguments.
		 */
		$args = apply_filters( 'wp_page_menu_args', $args ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound,WPThemeReview.CoreFunctionality.PrefixAllGlobals.NonPrefixedHooknameFound

		$menu = '';

		$list_args = $args;

		// Show Home in the menu.
		if ( ! empty( $args['show_home'] ) ) {
			if ( true === $args['show_home'] || '1' === $args['show_home'] || 1 === $args['show_home'] ) {
				$text = __( 'Home', 'ayyash' );
			} else {
				$text = $args['show_home'];
			}
			$class = '';
			if ( is_front_page() && ! is_paged() ) {
				$class = 'class="current_page_item"';
			}
			$menu .= '<li ' . $class . '><a href="' . home_url( '/' ) . '">' . $args['link_before'] . $text . $args['link_after'] . '</a></li>';

			// If the front page is a page, add it to the exclude list.
			if ( 'page' === get_option( 'show_on_front' ) ) {
				if ( ! empty( $list_args['exclude'] ) ) {
					$list_args['exclude'] .= ',';
				} else {
					$list_args['exclude'] = ''; // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude
				}
				$list_args['exclude'] .= get_option( 'page_on_front' );
			}
		}

		$list_args['echo']     = false;
		$list_args['depth']    = 1;
		$list_args['title_li'] = '';
		$menu                 .= str_replace( array( "\r", "\n", "\t" ), '', wp_list_pages( $list_args ) ); // @phpstan-ignore-line

		if ( $menu ) {
			$menu = '<ul class="nav navbar-nav">' . $menu . '</ul>';
		}

		$menu = '<div class="' . esc_attr( $args['menu_class'] ) . '">' . $menu . "</div>\n";

		/**
		 * Filter the HTML output of a page-based menu.
		 *
		 * @see wp_page_menu()
		 *
		 * @param string $menu The HTML output.
		 * @param array $args An array of arguments.
		 */
		$menu = apply_filters( 'wp_page_menu', $menu, $args ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound,WPThemeReview.CoreFunctionality.PrefixAllGlobals.NonPrefixedHooknameFound

		if ( $args['echo'] ) {
			echo $menu; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
		return $menu;
	}
}

if ( class_exists( 'WooCommerce' ) ) {
	/**
	 * CPT notice.
	 *
	 * @return void
	 */
	function ayyash_show_cpt_archive_notice() {
		global $post;
		$shop_page_id = wc_get_page_id( 'shop' );
		if ( $post && absint( $shop_page_id ) === absint( $post->ID ) ) {
			?>
			<div class="notice notice-warning">
				<p><?php esc_html_e( 'If you are in shop page which is selected as WooCommerce archive page then page option will not work. You have to select settings from Customizer', 'ayyash' ); ?></p>
			</div>
			<?php
		}
	}

	add_action( 'admin_notices', 'ayyash_show_cpt_archive_notice', 100 );
}

if ( ! function_exists( 'ayyash_wpcf7_form_class_attr') ) {
	/**
	 * Contact Form 7 wpcf7_form_class_attr callback
	 *
	 * @param $class
	 *
	 * @return string
	 */
	function ayyash_wpcf7_form_class_attr( $class ) {
		$class .= ' ayyash-' . ayyash_get_mod( 'layout_wpcf7_columns' );

		$inline_acceptance_btn = ayyash_get_mod('layout_wpcf7_inline_acceptance_btn');

		if ( $inline_acceptance_btn ) {
			$class .= ' ayyash-inline-acceptance-btn';
		}

		return $class;
	}

	add_filter( 'wpcf7_form_class_attr', 'ayyash_wpcf7_form_class_attr', 10, 1 );
}

/**
 * Get Layout for a view.
 *
 * @param string $view View.
 *
 * @return string
 */
function ayyash_get_content_layout( $view = '' ) {
	if ( '' === $view ) {
		$view = ayyash_get_current_screen();
	}

	$layout = wp_cache_get( 'layout_' . $view . '_style' );

	if ( false === $layout ) {
		$layout = ayyash_get_mod( 'layout_' . $view . '_style' );
		wp_cache_set( 'layout_' . $view . '_style', $layout );
	}

	return apply_filters( 'ayyash_content_layout', $layout, $view );
}

/**
 * Get post format content class for layout.
 *
 * @param string $layout
 * @param string $class
 *
 * @return void
 */
function ayyash_get_post_format_classes( $layout = 'normal', $class = '' ) {

	$map = [ 'grid', 'normal', 'medium' ];

	if ( ! in_array( $layout, $map, true ) ) {
		$layout = 'normal';
	}

	$format  = get_post_format();
	$classes = [
		'blog-' . $layout,
		'post-' . $format,
		'entry-' . $format . '-post-format',
		$format,
	];

	if ( 'medium' === $layout ) {
		$classes[] = 'medium-left';
	}

	if ( 'gallery' === $format ) {
		$classes[] = 'carousel';
		$classes[] = 'slide';
		$classes[] = 'blog-gallery-slider';
	}

	// Animations
	$classes[] = 'effect';
	$classes[] = 'slide-top';

	if ( ! empty( $class ) ) {
		if ( is_string( $class ) ) {
			$class = preg_split( '#\s+#', $class );
		}

		if ( is_array( $class ) ) {
			$classes = array_merge( $classes, $class );
		}
	}

	if ( ! is_array( $class ) ) {
		// Ensure that we always coerce class to being an array.
		$class = array();
	}

	/**
	 * Filters the list of CSS post-format class names for the current post in the loop.
	 *
	 * @param string[] $classes An array of body class names.
	 * @param string[] $class   An array of additional class names added to the body.
	 */
	$classes = apply_filters( 'ayyash_post_format_class', $classes, $class );

	$classes = array_map( 'esc_attr', $classes );

	echo 'class="' . esc_attr( implode( ' ', array_unique( $classes ) ) ) . '"';
}

/**
 * Render oEmbed content.
 *
 * @param string $src Link to render.
 * @param bool $echo display or return content.
 *                       Default is true (display)
 *
 * @return void|string|false|true return embed html or false, true if displayed.
 *
 * @see WP_Embed::shortcode()
 * WP Embed uses current (global) post's id (meta) to cache the oEmbed api responses.
 */
function ayyash_render_embedded( $src, $echo = true ) {
	global $wp_embed;

	if ( ! strpos( $src, '://' ) ) {
		$src = ( is_ssl() ? 'http' : 'https' ) . '://' . $src;
	}

	$src = esc_url_raw( $src );
	if ( ! $src ) {
		return;
	}

	$embedded = $wp_embed->run_shortcode( '[embed]' . $src . '[/embed]' );

	$embedded = apply_filters( 'ayyash_render_embedded', $embedded, $src );

	if ( ! $echo ) {
		return $embedded;
	}

	if ( $embedded ) {
		echo $embedded; // phpcs:ignore WordPress.Security.EscapeOutput
		return true;
	}
	return false;
}

/**
 * Gets the first instance of a block in the content, and then break away.
 *
 * Scrapped from Twenty Twenty-One 1.0
 *
 * @param string      $block_name The full block type name, or a partial match.
 *                                Example: `core/image`, `core-embed/*`.
 * @param string|null $content    The content to search in. Use null for get_the_content().
 * @param int         $instances  How many instances of the block will be printed (max). Defaults to 1.
 *
 * @return bool Returns true if a block was located & printed, otherwise false.
 */
function ayyash_get_first_instance_of_block( $block_name, $content = null, $instances = 1 ) {

	if ( ! $content ) {
		$content = get_the_content();
	}

	// Parse blocks in the content.
	$blocks = parse_blocks( $content );

	$instances_count = 0;
	$blocks_content  = '';

	// Loop blocks.
	foreach ( $blocks as $block ) {

		// Sanity check.
		if ( ! isset( $block['blockName'] ) ) {
			continue;
		}

		// Check if this the block matches the $block_name.
		// If the block ends with *, try to match the first portion.
		/** @noinspection PhpLanguageLevelInspection */
		if ( '*' === $block_name[-1] ) {
			$is_matching_block = 0 === strpos( $block['blockName'], rtrim( $block_name, '*' ) );
		} else {
			$is_matching_block = $block_name === $block['blockName'];
		}

		if ( $is_matching_block ) {

			// Add the block HTML.
			$blocks_content .= render_block( $block );

			// Increment count.
			$instances_count++;

			// Break the loop if the $instances count was reached.
			if ( $instances_count >= $instances ) {
				break;
			}
		}
	}

	if ( $blocks_content ) {
		return apply_filters( 'the_content', $blocks_content ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound,WPThemeReview.CoreFunctionality.PrefixAllGlobals.NonPrefixedHooknameFound
	}

	return false;
}

/**
 * Print the first instance of a block in the content, and then break away.
 *
 * Scrapped from Twenty Twenty-One 1.0
 *
 * @param string      $block_name The full block type name, or a partial match.
 *                                Example: `core/image`, `core-embed/*`.
 * @param string|null $content    The content to search in. Use null for get_the_content().
 * @param int         $instances  How many instances of the block will be printed (max). Defaults to 1.
 *
 * @return void
 */
function ayyash_print_first_instance_of_block( $block_name, $content = null, $instances = 1 ) {
	echo ayyash_get_first_instance_of_block( $block_name, $content, $instances ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * Ayyash Post view Count
 */
if ( ! function_exists( 'ayyash_post_view_count' ) ) {
	/**
	 * Ayyash post view count
	 *
	 * @return void
	 */
	function ayyash_post_view_count() {
		if ( ! isset($_POST['nonce']) || wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), basename(__FILE__)) ) {
			return;
		}

		$count_key      = 'ayyash_post_views_count';
		$post_id        = intval( isset( $_POST['post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) : '' );
		$view_count     = get_post_meta( $post_id, $count_key, true );
		$view_count     = ( '' == $view_count ) ? 0 : $view_count;
		$new_view_count = $view_count + 1;

		if ( metadata_exists('post', $post_id, $count_key ) ) {
			update_post_meta( $post_id, $count_key, $new_view_count );
		} else {
			add_post_meta( $post_id, $count_key, $new_view_count );
		}
	}
	add_action('wp_ajax_ayyash_post_view_count', 'ayyash_post_view_count');
}

/**
 * Ayyash Post Excerpt
 */
if ( ! function_exists( 'get_ayyash_excerpt' ) ) {
	/**
	 * Ayyash Excerpt for Homepage.
	 *
	 * @return string
	 */
	function get_ayyash_excerpt( $post_id = '', $excerpt_length = '' ) {

		//set excerpt length
		if ( ! empty($excerpt_length ) ) {
			$excerpt_length;
		} else {
			$excerpt_length = 30;
		}

		//set excerpt
		$excerpt = '';
		if ( ! empty($post_id) ) {
			$excerpt = explode(' ', get_the_excerpt($post_id), $excerpt_length);
		} else {
			$excerpt = explode(' ', get_the_excerpt(), $excerpt_length);
		}

		if ( count($excerpt) >= $excerpt_length ) {
			array_pop($excerpt);
			$excerpt = implode(' ', $excerpt) . '...';
		} else {
			$excerpt = implode(' ', $excerpt);
		}

		return preg_replace('`\[[^\]]*\]`', '', $excerpt);
	}
}

/**
 * Ayyash blog home page date
 */
if ( ! function_exists( 'ayyash_date' ) ) {
	/**
	 * Function Name        : ayyash_date
	 * Function return Type : html
	 * Function Since       : 1.0.0
	 *
	 * @return void
	 */
	function ayyash_date() {

		if ( ayyash_get_mod('layout_blog_home_date') ) {
			$date_format = ayyash_get_mod('layout_blog_home_date_format');
			?>
			<div class="ayyash-date ms-lg-auto">
				<i class="fas fa-calendar-alt"></i>
				<?php echo esc_html( wp_date( $date_format ) ); ?>
			</div>
			<?php
		}
	}
}

/**
 * Ayyash blog home Category Menu
 */
if ( ! function_exists( 'ayyash_cat_menu' ) ) {
	/**
	 * Function Name        : ayyash_cat_menu
	 * Function Hooked      : ayyash_home_page_sections
	 * Function return Type : html
	 * Function Since       : 1.0.0
	 *
	 * @return void
	 */
	function ayyash_cat_menu() {

		if ( ! ayyash_get_mod( 'layout_blog_home_category' ) ) {
			return;
		}

		$get_cat_all_slug = ayyash_get_mod('layout_blog_home_categories_menu_control');

		$categories = [];
		if ( ! empty( $get_cat_all_slug ) ) {
			foreach ( $get_cat_all_slug as $single_cat_slug ) {
				$categories [] = get_term_by( 'slug', $single_cat_slug, 'category' ); //get selected category by slug
			}
		}

		?>
		<ul class="ayyash-cat-menu d-none d-lg-block">
			<li class="active"><a href="#">All</a></li>
			<?php foreach ( $categories as $category ) {
				printf( '<li><a href="%1$s">%2$s</a></li>',
					esc_url( get_category_link( $category->term_id ) ),
					esc_html( $category->name )
				);
			} ?>
		</ul>

		<div class="ayyash-mobile-cat-menu d-lg-none">
			<select class="ayyash-cat-select" id="ayyash-cat-select">
				<option selected>All</option selected>
				<?php foreach ( $categories as $category ) {
					printf( '<option value="%1$s">%2$s</option>',
						esc_attr( $category->term_id ),
						esc_html( $category->name )
					);
				} ?>
			</select>

			<?php
			/*Use this wp core function for change location*/
			echo wp_kses_post( build_dropdown_script_block_core_categories( 'ayyash-cat-select' ) );
			?>
		</div>
		<?php
	}
}

if ( ! function_exists( 'ayyash_transparent_background' ) ) {

	/**
	 * Header Transparent background
	 *
	 * @return false|string|void
	 */
	function ayyash_transparent_background() {
		$enable_background_transparency = ayyash_get_mod( 'layout_header_transparency_positioning' );
		$header_transparent_cls         = 'transparent-header';

		$excluded_pages_list = ayyash_get_mod( 'layout_header_transparency_exclude_pages' );
		$excluded_pages      = explode( ',', str_replace( ' ', '', $excluded_pages_list ) );

		// Enables transparent header for starter content
		if ( is_page_template( 'template-starter.php' ) ) {
			return $header_transparent_cls;
		}

		// Enable transparent header based on customizer settings
		if ( $enable_background_transparency ) {
			if ( is_front_page() && ! ayyash_get_mod( 'layout_header_transparency_front_page' ) ) {
				return $header_transparent_cls;
			} elseif ( is_home() && ! ayyash_get_mod( 'layout_header_transparency_disable_posts' ) ) {
				return $header_transparent_cls;
			} elseif ( is_page() && ! ayyash_get_mod( 'layout_header_transparency_disable_pages' ) ) {
				return $header_transparent_cls;
			} elseif ( is_archive() && ! ayyash_get_mod( 'layout_header_transparency_disable_archives' ) ) {
				return $header_transparent_cls;
			} elseif ( is_search() && ! ayyash_get_mod( 'layout_header_transparency_disable_search' ) ) {
				return $header_transparent_cls;
			} elseif ( is_404() && ! ayyash_get_mod( 'layout_header_transparency_disable_404' ) ) {
				return $header_transparent_cls;
			} elseif ( function_exists( 'is_woocommerce' ) && is_woocommerce() && ! ayyash_get_mod( 'layout_header_transparency_disable_products' ) ) {
				return $header_transparent_cls;
			} elseif ( ! empty( $excluded_pages_list ) ) {
				if ( is_page( $excluded_pages ) ) {
					return $header_transparent_cls;
				}
			} else {
				return false;
			}
		}
	}
}

if ( ! function_exists( 'ayyash_filter_attachment_image_attributes' ) ) {
	/**
	 * Filters the list of attachment image attributes.
	 *
	 * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
	 *
	 * @return string[]
	 * @see wp_get_attachment_image()
	 */
	function ayyash_filter_attachment_image_attributes( $attr ) {

		if ( ! ayyash_maybe_lazyload_post_thumbnail() ) {
			return $attr;
		}

		// Data Src.
		$attr['data-src'] = $attr['src'];

		// Setting 1px as default placeholder gif image.
		$attr['src'] = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';

		/**
		 * @TODO Make a new image size ayyash_lazy_preview with soft crop.
		 *       get the src for ayyash_lazy_preview size & set as src for the img, and set some blur effect with css.
		 *       it also needs to be tested with loading="lazy" attribute.
		 */

		// Data Src Set.
		if ( isset( $attr['srcset'] ) ) {
			$attr['data-srcset'] = $attr['srcset'];
			unset( $attr['srcset'] );
		}

		// Lazy & no-js support classes.
		$attr['class'] .= ' lazy hide-if-no-js';

		// support for bootstrap image responsive class for wc loop.
		if ( ! empty( $attr['auto_size'] ) ) {
			unset( $attr['auto_size'] );
			$attr['class'] .= ' img-responsive';
		}

		return $attr;
	}
}
