<?php


namespace SearchFilterSort\Filter;

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

class AdminHooks
{

    public function __construct()
    {
        add_filter( 'manage_edit-'.SFS_FILTERS_SET_POST_TYPE.'_columns', array( $this, 'filterSetPostTypeCol' ) );
        add_action( 'manage_'.SFS_FILTERS_SET_POST_TYPE.'_posts_custom_column', array( $this, 'filterSetPostTypeColContent'), 10, 2 );

        add_filter( 'manage_edit-'.SFS_FILTERS_SET_POST_TYPE.'_sortable_columns', array( $this, 'filterSetSortableColumn') );
        add_action( 'pre_get_posts', array( $this, 'filterSetOrderby' ) );

        add_action('admin_notices', [$this, 'adminNotices'] );
        add_action('admin_notices', [$this, 'checkForbiddenPrefixes'] );

        add_filter( 'plugin_action_links_' . SFS_PLUGIN_BASENAME, [$this,'actionsLink'] );

        add_action( 'current_screen', [$this, 'currentScreen' ] );
        add_action( 'sfswp_admin_toolbar_right', [$this, 'aboutPro' ] );
    }

    public function aboutPro()
    {
        if ( ! defined('SFS_FILTERS_PRO') ) {
            if ( sfs_ask_for_help() ) {
                echo '<a class="sfswp-tab sfswp-help-me" href="'.admin_url( 'edit.php?post_type=sfs-set&page=sfs-settings&tab=helpme' ).'">'.esc_html__( 'Need Your Help', 'searchfiltersort' ).'</a>'."\r\n";
            }

            echo '<a class="sfswp-tab sfswp-get-pro" href="'.admin_url( 'edit.php?post_type=sfs-set&page=sfs-settings&tab=aboutpro' ).'">'.esc_html__( 'About PRO', 'searchfiltersort' ).'</a>'."\r\n";
            echo '<a class="sfswp-tab sfswp-get-pro button button-primary" href="'.esc_url(SFS_PLUGIN_URL .'/?get_pro=true').'" target="_blank">'.esc_html__( 'Get PRO', 'searchfiltersort' ).'</a>'."\r\n";
        }

        $this->addHelpTab();

    }

    public function addHelpTab() {
        $screen = get_current_screen();

        if( is_null( $screen ) ){
            return false;
        }

        // Overview tab.
        $screen->add_help_tab(
            array(
                'id'      => 'overview',
                'title'   => esc_html__( 'Overview', 'searchfiltersort' ),
                'content' =>
                    '<p><strong>' . esc_html__( 'Overview', 'searchfiltersort' ) . '</strong></p>' .
                    '<p>' . esc_html__( 'SearchFilterSort — WordPress & WooCommerce product filter plugin that allows you to design a flexible filtering system.', 'searchfiltersort' ) . '</p>'.
                    '<p>' . esc_html__( 'It is fast, convenient, intuitive, and contains unique SEO features (in the PRO version).', 'searchfiltersort' ) . '</p>'
            )
        );

        // Help tab.
        $screen->add_help_tab(
            array(
                'id'      => 'help',
                'title'   => esc_html__( 'Help & Support', 'searchfiltersort' ),
                'content' =>
                    '<p><strong>' . esc_html__( 'Help & Support', 'searchfiltersort' ) . '</strong></p>' .
                    '<ul>' .
                    '<li>' . wp_kses( sprintf(
                                        __( '<a href="%s" target="_blank">Documentation</a>. Common information on how to work with the plugin can be found in our documentation.', 'searchfiltersort' ),
                                        'https://www.searchfiltersort.com/how-to-add-a-search-filter-to-your-wordpress-site/'
                                        ),
                                        array(
                                            'a' => array( 'href' => true, 'target' => true )
                                        )
                        ). '</li>' .
                    '<li>' . wp_kses(
                                sprintf(
                                    __( '<a href="%s" target="_blank">Support</a>. Create a technical support request if you are unable to resolve the issue yourself.', 'searchfiltersort' ),
                                    'https://www.searchfiltersort.com/how-to-add-a-search-filter-to-your-wordpress-site/'
                                ),
                                array(
                                    'a' => array( 'href' => false, 'target' => true )
                                )
                    ). '</li>' .
                    '</ul>'
            )
        );

        // Sidebar.
        $screen->set_help_sidebar(
            '<p><strong>' . esc_html__( 'Information', 'searchfiltersort' ) . '</strong></p>' .
            '<p><span class="dashicons dashicons-admin-plugins"></span> ' . sprintf( esc_html__( 'Version %s', 'searchfiltersort' ), SFS_PLUGIN_VER ) . '</p>' .
            '<p><span class="dashicons dashicons-wordpress"></span> <a href="https://wordpress.org/plugins/search-filter-sort/" target="_blank">' . esc_html__( 'View details', 'searchfiltersort' ) . '</a></p>' .
            '<p><span class="dashicons dashicons-admin-home"></span> <a href="https://www.searchfiltersort.com/" target="_blank" target="_blank">' . esc_html__( 'Visit website', 'searchfiltersort' ) . '</a></p>' .
            ''
        );
    }

    public function currentScreen( $screen )
    {
        $screenList = [SFS_FILTERS_SET_POST_TYPE];

        if( defined( 'SFS_SEO_RULES_POST_TYPE' ) ){
            $screenList[] = SFS_SEO_RULES_POST_TYPE;
        }

        $screenList = array_filter(array_unique($screenList));
        $post_type = isset( $screen->post_type ) ? $screen->post_type : '';

        if (!empty($post_type) && in_array( $post_type, $screenList ) ) {
            add_action( 'in_admin_header', [ $this, 'inAdminHeader' ] );
        }
    }

