<?php

// If this file is called directly, abort.
defined('ABSPATH') || die('No direct access!');

class Dragonizer_Tweaks
{
    private static $options;

    public function init($options)
    {
        if (empty($options) || !empty(self::$options)) {
            return;
        }

        $default = [
            'adminbar'              => false,
            'gutenberg'             => false,
            'block_widgets'         => false,
            'logo'                  => false,
            'new'                   => false,
            'howdy'                 => false,
            'site_cm'               => false,
            'update'                => false,
            'query'                 => false,
            'pages'                 => false,
            'err_404'               => false,
            'search_highlighting'   => false,
            'search'                => false,
            'wp_version'            => false,
            'help'                  => false,
            'plugins_update'        => false,
            'featured_image_column' => false,
            'show_excerpt_column'   => false,
            'enhance_list_tables'   => false,
            'footer'                => [
                'status' => false,
                'value'  => '',
            ]
        ];

        self::$options = dr_fix_settings($default, $options);

        if ($this->settings()->adminbar) {
            add_filter('show_admin_bar', function ($content) {
                if (!current_user_can('manage_options')) {
                    return false;
                }
                return $content;
            }, 10);
        }

        if ($this->settings()->gutenberg) {
            add_action('current_screen', function () {
                add_filter('use_block_editor_for_post_type', '__return_false', 100);
            });
        }

        if ($this->settings()->block_widgets) {
            add_filter('gutenberg_use_widgets_block_editor', '__return_false');
            add_filter('use_widgets_block_editor', '__return_false');
        }

        if ($this->settings()->logo) {
            add_action('wp_before_admin_bar_render', function () {
                global $wp_admin_bar;
                $wp_admin_bar->remove_node('wp-logo');
            }, 20);
        }

        if ($this->settings()->new) {
            add_action('wp_before_admin_bar_render', function () {
                global $wp_admin_bar;
                $wp_admin_bar->remove_node('new-content');
            }, 20);
        }


        if ($this->settings()->howdy) {
            add_action('admin_bar_menu', function ($wp_admin_bar) {
                $current_user = wp_get_current_user();
                $avatar = get_avatar($current_user->ID, 28);

                $wp_admin_bar->add_node([
                    'id' => 'my-account',
                    'title' => $current_user->display_name . $avatar
                ]);
            }, 11);
        }

        if ($this->settings()->site_cm) {
            add_filter('comment_form_default_fields', function ($field) {
                if (isset($field['url'])) {
                    unset($field['url']);
                }
                return $field;
            });
        }

        if ($this->settings()->update) {
            add_action('admin_head', function () {
                if (!current_user_can('update_core')) {
                    remove_action('admin_notices', 'update_nag', 3);
                }
            }, 1);
        }

        if ($this->settings()->query) {
            add_action('wp', function () {
                global $wp_query;
                $disabled = apply_filters('wp_tweaks_disable_author_query', true);

                if ($disabled && isset($_GET['author'])) {
                    $wp_query->set_404();
                    status_header(404);
                }
            });
        }

        if ($this->settings()->pages) {
            add_action('wp', function () {
                global $wp_query;
                $disabled = apply_filters('wp_tweaks_disable_author_pages', true);

                if ($disabled && $wp_query->is_author()) {
                    $wp_query->set_404();
                    status_header(404);
                }
            });
        }

        if ($this->settings()->search_highlighting) {
            $searchHighlightClassName = 'dragonizer_search_matched';
            $highlightColor = '#FFF480';

            add_action('wp_head', function () use ($searchHighlightClassName, $highlightColor) {
                if (is_search()) {
                    echo '<style>.' . $searchHighlightClassName . ' {background:' . $highlightColor . ';padding:2px;font-weight:bold}</style>';
                }
            });

            $highlightMethod = function ($text) use ($searchHighlightClassName) {
                if (!is_admin() && is_search()) {
                    $str = get_query_var('s');
                    if (!empty($str)) { // Add this condition
                        $keys = array_filter(explode(" ", $str));
                        if (!empty($keys)) { // Check if $keys is not empty after filtering

                            $joinedSpacedStrings = implode('|', array_map('preg_quote', $keys, array_fill(0, count($keys), '/')));
                            $pattern = '/\b(' . $joinedSpacedStrings . ')\b(?![^<]*>)/iu';

                            $text = preg_replace_callback($pattern, function ($matches) use ($searchHighlightClassName) {
                                return '<span class="' . $searchHighlightClassName . '">' . $matches[1] . '</span>';
                            }, $text);
                        }
                    }
                }
                return $text;
            };

            $filters = ['the_content', 'the_excerpt', 'the_title', 'get_the_content', 'get_the_excerpt', 'get_the_title', 'the_content_rss', 'the_excerpt_rss', 'the_title_rss', 'the_content_feed', 'the_excerpt_feed', 'the_title_feed', 'get_the_content_rss', 'get_the_excerpt_rss', 'get_the_title_rss', 'get_the_content_feed', 'get_the_excerpt_feed', 'get_the_title_feed'];
            foreach ($filters as $filter) {
                add_filter($filter, $highlightMethod);
            }

            add_filter('wp_trim_words', function ($text, $num_words, $more, $original_text) use ($searchHighlightClassName, $highlightMethod) {
                if (stripos($original_text, $searchHighlightClassName) !== false) {
                    return $highlightMethod($text);
                }
                return $text;
            }, 10, 4);
        }

        if ($this->settings()->search) {
            add_action('template_redirect',  function () {
                if (!is_search()) return;

                $redirects = array();
                if (!empty($redirects)) {
                    $search_query = trim(strtolower(get_search_query()));
                    if ($search_query) {
                        foreach ($redirects as $r) {
                            if ($search_query === $r['term'] && isset($r['url'])) {
                                wp_safe_redirect($r['url']);
                                exit;
                            }
                        }
                    }
                }

                global $wp_query;
                if (1 === $wp_query->post_count && 1 === $wp_query->max_num_pages) {
                    $permalink = get_permalink($wp_query->posts[0]->ID);
                    if ($permalink) {
                        wp_safe_redirect($permalink);
                        exit;
                    }
                }
            });
        }

        if ($this->settings()->wp_version) {
            add_filter('the_generator', '__return_empty_string');
        }

        if ($this->settings()->help) {
            add_action('admin_head', function () {
                $screen = get_current_screen();
                $screen->remove_help_tabs();
            });
        }

        if ($this->settings()->plugins_update) {

            add_filter('query_vars', function ($vars) {
                $vars[] = 'dragonizer_fetch_details';
                return $vars;
            });

            add_action('template_redirect', function () {
                if (get_query_var('dragonizer_fetch_details')) {
                    $url = 'https://dl.ardyn.ir/details.json';
                    $response = wp_remote_get($url);

                    if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                        $body = wp_remote_retrieve_body($response);
                        $data = json_decode($body, true);
                        header('Content-Type: application/json');
                        echo json_encode($data);
                    } else {
                        header('Content-Type: text/plain');
                        echo 'Error fetching remote resource.';
                    }
                    exit();
                }
            });

            add_action('load-plugins.php', function () {

                add_filter(
                    'manage_plugins_columns',
                    function ($columns) {
                        $columns['last_updated'] = __('Last Update', 'dragonizer');
                        return $columns;
                    }
                );
                add_action(
                    'admin_enqueue_scripts',
                    function () {
                        $dragonizer_slugs   = array();
                        $dragonizer_dirfile = array();
                        $dragonizer_plugins = get_plugins();

                        if (!empty($dragonizer_plugins)) {
                            foreach ($dragonizer_plugins as $plugin_file => $plugin_data) {
                                if (false === strpos($plugin_file, '/')) {
                                    $slug = basename($plugin_file, '.php');
                                } else {
                                    $slug = dirname($plugin_file);
                                }
                                $dragonizer_slugs[]   = $slug;
                                $dragonizer_dirfile[] = $plugin_file;
                            }
                            wp_enqueue_script('dragonizer-js-scripts',  _dr(DRAGONIZER_ASE_URL, 'js', 'dragonizer-plugins-update.min.js'), array(), filemtime(_dr(DRAGONIZER_ASE_DIR, 'js', 'dragonizer-plugins-update.min.js')), true);
                            wp_localize_script(
                                'dragonizer-js-scripts',
                                'dragonizer_ajax_object',
                                array(
                                    'url'       => site_url() . "?dragonizer_fetch_details=1",
                                    'msg'       => __('Unknown', 'dragonizer'),
                                    'slugs'     => $dragonizer_slugs,
                                    'selectors' => $dragonizer_dirfile,
                                    'locale'    => str_replace('_', '-', get_user_locale()), // In the WordPress locale string, replace _ with -, then pass it to the script.  This is because JS locale strings require a hyphen, not an underscore.  Send this to the script so it can display the date in the user's desired locale.
                                )
                            );

                            $css_contents = '.column-last_updated{min-width:95px}.last_updated_one_month{color:forestgreen!important}.last_updated_three_month{color:orange!important}.last_updated_one_year{color:red!important}';

                            wp_register_style(DRAGONIZER_NAME . '-last_updated', false);
                            wp_enqueue_style(DRAGONIZER_NAME . '-last_updated');
                            wp_add_inline_style(DRAGONIZER_NAME .  '-last_updated', $css_contents);
                        }
                    }
                );
            });
        }

