<?php
/**
 * Admin
 *
 * @package cyberpress/admin
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * CyberPress_Admin class for registering and creating posts, and for installing roles and user functions.
 */
class CyberPress_Admin {
    /**
     * Current Archive Pages.
     *
     * @var array
     */
    private $cyberpress_archive_pages;

    /**
     * CyberPress_Admin constructor.
     */
    public function __construct() {
        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
        add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_carbon_fields_assets' ), 12 );

        // cutsom post types.
        add_action( 'init', array( $this, 'add_custom_post_type' ), 0 );

        // show thumbnail in list table.
        add_filter( 'manage_game_posts_columns', array( $this, 'add_post_img_column' ) );
        add_filter( 'manage_game_posts_custom_column', array( $this, 'manage_post_img_column' ), 10, 2 );
        add_filter( 'manage_player_posts_columns', array( $this, 'add_post_img_column' ) );
        add_filter( 'manage_player_posts_custom_column', array( $this, 'manage_post_img_column' ), 10, 2 );
        add_filter( 'manage_team_posts_columns', array( $this, 'add_post_img_column' ) );
        add_filter( 'manage_team_posts_custom_column', array( $this, 'manage_post_img_column' ), 10, 2 );

        // custom post roles.
        add_action( 'admin_init', array( $this, 'add_role_caps' ) );
        add_filter( 'enter_title_here', array( $this, 'admin_title_placeholder_to_custom_redefine' ) );

        // Add a post display state for special CyberPress pages.
        add_filter( 'display_post_states', array( $this, 'add_display_post_states' ), 10, 2 );
        add_filter( 'admin_body_class', array( $this, 'add_admin_body_class' ) );
        add_action( 'init', array( $this, 'create_archive_posts' ), 9 );

        add_action( 'updated_option', array( $this, 'updated_archive_pages' ), 10, 3 );

        // ajax actions.
        add_action( 'wp_ajax_cyberpress_find_posts', array( $this, 'ajax_find_posts' ) );
        add_action( 'wp_ajax_cyberpress_get_tournament_stages', array( $this, 'get_tournament_stages' ) );
        add_action( 'wp_ajax_cyberpress_get_team_players', array( $this, 'get_team_players' ) );

        // exclude archive import.
        add_filter( 'wxr_importer.pre_process.post', array( $this, 'exclude_import_demo_archive_if_page_already_exist' ), 12, 1 );
    }

    /**
     * Exclude import archive page for themes import if archive already exist.
     *
     * @param array $data - Current import post data.
     * @return array
     */
    public function exclude_import_demo_archive_if_page_already_exist( $data ) {
        if (
            isset( $data['post_type'] ) &&
            'page' === $data['post_type'] &&
            isset( $data['post_title'] )
        ) {
            foreach ( CyberPress_Settings::$page_list_option_names as $page_name ) {
                if ( ucfirst( $page_name ) === $data['post_title'] ) {
                    return array();
                }
            }
        }

        return $data;
    }

    /**
     * Include scripts in WordPress admin panel.
     */
    public function admin_enqueue_scripts() {
        wp_enqueue_style( 'cyberpress-admin', cyberpress()->plugin_url . 'assets/admin/css/style.min.css', array(), '2.5.7' );
        wp_style_add_data( 'cyberpress-admin', 'rtl', 'replace' );
        wp_style_add_data( 'cyberpress-admin', 'suffix', '.min' );

        wp_enqueue_script( 'select2', cyberpress()->plugin_url . 'assets/vendor/select2/js/select2.min.js', array( 'jquery' ), '4.0.3', true );
        wp_enqueue_style( 'select2', cyberpress()->plugin_url . 'assets/vendor/select2/css/select2.css', array(), '4.0.3' );

        wp_enqueue_script( 'cyberpress-admin', cyberpress()->plugin_url . 'assets/admin/js/script.min.js', array( 'wp-i18n', 'jquery' ), '2.5.7', true );
        $data_init = array(
            'nonce' => wp_create_nonce( 'cyberpress-ajax-nonce' ),
        );
        wp_localize_script( 'cyberpress-admin', 'cyberpressAdminVariables', $data_init );
    }

