<?php

namespace App;

add_action('wp_dashboard_setup', function () {
    wp_add_dashboard_widget(
        'pim_dashboard_widget',
        esc_html__('Bitcream Dashboard PIM', 'wporg'),
        'App\PIM_dashboard'
    );

    global $wp_meta_boxes;
    $default_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
    $example_widget_backup = array('pim_dashboard_widget' => $default_dashboard['pim_dashboard_widget']);
    unset($default_dashboard['pim_dashboard_widget']);
    $sorted_dashboard = array_merge($example_widget_backup, $default_dashboard);
    $wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
});

add_filter('big_image_size_threshold', false);

function PIM_dashboard()
{
    $PIM_SITEURL = getenv("PIM_SITEURL");

    echo '<svg height="25" style="margin-top:10px;" width="auto" preserveAspectRatio="xMinYMin meet" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 309.48 57.91"><defs><style>.cls-1{fill:#1d2457;}.cls-2{fill:#00e67c;}</style></defs><g id="Livello_2" data-name="Livello 2"><g id="Livello_1-2" data-name="Livello 1"><rect class="cls-1" x="50.35" y="15.51" width="10" height="42.23"/><path class="cls-1" d="M21.38,15.16A21.18,21.18,0,0,0,10,18.47V0H0V36.35H0c0,.06,0,.12,0,.18A21.38,21.38,0,1,0,21.38,15.16Zm0,32.75A11.38,11.38,0,1,1,32.76,36.53,11.39,11.39,0,0,1,21.38,47.91Z"/><path class="cls-2" d="M116,57.91A21.38,21.38,0,1,1,131.1,21.42L124,28.49a11.38,11.38,0,1,0,0,16.09l7.07,7.07A21.24,21.24,0,0,1,116,57.91Z"/><path class="cls-2" d="M203.05,36.53a20.87,20.87,0,0,0-.59-4.9A21.35,21.35,0,1,0,197,51.41l-7.18-7a11.37,11.37,0,0,1-18.33-2.82h31.53Zm-31.62-4.9a11.35,11.35,0,0,1,20.5,0Z"/><path class="cls-2" d="M250.87,36.53a21.38,21.38,0,1,0-21.38,21.38,21.18,21.18,0,0,0,11.38-3.31v3h10v-21h0ZM229.49,47.91a11.38,11.38,0,1,1,11.38-11.38A11.39,11.39,0,0,1,229.49,47.91Z"/><path class="cls-2" d="M294.23,15.16a15.19,15.19,0,0,0-10.26,4,15.23,15.23,0,0,0-25.51,11.26V57.65h10V30.41a5.26,5.26,0,0,1,10.51,0V57.65h10V30.41a5.26,5.26,0,0,1,10.51,0V57.65h10V30.41A15.27,15.27,0,0,0,294.23,15.16Z"/><path class="cls-2" d="M136.41,36.63h0v21h10V37.12c0-6.27,5.1-12.13,11.38-12.13V15C146.15,15,136.68,25.07,136.41,36.63Z"/><path class="cls-1" d="M89.31,25V15.74H77.93V5h-10V36.53A21.4,21.4,0,0,0,89.31,57.91v-10A11.39,11.39,0,0,1,77.93,36.53V25Z"/><circle class="cls-1" cx="55.35" cy="5.04" r="5"/></g></g></svg>';
    echo '<div class="wrap">';
    echo '<h1>' . __('Hello!', 'thor') . '</h1>';
    echo '<h4>' . __('From Wordpress you can edit the contents of the site, with the exception of the decorations. In order to edit and manage decorations, you need to log into the PIM dashboard.', 'thor') . '</h4>';
    if ($PIM_SITEURL) {
        echo '<a href="' . $PIM_SITEURL . '" target="_blank"><button style="margin-top: 15px;" class="button button-primary">' . __('View PIM Dashboard', 'thor') . '</button></a>';
    }
    echo '</div>';
}


