<?php

namespace Dispatch\Functions;

class Assets {

    protected $styles;
    protected $scripts;

    public function __construct() {

        $this->styles = array([
            'src' => 'assets/dist/css/theme-styles.css',
        ]);

        $this->scripts = array([
            'src' => 'assets/dist/scripts/main.min.js',
            'in_footer' => true,
        ]);

        add_filter( 'wp_enqueue_scripts', [$this, 'init'] );

        add_filter( 'wp_enqueue_scripts', function(){
            wp_enqueue_script('jquery', false, array(), false, false);
        }, 1 );

    }

    public function init() {

        // wp_enqueue_style( 'fontastic-DWxNFxhfhUx3uzYsSgKeri', '//file.myfontastic.com/DWxNFxhfhUx3uzYsSgKeri/icons.css', array(), '', 'all' );
        wp_enqueue_script( 'google-maps', '//maps.googleapis.com/maps/api/js?key=' . get_field('google_api_key', 'options'), array(), '', 'all' );
        if ( get_field('at_pubid', 'options') ) {
            wp_enqueue_script( 'addthis', '//s7.addthis.com/js/300/addthis_widget.js#pubid=' . get_field('at_pubid', 'options'), array(), '', 'all' );
        }

        foreach( $this->styles as $style ) {

            $style = $this->format_asset( $style, 'style' );

            if ( isset( $style['exists'] ) && $style['exists'] ) {
                wp_enqueue_style( $style['handle'], $style['src'], $style['deps'], $style['ver'], $style['media'] );
            }

        }

        foreach( $this->scripts as $script ) {

            $script = $this->format_asset( $script, 'script' );

            if ( isset( $script['exists'] ) && $script['exists'] ) {
                wp_enqueue_script( $script['handle'], $script['src'], $script['deps'], $script['ver'], $script['media'] );
            }

        }

        wp_localize_script( sanitize_key('assets/dist/scripts/main.min.js'), 'qw_obj', [
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ] );
        wp_enqueue_script( 'juicer-embed-no-jquery', '//assets.juicer.io/embed-no-jquery.js', array(), '', 'all' );

    }

    private function format_asset( $asset, $asset_type = 'style' ) {

        $asset['deps'] = isset( $asset['deps'] ) ? $asset['deps'] : array();
        $asset['media'] = isset( $asset['media'] ) ? $asset['media'] : 'all';
        $asset['in_footer'] = isset( $asset['in_footer'] ) ? $asset['in_footer'] : ( $asset_type == 'style' ? false : true );
        $asset['handle'] = isset( $asset['handle'] ) ? $asset['handle'] : sanitize_key( $asset['src'] );

        if(!preg_match("@\/\/@", $asset['src'])) {
            if(file_exists(get_stylesheet_directory().'/'.$asset['src'])){
                $asset['ver'] = filemtime(get_stylesheet_directory().'/'.$asset['src']);
                $asset['exists'] = true;
            }
            $asset['src'] = get_stylesheet_directory_uri() . '/' . $asset['src'];
        }

        return $asset;

    }

}
