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

    $aster_startup_fonts_json_data = file_get_contents( $aster_startup_webfonts_json );
    if ( false === $aster_startup_fonts_json_data ) {
        return array();
    }

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

    $aster_startup_google_fonts = array();
    foreach ( $aster_startup_all_fonts as $aster_startup_font ) {
        $aster_startup_google_fonts[ $aster_startup_font['family'] ] = array(
            'family'   => $aster_startup_font['family'],
            'variants' => $aster_startup_font['variants'],
        );
    }
    return $aster_startup_google_fonts;
}


function aster_startup_get_all_google_font_families() {
    $aster_startup_google_fonts  = aster_startup_get_all_google_fonts();
    $aster_startup_font_families = array();
    foreach ( $aster_startup_google_fonts as $aster_startup_font ) {
        $aster_startup_font_families[ $aster_startup_font['family'] ] = $aster_startup_font['family'];
    }
    return $aster_startup_font_families;
}

function aster_startup_get_fonts_url() {
    $aster_startup_fonts_url = '';
    $aster_startup_fonts     = array();

    $aster_startup_all_fonts = aster_startup_get_all_google_fonts();

    if ( ! empty( get_theme_mod( 'aster_startup_site_title_font', 'Oswald' ) ) ) {
        $aster_startup_fonts[] = get_theme_mod( 'aster_startup_site_title_font', 'Oswald' );
    }

    if ( ! empty( get_theme_mod( 'aster_startup_site_description_font', 'Mulish' ) ) ) {
        $aster_startup_fonts[] = get_theme_mod( 'aster_startup_site_description_font', 'Nunito' );
    }

    if ( ! empty( get_theme_mod( 'aster_startup_header_font', 'Cormorant Garamond' ) ) ) {
        $aster_startup_fonts[] = get_theme_mod( 'aster_startup_header_font', 'Nunito' );
    }

    if ( ! empty( get_theme_mod( 'aster_startup_content_font', 'Mulish' ) ) ) {
        $aster_startup_fonts[] = get_theme_mod( 'aster_startup_content_font', 'Nunito' );
    }

    $aster_startup_fonts = array_unique( $aster_startup_fonts );

    foreach ( $aster_startup_fonts as $aster_startup_font ) {
        $aster_startup_variants      = $aster_startup_all_fonts[ $aster_startup_font ]['variants'];
        $aster_startup_font_family[] = $aster_startup_font . ':' . implode( ',', $aster_startup_variants );
    }

    $aster_startup_query_args = array(
        'family' => urlencode( implode( '|', $aster_startup_font_family ) ),
    );

    if ( ! empty( $aster_startup_font_family ) ) {
        $aster_startup_fonts_url = add_query_arg( $aster_startup_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $aster_startup_fonts_url;
}