add_action('add_meta_boxes', function () {
    $screens = ['decor'];
    foreach ($screens as $screen) {
        add_meta_box(
            'decor_pim_metabox',
            'Campi Decoro da PIM',
            'App\decor_pim_metabox_callback',
            $screen
        );
    }

    function decor_pim_metabox_callback($post)
    {
        $taxonomies = \App::get_decor_taxonomies();

        echo '<p style="font-weight: bold">' . __("Technical information", "thor") . '</p>';
        foreach ($taxonomies as $key => $taxonomy) {
            $term = get_the_terms($post, $key);
            $joined = '';

            if ($term) {
                $joined = join(', ', wp_list_pluck($term, 'name'));
            }

            echo '<div>';
            echo '<span>' . sprintf($taxonomy . "%s", __(' : '),) . '</span>';
            echo '<span>' . $joined . '</span>';
            echo '</div>';
        }

        echo '<br>';
        echo '<br>';
        $tints = get_post_meta($post->ID, '_tinte', true);
        echo '<p style="font-weight: bold;">' . __("Tints", "thor") . '</p>';
        if ($tints) {
            foreach ($tints as $key => $tint) {
                echo '<ul>';
                echo '<li>';
                echo '<img width="90" src="' . wp_get_attachment_url($tint['_immagine_di_anteprima_media_id']) . '"/>';
                echo '<br/>';
                echo '<span>' . $tint['_codice'] . '</span>';
                echo '</li>';
                echo '</ul>';
            }
        }

        echo '<br>';
        echo '<br>';

        echo '<p style="font-weight: bold">' . __("Tint debugging information", "thor") . '</p>';
        echo '<pre><code style="line-height: 1.7">' . json_encode($tints, JSON_PRETTY_PRINT) . '</code></pre>';
    }
});

add_action('pre_get_posts', function ($query) {
    if (is_admin() && !$query->is_main_query()) {
        return;
    }

    if ((is_post_type_archive('decor') || is_tax('decors-category')) && $query->is_main_query()) {
        $taxonomies = \App::get_decor_taxonomies(true);
        $query->set('tax_query', [
            'relation' => 'AND',
        ]);

        foreach ($taxonomies as $taxonomy => $label) {
            if ($_GET[$taxonomy]) {
                $query->set(
                    'tax_query',
                    [
                        [
                            'taxonomy' => $taxonomy,
                            'field'    => 'slug',
                            'relation' => 'or',
                            'terms'    => $_GET[$taxonomy],
                        ]
                    ]
                );
            }
        }

        if ($_GET['features']) {
            $query->set('tax_query', [
                [
                    'taxonomy' => 'features',
                    'field'    => 'slug',
                    'terms'    => $_GET['features'],
                ]
            ]);
        }

        $order = $_GET['order'];
        $query->set('order', 'ASC');

        if ($order && $order != 'DEF') {
            $query->set('orderby', 'name');
            $query->set('order', $order);
        }

        return $query;
    }
});

add_filter("wpseo_breadcrumb_links", function ($links) {
    if (is_singular('product')) {
        $breadcrumbs = [];

        $breadcrumbs[] = [
            'url' => get_home_url(),
            'text' => 'Home',
        ];

        $terms = get_the_terms($post, 'product-collection');
        if ($terms) {
            foreach ($terms as $term) {
                $breadcrumb_picker = get_field('breadcrumb_picker', $term);
                foreach ($breadcrumb_picker as $picker) {
                    $url = get_permalink($picker);
                    $title = get_the_title($picker);

                    $breadcrumbs[] = [
                        'url' => $url,
                        'text' => $title,
                    ];
                }
            }
        }


        $post = get_post(get_the_ID());
        if ($post->post_parent) {
            $breadcrumbs[] = [
                'url' => get_permalink($post->post_parent),
                'text' => get_the_title($post->post_parent),
            ];
        }

        $breadcrumbs[] = [
            'url' => get_permalink(),
            'text' => get_the_title(),
        ];

        return $breadcrumbs;
    }

    $custom_breadcrumb = get_field('custom_breadcrumb');

    if ($custom_breadcrumb) {
        $breadcrumbs = [];

        $breadcrumbs[] = [
            'url' => get_home_url(),
            'text' => 'Home',
        ];

        $breadcrumb_picker = get_field('breadcrumb_picker');
        if ($breadcrumb_picker) {
            foreach ($breadcrumb_picker as $picker) {
                $content_type = $picker['content_type'];

                if ($content_type == 'page') {
                    $url = get_permalink($picker['breadcrumb_page'][0]);
                    $title = get_the_title($picker['breadcrumb_page'][0]);
                } else {
                    $url = $picker['breadcrumb_link']['url'];
                    $title = $picker['breadcrumb_link']['title'];
                }

                $breadcrumbs[] = [
                    'url' => $url,
                    'text' => $title,
                ];
            }
        }

        $breadcrumbs[] = [
            'url' => get_permalink(),
            'text' => get_the_title(),
        ];

        return $breadcrumbs;
    }

    return $links;
});


