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

    $burger_joint_fonts_json_data = file_get_contents( $burger_joint_webfonts_json );
    if ( false === $burger_joint_fonts_json_data ) {
        return array();
    }

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

    $burger_joint_google_fonts = array();
    foreach ( $burger_joint_all_fonts as $burger_joint_font ) {
        $burger_joint_google_fonts[ $burger_joint_font['family'] ] = array(
            'family'   => $burger_joint_font['family'],
            'variants' => $burger_joint_font['variants'],
        );
    }
    return $burger_joint_google_fonts;
}


function burger_joint_get_all_google_font_families() {
    $burger_joint_google_fonts  = burger_joint_get_all_google_fonts();
    $burger_joint_font_families = array();
    foreach ( $burger_joint_google_fonts as $burger_joint_font ) {
        $burger_joint_font_families[ $burger_joint_font['family'] ] = $burger_joint_font['family'];
    }
    return $burger_joint_font_families;
}

function burger_joint_get_fonts_url() {
    $burger_joint_fonts_url = '';
    $burger_joint_fonts     = array();

    $burger_joint_all_fonts = burger_joint_get_all_google_fonts();

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

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

    if ( ! empty( get_theme_mod( 'burger_joint_header_font', 'Bebas Neue' ) ) ) {
        $burger_joint_fonts[] = get_theme_mod( 'burger_joint_header_font', 'Bebas Neue' );
    }

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

    $burger_joint_fonts = array_unique( $burger_joint_fonts );

    foreach ( $burger_joint_fonts as $burger_joint_font ) {
        $burger_joint_variants      = $burger_joint_all_fonts[ $burger_joint_font ]['variants'];
        $burger_joint_font_family[] = $burger_joint_font . ':' . implode( ',', $burger_joint_variants );
    }

    $burger_joint_query_args = array(
        'family' => urlencode( implode( '|', $burger_joint_font_family ) ),
    );

    if ( ! empty( $burger_joint_font_family ) ) {
        $burger_joint_fonts_url = add_query_arg( $burger_joint_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $burger_joint_fonts_url;
}

