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

/**
 * Class WpmsGscService
 */
class WpmsGscService
{
    /**
     * Google search console client
     *
     * @var object
     */
    private $client;
    /**
     * Profile
     *
     * @var string
     */
    private $profile;

    /**
     * WpmsGscService constructor.
     *
     * @param string $profile Profile
     *
     * @return void
     */
    public function __construct($profile = '')
    {
        $this->profile = $profile;
        $this->setClient();
    }

    /**
     * Returns the client
     *
     * @return mixed
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Removes the option and calls the clients clearData method to clear that one as well
     *
     * @return void
     */
    public function clearData()
    {
        // Clear client data
        $this->client->clearData();
    }

    /**
     * Get all sites
     *
     * @return array
     */
    public function getSites()
    {
        $sites    = array();
        $response = $this->client->do_request('sites', true);
        // list sites
        if (!empty($response->siteEntry)) {
            foreach ($response->siteEntry as $entry) {
                $sites[str_ireplace('sites/', '', (string) $entry->siteUrl)] = (string) $entry->siteUrl;
            }
            // Sort retrieved sites.
            asort($sites);
        }

        return $sites;
    }

    /**
     * Get crawl issues
     *
     * @return array
     */
    public function getCountCrawlIssue()
    {
        // Setup crawl error list
        $counts = $this->getCountCrawlError($this->profile);
        $return = array();
        if (!empty($counts->countPerTypes)) {
            foreach ($counts->countPerTypes as $category) {
                $return[$category->platform][$category->category] = array(
                    'count'      => $category->entries[0]->count,
                    'last_fetch' => null,
                );
            }
        }

        return $return;
    }

    /**
     * Fetching the issues from the GSC API
     *
     * @param string $plat Platform (desktop, mobile, feature phone).
     * @param string $cat  Issue type.
     *
     * @return mixed
     */
    public function fetchCatIssues($plat, $cat)
    {
        $url    = 'sites/' . urlencode($this->profile) . '/urlCrawlErrorsSamples?category=' . $cat . '&platform=' . $plat;
        $issues = $this->client->do_request($url, true);
        if (!empty($issues->urlCrawlErrorSample)) {
            return $issues->urlCrawlErrorSample;
        }
        return false;
    }

    /**
     * Sending request to mark issue as fixed
     *
     * @param string $url      Issue URL.
     * @param string $platform Platform (desktop, mobile, feature phone).
     * @param string $category Issue type.
     *
     * @return boolean
     */
    public function markAsFixed($url, $platform, $category)
    {
        $url      = 'sites/' . urlencode($this->profile) . '/urlCrawlErrorsSamples/' . urlencode(ltrim($url, '/')) . '?category=' . WpmsGscMapper::catToApi($category) . '&platform=' . WpmsGscMapper::platToApi($platform) . '';
        $response = $this->client->do_request($url, false, 'DELETE');
        return ($response->getResponseHttpCode() === 204);
    }

    /**
     * Set GSC client
     *
     * @return void
     */
    private function setClient()
    {
        try {
            if (!class_exists('Wpms_Api_Google', false)) {
                require_once WPMETASEO_ADDON_PLUGIN_DIR . '/inc/google-api/class-api-google.php';
                new Wpms_Api_Google();
            }
        } catch (Exception $exception) {
            echo '';
        }

        if (class_exists('Wpms_Api_Google_Client') === false) {
            wp_redirect(admin_url('admin.php?page=metaseo_console'));
            exit;
        }

        $conn = get_option('wpms_gsc_connect');
        if (!empty($conn['googleClientId']) && !empty($conn['googleClientSecret'])) {
            $client_id     = $conn['googleClientId'];
            $client_secret = $conn['googleClientSecret'];
        } else {
            $client_id     = WPMSEO_ADDON_CLIENT_ID;
            $client_secret = WPMSEO_ADDON_CLIENT_SECRET;
        }

        $gsc = array(
            'application_name' => 'WP Meta SEO',
            'client_id'        => $client_id,
            'client_secret'    => $client_secret,
            'redirect_uri'     => admin_url('admin.php?page=metaseo_settings&task=wpms_gsc&tab=settings'),
            'scopes'           => array('https://www.googleapis.com/auth/webmasters'),
        );

        $this->client = new Wpms_Api_Google_Client($gsc, 'wpms-gsc', 'https://www.googleapis.com/webmasters/v3/');
    }

    /**
     * Getting the crawl error counts
     *
     * @param string $profile Profile name string.
     *
     * @return object|boolean
     */
    private function getCountCrawlError($profile)
    {
        $url   = 'sites/' . urlencode($profile) . '/urlCrawlErrorsCounts/query';
        $count = $this->client->do_request($url, true);

        if (!empty($count)) {
            return $count;
        }

        return false;
    }
}
