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

/**
 * Class MetaSeoAddonAdmin
 * Class that holds most of the admin functionality for Meta SEO Addon.
 */
class MetaSeoAddonAdmin
{
    /**
     * Email configs
     *
     * @var array
     */
    public $email_settings;
    /**
     * Refresh token string
     *
     * @var string
     */
    public $option_refresh_token;
    /**
     * Access token string
     *
     * @var string
     */
    public $option_access_token;
    /**
     * Admin features
     *
     * @var array
     */
    public $admin_features;
    /**
     * XML sitemap file name
     *
     * @var string
     */
    public $wpms_sitemap_name = 'wpms-sitemap.xml';

    /**
     * Google client
     *
     * @var object
     */
    public $client;

    /**
     * MetaSeoAddonAdmin constructor.
     */
    public function __construct()
    {
        $this->email_settings = array(
            'showEmailSender'    => '',
            'showEmailTitle'     => 'WP Meta SEO report',
            'numberFrequency'    => 1,
            'showEmailFrequency' => 0,
            'showEmailSend'      => '',
            'showEmailContent'   => '',
            'wpms_email_meta'    => array(),
        );

        $this->admin_features = array(
            // Google Search Console.
            'metaseo_gsc' => new WpmsGsc(),
        );
        add_action('init', array($this, 'loadLangguage'));
        add_action('admin_enqueue_scripts', array($this, 'registerScriptStyle'));
        add_action('wp_ajax_wpmsemail_add', array($this, 'emailAddGoogleAnalytics'));
        add_action('wp_ajax_wpmsemail_remove_list', array($this, 'emailRemoveGoogleAnalytics'));
        add_action('wp_ajax_wpmsemail_reload_list', array($this, 'emailReloadGoogleAnalytics'));
        add_action('wp_ajax_wpmsemail_send', array($this, 'emailSend'));
        add_action('wp_ajax_wpmsemail_check_email', array($this, 'checkEmail'));
        add_action('wp_ajax_wpms_sitemaps_add_customUrl', array($this, 'sitemapsAddCustomUrl'));
        add_action('wp_ajax_wpms_clear_customUrl', array($this, 'clearCustomUrl'));
        add_action('wp_ajax_wpms_mark_fixed_crawl_issue', array('WpmsGscAjax', 'ajaxMarkAsFixed'));
        add_action('wp_ajax_wpms_gsc_create_redirect_url', array('WpmsGscAjax', 'ajaxCreateRedirect'));
        add_action('wp_ajax_wpms_filter_search_keywords', array($this, 'filterSearchKeywords'));
        add_action('wp_ajax_wpms_save_settingemail', array($this, 'saveEmailSettings'));
        add_action('wp_ajax_wpms_save_local_business', array($this, 'saveLocalBusiness'));
        add_action('wp_ajax_wpms_run_linkcheck', array($this, 'runLinkCheck'));
        add_action('wp_ajax_dash_duplicate_title', array($this, 'getDuplicateMetatitle'));
        add_action('wp_ajax_dash_duplicate_desc', array($this, 'getDuplicateMetadesc'));
        add_action('admin_enqueue_scripts', array($this, 'heartbeatEnqueue'));
        add_filter('heartbeat_received', array($this, 'heartbeatReceived'), 10, 2);
        add_filter('heartbeat_received', array($this, 'heartbeatLinkReceived'), 10, 2);

        add_action('post_updated', array($this, 'updatePost'), 10, 3);
        add_action('delete_post', array($this, 'deletePost'));
        add_action('edit_comment', array($this, 'updateComment'));
        add_action('deleted_comment', array($this, 'deletedComment'));
        add_filter('wpmsaddon_emailsettings', array($this, 'emailSettings'), 10, 2);
        add_filter('wpmsaddon_linksettings', array($this, 'linkSettings'), 10, 2);
        add_filter('wpmsaddon_local_business', array($this, 'localBusinessSettings'), 10, 3);
        add_filter('wpmsaddon_search_console', array($this, 'searchConsoleSettings'), 10, 1);
        add_filter('wpmsaddon_google_search_keywords', array($this, 'gscKeywords'), 10, 3);
        add_filter('wpms_get_countryList', array($this, 'countryList'), 10, 1);
        add_filter('wpms_get_languagesList', array($this, 'listLanguageSelect'), 10, 3);

        add_action('wpms_submit_sitemap', array($this, 'submitSitemap'), 10, 1);
        add_action('wpms_add_custom_redirect', array($this, 'addCustomRedirect'));

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Not a form, nonce is not required
        if (isset($_GET['task']) && $_GET['task'] === 'wpms_gsc') {
            if (!empty($_GET['code'])) {
                $authorization_code = trim($_GET['code']);
                // Google Search Console.
                $metaseo_gsc =  new WpmsGsc();
                $metaseo_gsc->authenticate($authorization_code);
                // Do redirect
                $url = admin_url('admin.php?page=metaseo_settings&tab=settings#search_console');
                header('Location: '.$url, true, 302);
                exit;
            }
        }
        // phpcs:enable
    }

    /**
     * Load selectbox languages list
     *
     * @param string       $html Default html
     * @param string|array $lang Current selected language
     * @param string       $type View type
     *
     * @return string
     */
    public function listLanguageSelect($html, $lang, $type = '')
    {
        if ($type === 'multiple') {
            $html .= '<select name="wpms_lang_list" class="wpms_lang_list" multiple="multiple">';
        } else {
            $html .= '<select name="wpms_lang_list" class="wpms_lang_list">';
        }

        $label = '';
        if (is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
            $label = esc_html__('WPML language', 'wpmsPro');
        } elseif (is_plugin_active('polylang/polylang.php')) {
            $label = esc_html__('Polylang language', 'wpmsPro');
        }

        if ($type === 'multiple') {
            $html .= '<option value="0" disabled>' . $label . '</option>';
        } else {
            $html .= '<option value="0">' . $label . '</option>';
        }
        if (is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
            // when use WPML plugin
            global $sitepress;
            $active_languages = $sitepress->get_active_languages();
            $active_languages = apply_filters('wpml_admin_language_switcher_active_languages', $active_languages);
            foreach ($active_languages as $key => $lg) {
                if ($type === 'multiple') {
                    if (in_array($key, $lang)) {
                        $html .= '<option selected value="' . esc_attr($key) . '">' . esc_html($lg['display_name']) . '</option>';
                    } else {
                        $html .= '<option value="' . esc_attr($key) . '">' . esc_html($lg['display_name']) . '</option>';
                    }
                } else {
                    if ($lang === $key) {
                        $html .= '<option selected value="' . esc_attr($key) . '">' . esc_html($lg['display_name']) . '</option>';
                    } else {
                        $html .= '<option value="' . esc_attr($key) . '">' . esc_html($lg['display_name']) . '</option>';
                    }
                }
            }
        } elseif (is_plugin_active('polylang/polylang.php')) {
            // when use polylang plugin
            if (function_exists('pll_the_languages')) {
                $active_languages = pll_the_languages(array( 'raw' => 1 ));
                foreach ($active_languages as $language) {
                    if ($type === 'multiple') {
                        if (in_array($language['slug'], $lang)) {
                            $html .= '<option selected value="' . esc_attr($language['slug']) . '">' . esc_html($language['name']) . '</option>';
                        } else {
                            $html .= '<option value="' . esc_attr($language['slug']) . '">' . esc_html($language['name']) . '</option>';
                        }
                    } else {
                        if ($lang === $language['slug']) {
                            $html .= '<option selected value="' . esc_attr($language['slug']) . '">' . esc_html($language['name']) . '</option>';
                        } else {
                            $html .= '<option value="' . esc_attr($language['slug']) . '">' . esc_html($language['name']) . '</option>';
                        }
                    }
                }
            }
        }

        $html .= '</select>';
        return $html;
    }

    /**
     * Loads translated strings.
     *
     * @return void
     */
    public function loadLangguage()
    {
        load_plugin_textdomain(
            'wpmsPro',
            false,
            dirname(plugin_basename(WPMSEO_ADDON_FILE)) . '/languages/'
        );
    }