    /**
     * Include Extend Carbon Fields script from WordPress editor.
     */
    public function enqueue_carbon_fields_assets() {
        wp_enqueue_script( 'cyberpress-carbon-fields', cyberpress()->plugin_url . 'assets/admin/js/carbon-fields.min.js', array( 'jquery', 'carbon-fields-core' ), '2.5.7', true );
        $data_init = array(
            'nonce' => wp_create_nonce( 'cyberpress-ajax-nonce' ),
        );
        wp_localize_script( 'cyberpress-carbon-fields', 'cyberpressAdminVariables', $data_init );
    }

    /**
     * Add custom post type.
     */
    public function add_custom_post_type() {
        // posts archive pages.
        $archives = array(
            'game'       => CyberPress_Settings::get_option( 'games_list_page_id', 'cyberpress_general' ),
            'player'     => CyberPress_Settings::get_option( 'players_list_page_id', 'cyberpress_general' ),
            'team'       => CyberPress_Settings::get_option( 'teams_list_page_id', 'cyberpress_general' ),
            'match'      => CyberPress_Settings::get_option( 'matches_list_page_id', 'cyberpress_general' ),
            'tournament' => CyberPress_Settings::get_option( 'tournaments_list_page_id', 'cyberpress_general' ),
        );

        // games items post type.
        register_post_type(
            'game',
            array(
                'labels'            => array(
                    'name'                => _x( 'Games', 'Post Type General Name', 'cyberpress' ),
                    'singular_name'       => _x( 'Game', 'Post Type Singular Name', 'cyberpress' ),
                    'menu_name'           => esc_html__( 'Games', 'cyberpress' ),
                    'parent_item_colon'   => esc_html__( 'Parent Game', 'cyberpress' ),
                    'all_items'           => esc_html__( 'All Games', 'cyberpress' ),
                    'view_item'           => esc_html__( 'View Game', 'cyberpress' ),
                    'add_new_item'        => esc_html__( 'Add New Game', 'cyberpress' ),
                    'add_new'             => esc_html__( 'Add New', 'cyberpress' ),
                    'edit_item'           => esc_html__( 'Edit Game', 'cyberpress' ),
                    'update_item'         => esc_html__( 'Update Game', 'cyberpress' ),
                    'search_items'        => esc_html__( 'Search Games', 'cyberpress' ),
                    'not_found'           => esc_html__( 'Not Found', 'cyberpress' ),
                    'not_found_in_trash'  => esc_html__( 'Not found in Trash', 'cyberpress' ),
                ),
                'public'            => true,
                'has_archive'       => current_theme_supports( 'cyberpress' ) ? ( $archives['game'] ? urldecode( get_page_uri( $archives['game'] ) ) : 'games' ) : false,
                'show_ui'           => true,
                // adding to custom menu manually.
                'show_in_menu'      => false,
                'show_in_rest'      => true,
                'show_in_admin_bar' => true,
                'menu_icon'         => 'dashicons-cyberpress-games',
                'taxonomies'        => array(),
                'capabilities'      => array(
                    'edit_post'          => 'edit_game',
                    'edit_posts'         => 'edit_games',
                    'edit_others_posts'  => 'edit_other_games',
                    'publish_posts'      => 'publish_games',
                    'read_post'          => 'read_game',
                    'read_private_posts' => 'read_private_games',
                    'delete_posts'       => 'delete_games',
                    'delete_post'        => 'delete_game',
                ),
                'rewrite'           => $archives['game'] ? array(
                    'slug' => get_post_field( 'post_name', $archives['game'] ),
                ) : array(
                    'slug' => 'games',
                ),
                'supports'          => array(
                    'title',
                    'editor',
                    'thumbnail',
                    'revisions',
                    'excerpt',
                ),
            )
        );
        register_post_type(
            'player',
            array(
                'labels'            => array(
                    'name'                      => _x( 'Players', 'Post Type General Name', 'cyberpress' ),
                    'singular_name'             => _x( 'Player', 'Post Type Singular Name', 'cyberpress' ),
                    'menu_name'                 => esc_html__( 'Players', 'cyberpress' ),
                    'parent_item_colon'         => esc_html__( 'Parent Player', 'cyberpress' ),
                    'all_items'                 => esc_html__( 'All Players', 'cyberpress' ),
                    'view_item'                 => esc_html__( 'View Player', 'cyberpress' ),
                    'add_new_item'              => esc_html__( 'Add New Player', 'cyberpress' ),
                    'add_new'                   => esc_html__( 'Add New', 'cyberpress' ),
                    'edit_item'                 => esc_html__( 'Edit Player', 'cyberpress' ),
                    'update_item'               => esc_html__( 'Update Player', 'cyberpress' ),
                    'search_items'              => esc_html__( 'Search Players', 'cyberpress' ),
                    'not_found'                 => esc_html__( 'Not Found', 'cyberpress' ),
                    'not_found_in_trash'        => esc_html__( 'Not found in Trash', 'cyberpress' ),
                    'featured_image'            => esc_html__( 'Your Photo', 'cyberpress' ),
                    'set_featured_image'        => esc_html__( 'Set Your Photo', 'cyberpress' ),
                    'remove_featured_image'     => esc_html__( 'Remove Your Photo', 'cyberpress' ),
                    'use_featured_image'        => esc_html__( 'Use as Your Photo', 'cyberpress' ),
                ),
                'public'            => true,
                'has_archive'       => current_theme_supports( 'cyberpress' ) ? ( $archives['player'] ? urldecode( get_page_uri( $archives['player'] ) ) : 'players' ) : false,
                'show_ui'           => true,
                // adding to custom menu manually.
                'show_in_menu'      => false,
                'show_in_rest'      => true,
                'show_in_admin_bar' => true,
                'menu_icon'         => 'dashicons-cyberpress-players',
                'taxonomies'        => array(),
                'capabilities'      => array(
                    'edit_post'          => 'edit_player',
                    'edit_posts'         => 'edit_players',
                    'edit_others_posts'  => 'edit_other_players',
                    'publish_posts'      => 'publish_players',
                    'read_post'          => 'read_player',
                    'read_private_posts' => 'read_private_players',
                    'delete_posts'       => 'delete_players',
                    'delete_post'        => 'delete_player',
                ),
                'rewrite'           => $archives['player'] ? array(
                    'slug' => get_post_field( 'post_name', $archives['player'] ),
                ) : true,
                'supports'          => array(
                    'editor',
                    'title',
                    'thumbnail',
                    'revisions',
                ),
            )
        );
        register_post_type(
            'team',
            array(
                'labels'            => array(
                    'name'                      => _x( 'Teams', 'Post Type General Name', 'cyberpress' ),
                    'singular_name'             => _x( 'Team', 'Post Type Singular Name', 'cyberpress' ),
                    'menu_name'                 => esc_html__( 'Teams', 'cyberpress' ),
                    'parent_item_colon'         => esc_html__( 'Parent Team', 'cyberpress' ),
                    'all_items'                 => esc_html__( 'All Teams', 'cyberpress' ),
                    'view_item'                 => esc_html__( 'View Team', 'cyberpress' ),
                    'add_new_item'              => esc_html__( 'Add New Team', 'cyberpress' ),
                    'add_new'                   => esc_html__( 'Add New', 'cyberpress' ),
                    'edit_item'                 => esc_html__( 'Edit Team', 'cyberpress' ),
                    'update_item'               => esc_html__( 'Update Team', 'cyberpress' ),
                    'search_items'              => esc_html__( 'Search Teams', 'cyberpress' ),
                    'not_found'                 => esc_html__( 'Not Found', 'cyberpress' ),
                    'not_found_in_trash'        => esc_html__( 'Not found in Trash', 'cyberpress' ),
                    'featured_image'            => esc_html__( 'Team Logo', 'cyberpress' ),
                    'set_featured_image'        => esc_html__( 'Set Team Logo', 'cyberpress' ),
                    'remove_featured_image'     => esc_html__( 'Remove Team Logo', 'cyberpress' ),
                    'use_featured_image'        => esc_html__( 'Use as Team Logo', 'cyberpress' ),
                ),
                'public'            => true,
                'has_archive'       => current_theme_supports( 'cyberpress' ) ? ( $archives['team'] ? urldecode( get_page_uri( $archives['team'] ) ) : 'teams' ) : false,
                'show_ui'           => true,
                // adding to custom menu manually.
                'show_in_menu'      => false,
                'show_in_rest'      => true,
                'show_in_admin_bar' => true,
                'menu_icon'         => 'dashicons-cyberpress-teams',
                'taxonomies'        => array(),
                'capabilities'      => array(
                    'edit_post'          => 'edit_team',
                    'edit_posts'         => 'edit_teams',
                    'edit_others_posts'  => 'edit_other_teams',
                    'publish_posts'      => 'publish_teams',
                    'read_post'          => 'read_team',
                    'read_private_posts' => 'read_private_teams',
                    'delete_posts'       => 'delete_teams',
                    'delete_post'        => 'delete_team',
                ),
                'rewrite'           => $archives['team'] ? array(
                    'slug' => get_post_field( 'post_name', $archives['team'] ),
                ) : true,
                'supports'          => array(
                    'title',
                    'editor',
                    'thumbnail',
                    'revisions',
                    'excerpt',
                    'page-attributes',
                ),
                'hierarchical'      => true,
            )
        );

        register_post_type(
            'match',
            array(
                'labels'            => array(
                    'name'                => _x( 'Matches', 'Post Type General Name', 'cyberpress' ),
                    'singular_name'       => _x( 'Match', 'Post Type Singular Name', 'cyberpress' ),
                    'menu_name'           => esc_html__( 'Matches', 'cyberpress' ),
                    'parent_item_colon'   => esc_html__( 'Parent Match', 'cyberpress' ),
                    'all_items'           => esc_html__( 'All Matches', 'cyberpress' ),
                    'view_item'           => esc_html__( 'View Match', 'cyberpress' ),
                    'add_new_item'        => esc_html__( 'Add New Match', 'cyberpress' ),
                    'add_new'             => esc_html__( 'Add New', 'cyberpress' ),
                    'edit_item'           => esc_html__( 'Edit Match', 'cyberpress' ),
                    'update_item'         => esc_html__( 'Update Match', 'cyberpress' ),
                    'search_items'        => esc_html__( 'Search Matches', 'cyberpress' ),
                    'not_found'           => esc_html__( 'Not Found', 'cyberpress' ),
                    'not_found_in_trash'  => esc_html__( 'Not found in Trash', 'cyberpress' ),
                ),
                'public'            => true,
                'has_archive'       => current_theme_supports( 'cyberpress' ) ? ( $archives['match'] ? urldecode( get_page_uri( $archives['match'] ) ) : 'matches' ) : false,
                'show_ui'           => true,
                // adding to custom menu manually.
                'show_in_menu'      => false,
                'show_in_rest'      => true,
                'show_in_admin_bar' => true,
                'menu_icon'         => 'dashicons-cyberpress-matches',
                'taxonomies'        => array(),
                'capabilities'      => array(
                    'edit_post'          => 'edit_match',
                    'edit_posts'         => 'edit_matches',
                    'edit_others_posts'  => 'edit_other_matches',
                    'publish_posts'      => 'publish_matches',
                    'read_post'          => 'read_match',
                    'read_private_posts' => 'read_private_matches',
                    'delete_posts'       => 'delete_matches',
                    'delete_post'        => 'delete_match',
                ),
                'rewrite'           => $archives['match'] ? array(
                    'slug' => get_post_field( 'post_name', $archives['match'] ),
                ) : true,
                'supports'          => array(
                    'title',
                    'editor',
                    'revisions',
                ),
            )
        );
        register_post_type(
            'tournament',
            array(
                'labels'            => array(
                    'name'                => _x( 'Tournaments', 'Post Type General Name', 'cyberpress' ),
                    'singular_name'       => _x( 'Tournament', 'Post Type Singular Name', 'cyberpress' ),
                    'menu_name'           => esc_html__( 'Tournaments', 'cyberpress' ),
                    'parent_item_colon'   => esc_html__( 'Parent Tournament', 'cyberpress' ),
                    'all_items'           => esc_html__( 'All Tournaments', 'cyberpress' ),
                    'view_item'           => esc_html__( 'View Tournament', 'cyberpress' ),
                    'add_new_item'        => esc_html__( 'Add New Tournament', 'cyberpress' ),
                    'add_new'             => esc_html__( 'Add New', 'cyberpress' ),
                    'edit_item'           => esc_html__( 'Edit Tournament', 'cyberpress' ),
                    'update_item'         => esc_html__( 'Update Tournaments', 'cyberpress' ),
                    'search_items'        => esc_html__( 'Search Tournaments', 'cyberpress' ),
                    'not_found'           => esc_html__( 'Not Found', 'cyberpress' ),
                    'not_found_in_trash'  => esc_html__( 'Not found in Trash', 'cyberpress' ),
                ),
                'public'            => true,
                'has_archive'       => current_theme_supports( 'cyberpress' ) ? ( $archives['tournament'] ? urldecode( get_page_uri( $archives['tournament'] ) ) : 'tournaments' ) : false,
                'show_ui'           => true,
                // adding to custom menu manually.
                'show_in_menu'      => false,
                'show_in_rest'      => true,
                'show_in_admin_bar' => true,
                'menu_icon'         => 'dashicons-cyberpress-tournaments',
                'taxonomies'        => array(),
                'capabilities'      => array(
                    'edit_post'          => 'edit_tournament',
                    'edit_posts'         => 'edit_tournaments',
                    'edit_others_posts'  => 'edit_other_tournaments',
                    'publish_posts'      => 'publish_tournaments',
                    'read_post'          => 'read_tournament',
                    'read_private_posts' => 'read_private_tournaments',
                    'delete_posts'       => 'delete_tournaments',
                    'delete_post'        => 'delete_tournament',
                ),
                'rewrite'           => $archives['tournament'] ? array(
                    'slug' => get_post_field( 'post_name', $archives['tournament'] ),
                ) : true,
                'supports'          => array(
                    'title',
                    'editor',
                    'revisions',
                ),
            )
        );

        $this->add_rewrite_rules( $archives );

        $this->maybe_flush_rewrite_rules();
    }

