<?php

/**
 * Creates a custom post type for Flexible_FAQs
 *
 * @package Flexible_FAQs
 */
namespace WPGO_Plugins\Flexible_Faqs;

/**
 *
 * This class registers the custom post type and taxonomy for groups.
 *
 * Class name suffix _CPT stands for [C]ustom_[P]ost_[T]ype.
 */
class Custom_Post_Type
{
    /**
     * Common root paths/directories.
     *
     * @var $module_roots
     */
    protected  $module_roots ;
    /**
     * Main class constructor.
     *
     * @param Array $module_roots Root plugin path/dir.
     * @param Array $custom_plugin_data Plugin data.
     */
    public function __construct(
        $module_roots,
        $custom_plugin_data,
        $utilities_fw,
        $new_features_arr,
        $plugin_data
    )
    {
        $this->module_roots = $module_roots;
        $this->custom_plugin_data = $custom_plugin_data;
        $this->utilities_fw = $utilities_fw;
        $this->no_faqs_text = __( "No FAQ's have been added yet. To get started click one of the buttons below.", 'flexible-faqs' );
        $this->plugin_data = $plugin_data;
        $this->new_features_arr = $new_features_arr;
        /* Register CPT and associated taxonomy. */
        add_action( 'init', array( &$this, 'register_post_type' ) );
        add_action( 'init', array( &$this, 'register_taxonomy' ) );
        /* Customize CPT columns on overview page. */
        add_filter( 'manage_wpgo_faq_posts_columns', array( &$this, 'change_overview_columns' ) );
        /* Which columns are displayed. */
        add_action(
            'manage_wpgo_faq_posts_custom_column',
            array( &$this, 'custom_column_content' ),
            10,
            2
        );
        /* The html output for each column. */
        add_filter( 'manage_edit-wpgo_faq_sortable_columns', array( &$this, 'sort_custom_columns' ) );
        /* Specify which columns are sortable. */
        /* Customize the CPT messages. */
        add_filter( 'post_updated_messages', array( &$this, 'update_cpt_messages' ) );
        add_filter( 'enter_title_here', array( &$this, 'title_placeholder' ) );
        /* Add meta boxes to faq custom post type. */
        add_action( 'admin_init', array( &$this, 'faq_cpt_meta_box_init' ) );
        add_action( 'add_meta_boxes', array( &$this, 'move_meta_boxes' ) );
        // Style action for the FAQ CPT editor.
        add_action( 'admin_enqueue_scripts', array( &$this, 'faq_cpt_scripts' ) );
        // Add an ID column to FAQ group admin page.
        add_action( 'manage_edit-wpgo_faq_group_columns', array( &$this, 'add_id_column' ) );
        add_filter( 'manage_edit-wpgo_faq_group_sortable_columns', array( &$this, 'add_id_column' ) );
        add_filter(
            'manage_wpgo_faq_group_custom_column',
            array( &$this, 'show_id_column' ),
            10,
            3
        );
        add_action( 'admin_print_styles-edit-tags.php', array( &$this, 'style_id_column' ) );
        // Hide certain meta boxes by default for FAQ CPT.
        add_action( 'admin_menu', array( &$this, 'remove_slug_meta_box' ) );
        // Add dropdown filter on wpgo_faq CPT edit.php to sort by taxonomy. These work OK but until I can figure out how to get the default taxonomy term to be associated automatically with new CPT items then I will leave this feature out as the show all option doesn't work properly.
        // add_action( 'restrict_manage_posts', array( &$this, 'taxonomy_filter_restrict_manage_posts' ) );
        // add_filter( 'parse_query', array( &$this, 'taxonomy_filter_post_type_request' ) ); //.
        add_action( 'admin_menu', array( &$this, 'rewrite_menu_label' ), 9999 );
    }
    
    // For some reason adding the numbered icon to a top-level CPT menu items outputs the HTML as a string rather than rendering it.
    // So for our plugins that use a top-level CPT menu item, this function rewrites the menu label to incorporate the correct HTML.
    public function rewrite_menu_label()
    {
        global  $menu ;
        // @todo calc this in constants.php just once and pass it in.
        $opt_pfx = $this->custom_plugin_data->db_option_prefix;
        $new_features_number = \WPGO_Plugins\Plugin_Framework\Upgrade_FW::calc_new_features( $opt_pfx, $this->new_features_arr, $this->plugin_data );
        $title = ( 0 === $new_features_number ? __( 'Flexible FAQs', 'flexible-faqs' ) : 'Flexible FAQs <span class="update-plugins count-' . $new_features_number . '"><span class="plugin-count">' . $new_features_number . '</span></span>' );
        if ( $menu ) {
            foreach ( $menu as $key => $value ) {
                if ( !(false === strpos( $value[0], 'Flexible FAQs' )) ) {
                    $menu[$key][0] = $title;
                }
            }
        }
    }
    
