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

    $bike_workshop_fonts_json_data = file_get_contents( $bike_workshop_webfonts_json );
    if ( false === $bike_workshop_fonts_json_data ) {
        return array();
    }

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

    $bike_workshop_google_fonts = array();
    foreach ( $bike_workshop_all_fonts as $bike_workshop_font ) {
        $bike_workshop_google_fonts[ $bike_workshop_font['family'] ] = array(
            'family'   => $bike_workshop_font['family'],
            'variants' => $bike_workshop_font['variants'],
        );
    }
    return $bike_workshop_google_fonts;
}


function bike_workshop_get_all_google_font_families() {
    $bike_workshop_google_fonts  = bike_workshop_get_all_google_fonts();
    $bike_workshop_font_families = array();
    foreach ( $bike_workshop_google_fonts as $bike_workshop_font ) {
        $bike_workshop_font_families[ $bike_workshop_font['family'] ] = $bike_workshop_font['family'];
    }
    return $bike_workshop_font_families;
}

function bike_workshop_get_fonts_url() {
    $bike_workshop_fonts_url = '';
    $bike_workshop_fonts     = array();

    $bike_workshop_all_fonts = bike_workshop_get_all_google_fonts();

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

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

    if ( ! empty( get_theme_mod( 'bike_workshop_header_font', 'Epilogue' ) ) ) {
        $bike_workshop_fonts[] = get_theme_mod( 'bike_workshop_header_font', 'Epilogue' );
    }

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

    $bike_workshop_fonts = array_unique( $bike_workshop_fonts );

    foreach ( $bike_workshop_fonts as $bike_workshop_font ) {
        $bike_workshop_variants      = $bike_workshop_all_fonts[ $bike_workshop_font ]['variants'];
        $bike_workshop_font_family[] = $bike_workshop_font . ':' . implode( ',', $bike_workshop_variants );
    }

    $bike_workshop_query_args = array(
        'family' => urlencode( implode( '|', $bike_workshop_font_family ) ),
    );

    if ( ! empty( $bike_workshop_font_family ) ) {
        $bike_workshop_fonts_url = add_query_arg( $bike_workshop_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $bike_workshop_fonts_url;
}