<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package wpmedia
 */

/* Exit if accessed directly */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function wpmedia_body_classes( $classes ) {
	$classes[] = 'idtheme kentooz';
	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	/* Blog layout */
	$layout = get_theme_mod( 'gmr_active-sticky-sidebar', 0 );

	if ( 0 !== $layout ) {
		$classes[] = 'gmr-disable-sticky';
	}

	/* Blog layout */
	$layout = get_theme_mod( 'gmr_layout', 'full-layout' );

	if ( 'box-layout' === $layout ) {
		$classes[] = 'gmr-box-layout';
	}

	return $classes;
}
add_filter( 'body_class', 'wpmedia_body_classes' );

/**
 * Adds custom classes to the array of post classes.
 *
 * @param array $classes Classes for the post element.
 * @return array
 */
function wpmedia_post_classes( $classes ) {
	if ( is_page() ) {
		$classes = array_diff( $classes, array( 'hentry' ) );
	}
	return $classes;
}
add_filter( 'post_class', 'wpmedia_post_classes' );

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function wpmedia_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'wpmedia_pingback_header' );

if ( ! function_exists( 'wpmedia_custom_excerpt_length' ) ) :
	/**
	 * Filter the except length to 8 characters.
	 *
	 * @since 1.0.0
	 *
	 * @param int $length Excerpt length.
	 * @return int (Maybe) modified excerpt length.
	 */
	function wpmedia_custom_excerpt_length( $length ) {
		$length = get_theme_mod( 'gmr_excerpt_number', 8 );
		// absint sanitize int non minus.
		return absint( $length );
	}
endif; // endif wpmedia_custom_excerpt_length.
add_filter( 'excerpt_length', 'wpmedia_custom_excerpt_length', 999 );

if ( ! function_exists( 'wpmedia_excerpt_more' ) ) :
	/**
	 * Filter the excerpt "read more" string.
	 *
	 * @param string $more "Read more" excerpt string.
	 * @return string (Maybe) modified "read more" excerpt string.
	 */
	function wpmedia_excerpt_more( $more ) {
		return '...';
	}
endif;
add_filter( 'excerpt_more', 'wpmedia_excerpt_more', 100 );

/**
 * Remove category, author tag and archive text title
 *
 * @since 1.0.0
 * @param array $title Title.
 * @return array
 */
function wpmedia_change_titlearchive( $title ) {
	if ( is_category() ) {
		$title = single_cat_title( '', false );
	} elseif ( is_tag() ) {
		$title = single_tag_title( '', false );
	} elseif ( is_author() ) {
		$author_id = get_the_author_meta( 'ID' );
		$title     = '<span class="vcard">' . get_the_author() . '</span><span class="author-numberpost">' . count_user_posts( $author_id ) . ' ' . esc_html__( 'Posts', 'wpmedia' ) . '</span>';
	} elseif ( is_tax() ) { // for custom post types.
		$title = sprintf( '%1$s', single_term_title( '', false ) );
	} elseif ( is_post_type_archive() ) {
		$title = post_type_archive_title( '', false );
	}
	return $title;
}
add_filter( 'get_the_archive_title', 'wpmedia_change_titlearchive' );

if ( ! function_exists( 'wpmedia_head_script' ) ) :
	/**
	 * Insert script in head section
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function wpmedia_head_script() {
		$ampheadscript = get_theme_mod( 'gmr_head_script_amp' );
		$headscript    = get_theme_mod( 'gmr_head_script' );
		if ( wpmedia_is_amp() ) {
			if ( isset( $ampheadscript ) && ! empty( $ampheadscript ) ) {
				echo $ampheadscript; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
		} else {
			if ( isset( $headscript ) && ! empty( $headscript ) ) {
				echo $headscript; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
		}
	}
endif; /* endif wpmedia_head_script */
add_action( 'wp_head', 'wpmedia_head_script' );

if ( ! function_exists( 'wpmedia_footer_script' ) ) :
	/**
	 * Insert script in footer section
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function wpmedia_footer_script() {
		$ampfooterscript = get_theme_mod( 'gmr_footer_script_amp' );
		$footerscript    = get_theme_mod( 'gmr_footer_script' );
		if ( wpmedia_is_amp() ) {
			if ( isset( $ampfooterscript ) && ! empty( $ampfooterscript ) ) {
				echo $ampfooterscript; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
		} else {
			if ( isset( $footerscript ) && ! empty( $footerscript ) ) {
				echo $footerscript; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
		}
	}
endif; /* endif wpmedia_footer_script */
add_action( 'wp_footer', 'wpmedia_footer_script' );