    /**
     * Remove the slug from metabox.
     */
    public function remove_slug_meta_box()
    {
        remove_meta_box( 'slugdiv', 'wpgo_faq', 'side' );
    }
    
    /**
     * Enqueue admin scripts for FAQ CPT.
     *
     * @param WP_Hook $hook current page name.
     */
    public function faq_cpt_scripts( $hook )
    {
        global  $pagenow, $typenow, $taxnow ;
        if ( 'post-new.php' != $hook && 'post.php' != $hook ) {
            return;
        }
        
        if ( 'wpgo_faq' === $typenow ) {
            // Initialize empty dependency array.
            $dep = array();
            
            if ( isset( $_GET['post'] ) ) {
                $faq_post_id = (int) $_GET['post'];
                $faq_questions = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_questions', true );
                $faq_answers = get_post_meta( $faq_post_id, '_wpgo_faq_cpt_answers', true );
            } else {
                $faq_questions = array();
                $faq_answers = array();
            }
            
            wp_enqueue_editor();
            wp_enqueue_media();
            // $jquery_ui_css_rel = 'assets/css/jquery-ui.css';
            // $jquery_ui_css_url = plugins_url($jquery_ui_css_rel, $this->module_roots['file']);
            // $jquery_ui_css_ver = filemtime($this->module_roots['dir'] . $jquery_ui_css_rel);
            $cpt_admin_js = $this->utilities_fw->get_enqueue_version( '/assets/js/cpt-admin-compiled.js', $this->custom_plugin_data->plugin_data['Version'] );
            $cpt_admin_css = $this->utilities_fw->get_enqueue_version( '/assets/css/cpt-admin.css', $this->custom_plugin_data->plugin_data['Version'] );
            wp_enqueue_script(
                'wpgo-faq-cpt-js',
                $cpt_admin_js['uri'],
                $dep,
                $cpt_admin_js['ver']
            );
            wp_enqueue_style(
                'wpgo-faq-cpt-css',
                $cpt_admin_css['uri'],
                array(),
                $cpt_admin_css['ver']
            );
            if ( $this->custom_plugin_data->is_premium ) {
                wp_enqueue_script( array( 'jquery-ui-core', 'jquery-ui-dialog' ) );
            }
            $sample_faqs = $this->custom_plugin_data->sample_faqs;
            $jquery_ui_js = $this->utilities_fw->get_enqueue_version( '/assets/js/jquery-ui.min.js', $this->custom_plugin_data->plugin_data['Version'] );
            wp_enqueue_script(
                'wpgo-jquery-ui-js',
                $jquery_ui_js['uri'],
                array(),
                $jquery_ui_js['ver']
            );
            wp_enqueue_style(
                'wpgo-jquery-ui-css',
                '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css',
                array(),
                '1.12.1'
            );
            // Localize the script with new data.
            $loc = array(
                'faq_questions' => $faq_questions,
                'faq_answers'   => $faq_answers,
                'sample_faqs'   => $sample_faqs,
                'plugin_url'    => $this->module_roots['uri'],
            );
            wp_localize_script( 'wpgo-faq-cpt-js', 'wpgo_faq', $loc );
            // echo '<pre style="margin-left:175px;">';
            // print_r( $loc );
            // echo '</pre>';
        }
    
    }
    
    /**
     * Add the FAQ set ID to the columns list for admin
     *
     * @param Array $columns list of column names.
     * @return Array Append `tax_id` to the columns array.
     */
    public function add_id_column( $columns )
    {
        return $columns + array(
            'tax_id' => 'ID',
        );
    }
    
    /**
     * Set internal style for the #tax_id
     */
    public function style_id_column()
    {
        echo  '<style>#tax_id{width:4em}</style>' ;
    }
    
    /**
     * Add the FAQ set ID to the columns list for admin
     *
     * @param String $v .
     * @param String $name Name of column.
     * @param String $id ID of columns.
     * @return String Return `$v` or `$id` based on the comparison.
     */
    public function show_id_column( $v, $name, $id )
    {
        return ( 'tax_id' === $name ? $id : $v );
    }
    
