<?php
/**
 * WP Meta SEO Pro main class
 */
class WpmsPro
{
    /**
     * The version of the plugin.
     *
     * @var string
     */
    public $version = '1.0.0';
    /**
     * The name of the plugin.
     *
     * @var string
     */
    public $plugin_name = 'wp-meta-seo-addon';

    /**
     * Constructor to initialize the plugin with dependencies and hooks.
     */
    public function __construct()
    {
        if (defined('WPMSPRO_VERSION')) {
            $this->version = WPMSPRO_VERSION;
        }

        $this->loadDependencies();
    }

    /**
     * Load all dependencies for the plugin.
     *
     * This method includes all necessary files and classes required for the plugin to function.
     * It checks if the user is in the admin area or on the public side and loads the appropriate files.
     *
     * @return void
     */
    private function loadDependencies()
    {

        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/functions.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-rewrite.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-sitemap.php');

        if (is_admin()) {
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-admin-base.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-content-list-table.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-category-meta-table.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-image-list-table.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-dashboard.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-broken-link-table.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-google-analytics.php');
            include_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmsga.php');

            $classMap = array(
                'WpmsGsc' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-gsc.php',
                'WpmsGscAjax' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-ajax.php',
                'WpmsGscCategoryFilters' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-category-filters.php',
                'WpmsGscCount' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-count.php',
                'WpmsGscIssue' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-issue.php',
                'WpmsGscIssues' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-issues.php',
                'WpmsGscMapper' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-mapper.php',
                'WpmsGscMarker' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-marker.php',
                'WpmsGscService' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-service.php',
                'WpmsGscTable' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/gsc/class.metaseo-table.php',
                'WPMSUtils' => WPMETASEO_ADDON_PLUGIN_DIR . '/inc/class.metaseo-utils.php',
            );

            foreach ($classMap as $item) {
                require_once $item;
            }

            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-addon-admin.php');
        } else {
            // Check again and modify title, meta title, meta description before output
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-opengraph.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmstools.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmsgapi.php');
            require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/class.metaseo-addon-site.php');
        }
    }

    /**
     * Run the plugin.
     *
     * This method is called to initialize the plugin and set up hooks for both admin and public sides.
     *
     * @return void
     */
    public function run()
    {
        //  $this->handleAjax();
        $GLOBALS['metaseo_sitemap'] = new WpmsProSitemap;

        $settings = get_option('_metaseo_settings');
        if (isset($settings['metaseo_removecatprefix']) && $settings['metaseo_removecatprefix'] === '1') {
            $GLOBALS['metaseo_rewrite'] = new WpmsProRewrite;
        }

        if (is_admin()) {
            $this->defineAdminHooks();
            $GLOBALS['metaseo_addon'] = new MetaSeoAddonAdmin;

            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Not a form, nonce is not required
            if (isset($_GET['task']) && $_GET['task'] === 'wpms_ga') {
                $this->doGAConnect();
            }
        } else {
            $this->definePublicHooks();
            $GLOBALS['metaseo_addon_site'] = new MetaSeoAddonSite;
        }

        add_action('plugins_loaded', function () {
            spl_autoload_register(array($this, 'wpms_redirect_load'));
        }, 14);
        add_action('init', 'wpmsProRemoveHelloElementorMetaDesc');

        add_action('cmb_render_text_link', 'wpmsProTextLink', 10, 2);
        add_action('template_redirect', 'wpmsProTemplateRedirect');


        add_action(
            'after_setup_theme',
            function () {
                //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, no need verification
                if (defined('ET_CORE') && !empty($_GET['et_fb'])) {
                    require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/divi-seo/divi.php');
                    new Divi;
                }
            },
            11
        );
    }