if ( ! function_exists( 'gmr_embed_oembed_html' ) ) :
	/**
	 * Add responsive oembed class only for youtube and vimeo.
	 *
	 * @add_filter embed_oembed_html
	 * @class gmr_embed_oembed_html
	 * @param string $html displaying html Format.
	 * @param string $url url ombed like youtube, video.
	 * @param string $attr Attribute Iframe.
	 * @param int    $post_id Post ID.
	 * @link https://developer.wordpress.org/reference/hooks/embed_oembed_html/
	 */
	function gmr_embed_oembed_html( $html, $url, $attr, $post_id ) {
		$classes = array();
		/* Add these classes to all embeds. */
		$classes_all = array(
			'gmr-video-responsive',
		);

		/* Check for different providers and add appropriate classes. */
		if ( false !== strpos( $url, 'vimeo.com' ) ) {
			$classes[] = 'gmr-embed-responsive gmr-embed-responsive-16by9';
		}

		if ( false !== strpos( $url, 'youtube.com' ) ) {
			$classes[] = 'gmr-embed-responsive gmr-embed-responsive-16by9';
		}

		if ( false !== strpos( $url, 'youtu.be' ) ) {
			$classes[] = 'gmr-embed-responsive gmr-embed-responsive-16by9';
		}

		$classes = array_merge( $classes, $classes_all );

		if ( has_block( 'core/embed' ) ) {
			return $html;
		} else {
			return '<div class="' . esc_attr( implode( ' ', $classes ) ) . '">' . $html . '</div>';
		}
	}
endif; /* endif gmr_embed_oembed_html */
add_filter( 'embed_oembed_html', 'gmr_embed_oembed_html', 99, 4 );

if ( ! function_exists( 'wpmedia_google_analytic' ) ) :
	/**
	 * Insert google analytics script via wp_footer hook
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function wpmedia_google_analytic() {
		$analyticid = get_theme_mod( 'gmr_analytic' );
		if ( isset( $analyticid ) && ! empty( $analyticid ) ) {
			if ( wpmedia_is_amp() ) {
				echo '<amp-analytics type="gtag" data-credentials="include">
				<script type="application/json">
				{
				  "vars" : {
					"gtag_id": "' . esc_attr( $analyticid ) . '",
					"config" : {
					  "' . esc_attr( $analyticid ) . '": { "groups": "default" }
					}
				  }
				}
				</script>
				</amp-analytics>
				';
			} else {
				echo '
				<!-- Google analytics -->
				<script>
					window.dataLayer = window.dataLayer || [];
					function gtag(){dataLayer.push(arguments);}
					gtag(\'js\', new Date());
					gtag(\'config\', \'' . esc_attr( $analyticid ) . '\');
				</script>';
			}
		}
	}
endif; /* endif wpmedia_google_analytic */
add_action( 'wp_footer', 'wpmedia_google_analytic', 10 );

if ( ! function_exists( 'wpmedia_facebook_pixel' ) ) :
	/**
	 * Insert facebook pixel script via wp_head hook
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function wpmedia_facebook_pixel() {
		$fbpixelid = get_theme_mod( 'gmr_pixel' );
		if ( isset( $fbpixelid ) && ! empty( $fbpixelid ) ) {
			if ( wpmedia_is_amp() ) {
				echo '<amp-pixel src="https://www.facebook.com/tr?id=' . esc_attr( $fbpixelid ) . '&ev=PageView&noscript=1" layout="nodisplay"></amp-pixel>';
			} else {
				echo '
				<!-- Facebook Pixel -->
				<script>
				!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
				n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
				n.push=n;n.loaded=!0;n.version=\'2.0\';n.queue=[];t=b.createElement(e);t.async=!0;
				t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
				document,\'script\',\'https://connect.facebook.net/en_US/fbevents.js\');

				fbq(\'init\', \'' . esc_attr( $fbpixelid ) . '\');
				fbq(\'track\', "PageView");</script>
				<noscript><img height="1" width="1" style="display:none"
				src="https://www.facebook.com/tr?id=' . esc_attr( $fbpixelid ) . '&ev=PageView&noscript=1"
				/></noscript>';
			}
		}
	}
endif; /* endif wpmedia_facebook_pixel */
add_action( 'wp_head', 'wpmedia_facebook_pixel', 10 );