    /**
     * Register FAQ post type.
     */
    public function register_post_type()
    {
        // @todo calc this in constants.php just once and pass it in.
        $opt_pfx = $this->custom_plugin_data->db_option_prefix;
        $new_features_number = \WPGO_Plugins\Plugin_Framework\Upgrade_FW::calc_new_features( $opt_pfx, $this->new_features_arr, $this->plugin_data );
        $title = ( 0 === $new_features_number ? __( 'Flexible FAQs', 'flexible-faqs' ) : 'Flexible FAQs <span class="update-plugins count-' . $new_features_number . '"><span class="plugin-count">' . $new_features_number . '</span></span>' );
        // $title = __( 'Flexible FAQs', 'flexible-faqs' );
        /* Post type arguments. */
        $args = array(
            'public'              => true,
            'has_archive'         => 'faqs',
            'can_export'          => false,
            'exclude_from_search' => false,
            'query_var'           => true,
            'rewrite'             => array(
            'slug' => 'faq',
        ),
            'capability_type'     => 'page',
            'publicly_queryable'  => false,
            'hierarchical'        => false,
            'taxonomies'          => array( 'wpgo_faq_group' ),
            'menu_icon'           => 'dashicons-editor-help',
            'supports'            => array(
            // 'editor',
            'author',
            'thumbnail',
            'title',
        ),
            'labels'              => array(
            'name'               => $title,
            'all_items'          => __( 'All FAQs', 'flexible-faqs' ),
            'singular_name'      => __( 'FAQ', 'flexible-faqs' ),
            'add_new'            => __( 'Add New FAQs', 'flexible-faqs' ),
            'add_new_item'       => __( 'Add New Set of FAQs', 'flexible-faqs' ),
            'edit_item'          => __( 'Edit FAQ', 'flexible-faqs' ),
            'new_item'           => __( 'New FAQ', 'flexible-faqs' ),
            'view_item'          => false,
            'search_items'       => __( 'Search FAQs', 'flexible-faqs' ),
            'not_found'          => sprintf( __( 'No FAQs Found. Now\'s a good time to %1$screate your first one%2$s!', 'flexible-faqs' ), '<a href="' . esc_url( get_admin_url() . 'post-new.php?post_type=' . $this->custom_plugin_data->cpt_slug ) . '">', '</a>' ),
            'not_found_in_trash' => __( 'No FAQs Found In Trash', 'flexible-faqs' ),
            'attributes'         => __( 'FAQ Attributes', 'flexible-faqs' ),
        ),
        );
        /* Register post type. */
        register_post_type( $this->custom_plugin_data->cpt_slug, $args );
    }
    
    /**
     * Register FAQ taxonomy.
     */
    public function register_taxonomy()
    {
        $cpt = $this->custom_plugin_data->cpt_slug;
        /* FAQ taxonomy arguments. */
        $args = array(
            'hierarchical'  => true,
            'query_var'     => true,
            'show_tagcloud' => false,
            'sort'          => true,
            'rewrite'       => array(
            'slug' => 'faqs',
        ),
            'labels'        => array(
            'name'              => __( 'FAQ Groups', 'flexible-faqs' ),
            'singular_name'     => __( 'FAQ Group', 'flexible-faqs' ),
            'edit_item'         => __( 'Edit FAQ Group', 'flexible-faqs' ),
            'update_item'       => __( 'Update FAQ', 'flexible-faqs' ),
            'add_new_item'      => __( 'Add New FAQ Group', 'flexible-faqs' ),
            'new_item_name'     => __( 'New FAQ Name', 'flexible-faqs' ),
            'all_items'         => __( 'All FAQs', 'flexible-faqs' ),
            'search_items'      => __( 'Search FAQs', 'flexible-faqs' ),
            'parent_item'       => __( 'Parent Genre', 'flexible-faqs' ),
            'parent_item_colon' => __( 'Parent Genre:', 'flexible-faqs' ),
            'not_found'         => __( 'No FAQ groups found. Now\'s a good time to create you\'re first one!', 'flexible-faqs' ),
        ),
        );
        /* Register the faq taxonomy. */
        register_taxonomy( $cpt . '_group', array( $cpt ), $args );
    }
    
