<?php

namespace ProudNerds\Core;

use Language_Pack_Upgrader;
use WP_Admin_Bar;
use WP_Customize_Manager;

/**
 * Class: WordPress
 *
 * Sets the preferences for default WordPress functionality.
 */
class Cleaner {
    /**
     * WordPress constructor.
     */
    public function __construct() {
        $this->add_actions();
        $this->add_filters();
        $this->remove_filter();
        $this->remove_roles();
        $this->set_options();
    }

    /**
     * Add the required actions.
     */
    private function add_actions() {
        add_action('wp_dashboard_setup', array(__CLASS__, 'remove_dashboard_widgets'), 10, 0);
        add_action('admin_bar_menu', array(__CLASS__, 'alter_wordpress_menu_bar'), 999, 1);
        add_action('admin_menu', array(__CLASS__, 'remove_admin_menu_pages'), 999, 0);
        add_action('do_meta_boxes', array(__CLASS__, 'remove_meta_box'), 10, 0);
        add_action('customize_register', array(__CLASS__, 'remove_customize_css'), 10, 1);
        add_action('widgets_init', array(__CLASS__, 'unregister_wordpress_widgets'), 10, 0);
        add_action('init', array(__CLASS__, 'disable_emojis'), 10, 0);
//        add_action('init', array(__CLASS__, 'remove_default_post_type'), 10, 0);
//        add_action('wp_footer', array(__CLASS__, 'deregister_scripts'), 10, 0);
//        add_action('init', array(__CLASS__, 'delete_sample_post'), 10, 0 );
        add_action('admin_head-user-edit.php', array(__CLASS__, 'remove_profile_fields'), 10, 0);
        add_action('admin_head-profile.php', array(__CLASS__, 'remove_profile_fields'), 10, 0);
        add_action('admin_init', array(__CLASS__, 'remove_post_types_support'), 10, 0);
        add_action('admin_head', array(__CLASS__, 'editor_role'), 10, 0);
        add_action('admin_init', array(__CLASS__, 'update_translations'), 10, 0);

        if(!USE_GUTENBERG){
             add_action('wp_print_styles', array(__CLASS__, 'wps_deregister_styles'), 100, 0);
        }
    }

    /**
     * Add the required filters.
     */
    private function add_filters() {

        add_filter('tiny_mce_plugins', array(__CLASS__, 'disable_emojis_tinymce'), 10, 1);
        add_filter('wp_resource_hints', array(__CLASS__, 'disable_emojis_remove_dns_prefetch'), 10, 2);
        add_filter('wp_headers', array(__CLASS__, 'remove_x_pingback'), 10, 1);
        add_filter('xmlrpc_enabled', '__return_false', 10, 0);
        add_filter('admin_head', array(__CLASS__, 'remove_help_tab'), 999, 3 );
        add_filter('style_loader_tag', array(__CLASS__, 'remove_type_attr'), 10, 2);
        add_filter('script_loader_tag', array(__CLASS__, 'remove_type_attr'), 10, 2);
        add_filter('intermediate_image_sizes_advanced', array(__CLASS__, 'prefix_remove_default_images'), 10, 1);
        if(USE_GUTENBERG){
            add_filter( 'block_categories_all', array(__CLASS__, 'pnAddBlockCategory'), 10, 2);
        }
        if(!USE_GUTENBERG){
            add_filter('use_block_editor_for_post', '__return_false', 10, 0);
            add_filter('gutenberg_can_edit_post_type', '__return_false', 10, 0);
        }

    }

    /**
     * Remove dashboard widgets.
     */
    static function remove_dashboard_widgets() {
        global $wp_meta_boxes;

        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
    }

    /**
     * Remove admin bar tools.
     *
     * @param WP_Admin_Bar $wp_admin_bar The WordPress admin bar.
     */
    static function alter_wordpress_menu_bar(WP_Admin_Bar $wp_admin_bar) {
        $wp_admin_bar->remove_node('new-content');
        $wp_admin_bar->remove_node('wp-logo');
        $wp_admin_bar->remove_node('my-account');
        $wp_admin_bar->remove_node('comments');

        // Add a logout link directly to the admin bar
        if(is_user_logged_in()) {
            $wp_admin_bar->add_menu([
                'id'     => 'log-out',
                'parent' => 'top-secondary',
                'title'  => __('Uitloggen', THEME_LANGUAGE_DOMAIN),
                'href'   => wp_logout_url(),
            ]);
        }
    }

