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

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

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

	/**
	 * Short Description. (use period)
	 *
	 * Long Description.
	 *
	 * @since    1.0.0
	 */
	public static function uninstall() {
        self::drop_tables();
        self::delete_cron();
        self::delete_options();
        self::delete_pages();
	}

    private static function drop_tables() {
        global $wpdb;
        $tableArray = [
            SCHOLAR_SYNC_DB_ARTICLES,
            SCHOLAR_SYNC_DB_AUTHORS,
            SCHOLAR_SYNC_DB_GROUP_AUTHORS,
            SCHOLAR_SYNC_DB_GROUPS,
            SCHOLAR_SYNC_DB_CO_AUTHORS,
            SCHOLAR_SYNC_DB_SYNC_LOG,
            SCHOLAR_SYNC_DB_SYNC_RUNS,
        ];

        foreach ($tableArray as $name) {
            $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- %i is the WordPress identifier placeholder (WP 6.2+)
        }
    }

    private static function delete_options() {
        $all_options = wp_load_alloptions();
        foreach ($all_options as $option_name => $option_value) {
            if ( strpos($option_name, SCHOLAR_SYNC_OPTION_PREFIX) === 0 ||
                 strpos($option_name, 'scholar_sync_') === 0 ) {
                delete_option($option_name);
            }
        }
    }

    private static function delete_cron() {
        wp_clear_scheduled_hook( 'scholar_sync_background_sync' );
    }

    private static function delete_pages() {
        global $wpdb;
        $name = 'scholar_sync_page_1';
        $page_id = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare('SELECT ID FROM %i WHERE post_name = %s', $wpdb->posts, $name) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
        );
        if (!empty($page_id)) {
            wp_delete_post($page_id, true);
        }
    }
}
