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

    $design_studio_fonts_json_data = file_get_contents( $design_studio_webfonts_json );
    if ( false === $design_studio_fonts_json_data ) {
        return array();
    }

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

    $design_studio_google_fonts = array();
    foreach ( $design_studio_all_fonts as $design_studio_font ) {
        $design_studio_google_fonts[ $design_studio_font['family'] ] = array(
            'family'   => $design_studio_font['family'],
            'variants' => $design_studio_font['variants'],
        );
    }
    return $design_studio_google_fonts;
}

function design_studio_get_all_google_font_families() {
    $design_studio_google_fonts  = design_studio_get_all_google_fonts();
    $design_studio_font_families = array();
    foreach ( $design_studio_google_fonts as $design_studio_font ) {
        $design_studio_font_families[ $design_studio_font['family'] ] = $design_studio_font['family'];
    }
    return $design_studio_font_families;
}

function design_studio_get_fonts_url() {
    $design_studio_fonts_url = '';
    $design_studio_fonts     = array();

    $design_studio_all_fonts = design_studio_get_all_google_fonts();

    if ( ! empty( get_theme_mod( 'design_studio_site_title_font', 'Sora' ) ) ) {
        $design_studio_fonts[] = get_theme_mod( 'design_studio_site_title_font', 'Sora' );
    }

    if ( ! empty( get_theme_mod( 'design_studio_site_description_font', 'DM Sans' ) ) ) {
        $design_studio_fonts[] = get_theme_mod( 'design_studio_site_description_font', 'DM Sans' );
    }

    if ( ! empty( get_theme_mod( 'design_studio_header_font', 'Sora' ) ) ) {
        $design_studio_fonts[] = get_theme_mod( 'design_studio_header_font', 'Sora' );
    }

    if ( ! empty( get_theme_mod( 'design_studio_content_font', 'DM Sans' ) ) ) {
        $design_studio_fonts[] = get_theme_mod( 'design_studio_content_font', 'DM Sans' );
    }

    $design_studio_fonts = array_unique( $design_studio_fonts );

    foreach ( $design_studio_fonts as $design_studio_font ) {
        $design_studio_variants      = $design_studio_all_fonts[ $design_studio_font ]['variants'];
        $design_studio_font_family[] = $design_studio_font . ':' . implode( ',', $design_studio_variants );
    }

    $design_studio_query_args = array(
        'family' => urlencode( implode( '|', $design_studio_font_family ) ),
    );

    if ( ! empty( $design_studio_font_family ) ) {
        $design_studio_fonts_url = add_query_arg( $design_studio_query_args, 'https://fonts.googleapis.com/css' );
    }

    return $design_studio_fonts_url;
}