    /**
     * Handle Google Analytics connection.
     *
     * This method processes the Google Analytics connection by checking for a code in the GET request,
     * authenticating with the Google API, and updating the options accordingly.
     *
     * @return void
     */
    public function doGAConnect()
    {

        if (!empty($_GET['code'])) {
            $google_analytics = get_option('wpms_google_alanytics');

            if (is_array($google_analytics)) {
                $google_analytics['code'] = $_GET['code'];

                require_once WPMETASEO_ADDON_PLUGIN_DIR . 'inc/google_analytics/wpmstools.php';
                $ggClient = WpmsGaTools::initClient($google_analytics['wpmsga_dash_clientid'], $google_analytics['wpmsga_dash_clientsecret']);

                try {
                    $ggClient->authenticate($google_analytics['code']);
                    $getAccessToken = $ggClient->getAccessToken();

                    if ($getAccessToken) {
                        $ggClient->setAccessToken($getAccessToken);
                        $google_analytics['googleCredentials'] = $getAccessToken;

                        if (empty($google_alanytics['profile_list'])) {
                            $service = new Google_Service_Analytics($ggClient);
                            $midnight = strtotime('tomorrow 00:00:00'); // UTC midnight
                            $midnight = $midnight + 8 * 3600; // UTC 8 AM
                            $error_timeout = $midnight - time();

                            $profiles = WpmsGaTools::refreshProfiles($service, $getAccessToken['access_token'], $error_timeout);
                            $google_analytics['profile_list'] = $profiles;
                        }

                        update_option('wpms_google_alanytics', $google_analytics);
                        // Do redirect
                        $redirectUrl = admin_url('admin.php?page=metaseo_google_analytics&view=wpms_gg_service_data');
                        header('Location: ' . $redirectUrl, true, 302);
                        exit;
                    }
                } catch (api\src\Service\Exception $e) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Log error for debug
                    error_log($e->getMessage());
                } catch (Exception $e) {
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Log error for debug
                    error_log($e->getMessage());
                }
            }
        }
    }

    /**
     * Define admin hooks for the plugin.
     *
     * This method sets up various hooks and actions that are specific to the admin area of the plugin.
     * It includes actions for initializing the admin base, handling redirects, and importing meta data.
     *
     * @return void
     */
    public function defineAdminHooks()
    {
        // to make wp_redirect() work in processAction()
        add_action('init', function () {
            ob_start();
        });

        add_action('plugins_loaded', array($this, 'wpmsAdminInit'), 15);

        /* * ****** Check and import meta data from other installed plugins for SEO ******* */
        add_action('admin_init', 'wpmsProYoastMessage');
    }


    /**
     * Define public hooks for the plugin.
     *
     * This method sets up various hooks and actions that are specific to the public side of the plugin.
     * It includes shortcodes, head actions, and filters for document titles.
     *
     * @return void
     */
    public function definePublicHooks()
    {
        // shortcode for breadcrumb
        add_shortcode('wpms_breadcrumb', 'wpmsBreadcrumbShortcode');

        add_action('wpmsseo_head', 'wpmsopengraph', 30);
        // Remove actions that we will handle through our wpseo_head call, and probably change the output of.
        remove_action('wp_head', 'rel_canonical');

        add_action('wp_head', 'wpmshead', 30);

        add_filter('pre_get_document_title', 'wpmstitle', 15);
        add_filter('wp_title', 'wpmstitle', 15, 3);
        add_filter('thematic_doctitle', 'wpmstitle', 15);
        add_filter('woo_title', 'wpmstitle', 99);
    }

    /**
     * Initialize the admin base class.
     *
     * This method creates an instance of the WpmsProAdminBase class and assigns it to the global variable.
     *
     * @return void
     */
    public function wpmsAdminInit()
    {
        $GLOBALS['metaseo_admin'] = new WpmsProAdminBase;
    }

    /**
     * Load redirect source
     *
     * @return void
     */
    public function wpms_redirect_load()
    {
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/gsc/redirect/class.metaseo-redirect-option.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/gsc/redirect/class.metaseo-redirect-option-exporter.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/gsc/redirect/class.metaseo-redirect-exporter.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/gsc/redirect/class.metaseo-redirect.php');
        require_once(WPMETASEO_ADDON_PLUGIN_DIR . 'inc/gsc/redirect/class.metaseo-redirect-manager.php');
    }
}
