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

    $resort_motel_fonts_json_data = file_get_contents( $resort_motel_webfonts_json );
    if ( false === $resort_motel_fonts_json_data ) {
        return array();
    }

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

    $resort_motel_google_fonts = array();
    foreach ( $resort_motel_all_fonts as $resort_motel_font ) {
        $resort_motel_google_fonts[ $resort_motel_font['family'] ] = array(
            'family'   => $resort_motel_font['family'],
            'variants' => $resort_motel_font['variants'],
        );
    }
    return $resort_motel_google_fonts;
}


function resort_motel_get_all_google_font_families() {
    $resort_motel_google_fonts  = resort_motel_get_all_google_fonts();
    $resort_motel_font_families = array();
    foreach ( $resort_motel_google_fonts as $resort_motel_font ) {
        $resort_motel_font_families[ $resort_motel_font['family'] ] = $resort_motel_font['family'];
    }
    return $resort_motel_font_families;
}

function resort_motel_get_fonts_url() {
    $resort_motel_fonts_url = '';
    $resort_motel_fonts     = array();

    $resort_motel_all_fonts = resort_motel_get_all_google_fonts();

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

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

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

    if ( ! empty( get_theme_mod( 'resort_motel_content_font', 'Poppins' ) ) ) {
        $resort_motel_fonts[] = get_theme_mod( 'resort_motel_content_font', 'Poppins' );
    }

    $resort_motel_fonts = array_unique( $resort_motel_fonts );

    foreach ( $resort_motel_fonts as $resort_motel_font ) {
        $resort_motel_variants      = $resort_motel_all_fonts[ $resort_motel_font ]['variants'];
        $resort_motel_font_family[] = $resort_motel_font . ':' . implode( ',', $resort_motel_variants );
    }

    $query_args = array(
        'family' => urlencode( implode( '|', $resort_motel_font_family ) ),
    );

    if ( ! empty( $resort_motel_font_family ) ) {
        $resort_motel_fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
    }

    return $resort_motel_fonts_url;
}