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

    $gamers_studio_fonts_json_data = file_get_contents( $gamers_studio_webfonts_json );
    if ( false === $gamers_studio_fonts_json_data ) {
        return array();
    }

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

    $gamers_studio_google_fonts = array();
    foreach ( $gamers_studio_all_fonts as $gamers_studio_font ) {
        $gamers_studio_google_fonts[ $gamers_studio_font['family'] ] = array(
            'family'   => $gamers_studio_font['family'],
            'variants' => $gamers_studio_font['variants'],
        );
    }
    return $gamers_studio_google_fonts;
}


function gamers_studio_get_all_google_font_families() {
    $gamers_studio_google_fonts  = gamers_studio_get_all_google_fonts();
    $gamers_studio_font_families = array();
    foreach ( $gamers_studio_google_fonts as $gamers_studio_font ) {
        $gamers_studio_font_families[ $gamers_studio_font['family'] ] = $gamers_studio_font['family'];
    }
    return $gamers_studio_font_families;
}

function gamers_studio_get_fonts_url() {
    $gamers_studio_fonts_url = '';
    $gamers_studio_fonts     = array();

    $gamers_studio_all_fonts = gamers_studio_get_all_google_fonts();

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

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

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

    if ( ! empty( get_theme_mod( 'gamers_studio_content_font', 'Jost' ) ) ) {
        $gamers_studio_fonts[] = get_theme_mod( 'gamers_studio_content_font', 'Jost' );
    }

    $gamers_studio_fonts = array_unique( $gamers_studio_fonts );

    foreach ( $gamers_studio_fonts as $gamers_studio_font ) {
        $gamers_studio_variants      = $gamers_studio_all_fonts[ $gamers_studio_font ]['variants'];
        $gamers_studio_font_family[] = $gamers_studio_font . ':' . implode( ',', $gamers_studio_variants );
    }

    $gamers_studio_query_args = array(
        'family' => urlencode( implode( '|', $gamers_studio_font_family ) ),
    );

    if ( ! empty( $gamers_studio_font_family ) ) {
        $gamers_studio_fonts_url = add_query_arg( $gamers_studio_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $gamers_studio_fonts_url;
}