    /**
     * Change the column labels on the custom post types overview page.
     *
     * @param Array $cols Names of the columns in admin screen for custom post type.
     * @return Array Associative array of updated overview columns.
     */
    public function change_overview_columns( $cols )
    {
        $cols = array(
            'cb'         => '<input type="checkbox">',
            'title'      => __( 'Title', 'flexible-faqs' ),
            'faq-number' => __( 'Active FAQs', 'flexible-faqs' ),
            'faq-author' => __( 'Author', 'flexible-faqs' ),
            'image'      => __( 'Image', 'flexible-faqs' ),
            'group'      => __( 'FAQ Group', 'flexible-faqs' ),
            'id'         => __( 'ID', 'flexible-faqs' ),
            'date'       => __( 'Date', 'flexible-faqs' ),
        );
        return $cols;
    }
    
    /**
     * Add some content to the custom columns from the custom post type.
     *
     * @param String $column Name of the column.
     * @param Int    $post_id ID of current custom post.
     */
    public function custom_column_content( $column, $post_id )
    {
        switch ( $column ) {
            case 'faq-author':
                $author_id = get_post_field( 'post_author', $post_id );
                echo  get_the_author_meta( 'display_name', $author_id ) ;
                break;
            case 'faq-number':
                $faq_count = Utility::get_faq_items_count( $post_id );
                echo  $faq_count['active_count'] ;
                break;
            case 'image':
                /* If no featured image set, use gravatar if specified. */
                
                if ( !($image = get_the_post_thumbnail( $post_id, array( 32, 32 ) )) ) {
                    $image = get_post_meta( $post_id, '_wpgo_faq_cpt_image', true );
                    
                    if ( trim( $image ) == '' ) {
                        $image = '<em>' . __( 'No image', 'flexible-faqs' ) . '</em>';
                    } else {
                        $image = get_avatar( $image, $size = '32' );
                    }
                
                }
                
                echo  $image ;
                break;
            case 'group':
                $taxonomy = 'wpgo_faq_group';
                $post_type = get_post_type( $post_id );
                $terms = get_the_terms( $post_id, $taxonomy );
                /* get_the_terms() only returns an array on success so need check for valid array. */
                
                if ( is_array( $terms ) ) {
                    $str = '';
                    foreach ( $terms as $term ) {
                        $str .= "<a href='edit.php?post_type={$post_type}&{$taxonomy}={$term->slug}'> " . esc_html( sanitize_term_field(
                            'name',
                            $term->name,
                            $term->term_id,
                            'group',
                            'edit'
                        ) ) . '</a>, ';
                    }
                    echo  rtrim( $str, ', ' ) ;
                } else {
                    echo  '<em>' . __( 'Not in any groups', 'flexible-faqs' ) . '</em>' ;
                }
                
                break;
            case 'id':
                echo  $post_id ;
                break;
        }
    }
    
    /**
     * Make custom columns sortable.
     *
     * @return Array An associative array of sorted column names.
     */
    public function sort_custom_columns()
    {
        return array(
            'title'      => 'title',
            'faq-author' => 'faq-author',
            'company'    => 'company',
            'date'       => 'date',
            'id'         => 'id',
        );
    }
    
    /**
     * Move featured image and author meta box.
     */
    public function move_meta_boxes()
    {
        $post_types = get_post_types( array(
            '_builtin' => false,
        ) );
        
        if ( in_array( 'wpgo_faq', $post_types ) ) {
            // Action hook to add FAQ status meta box at this point.
            do_action( 'wpgo_faq_info_meta_box' );
            remove_meta_box( 'authordiv', 'wpgo_faq', 'normal' );
            remove_meta_box( 'postimagediv', 'wpgo_faq', 'side' );
            // remove_meta_box('wpgo-faq-cpt-new-post', 'wpgo_faq', 'side');
            add_meta_box(
                'authordiv',
                __( 'FAQ Author', 'flexible-faqs' ),
                'post_author_meta_box',
                'wpgo_faq',
                'side',
                'low'
            );
        }
    
    }
    
    /**
     * Initialize custom post type meta boxes.
     */
    public function faq_cpt_meta_box_init()
    {
        add_meta_box(
            'wpgo-faq-cpt',
            __( 'Manage FAQs', 'flexible-faqs' ),
            array( &$this, 'faq_meta_box' ),
            'wpgo_faq',
            'normal',
            'high'
        );
        add_meta_box(
            'wpgo-faq-cpt_sc',
            __( 'FAQ Shortcodes', 'flexible-faqs' ),
            array( &$this, 'meta_box_shortcode' ),
            'wpgo_faq',
            'normal',
            'high'
        );
        // Add meta boxes to FAQs CPT editor.
        // Hook to save our meta box data when the post is saved.
        add_action( 'save_post', array( &$this, 'save_faq_meta_box' ) );
    }
    
