<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Fired during plugin activation
 *
 * @link       https://scholar-sync.org
 * @since      1.0.0
 *
 * @package    ScholarSync
 * @subpackage ScholarSync/includes
 */

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    ScholarSync
 * @subpackage ScholarSync/includes
 * @author     Scholar Sync Team <support@scholar-sync.org>
 */
class ScholarSync_Activator {

    /**
	 * Short Description. (use period)
	 *
	 * Long Description.
	 *
	 * @since    1.0.0
	 */
	public static function activate() {
        self::create_table_authors();
        self::create_table_articles();
        self::create_table_groups();
        self::create_table_group_authors();
        self::create_table_co_authors();
        self::create_table_sync_runs();
        self::create_table_sync_author_log();
        // API key registration is deferred until the admin gives explicit consent
        // to transmit data to scholar-sync.org (required for WordPress.org listing).
        // The consent notice is shown by ScholarSync_Admin::show_consent_notice().
        if ( get_option( 'scholar_sync_service_consent', false ) ) {
            self::crete_apikey();
        }
        // Schedule background sync cron (fires every 3 days).
        if ( ! wp_next_scheduled( 'scholar_sync_background_sync' ) ) {
            wp_schedule_event( time(), 'scholar_sync_every_3_days', 'scholar_sync_background_sync' );
        }
        // Temporarily disabled so the Freemius opt-in dialog can appear on first activation.
        // Re-enable after completing the Freemius integration verification.
        // self::redirect_to_onboard();
    }

    private static function getCustomTablePrefix()
    {
        global $wpdb;
        return $wpdb->prefix . 'ssync_';
    }

    /**
     * Run table creation for sites that already had the plugin installed
     * before Groups was introduced. Keyed on a DB version option so it only
     * runs once per upgrade.
     */
    public static function upgrade_tables() {
        $current = get_option( 'scholar_sync_db_version', '1.0' );
        if ( version_compare( $current, '1.1', '<' ) ) {
            self::create_table_groups();
            self::create_table_group_authors();
            update_option( 'scholar_sync_db_version', '1.1' );
            $current = '1.1';
        }
        if ( version_compare( $current, '1.2', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'group_authors';
            $col  = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'link_url' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $col ) ) {
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `link_url` varchar(1024) DEFAULT NULL', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            update_option( 'scholar_sync_db_version', '1.2' );
        }
        if ( version_compare( $current, '1.3', '<' ) ) {
            self::create_table_co_authors();
            update_option( 'scholar_sync_db_version', '1.3' );
            $current = '1.3';
        }
        if ( version_compare( $current, '1.4', '<' ) ) {
            self::create_table_sync_runs();
            self::create_table_sync_author_log();
            update_option( 'scholar_sync_db_version', '1.4' );
            $current = '1.4';
        }
        if ( version_compare( $current, '1.5', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'authors';
            $cols = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'openalex_id' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $cols ) ) {
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `openalex_id` varchar(30) DEFAULT NULL, ADD COLUMN `orcid_id` varchar(20) DEFAULT NULL', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            // Widen scholar_id to accommodate OpenAlex IDs (previously varchar(13)).
            $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i MODIFY COLUMN `scholar_id` varchar(30) DEFAULT NULL', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            update_option( 'scholar_sync_db_version', '1.5' );
            $current = '1.5';
        }
        if ( version_compare( $current, '1.6', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'articles';
            $col  = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'image_url' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $col ) ) {
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `image_url` varchar(1024) DEFAULT NULL', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            update_option( 'scholar_sync_db_version', '1.6' );
        }
        if ( version_compare( $current, '1.7', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'authors';
            $cols = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'citations_all_sync' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $cols ) ) {
                // Per-field sync guards for the 4 stats fields the sync-author service call can
                // now refresh (citations/h-index/i10-index/interests); drop columns confirmed
                // dead by code audit (openalex_id, all_data, is_custom, and the unused _prev trio).
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `citations_all_sync` tinyint(1) NOT NULL DEFAULT 1, ADD COLUMN `h_index_all_sync` tinyint(1) NOT NULL DEFAULT 1, ADD COLUMN `i10_index_all_sync` tinyint(1) NOT NULL DEFAULT 1, ADD COLUMN `interests_sync` tinyint(1) NOT NULL DEFAULT 1, DROP COLUMN `citations_prev`, DROP COLUMN `h_index_prev`, DROP COLUMN `i10_index_prev`, DROP COLUMN `all_data`, DROP COLUMN `openalex_id`, DROP COLUMN `is_custom`', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            update_option( 'scholar_sync_db_version', '1.7' );
        }
        if ( version_compare( $current, '1.8', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'articles';
            $cols = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'cited_by_value_sync' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $cols ) ) {
                // Per-field sync guard for cited_by_value, mirroring the authors-table pattern;
                // drop columns confirmed dead by code audit (custom_by, co_authors, cited_by_graph
                // had no producer or consumer; cites_id was written as '' on every insert and
                // never updated afterward, so the link it fed never actually rendered).
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `cited_by_value_sync` tinyint(1) NOT NULL DEFAULT 1, DROP COLUMN `custom_by`, DROP COLUMN `co_authors`, DROP COLUMN `cited_by_graph`, DROP COLUMN `cites_id`', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            update_option( 'scholar_sync_db_version', '1.8' );
        }
        if ( version_compare( $current, '1.9', '<' ) ) {
            global $wpdb;
            $name = self::getCustomTablePrefix() . 'authors';
            $cols = $wpdb->get_results( $wpdb->prepare( 'SHOW COLUMNS FROM %i LIKE %s', $name, 'position' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            if ( empty( $cols ) ) {
                // New manually-entered field for the Researcher Directory card redesign
                // (e.g. "Associate Professor"); remote sync has no equivalent data, same as
                // affiliations/directory_link.
                $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN `position` varchar(255) DEFAULT NULL', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- %i is the WordPress identifier placeholder (WP 6.2+)
            }
            update_option( 'scholar_sync_db_version', '1.9' );
        }
    }

    private static function create_table_groups() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'groups';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            $table_query = self::get_sql_for_table_groups( $name );
            include_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( $table_query );
        }
    }

