<?php
/**
 * Prohibit direct script loading
 */
defined('ABSPATH') || die('No direct script access allowed!');

/**
 * Class WpmsGscCategoryFilters
 */
class WpmsGscCategoryFilters
{
    /**
     * The counts per category
     *
     * @var array
     */
    private $wpms_gsc_category_counts = array();
    /**
     * All the possible filters
     *
     * @var array
     */
    private $wpms_gsc_filter = array();
    /**
     * The current category
     *
     * @var string
     */
    private $wpms_gsc_category;

    /**
     * WpmsGscCategoryFilters constructor.
     * Setting the hook to create the issues categories as the links
     *
     * @param array $platform_counts Set of issue counts by platform.
     */
    public function __construct(array $platform_counts)
    {
        if (!empty($platform_counts)) {
            $this->setCounts($platform_counts);
        }

        $this->createFilters();
    }

    /**
     * Returns the current filters as an array
     *
     * Only return categories with more than 0 issues
     *
     * @return array
     */
    public function convertArray()
    {
        $new_views = array();
        foreach ($this->wpms_gsc_category_counts as $category_name => $category) {
            $new_views[] = $this->createLink($category_name, $category['count']);
        }

        return $new_views;
    }

    /**
     * Setting the view counts based on the saved data. The info will be used to display the category filters
     *
     * @param array $platform_counts Set of counts by platform.
     *
     * @return void
     */
    private function setCounts(array $platform_counts)
    {
        $this->wpms_gsc_category_counts = $this->gscCounts($platform_counts);
    }

    /**
     * Setting the values for the filter
     *
     * @return void
     */
    private function createFilters()
    {
        $this->wpms_gsc_filter['access_denied'] = array(
            'value'       => esc_html__('Access denied', 'wpmsPro'),
            'description' => esc_html__('Server requires authentication or is blocking Googlebot
             from accessing the site.', 'wpmsPro')
        );

        $this->wpms_gsc_filter['faulty_redirects'] = array(
            'value'       => esc_html__('Faulty redirects', 'wpmsPro'),
            'description' => ''
        );

        $this->wpms_gsc_filter['not_followed'] = array(
            'value'       => esc_html__('Not followed', 'wpmsPro'),
            'description' => ''
        );

        $this->wpms_gsc_filter['not_found'] = array(
            'value'       => esc_html__('Not found', 'wpmsPro'),
            'description' => esc_html__('URL points to a non-existent page.', 'wpmsPro')
        );

        $this->wpms_gsc_filter['other'] = array(
            'value'       => esc_html__('Other', 'wpmsPro'),
            'description' => esc_html__('Google was unable to crawl this URL due
             to an undetermined issue.', 'wpmsPro')
        );

        $this->wpms_gsc_filter['roboted'] = array(
            'value'       => esc_html__('Blocked', 'wpmsPro'),
            'description' => sprintf(esc_html__('Googlebot could access your site,
             but certain URLs are blocked for Googlebot in your %1$s file.
              This block could either be for all Googlebots or even specifically
               for Googlebot-mobile.', 'wpmsPro'), '<code>robots.txt</code>')
        );

        $this->wpms_gsc_filter['server_error'] = array(
            'value'       => esc_html__('Server Error', 'wpmsPro'),
            'description' => esc_html__('Request timed out or site is blocking Google.', 'wpmsPro')
        );

        $this->wpms_gsc_filter['soft_404'] = array(
            'value'       => esc_html__('Soft 404', 'wpmsPro'),
            'description' => esc_html__("The target URL doesn't exist, but your server is not returning
             a 404 (file not found) error.", 'wpmsPro')
        );

        $this->wpms_gsc_category = $this->getCurrentCategory();
    }

    /**
     * Returns the value of the current category
     *
     * @return mixed
     */
    public function getCategory()
    {
        return $this->wpms_gsc_category;
    }

    /**
     * Parsing the category counts. When there are 0 issues for a specific category, just remove that one from the array
     *
     * @param array $cat_counts Set of counts for categories.
     *
     * @return mixed
     */
    private function gscCounts($cat_counts)
    {
        foreach ($cat_counts as $category_name => $category) {
            if ($category['count'] === '0') {
                unset($cat_counts[$category_name]);
            }
        }

        return $cat_counts;
    }

    /**
     * Creates a filter link
     *
     * @param string  $category Issue type.
     * @param integer $count    Count for the type.
     *
     * @return string
     */
    private function createLink($category, $count)
    {
        wp_enqueue_style('wpms-tippy-style');
        wp_enqueue_style('wpms-mytippy-style');
        wp_enqueue_script('wpms-tippy-core');
        wp_enqueue_script('wpms-tippy');
        wp_enqueue_script('wpms-my-tippy');
        $href  = add_query_arg(array('category' => $category, 'paged' => 1));
        $class = 'wpms_gsc_category';
        if ($this->wpms_gsc_category === $category) {
            $class .= ' current';
        }
        $html = '<a data-tippy="' . $this->wpms_gsc_filter[$category]['description'] . '"
         href="' . esc_attr($href) . '" class="' . esc_attr($class) . '">
         ' . $this->wpms_gsc_filter[$category]['value'] . '</a>
          (<span id="' . esc_attr('gsc_count_' . $category) . '">' . esc_html($count) . '</span>)';
        return $html;
    }

    /**
     * Getting the current view
     *
     * @return integer|mixed|null|string
     */
    private function getCurrentCategory()
    {
        $current_cat = filter_input(INPUT_GET, 'category');
        if ($current_cat) {
            return $current_cat;
        }

        if (!empty($this->wpms_gsc_category_counts)) {
            $current_cat = 'not_found';
            if (empty($this->wpms_gsc_category_counts[$current_cat])) {
                $current_cat = key($this->wpms_gsc_category_counts);
            }

            // redirect to set the category.
            $url = add_query_arg('category', $current_cat);
            wp_redirect($url);
            exit;
        }
        return false;
    }
}
