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

    $jeweler_shop_fonts_json_data = file_get_contents( $jeweler_shop_webfonts_json );
    if ( false === $jeweler_shop_fonts_json_data ) {
        return array();
    }

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

    $jeweler_shop_google_fonts = array();
    foreach ( $jeweler_shop_all_fonts as $jeweler_shop_font ) {
        $jeweler_shop_google_fonts[ $jeweler_shop_font['family'] ] = array(
            'family'   => $jeweler_shop_font['family'],
            'variants' => $jeweler_shop_font['variants'],
        );
    }
    return $jeweler_shop_google_fonts;
}

function jeweler_shop_get_all_google_font_families() {
    $jeweler_shop_google_fonts  = jeweler_shop_get_all_google_fonts();
    $jeweler_shop_font_families = array();
    foreach ( $jeweler_shop_google_fonts as $jeweler_shop_font ) {
        $jeweler_shop_font_families[ $jeweler_shop_font['family'] ] = $jeweler_shop_font['family'];
    }
    return $jeweler_shop_font_families;
}

function jeweler_shop_get_fonts_url() {
    $jeweler_shop_fonts_url = '';
    $jeweler_shop_fonts     = array();

    $jeweler_shop_all_fonts = jeweler_shop_get_all_google_fonts();

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

    if ( ! empty( get_theme_mod( 'jeweler_shop_site_description_font', 'Playfair Display' ) ) ) {
        $jeweler_shop_fonts[] = get_theme_mod( 'jeweler_shop_site_description_font', 'Playfair Display' );
    }

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

    if ( ! empty( get_theme_mod( 'jeweler_shop_content_font', 'Playfair Display' ) ) ) {
        $jeweler_shop_fonts[] = get_theme_mod( 'jeweler_shop_content_font', 'Playfair Display' );
    }

    $jeweler_shop_fonts = array_unique( $jeweler_shop_fonts );

    foreach ( $jeweler_shop_fonts as $jeweler_shop_font ) {
        $jeweler_shop_variants      = $jeweler_shop_all_fonts[ $jeweler_shop_font ]['variants'];
        $jeweler_shop_font_family[] = $jeweler_shop_font . ':' . implode( ',', $jeweler_shop_variants );
    }

    $jeweler_shop_query_args = array(
        'family' => urlencode( implode( '|', $jeweler_shop_font_family ) ),
    );

    if ( ! empty( $jeweler_shop_font_family ) ) {
        $jeweler_shop_fonts_url = add_query_arg( $jeweler_shop_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $jeweler_shop_fonts_url;
}