    /**
     * Display the meta box for faqs data fields.
     *
     * @param Object $post current post.
     * @param Array  $args Arguments passed to functions.
     */
    public function faq_meta_box( $post, $args )
    {
        global  $pagenow ;
        // Retrieve our custom meta box values.
        $faq_cpt_questions = get_post_meta( $post->ID, '_wpgo_faq_cpt_questions', true );
        $faq_cpt_answers = get_post_meta( $post->ID, '_wpgo_faq_cpt_answers', true );
        $faq_cpt_image = get_post_meta( $post->ID, '_wpgo_faq_cpt_image', true );
        $faq_item_count = ( is_array( $faq_cpt_questions ) ? count( $faq_cpt_questions ) : 0 );
        // Update faq width value if a custom width is used for the current theme.
        $w = ( defined( 'WPGO_FAQ_THUMB_WIDTH' ) ? WPGO_FAQ_THUMB_WIDTH : 50 );
        // Add empty Q & A fields if none defined.
        
        if ( !$faq_cpt_questions ) {
            $faq_cpt_questions = array();
            $faq_cpt_questions[] = '';
        }
        
        
        if ( !$faq_cpt_answers ) {
            $faq_cpt_answers = array();
            $faq_cpt_answers[] = '';
        }
        
        ?>

		<div class="sort-container">
		<div id="output-faq">
		<?php 
        $faq_message = '';
        $spinner = '';
        // For new posts.
        if ( 'post-new.php' === $pagenow ) {
            $faq_message = $this->no_faqs_text;
        }
        // For existing posts.
        if ( 'post.php' === $pagenow ) {
            
            if ( empty($faq_item_count) ) {
                $faq_message = $this->no_faqs_text;
            } else {
                $spinner = '<span class="spinner wpgo-spinner"></span>';
                echo  '<p class="add-faq-msg display-none">' . $this->no_faqs_text . '</p>' ;
            }
        
        }
        // Add wrapper if non-empty.
        if ( !empty($faq_message) ) {
            $faq_message = '<p class="add-faq-msg">' . $faq_message . '</p>';
        }
        ?>
		<?php 
        echo  $faq_message ;
        echo  $spinner ;
        ?>
		</div>
		</div>
		<div class="add-faq-container">
		<a href="#" class="button add-faq" title="<?php 
        _e( 'Add a blank new FAQ item.' );
        ?>"><?php 
        _e( 'Add New FAQ' );
        ?></a>
		<?php 
        $btn_class = 'display-none';
        if ( empty($faq_item_count) ) {
            $btn_class = '';
        }
        $faq_class = 'add-sample-faq';
        ?>
		<a href="#" class="button button-link <?php 
        echo  $faq_class . ' ' . $btn_class ;
        ?>" title="<?php 
        _e( 'Add a bunch of sample FAQ items in one go!' );
        ?>"><?php 
        _e( 'Add Sample FAQs' );
        ?></a>

		<!-- add field to save the count of questions and answers -->
		<input type='hidden' name='qa_count' class='qa-count' value='<?php 
        echo  $faq_item_count ;
        ?>'>
		</div>
		<?php 
    }
    