    private static function create_table_group_authors() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'group_authors';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            $table_query = self::get_sql_for_table_group_authors( $name );
            include_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( $table_query );
        }
    }

    private static function create_table_co_authors() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'co_authors';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            $table_query = self::get_sql_for_table_co_authors( $name );
            include_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( $table_query );
        }
    }

    public static function get_sql_for_table_groups( $name ) {
        return '
            CREATE TABLE `' . $name . '` (
                `group_id`   int(11)       NOT NULL AUTO_INCREMENT,
                `name`       varchar(255)  NOT NULL,
                `view_type`  enum(\'grid\',\'feed\') NOT NULL DEFAULT \'grid\',
                `settings`   longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
                `created`    timestamp     NOT NULL DEFAULT current_timestamp(),
                PRIMARY KEY (`group_id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ';
    }

    public static function get_sql_for_table_group_authors( $name ) {
        return '
            CREATE TABLE `' . $name . '` (
                `id`         int(11) NOT NULL AUTO_INCREMENT,
                `group_id`   int(11) NOT NULL,
                `author_id`  int(11) NOT NULL,
                `sort_order` int(11) NOT NULL DEFAULT 0,
                `link_url`   varchar(1024) DEFAULT NULL,
                PRIMARY KEY (`id`),
                KEY `group_id` (`group_id`),
                KEY `author_id` (`author_id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ';
    }

    public static function get_sql_for_table_co_authors( $name ) {
        return '
            CREATE TABLE `' . $name . '` (
                `co_author_id`  int(11)       NOT NULL AUTO_INCREMENT,
                `scholar_id`    varchar(20)   DEFAULT NULL,
                `full_name`     varchar(255)  NOT NULL,
                `short_name`    varchar(100)  NOT NULL,
                `image_url`     varchar(512)  DEFAULT NULL,
                `profile_link`  varchar(512)  DEFAULT NULL,
                `affiliations`  varchar(512)  DEFAULT NULL,
                `last_updated`  timestamp     NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
                `created`       timestamp     NOT NULL DEFAULT current_timestamp(),
                PRIMARY KEY (`co_author_id`),
                UNIQUE KEY `scholar_id` (`scholar_id`),
                UNIQUE KEY `short_name` (`short_name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ';
    }

    private static function create_table_sync_runs() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'sync_runs';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            include_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( self::get_sql_for_table_sync_runs( $name ) );
        }
    }

    private static function create_table_sync_author_log() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'sync_author_log';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            include_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( self::get_sql_for_table_sync_author_log( $name ) );
        }
    }

    public static function get_sql_for_table_sync_runs( $name ) {
        return "
            CREATE TABLE `{$name}` (
                `sync_run_id`       int(11)     NOT NULL AUTO_INCREMENT,
                `triggered_by`      enum('cron','manual') NOT NULL DEFAULT 'cron',
                `started_at`        datetime    NOT NULL,
                `completed_at`      datetime    DEFAULT NULL,
                `status`            enum('running','completed','failed') NOT NULL DEFAULT 'running',
                `stop_reason`       enum('none','frequency_limit','error') NOT NULL DEFAULT 'none',
                `authors_total`     int(11)     NOT NULL DEFAULT 0,
                `authors_succeeded` int(11)     NOT NULL DEFAULT 0,
                `authors_skipped`   int(11)     NOT NULL DEFAULT 0,
                `authors_errored`   int(11)     NOT NULL DEFAULT 0,
                `articles_created`  int(11)     NOT NULL DEFAULT 0,
                `articles_updated`  int(11)     NOT NULL DEFAULT 0,
                PRIMARY KEY (`sync_run_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ";
    }

    public static function get_sql_for_table_sync_author_log( $name ) {
        return "
            CREATE TABLE `{$name}` (
                `log_id`           int(11)      NOT NULL AUTO_INCREMENT,
                `sync_run_id`      int(11)      NOT NULL,
                `author_id`        int(11)      NOT NULL,
                `scholar_id`       varchar(20)  NOT NULL,
                `synced_at`        datetime     NOT NULL,
                `outcome`          enum('success','skipped_frequency','skipped_remaining','error') NOT NULL,
                `articles_created` int(11)      NOT NULL DEFAULT 0,
                `articles_updated` int(11)      NOT NULL DEFAULT 0,
                `error_code`       varchar(128) DEFAULT NULL,
                `error_message`    text         DEFAULT NULL,
                PRIMARY KEY (`log_id`),
                KEY `author_id` (`author_id`),
                KEY `sync_run_id` (`sync_run_id`),
                KEY `author_synced` (`author_id`, `synced_at`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ";
    }

    private static function create_table_articles() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'articles';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            $table_query = self::get_sql_for_table_articles($name);
            include_once (ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($table_query);
        }
    }

    private static function create_table_authors() {
        global $wpdb;
        $name = self::getCustomTablePrefix() . 'authors';
        if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $name ) ) != $name ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $name is built from trusted wpdb->prefix + plugin constant
            $table_query = self::get_sql_for_table_authors($name);
            include_once (ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($table_query);
        }
    }

    /**
     * Fire-and-forget notification to scholar-sync.org that this install's
     * Freemius plan/license has changed. Called on license activation,
     * deactivation, and change events. All Freemius context (user_id,
     * install_id, license_id, plan) is sent automatically via headers.
     */
    public static function notify_plan_update() {
        require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-remote.php';
        $remote = new ScholarSync_Remote( 'customer/update-plan' );
        if ( ! $remote->has_error() ) {
            $remote->retrieve_remote_data_post( [] );
        }
    }

    public static function crete_apikey() {
        require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-remote.php';
        $apikey = get_option(ScholarSync_Remote::$CUSTOMER_API_KEY );
        if (!$apikey) {
            $remote = new ScholarSync_Remote('customer/add', false);
            $remote->add_param_to_url('site-id', get_current_blog_id());
            $remote->retrieve_remote_data();
            if ($remote->has_error()) {
                // There was an error making the request
                $error_message = $remote->get_error_message();
            } else {
                // The request was successful
                $data = $remote->get_data();
                $apikey = $data['api-key'];
                update_option( ScholarSync_Remote::$CUSTOMER_API_KEY, $apikey);
            }
        }
    }

    /**
     * Generate 'CREATE TABLE' command
     * 1. SHOW CREATE TABLE wp_ssync_articles;
     * 2. Click on Extra Options
     * 3. Replace table name
     */

    public static function get_sql_for_table_articles($name) {
        return '
            CREATE TABLE `' . $name . '` (
                `article_id` int(11) NOT NULL AUTO_INCREMENT,
                `author_id` int(11) NOT NULL,
                `citation_id` varchar(64) NOT NULL,
                `title` varchar(512) NOT NULL,
                `link` varchar(1024) NOT NULL,
                `authors` varchar(1024) NOT NULL,
                `publication` varchar(1024) NOT NULL,
                `cited_by_value` int(11) NOT NULL DEFAULT 0,
                `cited_by_value_sync` tinyint(1) NOT NULL DEFAULT 1,
                `year` int(11) NOT NULL,
                `image_url` varchar(1024) DEFAULT NULL,
                `is_active` tinyint(1) NOT NULL DEFAULT 1,
                `is_custom` tinyint(4) NOT NULL DEFAULT 0,
                `all_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
                `last_updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
                `created` timestamp NOT NULL DEFAULT current_timestamp(),
                PRIMARY KEY (`article_id`),
                KEY `author_id` (`author_id`),
                KEY `citation_id` (`citation_id`)
                ) ENGINE=InnoDB AUTO_INCREMENT=1746 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ';
    }

    /**
     * Generate 'CREATE TABLE' command
     * 1. SHOW CREATE TABLE wp_ssync_authors;
     * 2. Click on Extra Options
     * 3. Replace table name
     */

     public static function get_sql_for_table_authors($name) {
        return '
            CREATE TABLE `' . $name . '` (
                  `author_id` int(11) NOT NULL AUTO_INCREMENT,
                  `scholar_id` varchar(30) DEFAULT NULL,
                  `orcid_id` varchar(20) DEFAULT NULL,
                  `name` varchar(255) NOT NULL,
                  `affiliations` varchar(255) NOT NULL,
                  `position` varchar(255) DEFAULT NULL,
                  `website` varchar(1024) NOT NULL,
                  `interests` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
                  `interests_sync` tinyint(1) NOT NULL DEFAULT 1,
                  `thumbnail` varchar(255) DEFAULT NULL,
                  `citations_all` int(11) DEFAULT NULL,
                  `citations_all_sync` tinyint(1) NOT NULL DEFAULT 1,
                  `h_index_all` int(11) DEFAULT NULL,
                  `h_index_all_sync` tinyint(1) NOT NULL DEFAULT 1,
                  `i10_index_all` int(11) DEFAULT NULL,
                  `i10_index_all_sync` tinyint(1) NOT NULL DEFAULT 1,
                  `per_year` longtext DEFAULT NULL,
                  `directory_link` varchar(255) DEFAULT NULL,
                  `last_updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
                  `created` timestamp NOT NULL DEFAULT current_timestamp(),
                  PRIMARY KEY (`author_id`),
                  UNIQUE KEY `scholar_id` (`scholar_id`)
                ) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
        ';
    }

    /**
     * Determine if a user can be redirected or not.
     * in case the use is not a developer or activating multiple plugins
     *
     * @return true if the user can be redirected. false if not.
     */
    private static function can_redirect_on_activation() {

        // If plugin is activated in network admin options, skip redirect.
        if ( is_network_admin() ) {
//            return false;
        }

        // Skip redirect if WP_DEBUG is enabled.
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
//            return false;
        }

        // Determine if multi-activation is enabled.
        $maybe_multi = filter_input( INPUT_GET, 'activate-multi', FILTER_VALIDATE_BOOLEAN );
        if ( $maybe_multi ) {
//            return false;
        }
        return true;
    }

    /**
     * Add an option upon activation to read in later when redirecting.
     */
    private static function redirect_to_onboard() {
        // Written as a full literal (same value as SCHOLAR_SYNC_OPTION_PREFIX . 'activation-redirect')
        // so the 'scholar-sync-option-' prefix is statically visible to Plugin Check / PHPCS.
        $option_name = 'scholar-sync-option-activation-redirect';

        if (self::can_redirect_on_activation()) {
            add_option($option_name, sanitize_text_field( __FILE__ ));

            add_action( 'admin_init', function() use ($option_name) {

                if (self::can_redirect_on_activation() && is_admin() ) {

                    // Read in option value.
                    if ( __FILE__ === get_option( $option_name) ) {
                        // Delete option value so no more redirects.
                        delete_option($option_name);
                        // Get redirect URL.
                        $url = admin_url( 'admin.php?page=scholar-sync-add-author-slug&onboard=1' );
                        wp_safe_redirect( $url );
                        exit;
                    }
                }
            });
        }
    }

}