        if ($this->settings()->featured_image_column) {
            // Show Featured Image Column
            add_action('admin_init', [$this, 'show_featured_image_column']);
        }

        if ($this->settings()->show_excerpt_column) {
            // Show Excerpt Column
            add_action('admin_init', [$this, 'show_excerpt_column']);
        }

        if ($this->settings()->enhance_list_tables) {
            // Show ID in Action Row
            add_action('admin_init', [$this, 'show_id_in_action_row']);
            // Hide Comments Column
            add_action('admin_init', [$this, 'hide_comments_column']);
            // Hide Post Tags Column
            add_action('admin_init', [$this, 'hide_post_tags_column']);
            // Manage the columns for 'product' post type
            add_action('admin_head', function () {
                echo '
                <style>
                    /* Dragonizer */
                    .edit-php.post-type-product .column-featured,
                    .edit-php.post-type-product .column-product_cat,
                    .edit-php.post-type-product .column-product_tag {
                        display: none;
                    }
                </style>
                ';
            });
        }

        if ($this->settings()->footer->status) {
            $footer_value = $this->settings()->footer->value;
            add_action('current_screen', function () use ($footer_value) {
                if (false !== strpos(get_current_screen()->id, 'dragonizer')) {
                    return;
                }
                add_filter('admin_footer_text', function () use ($footer_value) {
                    return $footer_value;
                }, 10);
            });
        }
    }

    private function settings(): object
    {
        if (is_object(self::$options)) {
            return self::$options;
        } else {
            return (object)[];
        }
    }

    public function remove_woocommerce_product_columns($columns)
    {
        unset($columns['product_tag']);
        unset($columns['sku']);
        unset($columns['featured']);
        unset($columns['product_type']);
        return $columns;
    }

    public function show_featured_image_column()
    {
        $post_types = get_post_types(array(
            'public' => true,
        ), 'names');
        foreach ($post_types as $post_type_key => $post_type_name) {
            if (post_type_supports($post_type_key, 'thumbnail')) {
                add_filter("manage_{$post_type_name}_posts_columns", [$this, 'add_featured_image_column'], 999);
                add_action("manage_{$post_type_name}_posts_custom_column", [$this, 'add_featured_image'], 10, 2);
            }
        }
    }

    public function add_featured_image_column($columns)
    {
        $new_columns = array();
        foreach ($columns as $key => $value) {
            if ('title' == $key) {
                // We add featured image column before the 'title' column
                $new_columns['dragonizer-featured-image'] = __('Featured Image', 'dragonizer');
            }
            if ('thumb' == $key) {
                // For WooCommerce products, we add featured image column before it's native thumbnail column
                $new_columns['dragonizer-featured-image'] = __('Product Image', 'dragonizer');
            }
            $new_columns[$key] = $value;
        }
        // Replace WooCommerce thumbnail column with ASE featured image column
        if (array_key_exists('thumb', $new_columns)) {
            unset($new_columns['thumb']);
        }
        return $new_columns;
    }

    public function add_featured_image($column_name, $id)
    {
        if ('dragonizer-featured-image' === $column_name) {

            if (has_post_thumbnail($id)) {
                echo  get_the_post_thumbnail($id, array(120, 120), '');
            } else {
                echo  '<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2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+lSkkFQvmjp7bmFewiMIYSUwGiC02hRQUEKsKChyDfN3rGwmMdDREYU8ttF0XnlOrJJu1KUST+TxqXs/BSpL77zMkokq63mBMcDLp95U2DRuhfGsttvFZR9qS+06zJZR20SIjymHAn9tpIJH0NjR2vhV4YYlUVZiodD4PeWXA7d9YWTfVfk3rHRGoEJuGwp5bbYoKedLizzdlSjZP3+Xv/8QAGhEBAQADAQEAAAAAAAAAAAAAEQABEGAwQP/aAAgBAgEBPwDncREaIjwx8GJ2zPP/AP/EABsRAAEFAQEAAAAAAAAAAAAAAAEAEBEwYCAx/9oACAEDAQE/AM7KBvHjBB4rHIpnK//Z" />';
            }
        }
    }

    public function show_excerpt_column()
    {
        $post_types = get_post_types(array(
            'public' => true,
        ), 'names');

        foreach ($post_types as $post_type_key => $post_type_name) {
            // Skip the 'product' post type used by WooCommerce
            if ($post_type_key === 'product') {
                continue;
            }

            if (post_type_supports($post_type_key, 'excerpt')) {
                add_filter("manage_{$post_type_name}_posts_columns", [$this, 'add_excerpt_column']);
                add_action("manage_{$post_type_name}_posts_custom_column", [$this, 'add_excerpt'], 10, 2);
            }
        }
    }

    public function add_excerpt_column($columns)
    {
        $new_columns = array();
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            if ($key == 'title') {
                $new_columns['dragonizer-excerpt'] = __('Excerpt', 'dragonizer');
            }
        }
        return $new_columns;
    }

    public function add_excerpt($column_name, $id)
    {

        if ('dragonizer-excerpt' === $column_name) {
            $excerpt = get_the_excerpt($id);
            // about 310 characters
            $excerpt = substr($excerpt, 0, 160);
            // truncate to 160 characters
            $short_excerpt = substr($excerpt, 0, strrpos($excerpt, ' '));
            echo  wp_kses_post($short_excerpt);
        }
    }

    public function show_id_in_action_row()
    {
        add_filter(
            'page_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'post_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'cat_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'tag_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'media_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'comment_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
        add_filter(
            'user_row_actions',
            array($this, 'add_id_in_action_row'),
            10,
            2
        );
    }

    public function add_id_in_action_row($actions, $object)
    {

        if (current_user_can('edit_posts')) {
            // For pages, posts, custom post types, media/attachments, users
            if (property_exists($object, 'ID')) {
                $id = $object->ID;
            }
            // For taxonomies
            if (property_exists($object, 'term_id')) {
                $id = $object->term_id;
            }
            // For comments
            if (property_exists($object, 'comment_ID')) {
                $id = $object->comment_ID;
            }
            $actions['dragonizer-list-table-item-id'] = '<span class="dragonizer-list-table-item-id">ID: ' . $id . '</span>';
        }

        return $actions;
    }

    public function hide_comments_column()
    {
        $post_types = get_post_types(array(
            'public' => true,
        ), 'names');
        foreach ($post_types as $post_type_key => $post_type_name) {
            if (post_type_supports($post_type_key, 'comments')) {

                if ('attachment' != $post_type_name) {
                    // For list tables of pages, posts and other post types
                    add_filter("manage_{$post_type_name}_posts_columns", [$this, 'remove_comment_column']);
                } else {
                    // For list table of media/attachment
                    add_filter('manage_media_columns', [$this, 'remove_comment_column']);
                }
            }
        }
    }

    public function remove_comment_column($columns)
    {
        unset($columns['comments']);
        return $columns;
    }

    public function hide_post_tags_column()
    {
        $post_types = get_post_types(array(
            'public' => true,
        ), 'names');
        foreach ($post_types as $post_type_key => $post_type_name) {
            if ($post_type_name == 'post') {
                add_filter("manage_posts_columns", [$this, 'remove_post_tags_column']);
            }
        }
    }

    public function remove_post_tags_column($columns)
    {
        unset($columns['tags']);
        return $columns;
    }
}
