<?php

namespace _121Digital\Connect\Comments;

use _121Digital\Connect\Core\Plugin;

class Comments
{
    public function register(): void
    {
        // Disable comments and trackbacks
        add_action('init', [$this, 'disablePostTypeComments']);

        // Close comments on the front-end
        add_filter('comments_open', [$this, 'closeComments'], 20, 2);
        add_filter('pings_open', [$this, 'closeComments'], 20, 2);

        // Hide existing comments
        add_filter('get_comments_number', [$this, 'hideComments'], 20, 2);

        // Remove comments menu from admin
        add_action('admin_menu', [$this, 'removeCommentsMenu']);

        // Redirect direct access to comments admin page
        add_action('admin_init', [$this, 'redirectCommentsPage']);

        // Block comment submission completely
        add_filter('preprocess_comment', [$this, 'blockCommentSubmission']);

        // Remove Help tabs and Screen Options
        add_action('admin_head', [$this, 'removeHelpTabsAndScreenOptions']);
    }

    public function disablePostTypeComments(): void
    {
        foreach (get_post_types() as $post_type) {
            if (post_type_supports($post_type, 'comments')) {
                remove_post_type_support($post_type, 'comments');
                remove_post_type_support($post_type, 'trackbacks');
            }
        }
    }

    public function closeComments($open, $post_id): bool
    {
        return false;
    }

    public function hideComments($count, $post_id): int
    {
        return 0;
    }

    public function removeCommentsMenu(): void
    {
        remove_menu_page('edit-comments.php');
    }

    public function redirectCommentsPage(): void
    {
        global $pagenow;
        if ($pagenow === 'edit-comments.php') {
            wp_redirect(admin_url());
            exit;
        }
    }

    public function blockCommentSubmission($commentdata)
    {
        Plugin::die('Comments are disabled.');
    }

    public function removeHelpTabsAndScreenOptions(): void
    {
        $screen = get_current_screen();
        if (method_exists($screen, 'remove_help_tabs')) {
            $screen->remove_help_tabs();
        }
        add_filter('screen_options_show_screen', '__return_false');
    }
}