    /**
     * Remove menu items.
     */
    static function remove_admin_menu_pages(){
        global $pagenow;

//        remove_menu_page('edit.php');
        remove_menu_page('edit-comments.php');

        $submenu_pages = array(
            add_query_arg('return', urlencode(remove_query_arg(wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI']))), 'customize.php') => 'themes.php',
            'options-writing.php' => 'options-general.php',
            'options-media.php' => 'options-general.php',
            'tools.php' => 'tools.php',
            'import.php' => 'tools.php',
            'export.php' => 'tools.php',
            'export_personal_data' => 'tools.php',
            'remove_personal_data' => 'tools.php'

        );

        if($submenu_pages){
            foreach($submenu_pages as $submenu_slug => $menu_slug){
                remove_submenu_page($menu_slug, $submenu_slug );

                if($submenu_slug === $pagenow && $menu_slug !== 'tools.php') {
                    wp_redirect(admin_url()); exit;
                }
            }
        }
    }

    /**
     * Remove Gutenberg stylesheet.
     */
    static function wps_deregister_styles(){
        wp_dequeue_style('wp-block-library');
    }

    /**
     * Remove meta boxes.
     */
    static function remove_meta_box(){
        $all_locations = get_post_types();

        $meta_boxes = array(
            'postdivrich' => 'normal',
            'postcustom' => 'normal'
        );

        foreach ($meta_boxes as $meta_box => $context) {
            remove_meta_box($meta_box, $all_locations, $context);
        }
    }

    /**
     * Remove custom CSS functionality.
     *
     * @param WP_Customize_Manager $wp_customize
     */
    public function remove_customize_css(WP_Customize_Manager $wp_customize) {
        $wp_customize->remove_section('custom_css');
        $wp_customize->remove_control('custom_css');
    }

    /**
     * Remove WordPress widgets.
     */
    static function unregister_wordpress_widgets() {
        if(get_option('link_manager_enabled')) {
            unregister_widget('WP_Widget_Links');
        }

        unregister_widget('WP_Widget_Media_Audio');
        unregister_widget('WP_Widget_Media_Image');
        unregister_widget('WP_Widget_Media_Gallery');
        unregister_widget('WP_Widget_Media_Video');
        unregister_widget('WP_Nav_Menu_Widget');
        unregister_widget('WP_Widget_Custom_HTML');
        unregister_widget('WP_Widget_Pages');
        unregister_widget('WP_Widget_Calendar');
        unregister_widget('WP_Widget_Archives');
        unregister_widget('WP_Widget_Links');
        unregister_widget('WP_Widget_Meta');
        unregister_widget('WP_Widget_Search');
        unregister_widget('WP_Widget_Text');
        unregister_widget('WP_Widget_Categories');
        unregister_widget('WP_Widget_Recent_Posts');
        unregister_widget('WP_Widget_Recent_Comments');
        unregister_widget('WP_Widget_RSS');
        unregister_widget('WP_Widget_Tag_Cloud');
        unregister_widget('WP_Nav_Menu_Widget');
    }

    /**
     * Remove emojis.
     */
    static function disable_emojis(){
        remove_action('welcome_panel', 'wp_welcome_panel', 10);
        remove_action('wp_head', 'print_emoji_detection_script', 7);
        remove_action('wp_print_styles', 'print_emoji_styles');
        remove_action('wp_head', 'print_emoji_detection_script', 7 );
        remove_action('admin_print_scripts', 'print_emoji_detection_script' );
        remove_action('wp_print_styles', 'print_emoji_styles' );
        remove_action('admin_print_styles', 'print_emoji_styles' );
    }

    /**
     * Remove default post types.
     */
    static function remove_default_post_type() {
        unregister_post_type('post');
        unregister_post_type('revision');
        unregister_post_type('custom_css');
        unregister_post_type('customize_changeset');
    }

    /**
     * Remove WordPress core scripts.
     */
    static function deregister_scripts() {
        wp_dequeue_script('wp-embed');
    }

    /**
     * Delete sample post.
     */
    static function delete_sample_post() {
        $default_post = get_posts(array('title' => 'Hallo wereld.'));
        $default_post = $default_post ?: get_posts(array('title' => 'Hello world!'));

        if($default_post) {
            wp_delete_post($default_post[0]->ID, $bypass_trash = true);
        }
    }

    /**
     * Remove profile fields with CSS.
     */
    static function remove_profile_fields() {
        $hide_fields = [
            'rich-editing',
            'syntax-highlighting',
            'admin-color',
            'comment-shortcuts',
            'admin-bar-front',
            'language',
            'facebook',
            'instagram',
            'linkedin',
            'myspace',
            'pinterest',
            'soundcloud',
            'tumblr',
            'twitter',
            'youtube',
            'wikipedia'
        ];

        foreach ($hide_fields as $hide_field) {
            echo '<style>tr.user-' . $hide_field . '-wrap{ display: none; }</style>';
        }

        // Fields that don't follow the wrapper naming pattern
        echo '<style>tr.user-profile-picture{ display: none; }</style>';
        echo '<style>#your-profile h2{ display: none; }</style>';
        echo '<style>tr td .description{ display: none; }</style>';
    }

    /**
     * Remove support for certain post types.
     */
    static function remove_post_types_support() {
        $post_types = get_post_types();

        $remove_support = array(
            'trackbacks',
            'revisions',
            'post-formats'
        );
        if(!USE_GUTENBERG){
            $remove_support[] = 'editor';
        }

        foreach ($post_types as $post_type) {
            foreach($remove_support as $support){
                if (post_type_supports($post_type, $support)) {
                    remove_post_type_support($post_type, $support);
                }
            }
        }
    }

    /**
     * Edit the default editor role.
     */
    static function editor_role() {
        $role_object = get_role('editor');
        $role_object->add_cap('edit_theme_options');

        if (current_user_can('editor')) {
            remove_menu_page('tools.php');
        }
    }

    /**
     * Filter function used to remove the tinymce emoji plugin.
     *
     * @param array $plugins
     * @return array
     */
    static function disable_emojis_tinymce(array $plugins): array {
        return !empty($plugins) ? array_diff($plugins, array('wpemoji')) : array();
    }

    /**
     * Remove emoji CDN hostname from DNS pre-fetching hints.
     *
     * @param array $urls
     * @param string $relation_type
     * @return array
     */
    static function disable_emojis_remove_dns_prefetch(array $urls, string $relation_type): array {
        if('dns-prefetch' == $relation_type) {
            $emoji_svg_url = apply_filters('emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/');
            $urls = array_diff($urls, array($emoji_svg_url));
        }

        return $urls;
    }

    /**
     * Disable XMLRPC.
     *
     * @param array $headers
     * @return array
     */
    static function remove_x_pingback(array $headers): array {
        unset($headers['X-Pingback']);
        return $headers;
    }

    /**
     * Remove help tabs.
     */
    static function remove_help_tab() {
        get_current_screen()->remove_help_tabs();
    }

    /**
     * Remove deprecated type from scripts and sheets.
     *
     * @param string $tag
     * @return string|string[]|null
     */
    static function remove_type_attr(string $tag): array|string|null {
        return preg_replace("/ type=['\"]text\/(javascript|css)['\"]/", '', $tag);
    }

    /**
     * Remove filters.
     */
    private function remove_filter() {
        remove_filter('the_content_feed', 'wp_staticize_emoji', 10);
        remove_filter('comment_text_rss', 'wp_staticize_emoji', 10);
        remove_filter('wp_mail', 'wp_staticize_emoji_for_email', 10);
    }

    /**
     * Remove unnecessary user roles.
     */
    private function remove_roles() {
        remove_role('subscriber');
        remove_role('contributor');
    }

    /**
     * Set default options.
     */
    private function set_options() {
        update_option('uploads_use_yearmonth_folders', 0);
        update_option('use_smilies', 0);
        update_option('use_trackback', 0);
        update_option('users_can_register', 0);
        update_option('use_balanceTags', 0);
        update_option('comments_notify', 0);
        update_option('comments_per_page', 0);
        update_option('current_theme', WP_DEFAULT_THEME);
        update_option('default_comment_status', 'closed');
        update_option('default_ping_status', 'closed');
        update_option('default_pingback_flag', 0);
        update_option('show_avatars', 0);
        update_option('show_comments_cookies_opt_in', 0);
        update_option('thread_comments', 0);
        update_option('thread_comments_depth', 0);
        update_option('thumbnail_size_h', 500);
        update_option('thumbnail_size_w', 500);
    }

    /**
     * Remove default image sizes.
     *
     * @param array $sizes
     * @return array
     */
    static function prefix_remove_default_images(array $sizes): array {
        unset($sizes['small']);
        unset($sizes['medium']);
        unset($sizes['large']);
        unset($sizes['medium_large']);

        return $sizes;
    }

    /**
     * Automatically update translations.
     */
    static function update_translations() {
        remove_action('admin_notices', 'update_nag', 3);
        $translations = wp_get_translation_updates();

        if (!empty($translations)) {
            echo '<style> body>.wrap { display: none; } </style>';
            require_once(ABSPATH . '/wp-admin/includes/class-wp-upgrader.php');
            require_once(ABSPATH . '/wp-admin/includes/class-language-pack-upgrader.php');
            (new Language_Pack_Upgrader())->bulk_upgrade($translations);
        } else {
            wp_clean_update_cache();
            wp_update_themes();
            wp_update_plugins();
        }
    }

    /**
     * Adds custom block category for acf gutenberg blocks
     */
    static function pnAddBlockCategory( $categories, $post){
        $item =  array(
                'slug' => 'proudnerds',
                'title' => 'Proud Nerds',
            );
        return [$item, ...$categories];

    }


}