<?php

namespace App;

use Roots\Sage\Container;
use WP_Widget;
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('muy-lindo', get_template_directory() . '/lang');
});

/**
 * Theme assets
 */

// function my_acf_init() {
    
//     acf_update_setting('google_api_key', 'AIzaSyCHQelNIaR33oBRYG3CbVqEBBdHgjwLAz8');
// }

// add_action('acf/init', 'my_acf_init');


add_action('wp_enqueue_scripts', function () {

    $maps_api_key = get_field('google_maps_api_key', 'option');
    $theme_version = muy_theme_version();
    $data = array(
        'baseApi' => get_home_url(null, 'wp-json/wp/v2'),
    );

    wp_register_script('muy-lindo/main.js', asset_path('scripts/main.js'), ['jquery', 'wp-i18n'], $theme_version, true);
    wp_localize_script('muy-lindo/main.js', 'wpData', $data);

    wp_enqueue_script( 'overlayscript', asset_path('scripts/blocks/overlay-block.js'), array(), '', true );

    wp_enqueue_script('gmaps', 'https://maps.googleapis.com/maps/api/js?key='.$maps_api_key, array('jquery'), true, true);
    wp_enqueue_script('muy-lindo/main.js');

    wp_enqueue_style('muy-lindo/main.css', asset_path('styles/main.css'), false, $theme_version);

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

function muy_default_color($color) {
    $mainColor = "#1f0a31";
    $sideColor = "#f2f2f2";
    
    if($color == "main") {
        return $mainColor;
    } elseif ($color == "side") {
        return $sideColor;
    } else {
        return $sideColor;
    }
}

/**
 * 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', 'muy-lindo');
    __('No results', 'muy-lindo');
}

/**
 * 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([
        'preheader_navigation' => __('Pre Header Navigation', 'muy-lindo'),
        'primary_navigation' => __('Primary Navigation', 'muy-lindo'),
        'overlay_primary_navigation' => __('Overlay Primary Navigation', 'muy-lindo'),
        'right_menu' => __('Right Menu', 'muy-lindo'),
    ]);

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

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

    /**
     * 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>'
    ];
    if (get_theme_mod('muy_overlay_type') === 'overlay-2') {
        
        register_sidebar([
            'name'          => __('Overlay Left', 'muy-lindo'),
            'id'            => 'overlay-left'
        ] + $config);
        register_sidebar([
            'name'          => __('Overlay Center Left', 'muy-lindo'),
            'id'            => 'overlay-center-left'
        ] + $config);
        register_sidebar([
            'name'          => __('Overlay Center Right', 'muy-lindo'),
            'id'            => 'overlay-center-right'
        ] + $config);
        register_sidebar([
            'name'          => __('Overlay Right', 'muy-lindo'),
            'id'            => 'overlay-right'
        ] + $config);
    } else {
        register_sidebar([
            'name'          => __('Overlay Right', 'muy-lindo'),
            'id'            => 'overlay-right'
        ] + $config);
    }
    register_sidebar([
        'name'          => __('Pre Footer', 'muy-lindo'),
        'id'            => 'pre-footer'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer one', 'muy-lindo'),
        'id'            => 'footer-one'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer two', 'muy-lindo'),
        'id'            => 'footer-two'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer three', 'muy-lindo'),
        'id'            => 'footer-three'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer four', 'muy-lindo'),
        'id'            => 'footer-four'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer five', 'muy-lindo'),
        'id'            => 'footer-five'
    ] + $config);
    register_sidebar([
        'name'          => __('Footer credits', 'muy-lindo'),
        'id'            => 'footer-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);
});

class social_widget extends \WP_Widget
{

    function __construct()
    {
        parent::__construct(

            'social_widget',

            __('Social Bar', 'muy-lindo'),

            array('description' => __('Social Bar Widget - edit the socials in the customizer', 'muy-lindo'),)
        );
    }


    public function widget($args, $instance)
    {

        $socials = array(
            'facebook',
            'whatsapp',
            'youtube',
            'vimeo',
            'linkedin',
            'instagram',
            'twitter',
            'pinterest',
            'flickr'
        );

        echo '<div class="socialbar-container '. $instance['align'] .'">';
        echo '<div class="socialbar">';

        foreach ($socials as &$social) {

            if (get_theme_mod('muy_social_' . $social)) {
                echo '<a href="' . esc_url(get_theme_mod('muy_social_'.$social)) . '" target="_blank" title="' . __('' . $social . '', 'muy-lindo') . '" class="' . $social . '">';
                $svg = insert_svg('images/social/svg/' . $social . '.svg');
                echo $svg;
                echo '</a>';
            }
        }

        echo "</div>";
        echo "</div>";
    }

    public function form($instance)
    {
        if (isset($instance['title'])) {
            $title = $instance['title'];
        } else {
            $title = __('Social Bar', 'muy-lindo');
        }

        if (isset($instance['align'])) {
            $align = $instance['align'];
        } else {
            $align = 'left';
        }
    ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Social Bar:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
            <label style="margin-top: 12px;display: inline-block;" for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Alignment:'); ?></label>
            <select
                class="widefat"
                id="<?php echo $this->get_field_id('align'); ?>"
                name="<?php echo $this->get_field_name('align'); ?>"
                type="text"
                value="<?php echo esc_attr($align); ?>"
            >
                <option <?php selected( $instance['align'], 'left'); ?> value="left"><?= __('Left','muy-lindo') ?></option>
                <option <?php selected( $instance['align'], 'center'); ?> value="center"><?= __('Center','muy-lindo') ?></option>
                <option <?php selected( $instance['align'], 'right'); ?> value="right"><?= __('Right','muy-lindo') ?></option>
            </select>
        </p>
<?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['align'] = (!empty($new_instance['align'])) ? strip_tags($new_instance['align']) : '';
        return $instance;
    }
}

function social_load_widget()
{
    register_widget(__NAMESPACE__ . '\\social_widget');
}
add_action('widgets_init', __NAMESPACE__ . '\\social_load_widget');

/**
 * 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}); ?>";
    });
});