if ( ! function_exists( 'wpmedia_nav_description' ) ) :
	/**
	 * Insert facebook pixel script via wp_head hook
	 *
	 * @param string $item_output Output item.
	 * @param string $item item.
	 * @param string $depth menu level.
	 * @param array  $args Argument.
	 * @since 1.0.0
	 * @return string
	 */
	function wpmedia_nav_description( $item_output, $item, $depth, $args ) {
		if ( ! empty( $item->description ) ) {
			$item_with_desc_output = str_replace( '">', '" data-desciption="' . esc_attr( $item->description ) . '">', $item_output );
			return $item_with_desc_output;
		}

		return $item_output;
	}
endif; /* endif wpmedia_nav_description */
add_filter( 'walker_nav_menu_start_el', 'wpmedia_nav_description', 10, 4 );

/**
 * Remove emoji CDN hostname from DNS prefetching hints.
 *
 * @param  array  $urls          URLs to print for resource hints.
 * @param  string $relation_type The relation type the URLs are printed for.
 * @return array                 Difference betwen the two arrays.
 */
function wpmedia_disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
	if ( 'dns-prefetch' === $relation_type ) {
		/** This filter is documented in wp-includes/formatting.php */
		$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );

		$urls = array_diff( $urls, array( $emoji_svg_url ) );
	}

	return $urls;
}

/**
 * Filter out the tinymce emoji plugin.
 *
 * @param array $plugins Plugins.
 */
function wpmedia_disable_emojis_tinymce( $plugins ) {
	if ( is_array( $plugins ) ) {
		return array_diff( $plugins, array( 'wpemoji' ) );
	} else {
		return array();
	}
}

/**
 * Disable the emoji's.
 */
function wpmedia_disable_emojis() {
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
	remove_action( 'wp_print_styles', 'print_emoji_styles' );
	remove_action( 'admin_print_styles', 'print_emoji_styles' );
	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
	add_filter( 'wp_resource_hints', 'wpmedia_disable_emojis_remove_dns_prefetch', 10, 2 );
	// Remove from TinyMCE.
	add_filter( 'tiny_mce_plugins', 'wpmedia_disable_emojis_tinymce' );
}

$removeemoji = get_theme_mod( 'gmr_remove-emoji', 0 );
if ( 0 !== $removeemoji ) {
	add_action( 'init', 'wpmedia_disable_emojis' );
}

/**
 * Remove post view counter style if using manual options.
 */
add_filter( 'pvc_enqueue_styles', '__return_false' );

if ( ! function_exists( 'gmr_thumbnail_upscale' ) ) :
	/**
	 * Thumbnail upscale
	 *
	 * @since 1.0.0
	 *
	 * @Source http://wordpress.stackexchange.com/questions/50649/how-to-scale-up-featured-post-thumbnail
	 * @param array $default for image sizes.
	 * @param array $orig_w for width orginal.
	 * @param array $orig_h for height sizes image original.
	 * @param array $new_w new width image sizes.
	 * @param array $new_h new height image sizes.
	 * @param bool  $crop croping for image sizes.
	 * @return array
	 */
	function gmr_thumbnail_upscale( $default, $orig_w, $orig_h, $new_w, $new_h, $crop ) {
		if ( ! $crop ) {
			return null;
		}

		if ( $orig_w <= 0 || $orig_h <= 0 ) {
			return null;
		}

		if ( $new_w <= 0 || $new_h <= 0 ) {
			return null;
		}

		$aspect_ratio = $orig_w / $orig_h;
		$size_ratio   = max( $new_w / $orig_w, $new_h / $orig_h );

		$crop_w = round( $new_w / $size_ratio );
		$crop_h = round( $new_h / $size_ratio );

		$s_x = floor( ( $orig_w - $crop_w ) / 2 );
		$s_y = floor( ( $orig_h - $crop_h ) / 2 );

		return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
	}
endif; // endif gmr_thumbnail_upscale.
add_filter( 'image_resize_dimensions', 'gmr_thumbnail_upscale', 10, 6 );