    /**
     * Save the custom post type meta box input field settings.
     *
     * @param Integer $post_id ID of current post.
     */
    public function save_faq_meta_box( $post_id )
    {
        global  $typenow ;
        /* Only work for specific post type */
        if ( 'wpgo_faq' != $typenow ) {
            return;
        }
        // echo '<pre>';
        // print_r( $_POST['wpgo_faq_cpt_disabled'] );
        // echo '</pre>';
        // die();
        // If no questions array then it's likely all FAQ items have been deleted.
        
        if ( isset( $_POST['qa_count'] ) && 0 == $_POST['qa_count'] ) {
            update_post_meta( $post_id, '_wpgo_faq_cpt_questions', array() );
            update_post_meta( $post_id, '_wpgo_faq_cpt_answers', array() );
            update_post_meta( $post_id, '_wpgo_faq_cpt_disabled', array() );
        }
        
        $disabled_items = array();
        // Sanitize and save the meta box data as post meta, using the post ID as a unique prefix.
        
        if ( isset( $_POST['wpgo_faq_cpt_questions'] ) && is_array( $_POST['wpgo_faq_cpt_questions'] ) ) {
            foreach ( $_POST['wpgo_faq_cpt_questions'] as $key => $value ) {
                $filtered = wp_kses( $value, $this->allowed_html_tags( 'q' ) );
                $_POST['wpgo_faq_cpt_questions'][$key] = $filtered;
                // echo "<pre>key [" . 'disabled-chk-' . ($key + 1) . "]:" . $key . "</pre>"; // .
                // Update disabled item array.
                
                if ( !isset( $_POST['wpgo_faq_cpt_disabled'] ) ) {
                    // If all disable FAQ item toggles are off then the $_POST['wpgo_faq_cpt_disabled'] array won't be set.
                    $disabled_items[] = '0';
                } else {
                    
                    if ( in_array( 'disabled-chk-' . ($key + 1), $_POST['wpgo_faq_cpt_disabled'] ) ) {
                        $disabled_items[] = '1';
                    } else {
                        $disabled_items[] = '0';
                    }
                
                }
            
            }
            // echo '<pre>';
            // print_r($_POST['wpgo_faq_cpt_disabled']);
            // print_r($disabled_items);
            // echo '</pre>';
            // die();
            update_post_meta( $post_id, '_wpgo_faq_cpt_questions', $_POST['wpgo_faq_cpt_questions'] );
            update_post_meta( $post_id, '_wpgo_faq_cpt_disabled', $disabled_items );
            // update_post_meta($post_id, '_wpgo_faq_cpt_questions', wp_kses($_POST['wpgo_faq_cpt_questions'], $this->allowed_html_tags('q')));
            // update_post_meta($post_id, '_wpgo_faq_cpt_questions', $_POST['wpgo_faq_cpt_questions']); // .
        }
        
        /* Sanitize and save the meta box data as post meta, using the post ID as a unique prefix. */
        
        if ( isset( $_POST['wpgo_faq_cpt_answers'] ) && is_array( $_POST['wpgo_faq_cpt_answers'] ) ) {
            foreach ( $_POST['wpgo_faq_cpt_answers'] as $key => $value ) {
                $filtered = wp_kses( $value, $this->allowed_html_tags( 'a' ) );
                $_POST['wpgo_faq_cpt_answers'][$key] = $filtered;
            }
            update_post_meta( $post_id, '_wpgo_faq_cpt_answers', $_POST['wpgo_faq_cpt_answers'] );
            // update_post_meta($post_id, '_wpgo_faq_cpt_answers', wp_kses($_POST['wpgo_faq_cpt_answers'], $this->allowed_html_tags('a')));
            // update_post_meta($post_id, '_wpgo_faq_cpt_answers', $_POST['wpgo_faq_cpt_answers']); // .
        }
        
        /**
         * Commented code
         * if ( isset( $_POST['wpgo_faq_cpt_image'] ) ) {
         * update_post_meta( $post_id, '_wpgo_faq_cpt_image', esc_attr( $_POST['wpgo_faq_cpt_image'] ) );
         * }
         */
    }
    