    /**
     * Prevent WordPress from sending a 404 for our new perma structure.
     * This is necessary to fix pagination work.
     *
     * @param array $archives - List of archive page ids.
     * @return void
     */
    public function add_rewrite_rules( $archives ) {
        foreach ( $archives as $archive_page ) {
            if ( $archive_page ) {
                add_rewrite_rule(
                    get_post_field( 'post_name', $archive_page ) . '/page/([0-9]+)?$',
                    'index.php?page_id=' . $archive_page . '&paged=$matches[1]',
                    'top'
                );
            }
        }
    }

    /**
     * Maybe flush rewrite rules if set cache flag.
     *
     * @return void
     */
    public function maybe_flush_rewrite_rules() {
        if ( get_transient( 'cyberpress_flush_rewrite_rules' ) ) {
            flush_rewrite_rules();
            set_transient( 'cyberpress_flush_rewrite_rules', false, 0 );
        }
    }

    /**
     * Updated Archive Page Settings.
     *
     * @param string $option - Option Name.
     * @param array  $old_value - Old value of settings.
     * @param array  $value - New value of settings.
     * @return void
     */
    public function updated_archive_pages( $option, $old_value, $value ) {
        if (
            'cyberpress_general' === $option &&
            (
                $old_value['games_list_page_id'] !== $value['games_list_page_id'] ||
                $old_value['players_list_page_id'] !== $value['players_list_page_id'] ||
                $old_value['teams_list_page_id'] !== $value['teams_list_page_id'] ||
                $old_value['matches_list_page_id'] !== $value['matches_list_page_id'] ||
                $old_value['tournaments_list_page_id'] !== $value['tournaments_list_page_id']
            )
        ) {
            set_transient( 'cyberpress_flush_rewrite_rules', true, 0 );
        }
    }

