<?php

namespace App;

use Roots\Sage\Container;
use Roots\Sage\Assets\JsonManifest;
use Roots\Sage\Template\Blade;
use Roots\Sage\Template\BladeProvider;

/**
 * I18n
*/
add_action('after_setup_theme', function () {
    load_theme_textdomain('thor', get_template_directory() . '/lang');
});

add_filter('get_search_form', function () {
    return template(config('theme.dir') . '/resources/views/searchform.blade.php');
});

/**
 * Theme assets
 */
add_action('wp_enqueue_scripts', function () {
    wp_register_script('thor/main.js', asset_path('scripts/main.js'), ['jquery', 'wp-i18n'], null, true);

    // $translations = wp_set_script_translations( 'thor/main.js', 'thor', get_template_directory().'/resources/lang/it_IT.json' );

    $data = array(
        'baseApi' => get_home_url(null, 'wp-json/wp/v2'),
        'results' => __('Results', 'thor'),
    );
    wp_localize_script( 'thor/main.js', 'wpData', $data );
    // wp_register_script('gmaps-api', 'https://maps.googleapis.com/maps/api/js?key=', array('jquery'), null, true);
    wp_enqueue_script('thor/main.js');

    wp_enqueue_style('thor/main.css', asset_path('styles/main.css'), false, null);

    if (is_single() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}, 100);

/**
 * this function is used to insert in the pot file the translation strings
 * used in javascript that otherwise would not be detected
*/
function loadTranslationInJavaScript() {
    __('Search', 'thor');
    __('Results', 'thor');
    __('No results', 'thor');
}

/**
 * Theme setup
 */
add_action('after_setup_theme', function () {
    /**
     * Enable features from Soil when plugin is activated
     * @link https://roots.io/plugins/soil/
     */
    add_theme_support('soil-clean-up');
    add_theme_support('soil-jquery-cdn');
    add_theme_support('soil-nav-walker');
    add_theme_support('soil-nice-search');
    add_theme_support('soil-relative-urls');

    /**
     * Enable plugins to manage the document title
     * @link https://developer.wordpress.org/reference/functions/add_theme_support/#title-tag
     */
    add_theme_support('title-tag');

    /**
     * Register navigation menus
     * @link https://developer.wordpress.org/reference/functions/register_nav_menus/
     */
    register_nav_menus([
        'primary_navigation' => __('Primary Navigation', 'thor'),
    ]);
    register_nav_menus([
        'language_selector' => __('Language Selector', 'thor'),
    ]);

    /**
     * Enable post thumbnails
     * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
     */
    add_theme_support('post-thumbnails');

    add_image_size( 'mini', 70, 9999 );
    add_image_size( 'full_hd', 1920, 9999 );

    //medium size support
    update_option( 'medium_size_w', 600 );
    update_option( 'medium_size_h', 9999 );
    update_option( 'medium_crop', 0 );

    //medium size support
    update_option( 'medium_large_size_w', 1024 );
    update_option( 'medium_large_size_h', 9999 );
    update_option( 'medium_large_crop', 0 );

    //large size support
    update_option( 'large_size_w', 1440 );
    update_option( 'large_size_h', 9999 );
    update_option( 'large_crop', 0 );

    /**
     * Enable HTML5 markup support
     * @link https://developer.wordpress.org/reference/functions/add_theme_support/#html5
     */
    add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);

    /**
     * Enable selective refresh for widgets in customizer
     * @link https://developer.wordpress.org/themes/advanced-topics/customizer-api/#theme-support-in-sidebars
     */
    add_theme_support('customize-selective-refresh-widgets');
}, 20);

/**
 * Register sidebars
 */
add_action('widgets_init', function () {
    $config = [
        'before_widget' => '<section class="widget %1$s %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>'
    ];
    register_sidebar([
        'name'          => __('Top Bar left', 'thor'),
        'id'            => 'top-bar-left'
    ] + $config);
    register_sidebar([
        'name'          => __('Top Bar right', 'thor'),
        'id'            => 'top-bar-right'
    ] + $config);
    register_sidebar([
        'name'          => __('Primary', 'thor'),
        'id'            => 'sidebar-primary'
    ] + $config);
    register_sidebar([
        'name'          => __('Pre Footer', 'thor'),
        'id'            => 'prefooter'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer', 'thor'),
        'id'            => 'footer'
    ] + $config);
    register_sidebar([
        'name'          => __('Credits', 'thor'),
        'id'            => 'credits'
    ] + $config);
});

/**
 * Updates the `$post` variable on each iteration of the loop.
 * Note: updated value is only available for subsequently loaded views, such as partials
 */
add_action('the_post', function ($post) {
    $keys = [];
    $fields = [];

    switch ($post->post_type) {
        case 'post':
            $keys = [];
            break;
    }

    foreach($keys as $key) {
        $fields[$key] = get_field($key, $post);
    }

    sage('blade')->share('fields', $fields);
    sage('blade')->share('post', $post);
});

add_filter('wp_nav_menu_objects', function ($items, $args) {
    foreach ($items as &$item) {
        $style = get_field('item_style', $item);
        if ($style) {
            $item->classes[] = $style;
            $item->classes[] = 'small';
        }
    }


    // return
    return $items;
}, 10, 2);

/**
 * Setup Sage options
 */
add_action('after_setup_theme', function () {
    /**
     * Add JsonManifest to Sage container
     */
    sage()->singleton('sage.assets', function () {
        return new JsonManifest(config('assets.manifest'), config('assets.uri'));
    });

    /**
     * Add Blade to Sage container
     */
    sage()->singleton('sage.blade', function (Container $app) {
        $cachePath = config('view.compiled');
        if (!file_exists($cachePath)) {
            wp_mkdir_p($cachePath);
        }
        (new BladeProvider($app))->register();
        return new Blade($app['view']);
    });

    /**
     * Create @asset() Blade directive
     */
    sage('blade')->compiler()->directive('asset', function ($asset) {
        return "<?= " . __NAMESPACE__ . "\\asset_path({$asset}); ?>";
    });

    /**
     * Create @svg() Blade directive
     */
    sage('blade')->compiler()->directive('svg', function ($path) {
        return "<?= " . __NAMESPACE__ . "\\insert_svg({$path}); ?>";
    });
});