    /**
     * List of allowed tags in Q/A edit fields.
     *
     * @param String $field string to remove htmls tags from.
     * @return Array List of tags that are allowed in the question's contents.
     */
    public function allowed_html_tags( $field )
    {
        $allowed_tags = array(
            'a'          => array(
            'src'    => array(),
            'class'  => array(),
            'href'   => array(),
            'rel'    => array(),
            'title'  => array(),
            'target' => array(),
            'style'  => array(),
        ),
            'abbr'       => array(
            'title' => array(),
        ),
            'b'          => array(),
            'blockquote' => array(
            'cite' => array(),
        ),
            'cite'       => array(
            'title' => array(),
        ),
            'code'       => array(),
            'del'        => array(
            'datetime' => array(),
            'title'    => array(),
        ),
            'dd'         => array(),
            'div'        => array(
            'class' => array(),
            'title' => array(),
            'style' => array(),
        ),
            'dl'         => array(),
            'dt'         => array(),
            'em'         => array(),
            'h1'         => array(),
            'h2'         => array(),
            'h3'         => array(),
            'h4'         => array(),
            'h5'         => array(),
            'h6'         => array(),
            'i'          => array(),
            'iframe'     => array(
            'width'           => array(),
            'height'          => array(),
            'src'             => array(),
            'frameborder'     => array(),
            'allow'           => array(),
            'allowfullscreen' => array(),
            'allow'           => array(),
            'style'           => array(),
        ),
            'img'        => array(
            'alt'    => array(),
            'class'  => array(),
            'height' => array(),
            'src'    => array(),
            'width'  => array(),
            'style'  => array(),
        ),
            'li'         => array(
            'class' => array(),
            'style' => array(),
        ),
            'ol'         => array(
            'class' => array(),
            'style' => array(),
        ),
            'p'          => array(
            'class' => array(),
            'style' => array(),
        ),
            'q'          => array(
            'cite'  => array(),
            'title' => array(),
        ),
            'span'       => array(
            'class' => array(),
            'title' => array(),
            'style' => array(),
        ),
            'table'      => array(
            'style' => array(),
        ),
            'thead'      => array(),
            'th'         => array(
            'style' => array(),
        ),
            'tr'         => array(
            'style' => array(),
        ),
            'td'         => array(
            'style' => array(),
        ),
            'strike'     => array(),
            'strong'     => array(),
            'ul'         => array(
            'class' => array(),
            'style' => array(),
        ),
        );
        // Don't allow certain elements to be used in 'Q' field.
        
        if ( 'q' == $field ) {
            unset( $allowed_tags['iframe'] );
            unset( $allowed_tags['ul'] );
            unset( $allowed_tags['ol'] );
            unset( $allowed_tags['li'] );
            unset( $allowed_tags['img'] );
            unset( $allowed_tags['blockquote'] );
            unset( $allowed_tags['table'] );
            unset( $allowed_tags['abbr'] );
            unset( $allowed_tags['p'] );
            unset( $allowed_tags['div'] );
            unset( $allowed_tags['table'] );
            unset( $allowed_tags['thead'] );
            unset( $allowed_tags['th'] );
            unset( $allowed_tags['tr'] );
            unset( $allowed_tags['td'] );
            unset( $allowed_tags['h1'] );
            unset( $allowed_tags['h2'] );
            unset( $allowed_tags['h3'] );
            unset( $allowed_tags['h4'] );
            unset( $allowed_tags['h5'] );
            unset( $allowed_tags['h6'] );
            unset( $allowed_tags['dd'] );
            unset( $allowed_tags['dl'] );
            unset( $allowed_tags['dt'] );
        }
        
        return $allowed_tags;
    }
    
    /**
     * Display meta box to show shortcode for the current faq.
     *
     * @param Object $post Object passed as Parameter.
     * @param Array  $args Array of args passed as Parameter.
     */
    public function meta_box_shortcode( $post, $args )
    {
        $id = $post->ID;
        $faq_terms = get_the_terms( $id, 'wpgo_faq_group' );
        $faq_description = __( 'Copy and paste the shortcode(s) above into a post, or page, to display a list of FAQs.', 'flexible-faqs' );
        $group_faq_html = '';
        
        if ( !empty($faq_terms) ) {
            $group_sc = '';
            foreach ( $faq_terms as $faq_term ) {
                $group_sc .= "[flexible-faqs group='{$faq_term->term_id}'] ";
            }
            $group_sc = trim( $group_sc );
            // trim trailing space.
            
            if ( count( $faq_terms ) > 1 ) {
                $group_label = 'Group FAQ shortcodes';
            } elseif ( count( $faq_terms ) == 1 ) {
                $group_label = 'Group FAQ shortcode';
            }
            
            $group_faq_html = '<tr><td>
				<h4 class="shordcode-label">' . $group_label . '</h4>
				<div class="wpgo-group-faq-cpt-sc">
					<input id="wpgo-group-faq-sc" class="shordcode-input" type="text" readonly value="' . $group_sc . '">
					<img title="Copy group FAQ shortcode to the clipboard" src="' . $this->module_roots['uri'] . '/assets/images/icons/copy.svg" class="wpgo-faq-shortcode-copy">
				</div>
			</td></tr>';
        }
        
        $single_sc = "[flexible-faqs id='{$id}'] ";
        $single_sc = trim( $single_sc );
        // trim trailing space.
        $single_sc_label = 'FAQ shortcode';
        $single_faq_html = '<tr><td>
			<h4 class="shordcode-label">' . $single_sc_label . '</h4>
			<div class="wpgo-single-faq-cpt-sc">
				<input id="wpgo-single-faq-sc" class="shordcode-input" type="text" readonly value="' . $single_sc . '">
				<img title="Copy single FAQ shortcode to the clipboard" src="' . $this->module_roots['uri'] . '/assets/images/icons/copy.svg" class="wpgo-faq-shortcode-copy">
			</div>
		</td></tr>';
        ?>

		<table width="100%">
			<tbody>
		<?php 
        echo  $single_faq_html ;
        echo  $group_faq_html ;
        ?>
			<tr>
				<td>
					<p class="description"><?php 
        echo  $faq_description ;
        ?></p>
				</td>
			</tr>
			</tbody>
		</table>
		<?php 
    }
    