    /**
     * Add featured image in cyberpress posts lists
     *
     * @param array $columns columns of the table.
     *
     * @return array
     */
    public function add_post_img_column( $columns = array() ) {
        $column_meta = array(
            'cyberpress_post_thumbs' => esc_html__( 'Thumbnail', 'cyberpress' ),
        );

        // insert after first column.
        $columns = array_slice( $columns, 0, 1, true ) + $column_meta + array_slice( $columns, 1, null, true );
        return $columns;
    }

    /**
     * Add thumb to the column
     *
     * @param bool $column_name column name.
     */
    public function manage_post_img_column( $column_name = false ) {
        if ( 'cyberpress_post_thumbs' === $column_name ) {
            echo '<a href="' . esc_url( get_edit_post_link() ) . '" class="cyberpress__thumbnail">';
            if ( has_post_thumbnail() ) {
                the_post_thumbnail( 'thumbnail' );
            }
            echo '</a>';
        }
    }

    /**
     * Automatically generated archive pages after plugin activation.
     */
    public function create_archive_posts() {
        $current_plugins = get_option( 'active_plugins', array() );
        $plugin_name     = 'cyberpress';
        array_filter(
            $current_plugins,
            function( $item ) use ( $plugin_name ) {
                if ( strripos( $item, $plugin_name ) > 0 && empty( $this->cyberpress_archive_pages ) && ! get_option( '_cyberpress_trying_to_add_archive_page' ) ) {

                    add_option( '_cyberpress_trying_to_add_archive_page', true );

                    $cyberpress_general_options = array(
                        'games_list_page_id'       => '',
                        'players_list_page_id'     => '',
                        'teams_list_page_id'       => '',
                        'matches_list_page_id'     => '',
                        'tournaments_list_page_id' => '',
                    );
                    foreach ( CyberPress_Settings::$page_list_option_names as $page_name ) {
                        $new_post_args = array(
                            'post_title'  => ucfirst( $page_name ),
                            'post_type'   => 'page',
                            'post_author' => get_current_user_id(),
                            'post_status' => 'publish',
                        );
                        $archive_page  = self::get_unset_archive_page( ucfirst( $page_name ) );

                        // Check page if Archive Exist and set as Archive page or Insert the post into the database.
                        $post_id = $archive_page ? $archive_page : wp_insert_post( $new_post_args );

                        if ( ! is_wp_error( $post_id ) ) {
                            $this->cyberpress_archive_pages[ $post_id ]                 = $page_name;
                            $cyberpress_general_options[ $page_name . '_list_page_id' ] = $post_id;
                        }
                    }

                    if ( ! empty( $this->cyberpress_archive_pages ) ) {
                        add_option( 'cyberpress_archive_pages', $this->cyberpress_archive_pages );
                        update_option( 'cyberpress_general', $cyberpress_general_options );
                        set_transient( 'cyberpress_flush_rewrite_rules', true, 0 );
                    }
                }
            }
        );
    }