    /**
     * Display email settings
     *
     * @param string $html           Html return
     * @param array  $email_settings Email configs
     *
     * @return string
     */
    public function emailSettings($html, $email_settings)
    {
        ob_start();
        require_once 'page/email_settings.php';
        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Display local business settings
     *
     * @param string $html           Html return
     * @param array  $local_business Business configs
     * @param array  $countrys       List country
     *
     * @return string
     */
    public function localBusinessSettings($html, $local_business, $countrys)
    {
        ob_start();
        require_once 'page/local_business.php';
        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Display search console settings
     *
     * @param string $html Html return
     *
     * @return string
     */
    public function searchConsoleSettings($html)
    {
        ob_start();
        require_once 'page/search_console_settings.php';
        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Display link settings
     *
     * @param string $html          Html return
     * @param array  $link_settings Link configs
     *
     * @return string
     */
    public function linkSettings($html, $link_settings)
    {
        ob_start();
        require_once 'page/link_settings.php';
        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Display tab google search keywords in meta box
     *
     * @param string $html         Html return
     * @param string $post_content Current post content
     * @param object $service      Google service webmasters
     *
     * @return string
     */
    public function gscKeywords($html, $post_content, $service)
    {
        $postBody  = new Wpms_Google_Service_SearchConsole_SearchAnalyticsQueryRequest();
        $endDate   = date('Y-m-d', time());
        // Set last 3 months
        $StartDate = date('Y-m-d', time() - (90 * 24 * 60 * 60));
        $postBody->setStartDate($StartDate);
        $postBody->setEndDate($endDate);
        // Fetch data metric
        // Set query default
        $postBody->setDimensions(array('query'));
        // get domain
        $option  = get_option(WPMS_GSC, array('profile' => ''));
        $profile = '';
        ob_start();
        if (!empty($option['profile'])) {
            $profile = $option['profile'];
            $profile = trim($profile, '/');
            try {
                $results_querys = $service->searchanalytics->query($profile, $postBody);
                require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/page/search_keywords.php');
            } catch (Exception $e) {
                echo 'Caught exception: ', esc_html($e->getMessage()), "\n";
            }
        } else {
            $url = admin_url('admin.php?page=metaseo_console&tab=settings');
            echo '<div class="wpmseotab wpmseo_gsc_keywords wpms-form-table" id="wpmseo_gsc_keywords">';
            echo '<div class="meta-box-top"><h1 class="wpms-top-h2">' . esc_html__('Google Search Console Keyword Suggestion', 'wpmsPro') . '</h1></div>';
            echo sprintf(
                esc_html__('Please go to %s to choose a profile', 'wpmsPro'),
                '<a target="_blank" href="' . esc_url($url) . '">' . esc_html__('Search Console', 'wpmsPro') . '</a>'
            );
            echo '</div>';
        }

        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Ajax search google keywords
     *
     * @return void
     */
    public function filterSearchKeywords()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            echo json_encode(array('status' => false));
            die();
        }

        $endDate   = date('Y-m-d', time());

        $keywords_type = 'query';

        if (isset($_POST['showitems']) && !empty($_POST['showitems'])) {
            $showitems = $_POST['showitems'];
        } else {
            $showitems = array();
        }

        if (isset($_POST['keycsl']) && !empty($_POST['keycsl'])) {
            $keycsl_filter = $_POST['keycsl'];
        } else {
            $keycsl_filter = '';
        }

        if (isset($_POST['dataSort']) && !empty($_POST['dataSort'])) {
            $data_sort = json_decode(stripslashes($_POST['dataSort']), true);
        } else {
            $data_sort = array();
        }

        if (isset($_POST['searchType']) && !empty($_POST['searchType'])) {
            $searchType = $_POST['searchType'];
        } else {
            $searchType = 'page';
        }

        if (isset($_POST['time']) && !empty($_POST['time'])) {
            $StartDate = date('Y-m-d', time() - ((int)$_POST['time'] * 24 * 60 * 60));
        } else {
            $StartDate = date('Y-m-d', time() - (90 * 24 * 60 * 60));
        }

        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 '';
        }

        $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/');
        if (!is_null($this->client->getAccessToken())) {
            $service  = new Wpms_Google_Service_SearchConsole($this->client);
            $postBody = new Wpms_Google_Service_SearchConsole_SearchAnalyticsQueryRequest();
            $postBody->setStartDate($StartDate);
            $postBody->setEndDate($endDate);

            // Fetch data metric
            $postBody->setDimensions(array($keywords_type));

            // Filter specific with page url
            if (!empty($keycsl_filter)) {
                $filter = new Wpms_Google_Service_SearchConsole_ApiDimensionFilter();
                $filter->setDimension($searchType);
                $filter->setOperator('contains');
                $filter->setExpression($keycsl_filter);

                $filtergroup = new Wpms_Google_Service_SearchConsole_ApiDimensionFilterGroup();
                $filtergroup->setFilters(array($filter));
                $postBody->setDimensionFilterGroups(array($filtergroup));
            }

            // get domain
            $option  = get_option(WPMS_GSC, array('profile' => ''));
            if (!empty($option['profile'])) {
                $profile        = $option['profile'];
                $profile        = trim($profile, '/');
                $results_querys = $service->searchanalytics->query($profile, $postBody);
                if (!empty($results_querys['rows'])) {
                    $results_query = $results_querys['rows'];
                    $html          = '';
                    $i             = 1;
                    $limit         = 20;
                    if (isset($_POST['page'])) {
                        $page = $_POST['page'];
                    } else {
                        $page = 1;
                    }

                    if (!empty($data_sort)) {
                        $results_query = $this->sortTable($results_query, $data_sort);
                    }

                    foreach ($results_query as $query) {
                        if (isset($query['keys'][0]) && $query['keys'][0] !== '') {
                            if ($i <= $page * $limit) {
                                if ($keywords_type === 'query') {
                                    $link = 'https://www.google.com/search?q=' . $query['keys'][0];
                                } else {
                                    $link = $query['keys'][0];
                                }
                                $html .= '<tr>';
                                $html .= '<td>' . esc_html($query['keys'][0]) . '<a target="_blank" class="wpms_open_in_new"
                                 href="' . esc_url($link) . '">
                                 <i class="material-icons wpms_open_in_new_icon">trending_up</i></a></td>';
                                $html .= '<td>' . esc_html($query['clicks']) . '</td>';
                                $html .= '<td>' . esc_html($query['impressions']) . '</td>';
                                $html .= '<td style="'.(in_array(4, $showitems) ? 'display:table-cell;' : '').'">' . esc_html(round($query['ctr'] * 100, 2)) . '%</td>';
                                $html .= '<td style="'.(in_array(5, $showitems) ? 'display:table-cell;' : '').'">' . esc_html(round($query['position'], 1)) . '</td>';
                                $html .= '</tr>';
                                $i ++;
                            }
                        }
                    }

                    wp_send_json(array('status' => true, 'html' => $html, 'page' => (int) $page + 1));
                }
            }
        }
        wp_send_json(array('status' => false));
    }

    /**
     * Sort table by ajax
     *
     * @param array $tables    Data colected from api
     * @param array $data_sort Sort data
     *
     * @return array
     */
    public function sortTable($tables, $data_sort)
    {
        $key = $data_sort[0];
        $order = $data_sort[1];

        usort($tables, function ($a, $b) use ($key, $order) {
            if (is_array($a[$key])) {
                // sort order
                $result = strcmp($a[$key][0], $b[$key][0]);
                return ($order === 'ascending') ? $result : (- $result);
            }

            if (is_float($a[$key]) || is_int($a[$key])) {
                if ($a[$key] === $b[$key]) {
                    return 0;
                }
                return ($order === 'ascending') ? (($a[$key] > $b[$key]) ? 1 : -1) : (($b[$key] > $a[$key]) ? 1 : -1);
            }
        });

        return $tables;
    }

    /**
     * Update last time update post
     *
     * @param integer $post_ID     Id of current post
     * @param string  $post_after  Post content after update
     * @param string  $post_before Post content before update
     *
     * @return void
     */
    public function updatePost($post_ID, $post_after, $post_before)
    {
        update_option('wpms_last_update_post', time());
    }

    /**
     * Update last time update post
     *
     * @param integer $post_id Id of current post
     *
     * @return void
     */
    public function deletePost($post_id)
    {
        update_option('wpms_last_update_post', time());
    }

    /**
     * Update last time update post
     *
     * @param integer $comment_ID Id of current comment
     *
     * @return void
     */
    public function updateComment($comment_ID)
    {
        update_option('wpms_last_update_post', time());
    }

    /**
     * Update last time update post
     *
     * @param integer $comment_ID Id of current comment
     *
     * @return void
     */
    public function deletedComment($comment_ID)
    {
        update_option('wpms_last_update_post', time());
    }

    /**
     * Load script and css
     *
     * @return void
     */
    public function registerScriptStyle()
    {
        global $current_screen;
        wp_register_script(
            'wpms_script_email',
            plugins_url('assets/js/email_script.js', dirname(__FILE__)),
            array('jquery'),
            WPMSEO_ADDON_VERSION
        );
        wp_register_script(
            'wpms_script_gsc',
            plugins_url('assets/js/wpms-admin-gsc.js', dirname(__FILE__)),
            array('jquery'),
            WPMSEO_ADDON_VERSION
        );
        wp_register_style(
            'wpmsaddon_style',
            plugins_url('assets/css/style.css', dirname(__FILE__)),
            array(),
            WPMSEO_ADDON_VERSION
        );
        wp_register_script(
            'wpms_script_link',
            plugins_url('assets/js/link_script.js', dirname(__FILE__)),
            array('jquery'),
            WPMSEO_ADDON_VERSION
        );
        wp_register_style(
            'wpmsaddon_gsc_style',
            plugins_url('assets/css/wpms_gsc_style.css', dirname(__FILE__)),
            array(),
            WPMSEO_ADDON_VERSION
        );
        $email_settings = get_option('_metaseo_addon_sendemail');
        if (is_array($email_settings)) {
            $this->email_settings = array_merge($this->email_settings, $email_settings);
        }

        if ($current_screen->base === 'wp-meta-seo_page_metaseo_google_sitemap') {
            wp_enqueue_script(
                'wpms-tablesorter-script',
                plugins_url('assets/js/tablesorter/jquery.tablesorter.js', dirname(__FILE__)),
                array('jquery'),
                WPMSEO_ADDON_VERSION
            );
            wp_enqueue_script(
                'wpms-addon-sitemaps-script',
                plugins_url('assets/js/sitemaps_script.js', dirname(__FILE__)),
                array('jquery'),
                WPMSEO_ADDON_VERSION
            );
        }

        if ($current_screen->base === 'wp-meta-seo_page_metaseo_settings') {
            wp_enqueue_media();
        }
        wp_localize_script(
            'wpms_script_email',
            'wpmsemailData',
            array(
                'wpms_email_meta' => $this->email_settings['wpms_email_meta']
            )
        );
    }

    /**
     * Display email header
     *
     * @return void
     */
    public function showHeader()
    {
        echo '<h1>' . esc_html__('EMAIL SEO REPORT', 'wpmsPro') . '</h1>';
    }

    /**
     * Display page Settings Email
     *
     * @return void
     */
    public function loadPageSendEmail()
    {
        wp_enqueue_style('wpmsaddon_style');
        wp_enqueue_script('wpms_script_email');
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- View request, no action
        if (isset($_POST['_metaseo_addon_sendemail'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- View request, no action
            update_option('_metaseo_addon_sendemail', $_POST['_metaseo_addon_sendemail']);
        }
        $toolbar = $this->getToolbar();

        // Get settings email
        $email_settings = get_option('_metaseo_addon_sendemail');
        if (is_array($email_settings)) {
            $this->email_settings = array_merge($this->email_settings, $email_settings);
        }

        $config          = get_option('wpmsemail_list_ga');
        $list_meta_datas = array(
            'newcontent'   => esc_html__('New content or updated content', 'wpmsPro'),
            'metatitle'    => esc_html__('Meta title', 'wpmsPro'),
            'metadesc'     => esc_html__('Meta description', 'wpmsPro'),
            'img_optimize' => esc_html__('Images not optimized (HTML resized)', 'wpmsPro'),
            'img_meta'     => esc_html__('Images titles and description', 'wpmsPro'),
            'permalink'    => esc_html__('Permalink optimization', 'wpmsPro'),
            'linkmeta'     => esc_html__('Links titles', 'wpmsPro'),
            'link_error'   => esc_html__('404 indexed errors', 'wpmsPro')
        );
        require_once WPMETASEO_ADDON_PLUGIN_DIR . 'inc/page/page_sendemail.php';
    }

    /**
     * Get google analytics toolbar
     *
     * @return array
     */
    public function getToolbar()
    {
        require_once WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmstools.php';
        $wpms_google_analytics = get_option('wpms_google_alanytics');
        if (isset($wpms_google_analytics['tableid_jail']) && isset($wpms_google_analytics['profile_list'])) {
            $wpms_profile = WpmsGaTools::getSelectedProfile($wpms_google_analytics['profile_list'], $wpms_google_analytics['tableid_jail']);
        }
        if (isset($wpms_profile[4])) {
            $property_type = $wpms_profile[4];
        } else {
            $property_type = 'UA';
        }
        $toolbar = array(
            'ajaxurl'    => admin_url('admin-ajax.php'),
            'dateList'   => array(
                'today'       => esc_html__('Today', 'wpmsPro'),
                'yesterday'   => esc_html__('Yesterday', 'wpmsPro'),
                '7daysAgo'    => sprintf(esc_html__('Last %d Days', 'wpmsPro'), 7),
                '14daysAgo'   => sprintf(esc_html__('Last %d Days', 'wpmsPro'), 14),
                '30daysAgo'   => sprintf(esc_html__('Last %d Days', 'wpmsPro'), 30),
                '90daysAgo'   => sprintf(esc_html__('Last %d Days', 'wpmsPro'), 90),
                '365daysAgo'  => sprintf(
                    _n(
                        '%s Year',
                        '%s Years',
                        1,
                        'wpmsPro'
                    ),
                    esc_html__('One', 'wpmsPro')
                ),
                '1095daysAgo' => sprintf(
                    _n(
                        '%s Year',
                        '%s Years',
                        3,
                        'wwpmsPro'
                    ),
                    esc_html__('Three', 'wpmsPro')
                ),
            ),
            'property_type' => $property_type,
            'reportList' => array(
                'sessions'          => esc_html__('Sessions', 'wpmsPro'),
                'users'             => esc_html__('Users', 'wpmsPro'),
                'organicSearches'   => esc_html__('Organic', 'wpmsPro'),
                'pageviews'         => esc_html__('Page Views', 'wpmsPro'),
                'visitBounceRate'   => esc_html__('Bounce Rate', 'wpmsPro'),
                'locations'         => esc_html__('Location', 'wpmsPro'),
                'contentpages'      => esc_html__('Pages', 'wpmsPro'),
                'referrers'         => esc_html__('Referrers', 'wpmsPro'),
                'searches'          => esc_html__('Searches', 'wpmsPro'),
                'trafficdetails'    => esc_html__('Traffic', 'wpmsPro'),
                'technologydetails' => esc_html__('Technology', 'wpmsPro'),
            ),
            'reportList_ga4' => array(
                'sessions' => esc_html__('Sessions', 'wpmsPro'),
                'users' => esc_html__('Users', 'wpmsPro'),
                'pageviews' => esc_html__('Page Views', 'wpmsPro'),
                'visitBounceRate' => esc_html__('Engagement', 'wpmsPro'),
                'organicSearches' => esc_html__('Transactions', 'wpmsPro'),
                'locations' => esc_html__('Location', 'wpmsPro'),
                'contentpages' => esc_html__('Pages', 'wpmsPro'),
                'referrers' => esc_html__('Referrers', 'wpmsPro'),
                'searches' => esc_html__('Searches', 'wpmsPro'),
                'trafficdetails' => esc_html__('Traffic', 'wpmsPro'),
                'technologydetails' => esc_html__('Technology', 'wpmsPro'),
            ),
        );

        return $toolbar;
    }

    /**
     * Ajax add new google analytics to report
     *
     * @return void
     */
    public function emailAddGoogleAnalytics()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        if (isset($_POST['data'])) {
            $config = get_option('wpmsemail_list_ga');
            if (!empty($config) && is_array($config)) {
                $config[$_POST['data'][0] . '-' . $_POST['data'][2]] = $_POST['data'];
            } else {
                $config                                              = array();
                $config[$_POST['data'][0] . '-' . $_POST['data'][2]] = $_POST['data'];
            }
            update_option('wpmsemail_list_ga', $config);
            wp_send_json(true);
        } else {
            wp_send_json(false);
        }
    }

    /**
     * Ajax remove google analytics list
     *
     * @return void
     */
    public function emailRemoveGoogleAnalytics()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        if (isset($_POST['value'])) {
            $config = get_option('wpmsemail_list_ga');
            if (isset($config[$_POST['value']])) {
                unset($config[$_POST['value']]);
                update_option('wpmsemail_list_ga', $config);
                wp_send_json(true);
            }
        } else {
            wp_send_json(false);
        }
    }

    /**
     * Ajax reload list google analytics to report
     *
     * @return void
     */
    public function emailReloadGoogleAnalytics()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        $config = get_option('wpmsemail_list_ga');
        wp_send_json($config);
    }

    /**
     * Do send email
     *
     * @return array
     */
    public function doSendEmail()
    {
        if (!class_exists('WpmsProDashboard')) {
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . '/inc/class.metaseo-dashboard.php');
        }

        $email_settings = array(
            'showEmailSender'    => '',
            'showEmailTitle'     => 'WP Meta SEO report',
            'numberFrequency'    => 1,
            'showEmailFrequency' => 0,
            'showEmailSend'      => '',
            'showEmailContent'   => '',
            'wpms_email_meta'    => array(),
        );

        $filters = array(
            'sessions',
            'users',
            'organicSearches',
            'pageviews',
            'visitBounceRate',
            'locations'
        );

        $settings = get_option('_metaseo_addon_sendemail');
        if (is_array($settings)) {
            $email_settings = array_merge($email_settings, $settings);
        }
        $email_settings['wpms_lastRun_sendemail'] = time();

        update_option('_metaseo_addon_sendemail', $email_settings);
        $to        = explode(',', $email_settings['showEmailSend']);
        $subject   = $email_settings['showEmailTitle'];
        $body      = $email_settings['showEmailContent'];
        $headers   = array();
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $email_to  = array();
        if (count($to) > 0) {
            foreach ($to as $mail) {
                if (is_email(trim($mail))) {
                    $email_to[] = $mail;
                }
            }
        }

        if (empty($email_to)) {
            $message = array('status'  => false,
                             'message' => esc_html__('The email to field is empty.', 'wpmsPro')
            );
            return $message;
        }

        $html   = '';
        $config = get_option('wpmsemail_list_ga');
        if (!empty($config)) {
            // get results from google analytics & create html
            $results = $this->getGoogleAnalytics($config);
            if (!empty($results) && (int) $results !== - 99 && (int) $results !== - 24) {
                foreach ($results as $k => $re) {
                    $q = explode('-', $k);
                    if (in_array($q[1], $filters)) {
                        $html .= $this->loadGaEmailHtml($re[0], $q, 1);
                    } elseif (in_array($q[1], array('contentpages', 'referrers', 'searches'))) {
                        if (count($re[1]) > 200) {
                            $limit_re = array_splice($re[1], 0, 200);
                        } else {
                            $limit_re = $re[1];
                        }
                        $html .= $this->loadGaEmailHtml($limit_re, $q, 1);
                    } else {
                        $toolbar = $this->getToolbar();
                        $title   = esc_html__('View: ', 'wpmsPro');
                        $title   .= $toolbar['dateList'][$q[0]] . ' / ' . $toolbar['reportList'][$q[1]];
                        if (!empty($re)) {
                            $html .= '<h1>' . esc_html($title) . '</h1>';
                        }
                        foreach ($re as $key_1 => $v) {
                            if ($key_1 > 0) {
                                $html .= $this->loadGaEmailHtml($v, $q, 0);
                            }
                        }
                    }
                }
            } else {
                $message = esc_html__('Google Analytics data cannot be added to the Email as it\'s not connected', 'wpmsPro');
            }
        }

        $list_meta_datas = array(
            'newcontent'   => esc_html__('New content or updated content', 'wpmsPro'),
            'metatitle'    => esc_html__('Meta title', 'wpmsPro'),
            'metadesc'     => esc_html__('Meta description', 'wpmsPro'),
            'img_optimize' => esc_html__('Images not optimized (HTML resized)', 'wpmsPro'),
            'img_meta'     => esc_html__('Images titles and description', 'wpmsPro'),
            'permalink'    => esc_html__('Permalink optimization', 'wpmsPro'),
            'linkmeta'     => esc_html__('Links titles', 'wpmsPro'),
            'link_error'   => esc_html__('404 errors count detected', 'wpmsPro')
        );

        // create html for meta data
        $dashopts = get_option('options_dashboard');
        if (!empty($email_settings['wpms_email_meta'])) {
            $html .= '<br><h1><b>' . esc_html__('WP META SEO DATA', 'wpmsPro') . '</b></h1>';
            foreach ($list_meta_datas as $key_2 => $v) {
                if (in_array($key_2, $email_settings['wpms_email_meta'])) {
                    if ($key_2 === 'img_optimize') {
                        $html .= '<p>' . $v . ' : ' . esc_html($dashopts['image_meta']['imgs_statis'][2]) . '%</p>';
                    } elseif ($key_2 === 'img_meta') {
                        $html .= '<p>' . $v . ' : ' . esc_html($dashopts['image_meta']['imgs_metas_statis'][2]) . '%</p>';
                    } elseif ($key_2 === 'permalink') {
                        $permalink = WpmsProDashboard::permalink();
                        $html      .= '<p>' . $v . ' : ' . esc_html($permalink) . '%</p>';
                    } elseif ($key_2 === 'link_error') {
                        $link_error = WpmsProDashboard::get404Link();
                        $html       .= '<p>' . $v . ' : ' . esc_html($link_error['percent']) . '%</p>';
                    } elseif ($key_2 === 'linkmeta') {
                        $linkmeta = WpmsProDashboard::linkMeta();
                        $html     .= '<p>' . $v . ' : ' . esc_html($linkmeta[0]) . '%</p>';
                    } else {
                        $html .= '<p>' . $v . ' : ' . esc_html($dashopts[$key_2][0]) . '%</p>';
                    }
                }
            }
        }

        // get content to send email
        ob_start();
        require_once 'page/content_email.php';
        $content_email = ob_get_contents();
        ob_end_clean();
        $body .= $content_email;

        // Do generate pdf content
        $upload_dir = wp_upload_dir();
        try {
            $this->doGeneratePdf($email_settings['showEmailContent'], $html, $subject, $upload_dir);
            $attachments = array($upload_dir['basedir'] . '/wpms-report.pdf');
        } catch (Exception $e) {
            $attachments = array();
        }

        $email_config = get_option('wpms_email_settings');
        if (empty($email_config['enable'])) {
            wp_mail($email_to, $subject, $body, $headers, $attachments);
            if (!empty($message)) {
                $message = array('status' => true, 'message' => $message);
            } else {
                $message = array('status'  => true,
                                 'message' => esc_html__('Oki doki, Email sent!', 'wpmsPro')
                );
            }
        } else {
            $message = $this->smtpSendMail(
                $email_to,
                $subject,
                $body,
                $email_settings,
                $email_config,
                $upload_dir['basedir']
            );
        }

        /**
         * Send email
         *
         * @param string The email of the recipient
         * @param string The email title
         * @param string Email content
         * @param string Email attachments
         */
        do_action('wpms_send_email', $email_to, $subject, $body, $attachments);
        return $message;
    }