    public function inAdminHeader()
    {
        $templateManager = Container::instance()->getTemplateManager();
        $templateManager->includeAdminView( 'header-navigation' );
    }

    public function actionsLink( $actions ) {
        $actionsLink = array(
            '<a href="' . admin_url( 'post-new.php?post_type=sfs-set' ) . '">'.esc_html__('Add Filters', 'searchfiltersort').'</a>',
            '<a href="' . admin_url( 'edit.php?post_type=sfs-set&page=sfs-settings' ) . '">'.esc_html__('Settings', 'searchfiltersort').'</a>'
        );

        $actions = array_merge( $actionsLink, $actions );

        if( ! defined( 'SFS_FILTERS_PRO' ) ){
            $actions[] = '<a href="' . esc_url(SFS_PLUGIN_URL .'/?get_pro=true') . '" class="sfswp-go-pro" target="_blank">'.esc_html__('Get PRO', 'searchfiltersort').'</a>';
        }

        return $actions;
    }

    public function checkForbiddenPrefixes()
    {
        $forbiddenPrefixes  = sfs_get_forbidden_prefixes();
        $savedPrefixes      = get_option( 'sfswp_filter_permalinks', [] );

        if ( ! is_array( $savedPrefixes ) ) {
            $savedPrefixes = maybe_unserialize( $savedPrefixes );
        }
        if ( ! is_array( $savedPrefixes ) ) {
            $savedPrefixes = []; // If still not an array, default to an empty array
        }

        $warningPrefixes    = [];

        foreach( $forbiddenPrefixes as $prefix ){
            if( in_array( $prefix, $savedPrefixes ) ){
                $warningPrefixes[] = $prefix;
            }
        }
        $permalinkOptionsUrl    = admin_url( 'edit.php?post_type=sfs-set&page=sfs-settings&tab=prefixes' );
        $permalinksTab          = new PermalinksTab();
        $permalinksTabLabel     = strtolower( $permalinksTab->getLabel() );

        if( ! empty( $warningPrefixes ) ){

            $message = wp_kses(
                            sprintf(
                                _n(
                                'Error: <strong>%s</strong> filter prefix is not allowed and must be changed on the Filter %s settings <a href="%s" target="_blank">page</a>. Otherwise this site will not work properly.',
                                'Error: following filter prefixes <strong>%s</strong> are not allowed and must be changed on the Filter %s settings <a href="%s" target="_blank">page</a>. Otherwise this site will not work properly.',
                                count($warningPrefixes),
                                'searchfiltersort'
                                ), implode( ', ', $warningPrefixes ), $permalinksTabLabel, $permalinkOptionsUrl
                            ),
                            array(
                                'strong' => array(),
                                'a' => array('href' => true, 'target' => true)
                            )
                        );

            ?>
            <div class="notice sfswp-error is-dismissible">
                <p><?php echo $message; // Already escaped ?></p>
            </div>
            <?php

        }

    }

    public function adminNotices()
    {
        $get = Container::instance()->getTheGet();
        /**
         * string
         */
        if( ! isset( $get['message'] ) ){
            return false;
        }

        $messageNum = sanitize_key($get['message']); // no need to escape
        $errors     = SFSFields::getErrorsList();

        ?>
        <?php foreach ( $errors  as $id => $message ) : ?>
            <?php if( isset( $errors[$messageNum] ) ): // no need to escape ?>
            <div class="sfswp-error is-dismissible">
                <p><?php echo $errors[$messageNum]; ?></p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.'); ?></span>
                </button>
            </div>
            <?php break; endif; ?>
        <?php endforeach; ?>
        <?php
    }

    public function filterSetOrderby( $query ) {
        if( ! is_admin() )
            return;

        if( $query->get('post_type') !== SFS_FILTERS_SET_POST_TYPE ){
            return;
        }

        $orderby = $query->get( 'orderby' );

        if( $orderby === 'menu_order title' ){
            $query->set( 'orderby', 'date' );
            $query->set( 'order', 'DESC' );
        }

        if( 'set_post_type' == $orderby ) {
            $query->set( 'meta_key', 'sfswp_filter_set_post_type' );
            $query->set( 'orderby', 'meta_value' );
        }

    }

    public function filterSetSortableColumn( $columns )
    {
        $columns['set_post_type'] = 'set_post_type';
        return $columns;
    }

    public function filterSetPostTypeCol( $columns )
    {
        $newColumns = [];

        foreach ( $columns as $columnId => $columnName ) {

            if( $columnId === 'date' ){
                continue;
            }

            $newColumns[$columnId] = $columnName;
            if( $columnId === 'title' ){
                $newColumns['set_post_type'] = esc_html__( 'Post type', 'searchfiltersort' );
            }
        }

        return $newColumns;
    }

    public function filterSetPostTypeColContent( $column_name, $post_id )
    {
        if( 'set_post_type' == $column_name ){
            $fss        = Container::instance()->getSFSSetService();
            $theSet     = $fss->getSet( $post_id );

            $postTypeSelected   = isset( $theSet['post_type']['value'] ) ? $theSet['post_type']['value'] : '';
            $postTypes          = isset( $theSet['post_type']['options'] ) ? $theSet['post_type']['options'] : '';
            $postType           = isset( $postTypes[ $postTypeSelected ] ) ? $postTypes[ $postTypeSelected ] : '';

            echo esc_html( $postType );
        }
    }

}

new AdminHooks();