<?php
/**
 * Additional features to allow styling of the templates.
 *
 * @package ComRepair
 */

/**
 * Adds custom classes to the array of body classes.
 */
function comrepair_body_classes( $classes ) {
	// Add class if sidebar is used
	if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
		if ( is_active_sidebar( 'shop-sidebar-1' ) ) {
			$classes[] = 'has-sidebar';

			if ( is_shop() || is_product_taxonomy() || is_product_category() || is_product_tag() ) {
				$classes[] = 'columns-3';
			}
		}
	} elseif ( is_active_sidebar( 'sidebar-1' ) && ( ! is_singular() || is_singular( 'post' ) ) && ! is_404() ) {
		$classes[] = 'has-sidebar';
	}
	// Add class if we're viewing the Customizer for easier styling of theme options.
	if ( is_customize_preview() ) {
		$classes[] = 'comrepair-customizer';
	}
	// Add class if page header is hidden on the page.
	if ( ! comrepair_show_page_header() ) {
		$classes[] = 'hide-page-header';
	}
	// Add class if Site Title and Tagline are hidden.
	if ( comrepair_is_site_branding_text_hidden() ) {
		$classes[] = 'hide-site-branding-text';
	}
	return $classes;
}
add_filter( 'body_class', 'comrepair_body_classes' );

/**
 * A "before" part of the wrapper of the main content on pages which were not built using
 * Visual Composer.
 *
 * The reason we don't want to wrap VC pages is because we don't want to be adding the
 * extra padding or margin that comes with the wrapper. This is because it's easier to add
 * those paddings or margins via Visual Composer itself.
 */
function comrepair_page_main_wrap_before() {
	if ( ! comrepair_is_vc_active_on_page() ) {
		echo '<div class="container">';
		echo '	<div class="main-wrap">';
	}
}
add_action( 'comrepair_page_main_before', 'comrepair_page_main_wrap_before' );
add_action( 'comrepair_single_main_before', 'comrepair_page_main_wrap_before' );

/**
 * An "after" part of the wrapper of the main content on pages which were not built using
 * Visual Composer.
 */
function comrepair_page_main_wrap_after() {
	if ( ! comrepair_is_vc_active_on_page() ) {
		echo '	</div><!-- .main-wrap -->';
		echo '</div><!-- .container -->';
	}
}
add_action( 'comrepair_page_main_after', 'comrepair_page_main_wrap_after' );
add_action( 'comrepair_single_main_after', 'comrepair_page_main_wrap_after' );

/**
 * Returns i18n friendly Google Fonts url.
 * As described in https://themeshaper.com/2014/08/13/how-to-add-google-fonts-to-wordpress-themes/
 */
function comrepair_google_fonts_url() {
	/* translators: If there are characters in your language that are not
	 * supported by Cabin, translate this to 'off'. Do not translate
	 * into your own language.
	 */
	$cabin = _x( 'on', 'Cabin font: on or off', 'comrepair' );
	/* translators: If there are characters in your language that are not
	 * supported by Open Sans, translate this to 'off'. Do not translate
	 * into your own language.
	 */
	$open_sans = _x( 'on', 'Open Sans font: on or off', 'comrepair' );
	if ( 'off' === $cabin && 'off' === $open_sans ) {
		return '';
	}
	$fonts = array();
	if ( 'off' !== $cabin ) {
		$fonts[] = 'Cabin:400,700';
	}
	if ( 'off' !== $open_sans ) {
		$fonts[] = 'Open Sans:300,300i,400,400i,700,700i';
	}
	$query_args = array(
		'family' => rawurlencode( implode( '|', $fonts ) ),
		'subset' => rawurlencode( 'latin,latin-ext' ),
	);
	return esc_url_raw( add_query_arg( $query_args, '//fonts.googleapis.com/css' ) );
}

/**
 * Returns a CSS string with style overrides based on customized theme options.
 */
function comrepair_get_inline_style() {
	$css = '';
	if ( $header_bg_color = get_theme_mod( 'header_bg_color' ) ) {
		$css .= '.page-title-wrap { background-color: ' . $header_bg_color . '; } ';
	}
	if ( $footer_bg_image_id = get_theme_mod( 'footer_bg_image_id' ) ) {
		$footer_bg_image_url = wp_get_attachment_image_url( $footer_bg_image_id, 'full' );
		$css .= '.site-footer { background-image: url(' . esc_url( $footer_bg_image_url ) . '); } ';
	}
	if ( $footer_bg_color = get_theme_mod( 'footer_bg_color' ) ) {
		$css .= '.footer-top-wrap { background-color: ' . $footer_bg_color . '; } ';
	}
	if ( $footer_bottom_bg_color = get_theme_mod( 'footer_bottom_bg_color' ) ) {
		$css .= '.footer-bottom-wrap { background-color: ' . $footer_bottom_bg_color . '; } ';
	}
	return $css;
}

/**
 * A filter to allow some additional tags and attributes in the content which are not allowed
 * by default in WordPress.
 */
function comrepair_wp_kses_allowed_html( $tags, $context ) {
	// <time></time>
	$tags['time'] = array( 'datetime' => true );
	// <span></span>
	if ( ! isset( $tags['span'] ) ) {
		$tags['span'] = array();
	}
	$tags['span']['class'] = true;
	return $tags;
}
add_filter( 'wp_kses_allowed_html', 'comrepair_wp_kses_allowed_html', 10, 2 );

