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

    $aster_ebooks_fonts_json_data = file_get_contents( $aster_ebooks_webfonts_json );
    if ( false === $aster_ebooks_fonts_json_data ) {
        return array();
    }

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

    $aster_ebooks_google_fonts = array();
    foreach ( $aster_ebooks_all_fonts as $aster_ebooks_font ) {
        $aster_ebooks_google_fonts[ $aster_ebooks_font['family'] ] = array(
            'family'   => $aster_ebooks_font['family'],
            'variants' => $aster_ebooks_font['variants'],
        );
    }
    return $aster_ebooks_google_fonts;
}


function aster_ebooks_get_all_google_font_families() {
    $aster_ebooks_google_fonts  = aster_ebooks_get_all_google_fonts();
    $aster_ebooks_font_families = array();
    foreach ( $aster_ebooks_google_fonts as $aster_ebooks_font ) {
        $aster_ebooks_font_families[ $aster_ebooks_font['family'] ] = $aster_ebooks_font['family'];
    }
    return $aster_ebooks_font_families;
}

function aster_ebooks_get_fonts_url() {
    $aster_ebooks_fonts_url = '';
    $aster_ebooks_fonts     = array();

    $aster_ebooks_all_fonts = aster_ebooks_get_all_google_fonts();

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

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

    if ( ! empty( get_theme_mod( 'aster_ebooks_header_font', 'Plus Jakarta Sans' ) ) ) {
        $aster_ebooks_fonts[] = get_theme_mod( 'aster_ebooks_header_font', 'Plus Jakarta Sans' );
    }

    if ( ! empty( get_theme_mod( 'aster_ebooks_content_font', 'Plus Jakarta Sans' ) ) ) {
        $aster_ebooks_fonts[] = get_theme_mod( 'aster_ebooks_content_font', 'Plus Jakarta Sans' );
    }

    $aster_ebooks_fonts = array_unique( $aster_ebooks_fonts );

    foreach ( $aster_ebooks_fonts as $aster_ebooks_font ) {
        $aster_ebooks_variants      = $aster_ebooks_all_fonts[ $aster_ebooks_font ]['variants'];
        $aster_ebooks_font_family[] = $aster_ebooks_font . ':' . implode( ',', $aster_ebooks_variants );
    }

    $aster_ebooks_query_args = array(
        'family' => urlencode( implode( '|', $aster_ebooks_font_family ) ),
    );

    if ( ! empty( $aster_ebooks_font_family ) ) {
        $aster_ebooks_fonts_url = add_query_arg( $aster_ebooks_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $aster_ebooks_fonts_url;
}