<?php

if ( ! function_exists( 'mindful_blog_get_all_google_fonts' ) ) :
	/**
	 * Returns list of Google fonts.
	 */
	function mindful_blog_get_all_google_fonts() {
		$mindful_blog_webfonts_json   = get_template_directory() . '/inc/google-webfonts.json';
		$mindful_blog_fonts_json_data = file_get_contents( $mindful_blog_webfonts_json );

		$mindful_blog_all_fonts = json_decode( $mindful_blog_fonts_json_data, true );

		$mindful_blog_google_fonts = array();
		foreach ( $mindful_blog_all_fonts as $mindful_blog_font ) {
			$mindful_blog_google_fonts[ $mindful_blog_font['family'] ] = array(
				'family'   => $mindful_blog_font['family'],
				'variants' => $mindful_blog_font['variants'],
			);
		}
		return $mindful_blog_google_fonts;
	}
endif;

if ( ! function_exists( 'mindful_blog_get_all_google_font_families' ) ) :
	/**
	 * Returns list of Google font families.
	 */
	function mindful_blog_get_all_google_font_families() {
		$mindful_blog_google_fonts  = mindful_blog_get_all_google_fonts();
		$mindful_blog_font_families = array();
		foreach ( $mindful_blog_google_fonts as $mindful_blog_font ) {
			$mindful_blog_font_families[ $mindful_blog_font['family'] ] = $mindful_blog_font['family'];
		}
		return $mindful_blog_font_families;
	}
endif;

if ( ! function_exists( 'mindful_blog_get_fonts_url' ) ) :
	/**
	 * Return Google fonts URL.
	 */
	function mindful_blog_get_fonts_url() {
		$mindful_blog_fonts_url = '';
		$mindful_blog_fonts     = array();

		$mindful_blog_all_fonts = mindful_blog_get_all_google_fonts();

		if ( ! empty( get_theme_mod( 'mindful_blog_site_title_font', 'Josefin Sans' ) ) ) {
			$mindful_blog_fonts[] = get_theme_mod( 'mindful_blog_site_title_font', 'Josefin Sans' );
		}

		if ( ! empty( get_theme_mod( 'mindful_blog_site_description_font', 'Inder' ) ) ) {
			$mindful_blog_fonts[] = get_theme_mod( 'mindful_blog_site_description_font', 'Inder' );
		}

		if ( ! empty( get_theme_mod( 'mindful_blog_header_font', 'Inder' ) ) ) {
			$mindful_blog_fonts[] = get_theme_mod( 'mindful_blog_header_font', 'Inder' );
		}

		if ( ! empty( get_theme_mod( 'mindful_blog_body_font', 'Inder' ) ) ) {
			$mindful_blog_fonts[] = get_theme_mod( 'mindful_blog_body_font', 'Inder' );
		}

		$mindful_blog_fonts = array_unique( $mindful_blog_fonts );

		foreach ( $mindful_blog_fonts as $mindful_blog_font ) {
			$mindful_blog_variants      = $mindful_blog_all_fonts[ $mindful_blog_font ]['variants'];
			$mindful_blog_font_family[] = $mindful_blog_font . ':' . implode( ',', $mindful_blog_variants );
		}

		$mindful_blog_query_args = array(
			'family' => urlencode( implode( '|', $mindful_blog_font_family ) ),
		);

		if ( ! empty( $mindful_blog_font_family ) ) {
			$mindful_blog_fonts_url = add_query_arg( $mindful_blog_query_args, 'https://fonts.googleapis.com/css' );
		}

		return $mindful_blog_fonts_url;
	}
endif;
