<?php
function cat_groomer_get_all_google_fonts() {
    $cat_groomer_webfonts_json = get_template_directory() . '/theme-library/google-webfonts.json';
    if ( ! file_exists( $cat_groomer_webfonts_json ) ) {
        return array();
    }

    $cat_groomer_fonts_json_data = file_get_contents( $cat_groomer_webfonts_json );
    if ( false === $cat_groomer_fonts_json_data ) {
        return array();
    }

    $cat_groomer_all_fonts = json_decode( $cat_groomer_fonts_json_data, true );
    if ( json_last_error() !== JSON_ERROR_NONE ) {
        return array();
    }

    $cat_groomer_google_fonts = array();
    foreach ( $cat_groomer_all_fonts as $cat_groomer_font ) {
        $cat_groomer_google_fonts[ $cat_groomer_font['family'] ] = array(
            'family'   => $cat_groomer_font['family'],
            'variants' => $cat_groomer_font['variants'],
        );
    }
    return $cat_groomer_google_fonts;
}


function cat_groomer_get_all_google_font_families() {
    $cat_groomer_google_fonts  = cat_groomer_get_all_google_fonts();
    $cat_groomer_font_families = array();
    foreach ( $cat_groomer_google_fonts as $cat_groomer_font ) {
        $cat_groomer_font_families[ $cat_groomer_font['family'] ] = $cat_groomer_font['family'];
    }
    return $cat_groomer_font_families;
}

function cat_groomer_get_fonts_url() {
    $cat_groomer_fonts_url = '';
    $cat_groomer_fonts     = array();

    $cat_groomer_all_fonts = cat_groomer_get_all_google_fonts();

    if ( ! empty( get_theme_mod( 'cat_groomer_site_title_font', 'Raleway' ) ) ) {
        $cat_groomer_fonts[] = get_theme_mod( 'cat_groomer_site_title_font', 'Raleway' );
    }

    if ( ! empty( get_theme_mod( 'cat_groomer_site_description_font', 'Raleway' ) ) ) {
        $cat_groomer_fonts[] = get_theme_mod( 'cat_groomer_site_description_font', 'Raleway' );
    }

    if ( ! empty( get_theme_mod( 'cat_groomer_header_font', 'Lilita One' ) ) ) {
        $cat_groomer_fonts[] = get_theme_mod( 'cat_groomer_header_font', 'Lilita One' );
    }

    if ( ! empty( get_theme_mod( 'cat_groomer_content_font', 'Kodchasan' ) ) ) {
        $cat_groomer_fonts[] = get_theme_mod( 'cat_groomer_content_font', 'Kodchasan' );
    }

    $cat_groomer_fonts = array_unique( $cat_groomer_fonts );

    foreach ( $cat_groomer_fonts as $cat_groomer_font ) {
        $cat_groomer_variants      = $cat_groomer_all_fonts[ $cat_groomer_font ]['variants'];
        $cat_groomer_font_family[] = $cat_groomer_font . ':' . implode( ',', $cat_groomer_variants );
    }

    $cat_groomer_query_args = array(
        'family' => urlencode( implode( '|', $cat_groomer_font_family ) ),
    );

    if ( ! empty( $cat_groomer_font_family ) ) {
        $cat_groomer_fonts_url = add_query_arg( $cat_groomer_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $cat_groomer_fonts_url;
}