/**
 * A filter to allow skype: protocol in the links.
 */
function comrepair_kses_allowed_protocols( $protocols ) {
	$protocols[] = 'skype';
	return $protocols;
}
add_filter( 'kses_allowed_protocols', 'comrepair_kses_allowed_protocols' );

/**
 * A filter to customize the arguments passed to the WP Tag Cloud Widget generating function.
 */
function comrepair_tag_cloud_args( $args ) {
	$args['smallest'] = $args['largest'] = 1;
	$args['unit'] = 'em';
	$args['separator'] = ', ';
	return $args;
}
add_filter( 'widget_tag_cloud_args', 'comrepair_tag_cloud_args' );
add_filter( 'woocommerce_product_tag_cloud_widget_args', 'comrepair_tag_cloud_args' );

/**
 * Finds an appropriate theme setting value by the key, first trying a post_meta for the
 * given key (prefixed with our theme slug) and if not found then trying a theme_mod.
 *
 * Useful for cases where we have a theme_mod which we want to be able to override on some
 * pages using post_meta.
 */
function comrepair_get_setting( $key ) {
	$post_meta = get_post_meta( get_the_ID(), '_comrepair_' . $key, true );
	if ( ! empty( $post_meta ) ) {
		return $post_meta;
	}
	global $comrepair_defaults;
	return get_theme_mod( $key, $comrepair_defaults[ $key ] );
}

/**
 * Check whether we should show the page header on the current page.
 */
function comrepair_show_page_header() {
	if ( ! is_singular() ) {
		return ! is_front_page();
	}
	$post_meta = get_post_meta( get_the_ID(), '_comrepair_show_page_header', true );
	if ( ! empty( $post_meta ) ) {
		return 'show' === $post_meta;
	}
	if ( is_front_page() ) {
		return false;
	}
	return 'hide' !== get_theme_mod( 'show_page_header' );
}

/**
 * Check if Visual Composer is activated on the current page.
 */
function comrepair_is_vc_active_on_page() {
	$vc_status = get_post_meta( get_the_ID(), '_wpb_vc_js_status', true );
	return $vc_status && 'false' !== $vc_status;
}

/**
 * Query WooCommerce plugin activation.
 */
function comrepair_is_woocommerce_activated() {
	return class_exists( 'WooCommerce' ) ? true : false;
}

/**
 * Retreives the footer tagline string which was set via the Customizer.
 */
function comrepair_get_footer_tagline() {
	return html_entity_decode( get_theme_mod( 'footer_tagline', comrepair_get_default( 'footer_tagline' ) ) );
}

/**
 * Converts a given date string into relative date format (e.g 10 minutes ago).
 */
function comrepair_to_relative_date( $date ) {
	$now = current_time( 'timestamp' );
	$date = strtotime( $date );
	if ( $now - $date < MINUTE_IN_SECONDS ) {
		return _x( 'just now', 'relative time', 'comrepair' );
	} else {
		/* translators: relative time format, e.g 10 minutes ago */
		return sprintf( _x( '%s ago', 'relative time', 'comrepair' ), human_time_diff( $date, $now ) );
	}
}

/**
 * Checks that a user with the given user id is the author of the post.
 */
function comrepair_is_post_author( $user_id, $post_id = null ) {
	return ( $user_id > 0 ) && ( $post = get_post( $post_id ) ) && ( $user_id === $post->post_author );
}

/**
 * Checks whether the given info block is active and should be displayed.
 */
function comrepair_is_active_header_info_block( $id ) {
	return '' !== get_theme_mod( 'header_info_block_text_' . $id, '' );
}

/**
 * Checks whether Site Title and Tagline text were hidden via an option in the Customizer.
 */
function comrepair_is_site_branding_text_hidden() {
	return 'blank' === get_header_textcolor();
}

/**
 * Initialize the $wp_filesystem global if it was not initialized before.
 */
function comrepair_init_wp_filesystem() {
	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}
	global $wp_filesystem;
	if ( ! $wp_filesystem ) {
		WP_Filesystem();
	}
	return $wp_filesystem;
}

/**
 * Recursive search and replace.
 *  - If $data argument is a string then a regular string search and replace is performed.
 *  - If $data argument is an array then search and replace is called recursively for each value.
 *  - If $data argument is an object then search and replace is called recursively for each object var.
 *  - Otherwise the $data is returned unmodified.
 */
function comrepair_recursive_replace( $from, $to, $data ) {
	if ( is_string( $data ) ) {
		$data = str_replace( $from, $to, $data );
	} elseif ( is_array( $data ) ) {
		$_tmp = array();
		foreach ( $data as $key => $value ) {
			$_tmp[ $key ] = comrepair_recursive_replace( $from, $to, $value );
		}
		$data = $_tmp;
		unset( $_tmp );
	} elseif ( is_object( $data ) ) {
		$_tmp = $data;
		$props = get_object_vars( $data );
		foreach ( $props as $key => $value ) {
			$_tmp->$key = comrepair_recursive_replace( $from, $to, $value );
		}
		$data = $_tmp;
		unset( $_tmp );
	}
	return $data;
}