    /**
     * Get Unset Archive Page.
     *
     * @param string $title - Page Title.
     * @return int|bool
     */
    public static function get_unset_archive_page( $title ) {
        $query_opts = array(
            'post_status'            => 'publish',
            'ignore_sticky_posts'    => 1,
            'posts_per_page'         => 50,
            'post_type'              => 'page',
            'post_title'             => $title,
        );

        $search_results = new WP_Query( $query_opts );

        if ( $search_results->have_posts() ) {
            while ( $search_results->have_posts() ) {
                $search_results->the_post();
                if ( $search_results->post->post_title === $title ) {
                    $post_id = $search_results->post->ID;
                    break;
                }
            }
        }

        return isset( $post_id ) ? $post_id : false;
    }

    /**
     * Add Roles
     */
    public function add_role_caps() {
        global $wp_roles;

        if ( isset( $wp_roles ) ) {
            // game roles.
            $wp_roles->add_cap( 'administrator', 'edit_game' );
            $wp_roles->add_cap( 'administrator', 'edit_games' );
            $wp_roles->add_cap( 'administrator', 'edit_other_games' );
            $wp_roles->add_cap( 'administrator', 'publish_games' );
            $wp_roles->add_cap( 'administrator', 'read_game' );
            $wp_roles->add_cap( 'administrator', 'read_private_games' );
            $wp_roles->add_cap( 'administrator', 'delete_games' );
            $wp_roles->add_cap( 'administrator', 'delete_game' );

            $wp_roles->add_cap( 'editor', 'read_game' );
            $wp_roles->add_cap( 'editor', 'read_private_games' );

            $wp_roles->add_cap( 'author', 'read_game' );
            $wp_roles->add_cap( 'author', 'read_private_games' );

            $wp_roles->add_cap( 'contributor', 'read_game' );
            $wp_roles->add_cap( 'contributor', 'read_private_games' );

            // player roles.
            $wp_roles->add_cap( 'administrator', 'edit_player' );
            $wp_roles->add_cap( 'administrator', 'edit_players' );
            $wp_roles->add_cap( 'administrator', 'edit_other_players' );
            $wp_roles->add_cap( 'administrator', 'publish_players' );
            $wp_roles->add_cap( 'administrator', 'read_player' );
            $wp_roles->add_cap( 'administrator', 'read_private_players' );
            $wp_roles->add_cap( 'administrator', 'delete_players' );
            $wp_roles->add_cap( 'administrator', 'delete_player' );

            $wp_roles->add_cap( 'editor', 'read_player' );
            $wp_roles->add_cap( 'editor', 'read_private_players' );

            $wp_roles->add_cap( 'author', 'read_player' );
            $wp_roles->add_cap( 'author', 'read_private_players' );

            $wp_roles->add_cap( 'contributor', 'read_player' );
            $wp_roles->add_cap( 'contributor', 'read_private_players' );

            // team roles.
            $wp_roles->add_cap( 'administrator', 'edit_team' );
            $wp_roles->add_cap( 'administrator', 'edit_teams' );
            $wp_roles->add_cap( 'administrator', 'edit_other_teams' );
            $wp_roles->add_cap( 'administrator', 'publish_teams' );
            $wp_roles->add_cap( 'administrator', 'read_team' );
            $wp_roles->add_cap( 'administrator', 'read_private_teams' );
            $wp_roles->add_cap( 'administrator', 'delete_teams' );
            $wp_roles->add_cap( 'administrator', 'delete_team' );

            $wp_roles->add_cap( 'editor', 'read_team' );
            $wp_roles->add_cap( 'editor', 'read_private_teams' );

            $wp_roles->add_cap( 'author', 'read_team' );
            $wp_roles->add_cap( 'author', 'read_private_teams' );

            $wp_roles->add_cap( 'contributor', 'read_team' );
            $wp_roles->add_cap( 'contributor', 'read_private_teams' );

            // match roles.
            $wp_roles->add_cap( 'administrator', 'edit_match' );
            $wp_roles->add_cap( 'administrator', 'edit_matches' );
            $wp_roles->add_cap( 'administrator', 'edit_other_matches' );
            $wp_roles->add_cap( 'administrator', 'publish_matches' );
            $wp_roles->add_cap( 'administrator', 'read_match' );
            $wp_roles->add_cap( 'administrator', 'read_private_matches' );
            $wp_roles->add_cap( 'administrator', 'delete_matches' );
            $wp_roles->add_cap( 'administrator', 'delete_match' );

            $wp_roles->add_cap( 'editor', 'read_match' );
            $wp_roles->add_cap( 'editor', 'read_private_matches' );

            $wp_roles->add_cap( 'author', 'read_match' );
            $wp_roles->add_cap( 'author', 'read_private_matches' );

            $wp_roles->add_cap( 'contributor', 'read_match' );
            $wp_roles->add_cap( 'contributor', 'read_private_matches' );

            // tournament roles.
            $wp_roles->add_cap( 'administrator', 'edit_tournament' );
            $wp_roles->add_cap( 'administrator', 'edit_tournaments' );
            $wp_roles->add_cap( 'administrator', 'edit_other_tournaments' );
            $wp_roles->add_cap( 'administrator', 'publish_tournaments' );
            $wp_roles->add_cap( 'administrator', 'read_tournament' );
            $wp_roles->add_cap( 'administrator', 'read_private_tournaments' );
            $wp_roles->add_cap( 'administrator', 'delete_tournaments' );
            $wp_roles->add_cap( 'administrator', 'delete_tournament' );

            $wp_roles->add_cap( 'editor', 'read_tournament' );
            $wp_roles->add_cap( 'editor', 'read_private_tournaments' );

            $wp_roles->add_cap( 'author', 'read_tournament' );
            $wp_roles->add_cap( 'author', 'read_private_tournaments' );

            $wp_roles->add_cap( 'contributor', 'read_tournament' );
            $wp_roles->add_cap( 'contributor', 'read_private_tournaments' );
        }
    }