    /**
     * Do generate pdf content
     *
     * @param string $EmailContent Email content
     * @param string $html         Email HTML
     * @param string $subject      Email subject
     * @param array  $upload_dir   Upload dir
     *
     * @return void
     */
    public function doGeneratePdf($EmailContent, $html, $subject, $upload_dir)
    {
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . '/inc/fpdf/html2pdf.php');
        $pdf = new PDF();
        $pdf->AddPage();
        // header
        $pdf->SetFont('Arial', '', 10);
        $pdf->SetMargins(30, 0, 30);
        $pdf->SetTextColor(75, 72, 72);
        $pdf->WriteHTML($EmailContent);
        $pdf->Ln();
        $pdf->SetFillColor(100, 183, 235);
        $pdf->SetTextColor(255, 255, 255);
        $pdf->MultiCell(0, 10, '', 0, 'J', true);
        $pdf->SetFont('Arial', '', 18);
        $pdf->MultiCell(0, 7, esc_html__('               WP Meta SEO', 'wpmsPro'), 0, 'L', true);
        $pdf->SetFont('Arial', 'B', 18);
        $pdf->MultiCell(0, 7, '               ' . $subject, 0, 'L', true);
        $pdf->MultiCell(0, 10, '', 0, 'J', true);
        $pdf->SetFont('Arial', '', 10);
        $pdf->Image(WPMETASEO_ADDON_PLUGIN_URL . 'assets/images/icon_metaseo.png', 35, 33, - 300);
        $pdf->Ln();
        // content
        $pdf->SetTextColor(75, 72, 72);
        $pdf->WriteHTML('<b>Hello,</b>');
        $pdf->Ln();
        $pdf->WriteHTML($html);
        $pdf->Output('F', $upload_dir['basedir'] . '/wpms-report.pdf');
    }

    /**
     * Do send email wwith smtp
     *
     * @param string $to_email       Email to
     * @param string $subject        Email subject
     * @param string $message        Message
     * @param array  $email_settings Email settings in email page
     * @param array  $email_config   Email configs in settings
     * @param string $file_to_attach Path to the attachment.
     *
     * @return array
     */
    public function smtpSendMail($to_email, $subject, $message, $email_settings, $email_config, $file_to_attach)
    {
        $errors = '';
        require_once(ABSPATH . WPINC . '/class-phpmailer.php');
        $mail = new PHPMailer();

        $charset       = get_bloginfo('charset');
        $mail->CharSet = $charset;

        $from_name  = 'WP Meta SEO';
        $from_email = $email_settings['showEmailSender'];

        $mail->IsSMTP();

        /* If using smtp auth, set the username & password */
        if ('yes' === $email_config['autentication']) {
            $mail->SMTPAuth = true;
            $mail->Username = $email_config['username'];
            $mail->Password = $this->smtpGetPassword($email_config);
        }

        /* Set the SMTPSecure value, if set to none, leave this blank */
        if ($email_config['type_encryption'] !== 'none') {
            $mail->SMTPSecure = $email_config['type_encryption'];
        }

        /* PHPMailer 5.2.10 introduced this option. However, this might cause issues
         if the server is advertising TLS with an invalid certificate. */
        $mail->SMTPAutoTLS = false;

        /* Set the other options */
        $mail->Host = $email_config['host'];
        $mail->Port = $email_config['port'];
        $mail->SetFrom($from_email, $from_name);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->MsgHTML($message);
        foreach ($to_email as $emailto) {
            $mail->AddAddress($emailto);
        }
        $mail->AddAttachment($file_to_attach, 'wpms-report.pdf');
        $mail->SMTPDebug = 0;

        /* Send mail and return result */
        if (!$mail->Send()) {
            $errors = $mail->ErrorInfo;
        }

        $mail->ClearAddresses();
        $mail->ClearAllRecipients();

        if (!empty($errors)) {
            $message = array('status' => false, 'message' => $errors);
            return $message;
        } else {
            $message = array('status' => true, 'message' => esc_html__('Oki doki, Email sent!', 'wpmsPro'));
            return $message;
        }
    }

    /**
     * SMTP get password
     *
     * @param array $email_config Email configs
     *
     * @return boolean|string
     */
    public function smtpGetPassword($email_config)
    {
        $temp_password = $email_config['password'];
        $decoded_pass  = base64_decode($temp_password);
        /* no additional checks for servers that aren't configured with mbstring enabled */
        if (!function_exists('mb_detect_encoding')) {
            return $decoded_pass;
        }
        /* end of mbstring check */
        if (base64_encode($decoded_pass) === $temp_password) {  //it might be encoded
            if (false === mb_detect_encoding($decoded_pass)) {  //could not find character encoding.
                $password = $temp_password;
            } else {
                $password = base64_decode($temp_password);
            }
        } else { //not encoded
            $password = $temp_password;
        }
        return $password;
    }

    /**
     * Ajax send email
     *
     * @return void
     */
    public function emailSend()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        $params = array(
            'showEmailSender',
            'showEmailTitle',
            'numberFrequency',
            'showEmailFrequency',
            'showEmailSend',
            'showEmailContent',
            'wpms_email_meta'
        );

        $configs = array();
        foreach ($params as $param) {
            $value = null;
            if (isset($_POST[$param])) {
                $value = $_POST[$param];
                if (!is_array($value)) {
                    $value = trim($value);
                }

                $value = wp_unslash($value);

                if ($param !== 'wpms_email_meta') {
                    $configs[$param] = $value;
                } else {
                    if ($value !== '') {
                        $configs[$param] = explode(',', $value);
                    } else {
                        $configs[$param] = array();
                    }
                }
            }
        }
        update_option('_metaseo_addon_sendemail', $configs);

        $message = $this->doSendEmail();
        wp_send_json($message);
    }

    /**
     * Load table HTML for filter
     *
     * @param array   $re     Results
     * @param array   $filter Filter list
     * @param integer $tool   Check google ananytics type
     *
     * @return string
     */
    public function loadGaEmailHtml($re, $filter, $tool)
    {
        $html    = '';
        $toolbar = $this->getToolbar();
        $title   = esc_html__('View: ', 'wpmsPro');
        $title   .= $toolbar['dateList'][$filter[0]] . ' / ' . $toolbar['reportList'][$filter[1]];
        if (!empty($re) && is_array($re)) {
            if ((int) $tool === 1) {
                $html = '<h1><b>' . esc_html($title) . '</b></h1><br>';
            }
            $html .= '<table align="center" cellpadding="5" cellspacing="0" border="1"
 style="border: #ccc 1px solid;width: 100%;margin-bottom: 20px">';
            foreach ($re as $k => $r) {
                if ((int) $k === 0) {
                    $html .= '<tr style="font-weight: bold;">';
                } else {
                    $html .= '<tr>';
                }
                $html .= '<td width="300" height="30" style="border-bottom: #ccc 1px solid;">' . esc_html($r[0]) . '</td>';
                $html .= '<td width="300" height="30" style="border-bottom: #ccc 1px solid">' . esc_html($r[1]) . '</td>';
                $html .= '</tr>';
            }
            $html .= '</table><br>';
        }

        return $html;
    }

    /**
     * Get Google Analytics data
     *
     * @param array $config Google analytics config
     *
     * @return array|string
     */
    public function getGoogleAnalytics($config)
    {
        // Include api
        include_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmstools.php');
        include_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmsgapi.php');
        // Get settings GA
        $google_alanytics = get_option('wpms_google_alanytics');
        if (!empty($google_alanytics['tableid_jail'])) {
            $projectId = $google_alanytics['tableid_jail'];
        } else {
            return '-99'; // no tracking id selected
        }

        // Supported GA4
        // get selected profile
        $profile_info = WpmsGaTools::getSelectedProfile($google_alanytics['profile_list'], $projectId);
        $property_type = 'UA'; // Default GA property type = Universal Analytics
        if (!empty($profile_info) && isset($profile_info[4]) && $profile_info[4] === 'GA4') {
            $property_type = 'GA4';
            $projectId = $profile_info[2];
        }
        if (!empty($google_alanytics['googleCredentials'])) {
            if (empty($controller)) {
                $controller = new WpmsGapiController();
            }
        } else {
            return '-24';
        }
        if (isset($profile_info[5]) && !empty($profile_info[5])) {
            $controller->timeshift = $profile_info[5];
        } else {
            $controller->timeshift = (int) current_time('timestamp') - time();
        }
        $results          = array();
        if (!empty($config) && is_array($config)) {
            foreach ($config as $k => $v) {
                // Date to get GA data
                $from      = $v[0];
                if (!isset($from) || empty($from)) {
                    return '-24';
                }
                $to = 'yesterday'; // default
                if ($from === 'today') {
                    $to = 'today';
                }

                // Query to get GA data
                if (in_array($v[2], array('referrers', 'contentpages', 'searches'))) {
                    $query = 'channelGrouping,' . $v[2];
                } elseif ($v[2] === 'trafficdetails' || $v[2] === 'technologydetails') {
                    if ($v[2] === 'trafficdetails') {
                        $query = 'channelGrouping,medium,visitorType,source,socialNetwork';
                    } else {
                        $query = 'deviceCategory,browser,operatingSystem,screenResolution,mobileDeviceBranding';
                    }
                } elseif ($v[2] === 'locations') {
                    $query = $v[2];
                } else {
                    $query = $v[2] . ',bottomstats';
                }

                if (ob_get_length()) {
                    ob_clean();
                }

                $filter = false;

                $queries     = explode(',', $query);
                $results[$k] = array();
                foreach ($queries as $value) {
                    $results[$k][] = $controller->get($projectId, $value, $from, $to, $filter, $property_type);
                }
            }
        }

        return $results;
    }

    /**
     * Ajax check email
     *
     * @return void
     */
    public function checkEmail()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        if (isset($_POST['listemail'])) {
            $lists = explode(',', $_POST['listemail']);
            if (count($lists) > 0) {
                $email_wrong = array();
                foreach ($lists as $mail) {
                    if (!is_email(trim($mail))) {
                        $email_wrong[] = $mail;
                    }
                }
                if (count($email_wrong) > 0) {
                    wp_send_json(
                        array(
                            'status'      => false,
                            'email_wrong' => $email_wrong,
                            'message'     => esc_html__('Please add an Email to receive reports', 'wpmsPro')
                        )
                    );
                } else {
                    wp_send_json(array('status' => true));
                }
            } else {
                wp_send_json(
                    array(
                        'status'  => false,
                        'message' => esc_html__('Please add an Email to receive reports', 'wpmsPro')
                    )
                );
            }
        }
    }

    /**
     * Includes a script heartbeat
     *
     * @return void
     */
    public function heartbeatEnqueue()
    {
        wp_enqueue_script('heartbeat');
        add_action('admin_print_footer_scripts', array($this, 'heartbeatFooterJs'), 20);
        add_action('admin_print_footer_scripts', array($this, 'heartbeatLinkFooterJs'), 20);
    }

    /**
     * Inject our JS into the admin footer
     *
     * @return void
     */
    public function heartbeatFooterJs()
    {
        ?>
        <script>
            (function ($) {
                var wpms_dash_auto = 0;

                /* ajax save meta title */
                function wpmsDashMetatitle() {
                    jQuery.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'wpms',
                            task: 'dash_metatitle',
                            wpms_nonce: wpms_localize.wpms_nonce
                        },
                        success: function () {
                            wpms_dash_auto++;
                            if (wpms_dash_auto === 1) {
                                wpmsDashImgsmeta(1, 0, 0, 0);
                            }
                        }
                    });
                }

                /* ajax save images meta */
                function wpmsDashImgsmeta(page, imgs_statis, imgs_meta, imgs_count) {
                    $.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'wpms',
                            task: 'dash_imgsmeta',
                            page: page,
                            imgs_statis: imgs_statis,
                            imgs_metas_statis: imgs_meta,
                            imgs_count: imgs_count,
                            wpms_nonce: wpms_localize.wpms_nonce
                        },
                        success: function (res) {
                            if (typeof res.status === "undefined") {
                                wpmsDashImgsmeta(
                                    page + 1,
                                    res.imgs_statis[0],
                                    res.imgs_metas_statis[0],
                                    res.imgs_count
                                );
                            } else {
                                wpms_dash_auto++;
                                if (wpms_dash_auto === 2) {
                                    wpmsDashNewcontent();
                                }
                            }
                        }
                    });
                }

                /* ajax save new content updated */
                function wpmsDashNewcontent() {
                    jQuery.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'wpms',
                            task: 'dash_newcontent',
                            wpms_nonce: wpms_localize.wpms_nonce
                        },
                        success: function () {
                            wpms_dash_auto++;
                            if (wpms_dash_auto === 3) {
                                wpmsDashMetadesc();
                            }
                        }
                    });
                }

                function wpmsDashMetadesc() {
                    jQuery.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'wpms',
                            task: 'dash_metadesc',
                            wpms_nonce: wpms_localize.wpms_nonce
                        },
                        success: function () {
                            wpms_dash_auto++;
                            if (wpms_dash_auto === 4) {
                                wpmssendemail();
                            }
                        }
                    });
                }

                /* Ajax send email */
                function wpmssendemail() {
                    jQuery.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'wpmsemail_send',
                            wpms_nonce: wpms_localize.wpms_nonce
                        },
                        success: function () {
                            wpms_dash_auto = 0;
                            $('.wpmsemail_spinner').hide();
                        }
                    });
                }


                // Hook into the heartbeat-send
                $(document).on('heartbeat-send', function (e, data) {
                    data['wpms_heartbeat'] = 'wpms_queue_process';
                });

                $(document).on('heartbeat-tick', function (e, data) {
                    if (!data['wpms_save_dash'])
                        return;

                    if (data['wpms_save_dash'] === 1) {
                        wpmsDashMetatitle();
                    }
                });
            }(jQuery));
        </script>
        <?php
    }

    /**
     * Inject our JS into the admin footer
     *
     * @return void
     */
    public function heartbeatLinkFooterJs()
    {
        ?>
        <script>
            (function ($) {
                function wpms_autoscan_link(paged, comment_paged) {
                    jQuery.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        dataType: 'json',
                        data: {
                            'action': 'wpms',
                            'task': 'scan_link',
                            'paged': paged,
                            'comment_paged': comment_paged,
                            'wpms_nonce': wpms_localize.wpms_nonce
                        },
                        success: function (res) {
                            if (!res.status) {
                                if (res.type === 'limit') {
                                    wpms_autoscan_link(paged, comment_paged)
                                } else if (res.type === 'limit_comment_content') {
                                    comment_paged = parseInt(res.paged) + 1;
                                    wpms_autoscan_link(paged, comment_paged)
                                } else {
                                    paged = parseInt(res.paged) + 1;
                                    wpms_autoscan_link(paged, comment_paged)
                                }
                            } else {

                            }
                        }
                    });
                }

                // Hook into the heartbeat-send
                $(document).on('heartbeat-send', function (e, data) {
                    data['wpms_heartbeat'] = 'wpms_queue_process';
                });

                $(document).on('heartbeat-tick', function (e, data) {
                    if (!data['wpms_scanlink_ajax'])
                        return;

                    if (data['wpms_scanlink_ajax'] === 1) {
                        wpms_autoscan_link(1, 1);
                    }
                });
            }(jQuery));
        </script>
        <?php
    }

    /**
     * Modify the data that goes back with the heartbeat-tick
     *
     * @param array $response Response of heartbeat ajax
     * @param array $data     Data of heartbeat ajax
     *
     * @return mixed
     */
    public function heartbeatReceived($response, $data)
    {
        $email_settings = get_option('_metaseo_addon_sendemail');
        if (empty($email_settings) || empty($email_settings['showEmailFrequency'])) {
            $response['wpms_save_dash'] = 0;
            return $response;
        }

        if (isset($data['wpms_heartbeat']) && $data['wpms_heartbeat'] === 'wpms_queue_process') {
            if (isset($email_settings['wpms_lastRun_sendemail']) && !empty($email_settings['wpms_lastRun_sendemail'])) {
                $lastRun = $email_settings['wpms_lastRun_sendemail'];
            } else {
                $lastRun = time();
            }

            if (isset($email_settings['numberFrequency']) && is_numeric($email_settings['numberFrequency'])) {
                $numberFrequency = $email_settings['numberFrequency'];
            } else {
                $numberFrequency = 1;
            }

            $time_send = 0;
            switch ($email_settings['showEmailFrequency']) {
                case 'day':
                    $time_send = $numberFrequency * 24 * 60 * 60;
                    break;
                case 'week':
                    $time_send = $numberFrequency * 7 * 24 * 60 * 60;
                    break;
                case 'month':
                    $time_send = $numberFrequency * 30 * 24 * 60 * 60;
                    break;
            }

            if ((int) $time_send === 0) {
                $response['wpms_save_dash'] = 0;
                return $response;
            }

            if (time() - (int) $lastRun < (int) $time_send) {
                $response['wpms_save_dash'] = 0;
                return $response;
            }

            $dashopts = get_option('options_dashboard');
            if (!empty($dashopts) && is_array($dashopts)) {
                if (empty($dashopts['metatitle']) || empty($dashopts['metadesc'])
                    || empty($dashopts['newcontent']) || empty($dashopts['image_meta'])) {
                    $response['wpms_save_dash'] = 1;
                    return $response;
                }

                $option_last_update_post = get_option('wpms_last_update_post');
                $option_last_dash_update = get_option('_wpms_dash_last_update');
                if (!empty($option_last_update_post) && $option_last_update_post > $option_last_dash_update) {
                    $response['wpms_save_dash'] = 1;
                    return $response;
                }
            } else {
                $response['wpms_save_dash'] = 1;
                return $response;
            }
            $this->doSendEmail();
        }
        return $response;
    }

    /**
     * Modify the data that goes back with the heartbeat-tick
     *
     * @param array $response Response of heartbeat ajax
     * @param array $data     Data of heartbeat ajax
     *
     * @return mixed
     */
    public function heartbeatLinkReceived($response, $data)
    {
        $link_settings = get_option('wpms_link_settings');
        if (empty($link_settings) || empty($link_settings['showlinkFrequency'])) {
            $response['wpms_scanlink_ajax'] = 0;
            return $response;
        }

        if (empty($link_settings['enable'])) {
            $response['wpms_scanlink_ajax'] = 0;
            return $response;
        }

        if (isset($data['wpms_heartbeat']) && $data['wpms_heartbeat'] === 'wpms_queue_process') {
            $lastRun = $link_settings['wpms_lastRun_scanlink'];
            if (empty($lastRun)) {
                $lastRun = time();
            }

            if (isset($link_settings['numberFrequency']) && is_numeric($link_settings['numberFrequency'])) {
                $numberFrequency = $link_settings['numberFrequency'];
            } else {
                $numberFrequency = 1;
            }

            $time_send = 0;
            switch ($link_settings['showlinkFrequency']) {
                case 'day':
                    $time_send = $numberFrequency * 24 * 60 * 60;
                    break;
                case 'week':
                    $time_send = $numberFrequency * 7 * 24 * 60 * 60;
                    break;
                case 'month':
                    $time_send = $numberFrequency * 30 * 24 * 60 * 60;
                    break;
            }

            if ((int) $time_send === 0) {
                $response['wpms_scanlink_ajax'] = 0;
                return $response;
            }

            if (time() - (int) $lastRun < (int) $time_send) {
                $response['wpms_scanlink_ajax'] = 0;
                return $response;
            }

            $response['wpms_scanlink_ajax'] = 1;
            // Update last run time
            $link_settings['wpms_lastRun_scanlink'] = time();
            update_option('wpms_link_settings', $link_settings);
        }
        return $response;
    }

    /**
     * Submit sitemap to google
     *
     * @param string $sitemapUrl Url of sitemap
     *
     * @return void
     */
    public function submitSitemap($sitemapUrl)
    {
        if (0 !== (int) get_option('blog_public')) {
            if (!class_exists('Wpms_Api_Google', false)) {
                // Require the file
                require_once WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google-api/class-api-google.php';
                // Initialize the Google API Class to set the autoloader
                new Wpms_Api_Google();
            }
            $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'),
            );

            $client       = new Wpms_Api_Google_Client($gsc, 'wpms-gsc', 'https://www.googleapis.com/webmasters/v3/');
            $access_token = get_option('wpms-gsc-access_token');
            if (empty($access_token)) {
                return;
            }
            $client->setAccessToken(json_encode($access_token));
            $sitemapUrl           = urlencode($sitemapUrl);
            $check_sitemap_submit = $client->do_request(
                'sites/' . urlencode(site_url()) . '/sitemaps/' . $sitemapUrl,
                true,
                'GET'
            );

            if (empty($check_sitemap_submit)) {
                $client->do_request(
                    'sites/' . urlencode(site_url()) . '/sitemaps/' . $sitemapUrl,
                    true,
                    'PUT'
                );
            } else {
                $sitemapUrl = site_url('wpms-sitemap.xml');
                $sitemapUrl = htmlentities($sitemapUrl, ENT_COMPAT, 'UTF-8', true);
                // Ping Google and Bing.
                wp_remote_get(
                    'http://www.google.com/webmasters/tools/ping?sitemap=' . $sitemapUrl,
                    array(
                        'blocking' => false
                    )
                );
            }

            update_option('wpms_sitemap_submit', 1);
        }
    }

    /**
     * Add custom redirect url
     *
     * @param string $wpms_nonce Wpms nonce
     *
     * @return void
     */
    public function addCustomRedirect($wpms_nonce)
    {
        if (empty($wpms_nonce)
            || !wp_verify_nonce($wpms_nonce, 'wpms_nonce')) {
            die();
        }

        if (empty($_POST['new_link']) || empty($_POST['new_link'])) {
            wp_send_json(array('status' => false, 'message' => esc_html__('Field is empty!', 'wpmsPro')));
        }
        if (isset($_POST['status_link_redirect'])) {
            $status_redirect = $_POST['status_link_redirect'];
        } else {
            $status_redirect = 302;
        }

        $new_link = str_replace(home_url(), '', $_POST['new_link']);
        $new_link = stripslashes($new_link);
        global $wpdb;
        $link_detail = $wpdb->get_row($wpdb->prepare(
            'SELECT * FROM ' . $wpdb->prefix . 'wpms_links WHERE link_url=%s',
            array(
                $_POST['new_link']
            )
        ));
        if (!empty($link_detail)) {
            wp_send_json(array('status' => false, 'message' => esc_html__('The link you are trying to redirect is already in the URL list, please edit it from there', 'wpmsPro')));
        } else {
            $status      = WpmsProBrokenLinkTable::getUrlStatus(($new_link));
            $status_text = WpmsProBrokenLinkTable::getStatusText($status);

            $value = array(
                'link_url'          => $new_link,
                'link_final_url'    => $new_link,
                'link_url_redirect' => stripslashes($_POST['link_redirect']),
                'link_text'         => esc_html__('Custom redirect', 'wpmsPro'),
                'type'              => 'add_custom',
                'status_code'       => $status,
                'status_text'       => $status_text,
                'broken_indexed'    => 0,
                'broken_internal'   => 0,
                'warning'           => 0,
                'dismissed'         => 0,
                'meta_title'        => $status_redirect
            );
            $wpdb->insert($wpdb->prefix . 'wpms_links', $value);
        }
    }

    /**
     * Ajax remove custom url
     *
     * @return void
     */
    public function clearCustomUrl()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        if (isset($_POST['idUrl'])) {
            $lists = get_option('wpms_customUrls_list');
            if (isset($lists[$_POST['idUrl']])) {
                unset($lists[$_POST['idUrl']]);
            }
            // update list custom url
            update_option('wpms_customUrls_list', $lists);
            // update sitemap settings
            $settings = get_option('_metaseo_settings_sitemap');
            if (isset($settings['wpms_sitemap_customUrl'])) {
                if (isset($settings['wpms_sitemap_customUrl'][$_POST['idUrl']])) {
                    unset($settings['wpms_sitemap_customUrl'][$_POST['idUrl']]);
                    update_option('_metaseo_settings_sitemap', $settings);
                }
            }

            wp_send_json(true);
        }
        wp_send_json(false);
    }

    /**
     * Ajax add custom url
     *
     * @return void
     */
    public function sitemapsAddCustomUrl()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        if (isset($_POST['link']) && $_POST['link'] !== '' && isset($_POST['title'])) {
            $lists = get_option('wpms_customUrls_list');
            $key   = time();
            if (!empty($lists) && is_array($lists)) {
                $lists[$key] = array('link' => $_POST['link'], 'title' => $_POST['title']);
            } else {
                $lists       = array();
                $lists[$key] = array('link' => $_POST['link'], 'title' => $_POST['title']);
            }
            update_option('wpms_customUrls_list', $lists);
            $html = $this->createCustomUrlSettings($_POST['link'], $_POST['title'], $key);
            wp_send_json(array('status' => true, 'html' => $html));
        }
        wp_send_json(array('status' => false));
    }

    /**
     * Create custom url settings
     *
     * @param string $link  URL
     * @param string $title Title
     * @param string $key   Key
     *
     * @return string
     */
    public function createCustomUrlSettings($link, $title, $key)
    {
        if (!class_exists('WpmsProContentListTable')) {
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . '/inc/class.metaseo-sitemap.php');
        }

        $sitemap       = new WpmsProSitemap();
        $html          = '';
        $pagefrequency = 'monthly';
        $pagepriority  = '1.0';
        $slpr          = $sitemap->viewPriority(
            'priority_customUrl_' . $key,
            '_metaseo_settings_sitemap[wpms_sitemap_customUrl][' . $key . '][priority]',
            $pagepriority
        );
        $slfr          = $sitemap->viewFrequency(
            'frequency_customUrl_' . $key,
            '_metaseo_settings_sitemap[wpms_sitemap_customUrl][' . $key . '][frequency]',
            $pagefrequency
        );
        $html          .= '<div class="wpms_row wpms_row_record" data-id="' . $key . '">';
        $html          .= '<div style="float:left;line-height:30px">';
        if (isset($title) && $title !== '') {
            $title = '<a target="_blank" href="' . esc_url($link) . '">' . esc_html($title) . '</a>';
        } else {
            $title = '<a target="_blank" href="' . esc_url($link) . '">' . esc_html($title) . '</a>';
        }

        $html .= '<input class="wpms_sitemap_input_link checked" type="hidden"
                     data-type="custom_url" value="' . esc_url($link) . '">';
        $html .= '<div class="pure-checkbox">';
        $html .= '<input class="cb_sitemaps_customUrl wpms_xmap_customUrl"
                     id="' . esc_attr('wpms_sitemap_customUrl' . $key) . '" type="checkbox"
                      name="' . esc_attr('_metaseo_settings_sitemap[wpms_sitemap_customUrl][' . esc_attr($key) . '][customUrl_id]') . '"
                       value="' . esc_attr($key) . '" checked>';
        // phpcs:ignore WordPress.Security.EscapeOutput -- Content escaped in previous line (same function)
        $html .= '<label for="' . esc_attr('wpms_sitemap_customUrl' . $key) . '" class="wpms-text">' . $title . '</label>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '<div class="wpms_right">' . $slpr . $slfr;
        $html .= '<i class="material-icons wpms_clear_customUrl">clear</i></div>';
        $html .= '</div>';
        return $html;
    }

    /**
     * Get where for list posts
     *
     * @return array
     */
    public static function getWherePosts()
    {
        $post_types = WpmsProContentListTable::getPostTypes();
        foreach ($post_types as &$post_type) {
            $post_type = esc_sql($post_type);
        }
        $post_types = implode("', '", $post_types);

        $states = get_post_stati(array('show_in_admin_all_list' => true));
        foreach ($states as &$state) {
            $state = esc_sql($state);
        }

        $all_states = implode("', '", $states);
        $where      = array();
        $where[]    = 'post_type IN (\'' . $post_types . '\')';
        $where[]    = 'post_status IN (\'' . $all_states . '\')';
        return $where;
    }

    /**
     * Ajax get post duplicate metatitle
     *
     * @return void
     */
    public function getDuplicateMetatitle()
    {
        global $wpdb;
        $where                 = $this->getWherePosts();
        $total_items           = WpmsProDashboard::getCountPost();
        $where[]               = 'mt.meta_key = "_metaseo_metatitle"';
        $where[]               = 'mt.meta_value IN (SELECT DISTINCT meta_value FROM ' . $wpdb->postmeta . ' WHERE meta_key="_metaseo_metatitle" AND meta_value != "" GROUP BY meta_value HAVING COUNT(*) >= 2)';
        $total_items_duplicate = $wpdb->get_var($wpdb->prepare('SELECT COUNT(ID) '
                                                               . ' FROM ' . $wpdb->posts . ' as p'
                                                               . ' LEFT JOIN (SELECT * FROM ' . $wpdb->postmeta . ' WHERE meta_key = %s) mt ON mt.post_id = p.ID '
                                                               . ' WHERE ' . implode(' AND ', $where), array('_metaseo_metatitle'))); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Variable has been prepare
        $item_true             = (int) $total_items - (int) $total_items_duplicate;
        if ((int) $total_items !== 0) {
            $percent = ceil($item_true * 100 / $total_items);
        } else {
            $percent = 100;
        }

        wp_send_json(array(
            'total_items'          => (int) $total_items,
            'count_post_duplicate' => (int) $total_items_duplicate,
            'percent'              => $percent
        ));
    }

    /**
     * Get post duplicate metatitle
     *
     * @return void
     */
    public function getDuplicateMetadesc()
    {
        global $wpdb;
        $where                 = $this->getWherePosts();
        $total_items           = WpmsProDashboard::getCountPost();
        $where[]               = 'mt.meta_key = "_metaseo_metadesc"';
        $where[]               = 'mt.meta_value IN (SELECT DISTINCT meta_value FROM ' . $wpdb->postmeta . ' WHERE meta_key="_metaseo_metadesc" AND meta_value != "" GROUP BY meta_value HAVING COUNT(*) >= 2)';
        $total_items_duplicate = $wpdb->get_var($wpdb->prepare('SELECT COUNT(ID) '
                                                               . ' FROM ' . $wpdb->posts . ' as p'
                                                               . ' LEFT JOIN (SELECT * FROM ' . $wpdb->postmeta . ' WHERE meta_key = %s) mt ON mt.post_id = p.ID '
                                                               . ' WHERE ' . implode(' AND ', $where), array('_metaseo_metadesc'))); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Variable has been prepare
        $item_true             = (int) $total_items - (int) $total_items_duplicate;

        if ((int) $total_items !== 0) {
            $percent = ceil($item_true * 100 / $total_items);
        } else {
            $percent = 100;
        }
        wp_send_json(array(
            'total_items'          => (int) $total_items,
            'count_post_duplicate' => (int) $total_items_duplicate,
            'percent'              => $percent
        ));
    }

    /**
     * Update option wpms_email_settings
     *
     * @return void
     */
    public function saveEmailSettings()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        $params       = array('enable', 'host', 'type_encryption', 'port', 'autentication', 'username', 'password');
        $settingemail = array();
        foreach ($params as $param) {
            if (isset($_POST[$param])) {
                $settingemail[$param] = $_POST[$param];
            }
        }
        update_option('wpms_email_settings', $settingemail);
        wp_send_json(true);
    }

    /**
     * Get url status
     *
     * @param string $url URL
     *
     * @return string
     */
    public function getUrlStatus($url)
    {
        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- Hide warning when get_headers() function fails
        $status = @get_headers($url, 0);
        if (strpos($url, 'mailto:') !== false) {
            return 'Not checked';
        }

        if (strpos($url, '#') === 0 || strpos($url, 'tel:') === 0) {
            return 'HTTP/1.1 200 OK';
        }
        if (isset($status[0])) {
            return $status[0];
        } else {
            return 'Server Not Found';
        }
    }

    /**
     * Ajax run link checker
     *
     * @return void
     */
    public function runLinkCheck()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        $urls                            = array();
        $DomDocument                     = new DOMDocument();
        $DomDocument->preserveWhiteSpace = false;

        if (is_multisite()) {
            $home_url = preg_replace(
                '/[^a-zA-ZА-Яа-я0-9\s]/',
                '_',
                str_replace(
                    'http://',
                    '',
                    str_replace('https://', '', ABSPATH)
                )
            );
            $path     = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', ABSPATH), '/') . '/wpms-sitemap_' . $home_url . '.xml';
        } else {
            $path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', ABSPATH), '/') . '/' . $this->wpms_sitemap_name;
            if (is_writable(ABSPATH)) {
                $path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', ABSPATH), '/') . '/' . $this->wpms_sitemap_name;
            } else {
                $upload_dir = wp_upload_dir();
                $path = $upload_dir['basedir']. '/' . $this->wpms_sitemap_name;
            }
        }

        if (!file_exists($path)) {
            wp_send_json(array('status' => false, 'msg' => esc_html__('wpms-sitemap.xml file is not exists, please regenerate sitemaps before run sitemap link check!', 'wpmsPro') ));
        }

        // fixme:: why use $link here, DOMDocument::load() need path to the XML document
        //$DomDocument->load($link);
        $DomDocument->load($path);
        $DomNodeList = $DomDocument->getElementsByTagName('loc');
        $lastmods    = $DomDocument->getElementsByTagName('lastmod');
        $changefreq  = $DomDocument->getElementsByTagName('changefreq');
        $priority    = $DomDocument->getElementsByTagName('priority');

        $per_page   = 20;
        if ($DomNodeList->length <= $per_page) {
            $count_page = 1;
        } else {
            $count_page = ceil($DomNodeList->length / $per_page);
        }

        if (isset($_POST['page'])) {
            $page = $_POST['page'];
        } else {
            $page = 1;
        }

        if ((int) $page < 1) {
            $page = 1;
        }

        if ((int) $page > (int) $count_page) {
            $page = $count_page;
        }

        $start = ($page - 1) * $per_page;
        $end   = ($page * $per_page);
        $max_num = 0;
        $limit = 1;
        if ($DomNodeList->length < $per_page) {
            $percent = ($limit/$DomNodeList->length)*100;
        } else {
            $percent = ($limit/$per_page)*100;
        }

        foreach ($DomNodeList as $k => $url) {
            if ($k >= $start && $k < $end && (int)$_POST['subpage'] === (int) $k) {
                $status = $this->getUrlStatus($url->nodeValue);
                $urls[] = array(
                    'url'        => $url->nodeValue,
                    'lastmod'    => $lastmods[$k]->nodeValue,
                    'changefreq' => $changefreq[$k]->nodeValue,
                    'priority'   => $priority[$k]->nodeValue,
                    'status'     => $status
                );
                $max_num++;

                if ($max_num >= $limit) {
                    wp_send_json(array('status' => false, 'urls' => $urls, 'percent' => $percent));
                }
            }
        }

        $html = $this->generationLink($per_page, $count_page, $page, $DomNodeList->length);
        wp_send_json(array('status' => true, 'html' => $html));
    }

    /**
     * Generation list links
     *
     * @param integer $per_page    Per page
     * @param integer $count_page  Count page
     * @param integer $page        Current page
     * @param integer $count_items Count items
     *
     * @return string
     */
    public function generationLink($per_page, $count_page, $page = 1, $count_items = 0)
    {
        $html  = '';
        ob_start();
        require_once 'page/link_sitemap_table.php';
        $html .= ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Update option wpms_email_settings
     *
     * @return void
     */
    public function saveLocalBusiness()
    {
        if (empty($_POST['wpms_nonce'])
            || !wp_verify_nonce($_POST['wpms_nonce'], 'wpms_nonce')) {
            die();
        }

        $params                 = array(
            'enable',
            'logo',
            'type_name',
            'country',
            'address',
            'city',
            'state',
            'phone',
            'pricerange'
        );
        $setting_local_business = array();
        foreach ($params as $param) {
            if (isset($_POST[$param])) {
                $setting_local_business[$param] = $_POST[$param];
            }
        }
        update_option('wpms_local_business', $setting_local_business);
        wp_send_json(true);
    }

    /**
     * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
     *
     * @return void
     */
    public static function pluginAddonActivation()
    {

        global $wp_version;

        if (!class_exists('DOMDocument')) {
            deactivate_plugins(basename(__FILE__));
            wp_die(
                '<p>To active WP Meta SEO plugin , please install  “dom” PHP extension </p>',
                'Plugin Activation Error',
                array(
                    'response'  => 200,
                    'back_link' => true
                )
            );
        }

        // Setup wizard redirect
        if (is_null(get_option('wpmsPro_activation_redirect', null)) && empty(get_option('wpmsPro_version', null))) {
            update_option('wpmsPro_first_installed', '1');
            add_option('wpmsPro_activation_redirect', '1');
            return;
        }

        if (is_multisite() && ms_is_switched()) {
            delete_option('rewrite_rules');
        } else {
            $wpmsseo_rewrite = new WpmsProRewrite();
            $wpmsseo_rewrite->wpmsScheduleFlush();
        }

        //Set two param as flags that determine whether show import meta data
        // from other SEO plugin button or not to 0
        update_option('_aio_import_notice_flag', 0);
        update_option('_yoast_import_notice_flag', 0);
        update_option('plugin_to_sync_with', 0);

        if (!class_exists('Wpms_Api_Google', false)) {
            // Require the file
            require_once WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google-api/class-api-google.php';
            // Initialize the Google API Class to set the autoloader
            new Wpms_Api_Google();
        }

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

        $wpms_googleapi = new Wpms_Api_Google_Client($gsc, 'wpms-gsc', 'https://www.googleapis.com/webmasters/v3/');
        // Clear old data
        $wpms_googleapi->clearData();
    }

    /**
     * Attached to deactivate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
     *
     * @return void
     */
    public static function pluginAddonDeactivation()
    {
        if (is_multisite() && ms_is_switched()) {
            delete_option('rewrite_rules');
        } else {
            add_action('shutdown', 'flush_rewrite_rules');
        }
    }

    /**
     * Get list country
     *
     * @param array $array List country
     *
     * @return array
     */
    public function countryList($array)
    {
        return array_merge(
            $array,
            array(
                'AF' => 'Afghanistan',
                'AX' => 'Aland Islands',
                'AL' => 'Albania',
                'DZ' => 'Algeria',
                'AS' => 'American Samoa',
                'AD' => 'Andorra',
                'AO' => 'Angola',
                'AI' => 'Anguilla',
                'AQ' => 'Antarctica',
                'AG' => 'Antigua and Barbuda',
                'AR' => 'Argentina',
                'AM' => 'Armenia',
                'AW' => 'Aruba',
                'AU' => 'Australia',
                'AT' => 'Austria',
                'AZ' => 'Azerbaijan',
                'BS' => 'Bahamas',
                'BH' => 'Bahrain',
                'BD' => 'Bangladesh',
                'BB' => 'Barbados',
                'BY' => 'Belarus',
                'BE' => 'Belgium',
                'BZ' => 'Belize',
                'BJ' => 'Benin',
                'BM' => 'Bermuda',
                'BT' => 'Bhutan',
                'BO' => 'Bolivia, Plurinational State of',
                'BQ' => 'Bonaire, Sint Eustatius and Saba',
                'BA' => 'Bosnia and Herzegovina',
                'BW' => 'Botswana',
                'BV' => 'Bouvet Island',
                'BR' => 'Brazil',
                'IO' => 'British Indian Ocean Territory',
                'BN' => 'Brunei Darussalam',
                'BG' => 'Bulgaria',
                'BF' => 'Burkina Faso',
                'BI' => 'Burundi',
                'KH' => 'Cambodia',
                'CM' => 'Cameroon',
                'CA' => 'Canada',
                'CV' => 'Cape Verde',
                'KY' => 'Cayman Islands',
                'CF' => 'Central African Republic',
                'TD' => 'Chad',
                'CL' => 'Chile',
                'CN' => 'China',
                'CX' => 'Christmas Island',
                'CC' => 'Cocos (Keeling) Islands',
                'CO' => 'Colombia',
                'KM' => 'Comoros',
                'CG' => 'Congo',
                'CD' => 'Congo, the Democratic Republic of the',
                'CK' => 'Cook Islands',
                'CR' => 'Costa Rica',
                'CI' => 'Côte d Ivoire',
                'HR' => 'Croatia',
                'CU' => 'Cuba',
                'CW' => 'Curaçao',
                'CY' => 'Cyprus',
                'CZ' => 'Czech Republic',
                'DK' => 'Denmark',
                'DJ' => 'Djibouti',
                'DM' => 'Dominica',
                'DO' => 'Dominican Republic',
                'EC' => 'Ecuador',
                'EG' => 'Egypt',
                'SV' => 'El Salvador',
                'GQ' => 'Equatorial Guinea',
                'ER' => 'Eritrea',
                'EE' => 'Estonia',
                'ET' => 'Ethiopia',
                'FK' => 'Falkland Islands (Malvinas)',
                'FO' => 'Faroe Islands',
                'FJ' => 'Fiji',
                'FI' => 'Finland',
                'FR' => 'France',
                'GF' => 'French Guiana',
                'PF' => 'French Polynesia',
                'TF' => 'French Southern Territories',
                'GA' => 'Gabon',
                'GM' => 'Gambia',
                'GE' => 'Georgia',
                'DE' => 'Germany',
                'GH' => 'Ghana',
                'GI' => 'Gibraltar',
                'GR' => 'Greece',
                'GL' => 'Greenland',
                'GD' => 'Grenada',
                'GP' => 'Guadeloupe',
                'GU' => 'Guam',
                'GT' => 'Guatemala',
                'GG' => 'Guernsey',
                'GN' => 'Guinea',
                'GW' => 'Guinea-Bissau',
                'GY' => 'Guyana',
                'HT' => 'Haiti',
                'HM' => 'Heard Island and McDonald Islands',
                'VA' => 'Holy See (Vatican City State)',
                'HN' => 'Honduras',
                'HK' => 'Hong Kong',
                'HU' => 'Hungary',
                'IS' => 'Iceland',
                'IN' => 'India',
                'ID' => 'Indonesia',
                'IR' => 'Iran, Islamic Republic of',
                'IQ' => 'Iraq',
                'IE' => 'Ireland',
                'IM' => 'Isle of Man',
                'IL' => 'Israel',
                'IT' => 'Italy',
                'JM' => 'Jamaica',
                'JP' => 'Japan',
                'JE' => 'Jersey',
                'JO' => 'Jordan',
                'KZ' => 'Kazakhstan',
                'KE' => 'Kenya',
                'KI' => 'Kiribati',
                'KP' => 'Korea, Democratic People\'s Republic of',
                'KR' => 'Korea, Republic of,',
                'KW' => 'Kuwait',
                'KG' => 'Kyrgyzstan',
                'LA' => 'Lao Peoples Democratic Republic',
                'LV' => 'Latvia',
                'LB' => 'Lebanon',
                'LS' => 'Lesotho',
                'LR' => 'Liberia',
                'LY' => 'Libya',
                'LI' => 'Liechtenstein',
                'LT' => 'Lithuania',
                'LU' => 'Luxembourg',
                'MO' => 'Macao',
                'MK' => 'Macedonia, the former Yugoslav Republic of',
                'MG' => 'Madagascar',
                'MW' => 'Malawi',
                'MY' => 'Malaysia',
                'MV' => 'Maldives',
                'ML' => 'Mali',
                'MT' => 'Malta',
                'MH' => 'Marshall Islands',
                'MQ' => 'Martinique',
                'MR' => 'Mauritania',
                'MU' => 'Mauritius',
                'YT' => 'Mayotte',
                'MX' => 'Mexico',
                'FM' => 'Micronesia, Federated States of',
                'MD' => 'Moldova, Republic of',
                'MC' => 'Monaco',
                'MN' => 'Mongolia',
                'ME' => 'Montenegro',
                'MS' => 'Montserrat',
                'MA' => 'Morocco',
                'MZ' => 'Mozambique',
                'MM' => 'Myanmar',
                'NA' => 'Namibia',
                'NR' => 'Nauru',
                'NP' => 'Nepal',
                'NL' => 'Netherlands',
                'NC' => 'New Caledonia',
                'NZ' => 'New Zealand',
                'NI' => 'Nicaragua',
                'NE' => 'Niger',
                'NG' => 'Nigeria',
                'NU' => 'Niue',
                'NF' => 'Norfolk Island',
                'MP' => 'Northern Mariana Islands',
                'NO' => 'Norway',
                'OM' => 'Oman',
                'PK' => 'Pakistan',
                'PW' => 'Palau',
                'PS' => 'Palestine, State of',
                'PA' => 'Panama',
                'PG' => 'Papua New Guinea',
                'PY' => 'Paraguay',
                'PE' => 'Peru',
                'PH' => 'Philippines',
                'PN' => 'Pitcairn',
                'PL' => 'Poland',
                'PT' => 'Portugal',
                'PR' => 'Puerto Rico',
                'QA' => 'Qatar',
                'RE' => 'Reunion',
                'RO' => 'Romania',
                'RU' => 'Russian Federation',
                'RW' => 'Rwanda',
                'BL' => 'Saint Barthélemy',
                'SH' => 'Saint Helena, Ascension and Tristan da Cunha',
                'KN' => 'Saint Kitts and Nevis',
                'LC' => 'Saint Lucia',
                'MF' => 'Saint Martin (French part)',
                'PM' => 'Saint Pierre and Miquelon',
                'VC' => 'Saint Vincent and the Grenadines',
                'WS' => 'Samoa',
                'SM' => 'San Marino',
                'ST' => 'Sao Tome and Principe',
                'SA' => 'Saudi Arabia',
                'SN' => 'Senegal',
                'RS' => 'Serbia',
                'SC' => 'Seychelles',
                'SL' => 'Sierra Leone',
                'SG' => 'Singapore',
                'SX' => 'Sint Maarten (Dutch part)',
                'SK' => 'Slovakia',
                'SI' => 'Slovenia',
                'SB' => 'Solomon Islands',
                'SO' => 'Somalia',
                'ZA' => 'South Africa',
                'GS' => 'South Georgia and the South Sandwich Islands',
                'SS' => 'South Sudan',
                'ES' => 'Spain',
                'LK' => 'Sri Lanka',
                'SD' => 'Sudan',
                'SR' => 'Suriname',
                'SJ' => 'Svalbard and Jan Mayen',
                'SZ' => 'Swaziland',
                'SE' => 'Sweden',
                'CH' => 'Switzerland',
                'SY' => 'Syrian Arab Republic',
                'TW' => 'Taiwan, Province of China',
                'TJ' => 'Tajikistan',
                'TZ' => 'Tanzania, United Republic of',
                'TH' => 'Thailand',
                'TL' => 'Timor-Leste',
                'TG' => 'Togo',
                'TK' => 'Tokelau',
                'TO' => 'Tonga',
                'TT' => 'Trinidad and Tobago',
                'TN' => 'Tunisia',
                'TR' => 'Turkey',
                'TM' => 'Turkmenistan',
                'TC' => 'Turks and Caicos Islands',
                'TV' => 'Tuvalu',
                'UG' => 'Uganda',
                'UA' => 'Ukraine',
                'AE' => 'United Arab Emirates',
                'GB' => 'United Kingdom',
                'US' => 'United States',
                'UM' => 'United States Minor Outlying Islands',
                'UY' => 'Uruguay',
                'UZ' => 'Uzbekistan',
                'VU' => 'Vanuatu',
                'VE' => 'Venezuela, Bolivarian Republic of',
                'VN' => 'Viet Nam',
                'VG' => 'Virgin Islands, British',
                'VI' => 'Virgin Islands, U.S.',
                'WF' => 'Wallis and Futuna',
                'EH' => 'Western Sahara',
                'YE' => 'Yemen',
                'ZM' => 'Zambia',
                'ZW' => 'Zimbabwe',
            )
        );
    }
}