    /**
     * Save the custom post type meta box input field settings.
     *
     * @param Array $messages An array of strings to display as notification messages.
     * @return Array Updated list of notifications for the admin.
     */
    public function update_cpt_messages( $messages )
    {
        global  $post, $post_ID ;
        $messages['wpgo_faq'] = array(
            0  => '',
            1  => sprintf( __( 'FAQ updated.', 'flexible-faqs' ), esc_url( get_permalink( $post_ID ) ) ),
            2  => __( 'Custom field updated.', 'flexible-faqs' ),
            3  => __( 'Custom field deleted.', 'flexible-faqs' ),
            4  => __( 'FAQ updated.', 'flexible-faqs' ),
            5  => ( isset( $_GET['revision'] ) ? sprintf( __( 'FAQ restored to revision from %s', 'flexible-faqs' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false ),
            6  => sprintf( __( 'FAQ published.', 'flexible-faqs' ), esc_url( get_permalink( $post_ID ) ) ),
            7  => __( 'FAQ saved.', 'flexible-faqs' ),
            8  => sprintf( __( 'FAQ submitted.', 'flexible-faqs' ), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ) ),
            9  => sprintf(
            // Translators: Publish box date format, see http://php.net/date.
            __( 'FAQ scheduled for: %1$s.', 'flexible-faqs' ),
            '<strong>' . date_i18n( __( 'M j, Y @ G:i', 'flexible-faqs' ), strtotime( $post->post_date ) ) . '</strong>',
            esc_url( get_permalink( $post_ID ) )
        ),
            10 => sprintf( __( 'FAQ draft updated.', 'flexible-faqs' ), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ) ),
        );
        return $messages;
    }
    
    /**
     * Filter the request to just give posts for the given taxonomy.
     */
    public function taxonomy_filter_restrict_manage_posts()
    {
        global  $typenow ;
        /* Only work for specific post type */
        if ( 'wpgo_faq' != $typenow ) {
            return;
        }
        $post_types = get_post_types( array(
            '_builtin' => false,
        ) );
        
        if ( in_array( $typenow, $post_types ) ) {
            $filters = get_object_taxonomies( $typenow );
            foreach ( $filters as $tax_slug ) {
                
                if ( !isset( $_GET[$tax_slug] ) ) {
                    $selected = '';
                } else {
                    $selected = $_GET[$tax_slug];
                }
                
                $tax_obj = get_taxonomy( $tax_slug );
                wp_dropdown_categories( array(
                    'taxonomy'     => $tax_slug,
                    'name'         => $tax_obj->name,
                    'orderby'      => 'name',
                    'selected'     => $selected,
                    'hierarchical' => $tax_obj->hierarchical,
                    'show_count'   => true,
                    'hide_empty'   => true,
                ) );
            }
        }
    
    }
    
    /**
     * Add a filter to the query so the dropdown will work.
     *
     * @param String $query SQL query passed as parameter.
     */
    public function taxonomy_filter_post_type_request( $query )
    {
        global  $pagenow, $typenow ;
        
        if ( 'edit.php' == $pagenow ) {
            $filters = get_object_taxonomies( $typenow );
            foreach ( $filters as $tax_slug ) {
                $var =& $query->query_vars[$tax_slug];
                
                if ( isset( $var ) ) {
                    $term = get_term_by( 'id', $var, $tax_slug );
                    $var = $term->slug;
                }
            
            }
        }
    
    }
    
    /**
     * Change default placeholder text for post title.
     *
     * @param String $title Title for the post/page.
     * @return String Placeholder title for the CPT `wpgo_faq`.
     */
    public function title_placeholder( $title )
    {
        $screen = get_current_screen();
        if ( isset( $screen->post_type ) ) {
            if ( 'wpgo_faq' == $screen->post_type ) {
                $title = 'Enter FAQs title here. e.g. FAQs, Help, Support';
            }
        }
        return $title;
    }

}