    /**
     * Function for adding a class-attribute inside the custom posts.
     *
     * @param string $class - css class.
     * @return string
     */
    public function add_admin_body_class( $class ) {
        $post_type = get_post_type();
        if ( 'player' === $post_type || 'game' === $post_type || 'match' === $post_type || 'team' === $post_type || 'tournament' === $post_type ) {
            global $post;
            $class .= ' cyberpress ';
            if ( wp_get_post_parent_id( $post->ID ) ) {
                $class .= 'cyberpress-child-post ';
            }
        }
        return $class;
    }

    /**
     * Substitution of the placeholder for the title field inside custom posts.
     *
     * @param string $title_placeholder - current placeholder of the title post field.
     * @return mixed
     */
    public function admin_title_placeholder_to_custom_redefine( $title_placeholder ) {
        $post_type = get_post_type();
        if ( 'player' === $post_type ) {
            $title_placeholder = esc_html__( 'Enter nickname here', 'cyberpress' );
        }
        if ( 'team' === $post_type ) {
            $title_placeholder = esc_html__( 'Enter the name of the team', 'cyberpress' );
        }
        if ( 'match' === $post_type ) {
            $title_placeholder = esc_html__( 'Enter the name of the match', 'cyberpress' );
        }
        if ( 'tournament' === $post_type ) {
            $title_placeholder = esc_html__( 'Enter the name of the tournament', 'cyberpress' );
        }
        return $title_placeholder;
    }
    /**
     * Add a post display state for special CyberPress pages in the page list table.
     *
     * @param array   $post_states An array of post display states.
     * @param WP_Post $post        The current post object.
     * @return array $post_states  An array of post display states.
     */
    public function add_display_post_states( $post_states, $post ) {
        if ( 'page' === $post->post_type ) {
            $page_list_option_names = CyberPress_Settings::$page_list_option_names;
            foreach ( $page_list_option_names as $page_option_name ) {
                if ( intval( CyberPress_Settings::get_option( $page_option_name . '_list_page_id', 'cyberpress_general' ) ) === $post->ID ) {
                    $status_name = '';
                    switch ( $page_option_name ) {
                        case 'games':
                            $status_name = esc_html__( 'Games', 'cyberpress' );
                            break;
                        case 'players':
                            $status_name = esc_html__( 'Players', 'cyberpress' );
                            break;
                        case 'teams':
                            $status_name = esc_html__( 'Teams', 'cyberpress' );
                            break;
                        case 'matches':
                            $status_name = esc_html__( 'Matches', 'cyberpress' );
                            break;
                        case 'tournaments':
                            $status_name = esc_html__( 'Tournaments', 'cyberpress' );
                            break;
                    }
                    $post_states[] = $status_name;
                }
            }
        }
        return $post_states;
    }

