<?php

namespace HelpGent\App\BackgroundServices;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\BackgroundProcessors\BackgroundProcessor;

class FontBackgroundService extends BackgroundService {
    public function boot(): void {
        $this->background_processor = new BackgroundProcessor( 'font_family' );
    }

    public static function download_font( $args = [] ): bool {
        $font_family = $args['font_family'];
        $directory   = helpgent_font_family_dir( $font_family );

        $wp_filesystem = helpgent_filesystem();

        if ( ! $wp_filesystem->is_dir( $directory ) ) {
            $wp_filesystem->mkdir( $directory );
        }

        $fonts      = json_decode( file_get_contents( helpgent_dir( 'app/fonts.json' ) ), true );
        $font_files = $fonts[ $font_family ]['files'];

        foreach ( $font_files as $variation => $variations ) {
            foreach ( $variations as $extension => $url ) {
                $file_name = "{$directory}/{$variation}.{$extension}";

                if ( ! is_file( $file_name ) ) {
                    /**
                     * Download font family
                     */
                    $font = wp_remote_get( $url );
                
                    if ( 200 === wp_remote_retrieve_response_code( $font ) ) {
                        $wp_filesystem->put_contents( $file_name, wp_remote_retrieve_body( $font ) );
                    }
                }
            }
        }

        return false;
    }
}