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

    $dog_pet_house_fonts_json_data = file_get_contents( $dog_pet_house_webfonts_json );
    if ( false === $dog_pet_house_fonts_json_data ) {
        return array();
    }

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

    $dog_pet_house_google_fonts = array();
    foreach ( $dog_pet_house_all_fonts as $dog_pet_house_font ) {
        $dog_pet_house_google_fonts[ $dog_pet_house_font['family'] ] = array(
            'family'   => $dog_pet_house_font['family'],
            'variants' => $dog_pet_house_font['variants'],
        );
    }
    return $dog_pet_house_google_fonts;
}


function dog_pet_house_get_all_google_font_families() {
    $dog_pet_house_google_fonts  = dog_pet_house_get_all_google_fonts();
    $dog_pet_house_font_families = array();
    foreach ( $dog_pet_house_google_fonts as $dog_pet_house_font ) {
        $dog_pet_house_font_families[ $dog_pet_house_font['family'] ] = $dog_pet_house_font['family'];
    }
    return $dog_pet_house_font_families;
}

function dog_pet_house_get_fonts_url() {
    $dog_pet_house_fonts_url = '';
    $dog_pet_house_fonts     = array();

    $dog_pet_house_all_fonts = dog_pet_house_get_all_google_fonts();

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

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

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

    if ( ! empty( get_theme_mod( 'dog_pet_house_content_font', 'Kodchasan' ) ) ) {
        $dog_pet_house_fonts[] = get_theme_mod( 'dog_pet_house_content_font', 'Kodchasan' );
    }

    $dog_pet_house_fonts = array_unique( $dog_pet_house_fonts );

    foreach ( $dog_pet_house_fonts as $dog_pet_house_font ) {
        $dog_pet_house_variants      = $dog_pet_house_all_fonts[ $dog_pet_house_font ]['variants'];
        $dog_pet_house_font_family[] = $dog_pet_house_font . ':' . implode( ',', $dog_pet_house_variants );
    }

    $dog_pet_house_query_args = array(
        'family' => urlencode( implode( '|', $dog_pet_house_font_family ) ),
    );

    if ( ! empty( $dog_pet_house_font_family ) ) {
        $dog_pet_house_fonts_url = add_query_arg( $dog_pet_house_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $dog_pet_house_fonts_url;
}