    /**
     * Find posts ajax
     */
    public function ajax_find_posts() {
        check_ajax_referer( 'cyberpress-ajax-nonce', 'nonce' );
        if ( ! isset( $_GET['q'] ) ) {
            wp_die();
        }
        $post_type = isset( $_GET['post_type'] ) ? sanitize_text_field( wp_unslash( $_GET['post_type'] ) ) : 'page';
        if ( ! $post_type || 'custom_query' === $post_type ) {
            $post_type = 'any';
        }

        $result = array();

        $the_query = new WP_Query(
            array(
                's'              => sanitize_text_field( wp_unslash( $_GET['q'] ) ),
                'posts_per_page' => 50,
                'post_type'      => $post_type,
            )
        );
        if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $result[] = array(
                    'id'    => get_the_ID(),
                    'title' => get_the_title(),
                );
            }
            wp_reset_postdata();
        }

        // phpcs:ignore
        echo json_encode( $result );

        wp_die();
    }

    /**
     * Ajax function to get a json list of tournament stages.
     */
    public function get_tournament_stages() {
        check_ajax_referer( 'cyberpress-ajax-nonce', 'nonce' );
        if ( ! isset( $_REQUEST['tournament_id'] ) ) {
            wp_die();
        }
        $result                                 = array();
        $tournament_stage_options_choises_array = array(
            0 => array(
                'stage' => esc_html__( 'Choose stage of tournament', 'cyberpress' ),
            ),
        );
        $cyberpress_tournament_stages           = carbon_get_post_meta( sanitize_key( $_REQUEST['tournament_id'] ), 'cyberpress_tournament_stages' );

        if ( isset( $cyberpress_tournament_stages ) && is_array( $cyberpress_tournament_stages ) && ! empty( $cyberpress_tournament_stages ) ) {
            $result = array_merge( $tournament_stage_options_choises_array, $cyberpress_tournament_stages );
        }

        // phpcs:ignore
        echo json_encode( $result );

        wp_die();
    }

    /**
     * Ajax function to get a json list of team players.
     */
    public function get_team_players() {
        check_ajax_referer( 'cyberpress-ajax-nonce', 'nonce' );
        if ( ! isset( $_REQUEST['team_id'] ) ) {
            wp_die();
        }
        $result                  = array();
        $cyberpress_team_players = carbon_get_post_meta( sanitize_key( $_REQUEST['team_id'] ), 'cyberpress_team_players' );
        if ( isset( $cyberpress_team_players ) && is_array( $cyberpress_team_players ) && ! empty( $cyberpress_team_players ) ) {
            $result = $cyberpress_team_players;
        }

        // phpcs:ignore
        echo json_encode( $result );

        wp_die();
    }

}