/**
 * Add <body> classes
 */
add_filter('body_class', function (array $classes) {
    /** Add page slug if it doesn't exist */
    if (is_single() || is_page() && !is_front_page()) {
        if (!in_array(basename(get_permalink()), $classes)) {
            $classes[] = basename(get_permalink());
        }
    }

    /** Add class if sidebar is active */
    if (display_sidebar()) {
        $classes[] = 'sidebar-primary';
    }

    /** Clean up class names for custom templates */
    $classes = array_map(function ($class) {
        return preg_replace(['/-blade(-php)?$/', '/^page-template-views/'], '', $class);
    }, $classes);

    return array_filter($classes);
});

/**
 * Add "… Continued" to the excerpt
 */
add_filter('excerpt_more', function () {
    return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'thor') . '</a>';
});

/**
 * Template Hierarchy should search for .blade.php files
 */
collect([
    'index', '404', 'archive', 'author', 'category', 'tag', 'taxonomy', 'date', 'home',
    'frontpage', 'page', 'paged', 'search', 'single', 'singular', 'attachment', 'embed'
])->map(function ($type) {
    add_filter("{$type}_template_hierarchy", __NAMESPACE__ . '\\filter_templates');
});

add_filter('get_the_archive_title', function ($title) {
    if (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_author()) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } elseif (is_tax()) { //for custom post types
        $title = sprintf(__('%1$s'), single_term_title('', false));
    } elseif (is_post_type_archive()) {
        $title = post_type_archive_title('', false);
    }
    return $title;
});

/**
 * Render page using Blade
 */
add_filter('template_include', function ($template) {
    collect(['get_header', 'wp_head'])->each(function ($tag) {
        ob_start();
        do_action($tag);
        $output = ob_get_clean();
        remove_all_actions($tag);
        add_action($tag, function () use ($output) {
            echo $output;
        });
    });
    $data = collect(get_body_class())->reduce(function ($data, $class) use ($template) {
        return apply_filters("sage/template/{$class}/data", $data, $template);
    }, []);
    if ($template) {
        echo template($template, $data);
        return get_stylesheet_directory() . '/index.php';
    }
    return $template;
}, PHP_INT_MAX);

/**
 * Render comments.blade.php
 */
add_filter('comments_template', function ($comments_template) {
    $comments_template = str_replace(
        [get_stylesheet_directory(), get_template_directory()],
        '',
        $comments_template
    );

    $data = collect(get_body_class())->reduce(function ($data, $class) use ($comments_template) {
        return apply_filters("sage/template/{$class}/data", $data, $comments_template);
    }, []);

    $theme_template = locate_template(["views/{$comments_template}", $comments_template]);

    if ($theme_template) {
        echo template($theme_template, $data);
        return get_stylesheet_directory() . '/index.php';
    }

    return $comments_template;
}, 100);


if (function_exists('get_field')) {
    add_filter(
        'mime_types',
        function ($mimes) {
            $mimes['json'] = 'application/json';
            $mimes['json'] = 'text/plain';
            $mimes['svg'] = 'image/svg+xml';
            return $mimes;
        }
    );
}

add_filter('use_block_editor_for_post', function ($use_block_editor, $post) {
    if ($post->post_type !== 'product') return $use_block_editor;

    $args = array(
        'post_parent'    => $post->ID,
        'post_type'      => 'product',
    );
    $children = get_children($args);

    if ($children) {
        return true;
    }
    return false;
}, 10, 2);
